UNPKG

import-sync

Version:

Synchronously import dynamic ECMAScript Modules similar to CommonJS require. Basic wrapper around esm for compatibility with both ESM and CJS projects in NodeJS.

60 lines 2.36 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.findModuleFile = exports.getCallerDirname = void 0; const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const config_1 = require("./config"); /** * Get the file path of the caller function. * * Implementation inspired by: * - https://www.npmjs.com/package/callsite?activeTab=code * * @returns {string} absolute path or an empty string if no caller */ const getCallerDirname = () => { const orig = Error.prepareStackTrace; Error.prepareStackTrace = (_, stack) => stack; const err = new Error(); Error.captureStackTrace(err, exports.getCallerDirname); const stack = err.stack; Error.prepareStackTrace = orig; const callerFilePath = stack[1].getFileName(); /* istanbul ignore next */ return path_1.default.dirname(callerFilePath.startsWith('file://') ? callerFilePath.substring(7) : callerFilePath); }; exports.getCallerDirname = getCallerDirname; /** * Find the module file path by checking for available extensions * as defined by VALID_FILE_EXTENSIONS * * @param {string} filePath The absolute path to the file * @returns {string} The resolved file path with appended extension * @throws {Error} If the file path does not match any valid extensions */ const findFileWithExtensions = (filePath) => { for (const ext of config_1.VALID_FILE_EXTENSIONS) { const extFilePath = `${filePath}${ext}`; if (fs_1.default.existsSync(extFilePath)) { return extFilePath; } } throw new Error(`No such file '${filePath}' with matching extensions [${config_1.VALID_FILE_EXTENSIONS}]`); }; /** * Find the module file path * * @param {string} modulePath - The path to the module * @param {string} basePath - The base path for the module * @returns {string} The resolved file path * @throws {Error} If the file is not found */ const findModuleFile = (basePath, modulePath) => { const filePath = path_1.default.join(basePath, modulePath); return fs_1.default.existsSync(filePath) ? filePath : findFileWithExtensions(filePath); }; exports.findModuleFile = findModuleFile; //# sourceMappingURL=files.js.map