load-dotenv
Version:
Automatically load the closest .env file
113 lines (86 loc) • 2.43 kB
JavaScript
;
var path = require('node:path');
var node_url = require('node:url');
var process$1 = require('node:process');
var fs = require('node:fs');
const typeMappings = {
directory: 'isDirectory',
file: 'isFile',
};
function checkType(type) {
if (Object.hasOwnProperty.call(typeMappings, type)) {
return;
}
throw new Error(`Invalid type specified: ${type}`);
}
const matchType = (type, stat) => stat[typeMappings[type]]();
const toPath$1 = urlOrPath => urlOrPath instanceof URL ? node_url.fileURLToPath(urlOrPath) : urlOrPath;
function locatePathSync(
paths,
{
cwd = process$1.cwd(),
type = 'file',
allowSymlinks = true,
} = {},
) {
checkType(type);
cwd = toPath$1(cwd);
const statFunction = allowSymlinks ? fs.statSync : fs.lstatSync;
for (const path_ of paths) {
try {
const stat = statFunction(path.resolve(cwd, path_), {
throwIfNoEntry: false,
});
if (!stat) {
continue;
}
if (matchType(type, stat)) {
return path_;
}
} catch {}
}
}
const toPath = urlOrPath => urlOrPath instanceof URL ? node_url.fileURLToPath(urlOrPath) : urlOrPath;
const findUpStop = Symbol('findUpStop');
function findUpMultipleSync(name, options = {}) {
let directory = path.resolve(toPath(options.cwd) || '');
const {root} = path.parse(directory);
const stopAt = options.stopAt || root;
const limit = options.limit || Number.POSITIVE_INFINITY;
const paths = [name].flat();
const runMatcher = locateOptions => {
if (typeof name !== 'function') {
return locatePathSync(paths, locateOptions);
}
const foundPath = name(locateOptions.cwd);
if (typeof foundPath === 'string') {
return locatePathSync([foundPath], locateOptions);
}
return foundPath;
};
const matches = [];
// eslint-disable-next-line no-constant-condition
while (true) {
const foundPath = runMatcher({...options, cwd: directory});
if (foundPath === findUpStop) {
break;
}
if (foundPath) {
matches.push(path.resolve(directory, foundPath));
}
if (directory === stopAt || matches.length >= limit) {
break;
}
directory = path.dirname(directory);
}
return matches;
}
function findUpSync(name, options = {}) {
const matches = findUpMultipleSync(name, {...options, limit: 1});
return matches[0];
}
function findEnv(fileName = '') {
return findUpSync(fileName || process.env.ENV_FILE || '.env')
}
exports.findEnv = findEnv;
//# sourceMappingURL=find.js.map