Socket
Socket
Sign inDemoInstall

cosmiconfig

Package Overview
Dependencies
25
Maintainers
3
Versions
56
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 8.2.0 to 8.3.0

dist/util.d.ts

15

dist/Explorer.d.ts

@@ -1,15 +0,2 @@

import { ExplorerBase } from './ExplorerBase';
import { CosmiconfigResult, ExplorerOptions } from './types';
declare class Explorer extends ExplorerBase<ExplorerOptions> {
constructor(options: ExplorerOptions);
search(searchFrom?: string): Promise<CosmiconfigResult>;
private searchFromDirectory;
private searchDirectory;
private loadSearchPlace;
private loadFileContent;
private createCosmiconfigResult;
load(filepath: string): Promise<CosmiconfigResult>;
private _loadFile;
}
export { Explorer };
export {};
//# sourceMappingURL=Explorer.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Explorer = void 0;
var _path = _interopRequireDefault(require("path"));
var _cacheWrapper = require("./cacheWrapper");
var _ExplorerBase = require("./ExplorerBase");
var _getDirectory = require("./getDirectory");
var _readFile = require("./readFile");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class Explorer extends _ExplorerBase.ExplorerBase {
constructor(options) {
super(options);
}
async search(searchFrom = process.cwd()) {
if (this.config.metaConfigFilePath) {
const config = await this._loadFile(this.config.metaConfigFilePath, true);
if (config && !config.isEmpty) {
return config;
}
const promises_1 = __importDefault(require("node:fs/promises"));
const node_path_1 = __importDefault(require("node:path"));
const path_type_1 = require("path-type");
const ExplorerBase_js_1 = require("./ExplorerBase.js");
const loaders_js_1 = require("./loaders.js");
const util_js_1 = require("./util.js");
/**
* @internal
*/
class Explorer extends ExplorerBase_js_1.ExplorerBase {
async load(filepath) {
filepath = node_path_1.default.resolve(filepath);
const load = async () => {
return await this.config.transform(await this.#readConfiguration(filepath));
};
if (this.loadCache) {
return await (0, util_js_1.emplace)(this.loadCache, filepath, load);
}
return await load();
}
return await this.searchFromDirectory(await (0, _getDirectory.getDirectory)(searchFrom));
}
async searchFromDirectory(dir) {
const absoluteDir = _path.default.resolve(process.cwd(), dir);
const run = async () => {
const result = await this.searchDirectory(absoluteDir);
const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
if (nextDir) {
return this.searchFromDirectory(nextDir);
}
return await this.config.transform(result);
};
if (this.searchCache) {
return (0, _cacheWrapper.cacheWrapper)(this.searchCache, absoluteDir, run);
async search(from = '') {
if (this.config.metaConfigFilePath) {
this.loadingMetaConfig = true;
const config = await this.load(this.config.metaConfigFilePath);
this.loadingMetaConfig = false;
if (config && !config.isEmpty) {
return config;
}
}
const stopDir = node_path_1.default.resolve(this.config.stopDir);
from = node_path_1.default.resolve(from);
const search = async () => {
/* istanbul ignore if -- @preserve */
if (await (0, path_type_1.isDirectory)(from)) {
for (const place of this.config.searchPlaces) {
const filepath = node_path_1.default.join(from, place);
try {
const result = await this.#readConfiguration(filepath);
if (result !== null &&
!(result.isEmpty && this.config.ignoreEmptySearchPlaces)) {
return await this.config.transform(result);
}
}
catch (error) {
if (error.code === 'ENOENT' || error.code === 'EISDIR') {
continue;
}
throw error;
}
}
}
const dir = node_path_1.default.dirname(from);
if (from !== stopDir && from !== dir) {
from = dir;
if (this.searchCache) {
return await (0, util_js_1.emplace)(this.searchCache, from, search);
}
return await search();
}
return null;
};
if (this.searchCache) {
return await (0, util_js_1.emplace)(this.searchCache, from, search);
}
return await search();
}
return run();
}
async searchDirectory(dir) {
for await (const place of this.config.searchPlaces) {
const placeResult = await this.loadSearchPlace(dir, place);
if (this.shouldSearchStopWithResult(placeResult)) {
return placeResult;
}
} // config not found
return null;
}
async loadSearchPlace(dir, place) {
const filepath = _path.default.join(dir, place);
const fileContents = await (0, _readFile.readFile)(filepath);
return await this.createCosmiconfigResult(filepath, fileContents, false);
}
async loadFileContent(filepath, content) {
if (content === null) {
return null;
async #readConfiguration(filepath) {
const contents = await promises_1.default.readFile(filepath, { encoding: 'utf-8' });
return this.toCosmiconfigResult(filepath, await this.#loadConfiguration(filepath, contents));
}
if (content.trim() === '') {
return undefined;
async #loadConfiguration(filepath, contents) {
if (contents.trim() === '') {
return;
}
if (node_path_1.default.basename(filepath) === 'package.json') {
return ((0, util_js_1.getPropertyByPath)((0, loaders_js_1.loadJson)(filepath, contents), this.config.packageProp) ?? null);
}
const extension = node_path_1.default.extname(filepath);
try {
const loader = this.config.loaders[extension || 'noExt'] ??
this.config.loaders['default'];
if (loader !== undefined) {
// eslint-disable-next-line @typescript-eslint/return-await
return await loader(filepath, contents);
}
}
catch (error) {
error.filepath = filepath;
throw error;
}
throw new Error(`No loader specified for ${(0, ExplorerBase_js_1.getExtensionDescription)(extension)}`);
}
const loader = this.getLoaderEntryForFile(filepath);
try {
return await loader(filepath, content);
} catch (e) {
e.filepath = filepath;
throw e;
}
}
async createCosmiconfigResult(filepath, content, forceProp) {
const fileContent = await this.loadFileContent(filepath, content);
return this.loadedContentToCosmiconfigResult(filepath, fileContent, forceProp);
}
async load(filepath) {
return this._loadFile(filepath, false);
}
async _loadFile(filepath, forceProp) {
this.validateFilePath(filepath);
const absoluteFilePath = _path.default.resolve(process.cwd(), filepath);
const runLoad = async () => {
const fileContents = await (0, _readFile.readFile)(absoluteFilePath, {
throwNotFound: true
});
const result = await this.createCosmiconfigResult(absoluteFilePath, fileContents, forceProp);
return await this.config.transform(result);
};
if (this.loadCache) {
return (0, _cacheWrapper.cacheWrapper)(this.loadCache, absoluteFilePath, runLoad);
}
return runLoad();
}
}
exports.Explorer = Explorer;
//# sourceMappingURL=Explorer.js.map

@@ -1,21 +0,2 @@

import { Loader } from './index';
import { Cache, CosmiconfigResult, ExplorerOptions, ExplorerOptionsSync, LoadedFileContent } from './types';
declare class ExplorerBase<T extends ExplorerOptions | ExplorerOptionsSync> {
protected readonly loadCache?: Cache;
protected readonly searchCache?: Cache;
protected readonly config: T;
constructor(options: T);
clearLoadCache(): void;
clearSearchCache(): void;
clearCaches(): void;
private validateConfig;
protected shouldSearchStopWithResult(result: CosmiconfigResult): boolean;
protected nextDirectoryToSearch(currentDir: string, currentResult: CosmiconfigResult): string | null;
private loadPackageProp;
protected getLoaderEntryForFile(filepath: string): Loader;
protected loadedContentToCosmiconfigResult(filepath: string, loadedContent: LoadedFileContent, forceProp: boolean): CosmiconfigResult;
protected validateFilePath(filepath: string): void;
}
declare function getExtensionDescription(filepath: string): string;
export { ExplorerBase, getExtensionDescription };
export {};
//# sourceMappingURL=ExplorerBase.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ExplorerBase = void 0;
exports.getExtensionDescription = getExtensionDescription;
var _path = _interopRequireDefault(require("path"));
var _getPropertyByPath = require("./getPropertyByPath");
var _loaders = require("./loaders");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getExtensionDescription = exports.ExplorerBase = void 0;
const node_path_1 = __importDefault(require("node:path"));
const util_js_1 = require("./util.js");
/**
* @internal
*/
class ExplorerBase {
constructor(options) {
if (options.cache) {
this.loadCache = new Map();
this.searchCache = new Map();
#loadingMetaConfig = false;
config;
loadCache;
searchCache;
constructor(options) {
this.config = options;
if (options.cache) {
this.loadCache = new Map();
this.searchCache = new Map();
}
this.#validateConfig();
}
this.config = options;
this.validateConfig();
}
clearLoadCache() {
if (this.loadCache) {
this.loadCache.clear();
set loadingMetaConfig(value) {
this.#loadingMetaConfig = value;
}
}
clearSearchCache() {
if (this.searchCache) {
this.searchCache.clear();
#validateConfig() {
const config = this.config;
for (const place of config.searchPlaces) {
const extension = node_path_1.default.extname(place);
const loader = this.config.loaders[extension || 'noExt'] ??
this.config.loaders['default'];
if (loader === undefined) {
throw new Error(`Missing loader for ${getExtensionDescription(place)}.`);
}
if (typeof loader !== 'function') {
throw new Error(`Loader for ${getExtensionDescription(place)} is not a function: Received ${typeof loader}.`);
}
}
}
}
clearCaches() {
this.clearLoadCache();
this.clearSearchCache();
}
validateConfig() {
const config = this.config;
config.searchPlaces.forEach(place => {
const loaderKey = _path.default.extname(place) || 'noExt';
const loader = config.loaders[loaderKey];
if (!loader) {
throw new Error(`No loader specified for ${getExtensionDescription(place)}, so searchPlaces item "${place}" is invalid`);
}
if (typeof loader !== 'function') {
throw new Error(`loader for ${getExtensionDescription(place)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`);
}
});
}
shouldSearchStopWithResult(result) {
if (result === null) return false;
return !(result.isEmpty && this.config.ignoreEmptySearchPlaces);
}
nextDirectoryToSearch(currentDir, currentResult) {
if (this.shouldSearchStopWithResult(currentResult)) {
return null;
clearLoadCache() {
if (this.loadCache) {
this.loadCache.clear();
}
}
const nextDir = nextDirUp(currentDir);
if (nextDir === currentDir || currentDir === this.config.stopDir) {
return null;
clearSearchCache() {
if (this.searchCache) {
this.searchCache.clear();
}
}
return nextDir;
}
loadPackageProp(filepath, content) {
const parsedContent = _loaders.loaders.loadJson(filepath, content);
const packagePropValue = (0, _getPropertyByPath.getPropertyByPath)(parsedContent, this.config.packageProp);
return packagePropValue || null;
}
getLoaderEntryForFile(filepath) {
if (_path.default.basename(filepath) === 'package.json') {
return this.loadPackageProp.bind(this);
clearCaches() {
this.clearLoadCache();
this.clearSearchCache();
}
const loaderKey = _path.default.extname(filepath) || 'noExt';
const loader = this.config.loaders[loaderKey];
if (!loader) {
throw new Error(`No loader specified for ${getExtensionDescription(filepath)}`);
toCosmiconfigResult(filepath, config) {
if (config === null) {
return null;
}
if (config === undefined) {
return { filepath, config: undefined, isEmpty: true };
}
if (this.config.applyPackagePropertyPathToConfiguration ||
this.#loadingMetaConfig) {
config = (0, util_js_1.getPropertyByPath)(config, this.config.packageProp);
}
if (config === undefined) {
return { filepath, config: undefined, isEmpty: true };
}
return { config, filepath };
}
return loader;
}
loadedContentToCosmiconfigResult(filepath, loadedContent, forceProp) {
if (loadedContent === null) {
return null;
}
if (loadedContent === undefined) {
return {
filepath,
config: undefined,
isEmpty: true
};
}
if (this.config.usePackagePropInConfigFiles || forceProp) {
loadedContent = (0, _getPropertyByPath.getPropertyByPath)(loadedContent, this.config.packageProp);
}
if (loadedContent === undefined) {
return {
filepath,
config: undefined,
isEmpty: true
};
}
return {
config: loadedContent,
filepath
};
}
validateFilePath(filepath) {
if (!filepath) {
throw new Error('load must pass a non-empty string');
}
}
}
exports.ExplorerBase = ExplorerBase;
function nextDirUp(dir) {
return _path.default.dirname(dir);
/**
* @internal
*/
function getExtensionDescription(extension) {
/* istanbul ignore next -- @preserve */
return extension ? `extension "${extension}"` : 'files without extensions';
}
function getExtensionDescription(filepath) {
const ext = _path.default.extname(filepath);
return ext ? `extension "${ext}"` : 'files without extensions';
}
exports.getExtensionDescription = getExtensionDescription;
//# sourceMappingURL=ExplorerBase.js.map

@@ -1,15 +0,2 @@

import { ExplorerBase } from './ExplorerBase';
import { CosmiconfigResult, ExplorerOptionsSync } from './types';
declare class ExplorerSync extends ExplorerBase<ExplorerOptionsSync> {
constructor(options: ExplorerOptionsSync);
searchSync(searchFrom?: string): CosmiconfigResult;
private searchFromDirectorySync;
private searchDirectorySync;
private loadSearchPlaceSync;
private loadFileContentSync;
private createCosmiconfigResultSync;
loadSync(filepath: string): CosmiconfigResult;
private _loadFileSync;
}
export { ExplorerSync };
export {};
//# sourceMappingURL=ExplorerSync.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExplorerSync = void 0;
var _path = _interopRequireDefault(require("path"));
var _cacheWrapper = require("./cacheWrapper");
var _ExplorerBase = require("./ExplorerBase");
var _getDirectory = require("./getDirectory");
var _readFile = require("./readFile");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class ExplorerSync extends _ExplorerBase.ExplorerBase {
constructor(options) {
super(options);
}
searchSync(searchFrom = process.cwd()) {
if (this.config.metaConfigFilePath) {
const config = this._loadFileSync(this.config.metaConfigFilePath, true);
if (config && !config.isEmpty) {
return config;
}
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const path_type_1 = require("path-type");
const ExplorerBase_js_1 = require("./ExplorerBase.js");
const loaders_js_1 = require("./loaders.js");
const util_js_1 = require("./util.js");
/**
* @internal
*/
class ExplorerSync extends ExplorerBase_js_1.ExplorerBase {
load(filepath) {
filepath = node_path_1.default.resolve(filepath);
const load = () => {
return this.config.transform(this.#readConfiguration(filepath));
};
if (this.loadCache) {
return (0, util_js_1.emplace)(this.loadCache, filepath, load);
}
return load();
}
return this.searchFromDirectorySync((0, _getDirectory.getDirectorySync)(searchFrom));
}
searchFromDirectorySync(dir) {
const absoluteDir = _path.default.resolve(process.cwd(), dir);
const run = () => {
const result = this.searchDirectorySync(absoluteDir);
const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
if (nextDir) {
return this.searchFromDirectorySync(nextDir);
}
return this.config.transform(result);
};
if (this.searchCache) {
return (0, _cacheWrapper.cacheWrapperSync)(this.searchCache, absoluteDir, run);
search(from = '') {
if (this.config.metaConfigFilePath) {
this.loadingMetaConfig = true;
const config = this.load(this.config.metaConfigFilePath);
this.loadingMetaConfig = false;
if (config && !config.isEmpty) {
return config;
}
}
const stopDir = node_path_1.default.resolve(this.config.stopDir);
from = node_path_1.default.resolve(from);
const search = () => {
/* istanbul ignore if -- @preserve */
if ((0, path_type_1.isDirectorySync)(from)) {
for (const place of this.config.searchPlaces) {
const filepath = node_path_1.default.join(from, place);
try {
const result = this.#readConfiguration(filepath);
if (result !== null &&
!(result.isEmpty && this.config.ignoreEmptySearchPlaces)) {
return this.config.transform(result);
}
}
catch (error) {
if (error.code === 'ENOENT' || error.code === 'EISDIR') {
continue;
}
throw error;
}
}
}
const dir = node_path_1.default.dirname(from);
if (from !== stopDir && from !== dir) {
from = dir;
if (this.searchCache) {
return (0, util_js_1.emplace)(this.searchCache, from, search);
}
return search();
}
return null;
};
if (this.searchCache) {
return (0, util_js_1.emplace)(this.searchCache, from, search);
}
return search();
}
return run();
}
searchDirectorySync(dir) {
for (const place of this.config.searchPlaces) {
const placeResult = this.loadSearchPlaceSync(dir, place);
if (this.shouldSearchStopWithResult(placeResult)) {
return placeResult;
}
} // config not found
return null;
}
loadSearchPlaceSync(dir, place) {
const filepath = _path.default.join(dir, place);
const content = (0, _readFile.readFileSync)(filepath);
return this.createCosmiconfigResultSync(filepath, content, false);
}
loadFileContentSync(filepath, content) {
if (content === null) {
return null;
#readConfiguration(filepath) {
const contents = node_fs_1.default.readFileSync(filepath, 'utf8');
return this.toCosmiconfigResult(filepath, this.#loadConfiguration(filepath, contents));
}
if (content.trim() === '') {
return undefined;
#loadConfiguration(filepath, contents) {
if (contents.trim() === '') {
return;
}
if (node_path_1.default.basename(filepath) === 'package.json') {
return ((0, util_js_1.getPropertyByPath)((0, loaders_js_1.loadJson)(filepath, contents), this.config.packageProp) ?? null);
}
const extension = node_path_1.default.extname(filepath);
try {
const loader = this.config.loaders[extension || 'noExt'] ??
this.config.loaders['default'];
if (loader !== undefined) {
return loader(filepath, contents);
}
}
catch (error) {
error.filepath = filepath;
throw error;
}
throw new Error(`No loader specified for ${(0, ExplorerBase_js_1.getExtensionDescription)(extension)}`);
}
const loader = this.getLoaderEntryForFile(filepath);
try {
return loader(filepath, content);
} catch (e) {
e.filepath = filepath;
throw e;
/**
* @deprecated Use {@link ExplorerSync.prototype.load}.
*/
/* istanbul ignore next */
loadSync(filepath) {
return this.load(filepath);
}
}
createCosmiconfigResultSync(filepath, content, forceProp) {
const fileContent = this.loadFileContentSync(filepath, content);
return this.loadedContentToCosmiconfigResult(filepath, fileContent, forceProp);
}
loadSync(filepath) {
return this._loadFileSync(filepath, false);
}
_loadFileSync(filepath, forceProp) {
this.validateFilePath(filepath);
const absoluteFilePath = _path.default.resolve(process.cwd(), filepath);
const runLoadSync = () => {
const content = (0, _readFile.readFileSync)(absoluteFilePath, {
throwNotFound: true
});
const cosmiconfigResult = this.createCosmiconfigResultSync(absoluteFilePath, content, forceProp);
return this.config.transform(cosmiconfigResult);
};
if (this.loadCache) {
return (0, _cacheWrapper.cacheWrapperSync)(this.loadCache, absoluteFilePath, runLoadSync);
/**
* @deprecated Use {@link ExplorerSync.prototype.search}.
*/
/* istanbul ignore next */
searchSync(from = '') {
return this.search(from);
}
return runLoadSync();
}
}
exports.ExplorerSync = ExplorerSync;
//# sourceMappingURL=ExplorerSync.js.map

@@ -1,56 +0,25 @@

import { Config, CosmiconfigResult, Loaders, LoadersSync } from './types';
type LoaderResult = Config | null;
export type Loader = ((filepath: string, content: string) => Promise<LoaderResult>) | LoaderSync;
export type LoaderSync = (filepath: string, content: string) => LoaderResult;
export type Transform = ((CosmiconfigResult: CosmiconfigResult) => Promise<CosmiconfigResult>) | TransformSync;
export type TransformSync = (CosmiconfigResult: CosmiconfigResult) => CosmiconfigResult;
interface OptionsBase {
packageProp?: string | Array<string>;
searchPlaces?: Array<string>;
ignoreEmptySearchPlaces?: boolean;
stopDir?: string;
cache?: boolean;
}
export interface Options extends OptionsBase {
loaders?: Loaders;
transform?: Transform;
}
export interface OptionsSync extends OptionsBase {
loaders?: LoadersSync;
transform?: TransformSync;
}
export interface PublicExplorerBase {
clearLoadCache: () => void;
clearSearchCache: () => void;
clearCaches: () => void;
}
export interface PublicExplorer extends PublicExplorerBase {
search: (searchFrom?: string) => Promise<CosmiconfigResult>;
load: (filepath: string) => Promise<CosmiconfigResult>;
}
export interface PublicExplorerSync extends PublicExplorerBase {
search: (searchFrom?: string) => CosmiconfigResult;
load: (filepath: string) => CosmiconfigResult;
}
export * from './types.js';
import { Options, OptionsSync, PublicExplorer, PublicExplorerSync } from './types.js';
export declare const metaSearchPlaces: string[];
declare const defaultLoaders: Readonly<{
readonly '.mjs': Loader;
readonly '.cjs': Loader;
readonly '.js': Loader;
readonly '.json': Loader;
readonly '.yaml': Loader;
readonly '.yml': Loader;
readonly noExt: Loader;
export declare const defaultLoaders: Readonly<{
readonly '.mjs': import("./types.js").Loader;
readonly '.cjs': import("./types.js").Loader;
readonly '.js': import("./types.js").Loader;
readonly '.ts': import("./types.js").Loader;
readonly '.json': import("./types.js").LoaderSync;
readonly '.yaml': import("./types.js").LoaderSync;
readonly '.yml': import("./types.js").LoaderSync;
readonly noExt: import("./types.js").LoaderSync;
}>;
declare const defaultLoadersSync: Readonly<{
readonly '.cjs': Loader;
readonly '.js': Loader;
readonly '.json': Loader;
readonly '.yaml': Loader;
readonly '.yml': Loader;
readonly noExt: Loader;
export declare const defaultLoadersSync: Readonly<{
readonly '.cjs': import("./types.js").LoaderSync;
readonly '.js': import("./types.js").LoaderSync;
readonly '.ts': import("./types.js").LoaderSync;
readonly '.json': import("./types.js").LoaderSync;
readonly '.yaml': import("./types.js").LoaderSync;
readonly '.yml': import("./types.js").LoaderSync;
readonly noExt: import("./types.js").LoaderSync;
}>;
declare function cosmiconfig(moduleName: string, options?: Options): PublicExplorer;
declare function cosmiconfigSync(moduleName: string, options?: OptionsSync): PublicExplorerSync;
export { cosmiconfig, cosmiconfigSync, defaultLoaders, defaultLoadersSync };
export declare function cosmiconfig(moduleName: string, options?: Readonly<Options>): PublicExplorer;
export declare function cosmiconfigSync(moduleName: string, options?: Readonly<OptionsSync>): PublicExplorerSync;
//# sourceMappingURL=index.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cosmiconfig = cosmiconfig;
exports.cosmiconfigSync = cosmiconfigSync;
exports.metaSearchPlaces = exports.defaultLoadersSync = exports.defaultLoaders = void 0;
var _os = _interopRequireDefault(require("os"));
var _Explorer = require("./Explorer");
var _ExplorerSync = require("./ExplorerSync");
var _loaders = require("./loaders");
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cosmiconfigSync = exports.cosmiconfig = exports.defaultLoadersSync = exports.defaultLoaders = exports.metaSearchPlaces = void 0;
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
__exportStar(require("./types.js"), exports);
const node_os_1 = __importDefault(require("node:os"));
const Explorer_js_1 = require("./Explorer.js");
const ExplorerSync_js_1 = require("./ExplorerSync.js");
const loaders_js_1 = require("./loaders.js");
// this needs to be hardcoded, as this is intended for end users, who can't supply options at this point
const metaSearchPlaces = ['package.json', '.config.json', '.config.yaml', '.config.yml', '.config.js', '.config.cjs', '.config.mjs']; // do not allow mutation of default loaders. Make sure it is set inside options
exports.metaSearchPlaces = metaSearchPlaces;
const defaultLoaders = Object.freeze({
'.mjs': _loaders.loaders.loadJs,
'.cjs': _loaders.loaders.loadJs,
'.js': _loaders.loaders.loadJs,
'.json': _loaders.loaders.loadJson,
'.yaml': _loaders.loaders.loadYaml,
'.yml': _loaders.loaders.loadYaml,
noExt: _loaders.loaders.loadYaml
exports.metaSearchPlaces = [
'package.json',
'.config.json',
'.config.yaml',
'.config.yml',
'.config.js',
'.config.ts',
'.config.cjs',
'.config.mjs',
];
// do not allow mutation of default loaders. Make sure it is set inside options
exports.defaultLoaders = Object.freeze({
'.mjs': loaders_js_1.loadJs,
'.cjs': loaders_js_1.loadJs,
'.js': loaders_js_1.loadJs,
'.ts': loaders_js_1.loadTs,
'.json': loaders_js_1.loadJson,
'.yaml': loaders_js_1.loadYaml,
'.yml': loaders_js_1.loadYaml,
noExt: loaders_js_1.loadYaml,
});
exports.defaultLoaders = defaultLoaders;
const defaultLoadersSync = Object.freeze({
'.cjs': _loaders.loaders.loadJsSync,
'.js': _loaders.loaders.loadJsSync,
'.json': _loaders.loaders.loadJson,
'.yaml': _loaders.loaders.loadYaml,
'.yml': _loaders.loaders.loadYaml,
noExt: _loaders.loaders.loadYaml
exports.defaultLoadersSync = Object.freeze({
'.cjs': loaders_js_1.loadJsSync,
'.js': loaders_js_1.loadJsSync,
'.ts': loaders_js_1.loadTsSync,
'.json': loaders_js_1.loadJson,
'.yaml': loaders_js_1.loadYaml,
'.yml': loaders_js_1.loadYaml,
noExt: loaders_js_1.loadYaml,
});
exports.defaultLoadersSync = defaultLoadersSync;
const identity = function identity(x) {
return x;
return x;
};
function replaceMetaPlaceholders(paths, moduleName) {
return paths.map(path => path.replace('{name}', moduleName));
function getInternalOptions(moduleName, options) {
const metaExplorer = new ExplorerSync_js_1.ExplorerSync({
packageProp: 'cosmiconfig',
stopDir: process.cwd(),
searchPlaces: exports.metaSearchPlaces,
ignoreEmptySearchPlaces: false,
applyPackagePropertyPathToConfiguration: true,
loaders: exports.defaultLoaders,
transform: identity,
cache: true,
metaConfigFilePath: null,
});
const metaConfig = metaExplorer.search();
if (!metaConfig) {
return options;
}
if (metaConfig.config?.loaders) {
throw new Error('Can not specify loaders in meta config file');
}
const overrideOptions = metaConfig.config ?? {};
if (overrideOptions.searchPlaces) {
overrideOptions.searchPlaces = overrideOptions.searchPlaces.map((path) => path.replace('{name}', moduleName));
}
overrideOptions.metaConfigFilePath = metaConfig.filepath;
return { ...options, ...overrideOptions };
}
function getExplorerOptions(moduleName, options) {
var _metaConfig$config;
const metaExplorer = new _ExplorerSync.ExplorerSync({
packageProp: 'cosmiconfig',
stopDir: process.cwd(),
searchPlaces: metaSearchPlaces,
ignoreEmptySearchPlaces: false,
usePackagePropInConfigFiles: true,
loaders: defaultLoaders,
transform: identity,
cache: true,
metaConfigFilePath: null
});
const metaConfig = metaExplorer.searchSync();
if (!metaConfig) {
return options;
}
if ((_metaConfig$config = metaConfig.config) !== null && _metaConfig$config !== void 0 && _metaConfig$config.loaders) {
throw new Error('Can not specify loaders in meta config file');
}
const overrideOptions = metaConfig.config ?? {};
if (overrideOptions.searchPlaces) {
overrideOptions.searchPlaces = replaceMetaPlaceholders(overrideOptions.searchPlaces, moduleName);
}
overrideOptions.metaConfigFilePath = metaConfig.filepath;
return { ...options,
...overrideOptions
};
function normalizeOptions(moduleName, options) {
const defaults = {
packageProp: moduleName,
searchPlaces: [
'package.json',
`.${moduleName}rc`,
`.${moduleName}rc.json`,
`.${moduleName}rc.yaml`,
`.${moduleName}rc.yml`,
`.${moduleName}rc.js`,
`.${moduleName}rc.ts`,
`.${moduleName}rc.cjs`,
`.${moduleName}rc.mjs`,
`.config/${moduleName}rc`,
`.config/${moduleName}rc.json`,
`.config/${moduleName}rc.yaml`,
`.config/${moduleName}rc.yml`,
`.config/${moduleName}rc.js`,
`.config/${moduleName}rc.ts`,
`.config/${moduleName}rc.cjs`,
`.config/${moduleName}rc.mjs`,
`${moduleName}.config.js`,
`${moduleName}.config.ts`,
`${moduleName}.config.cjs`,
`${moduleName}.config.mjs`,
],
ignoreEmptySearchPlaces: true,
stopDir: node_os_1.default.homedir(),
cache: true,
transform: identity,
loaders: exports.defaultLoaders,
metaConfigFilePath: null,
};
const normalizedOptions = {
...defaults,
...options,
loaders: {
...defaults.loaders,
...options.loaders,
},
};
return normalizedOptions;
}
function normalizeOptionsSync(moduleName, options) {
const defaults = {
packageProp: moduleName,
searchPlaces: [
'package.json',
`.${moduleName}rc`,
`.${moduleName}rc.json`,
`.${moduleName}rc.yaml`,
`.${moduleName}rc.yml`,
`.${moduleName}rc.js`,
`.${moduleName}rc.ts`,
`.${moduleName}rc.cjs`,
`.config/${moduleName}rc`,
`.config/${moduleName}rc.json`,
`.config/${moduleName}rc.yaml`,
`.config/${moduleName}rc.yml`,
`.config/${moduleName}rc.js`,
`.config/${moduleName}rc.ts`,
`.config/${moduleName}rc.cjs`,
`${moduleName}.config.js`,
`${moduleName}.config.ts`,
`${moduleName}.config.cjs`,
],
ignoreEmptySearchPlaces: true,
stopDir: node_os_1.default.homedir(),
cache: true,
transform: identity,
loaders: exports.defaultLoadersSync,
metaConfigFilePath: null,
};
const normalizedOptions = {
...defaults,
...options,
loaders: {
...defaults.loaders,
...options.loaders,
},
};
return normalizedOptions;
}
function cosmiconfig(moduleName, options = {}) {
const explorerOptions = getExplorerOptions(moduleName, options);
const normalizedOptions = normalizeOptions(moduleName, explorerOptions);
const explorer = new _Explorer.Explorer(normalizedOptions);
return {
search: explorer.search.bind(explorer),
load: explorer.load.bind(explorer),
clearLoadCache: explorer.clearLoadCache.bind(explorer),
clearSearchCache: explorer.clearSearchCache.bind(explorer),
clearCaches: explorer.clearCaches.bind(explorer)
};
} // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const internalOptions = getInternalOptions(moduleName, options);
const normalizedOptions = normalizeOptions(moduleName, internalOptions);
const explorer = new Explorer_js_1.Explorer(normalizedOptions);
return {
search: explorer.search.bind(explorer),
load: explorer.load.bind(explorer),
clearLoadCache: explorer.clearLoadCache.bind(explorer),
clearSearchCache: explorer.clearSearchCache.bind(explorer),
clearCaches: explorer.clearCaches.bind(explorer),
};
}
exports.cosmiconfig = cosmiconfig;
function cosmiconfigSync(moduleName, options = {}) {
const explorerOptions = getExplorerOptions(moduleName, options);
const normalizedOptions = normalizeOptionsSync(moduleName, explorerOptions);
const explorerSync = new _ExplorerSync.ExplorerSync(normalizedOptions);
return {
search: explorerSync.searchSync.bind(explorerSync),
load: explorerSync.loadSync.bind(explorerSync),
clearLoadCache: explorerSync.clearLoadCache.bind(explorerSync),
clearSearchCache: explorerSync.clearSearchCache.bind(explorerSync),
clearCaches: explorerSync.clearCaches.bind(explorerSync)
};
const internalOptions = getInternalOptions(moduleName, options);
const normalizedOptions = normalizeOptionsSync(moduleName, internalOptions);
const explorerSync = new ExplorerSync_js_1.ExplorerSync(normalizedOptions);
return {
search: explorerSync.search.bind(explorerSync),
load: explorerSync.load.bind(explorerSync),
clearLoadCache: explorerSync.clearLoadCache.bind(explorerSync),
clearSearchCache: explorerSync.clearSearchCache.bind(explorerSync),
clearCaches: explorerSync.clearCaches.bind(explorerSync),
};
}
function normalizeOptions(moduleName, options) {
const defaults = {
packageProp: moduleName,
searchPlaces: ['package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.js`, `.${moduleName}rc.cjs`, `.${moduleName}rc.mjs`, `.config/${moduleName}rc`, `.config/${moduleName}rc.json`, `.config/${moduleName}rc.yaml`, `.config/${moduleName}rc.yml`, `.config/${moduleName}rc.js`, `.config/${moduleName}rc.cjs`, `.config/${moduleName}rc.mjs`, `${moduleName}.config.js`, `${moduleName}.config.cjs`, `${moduleName}.config.mjs`].filter(Boolean),
ignoreEmptySearchPlaces: true,
stopDir: _os.default.homedir(),
cache: true,
transform: identity,
loaders: defaultLoaders,
metaConfigFilePath: null
};
const normalizedOptions = { ...defaults,
...options,
loaders: { ...defaults.loaders,
...options.loaders
}
};
return normalizedOptions;
}
function normalizeOptionsSync(moduleName, options) {
const defaults = {
packageProp: moduleName,
searchPlaces: ['package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.js`, `.${moduleName}rc.cjs`, `.config/${moduleName}rc`, `.config/${moduleName}rc.json`, `.config/${moduleName}rc.yaml`, `.config/${moduleName}rc.yml`, `.config/${moduleName}rc.js`, `.config/${moduleName}rc.cjs`, `${moduleName}.config.js`, `${moduleName}.config.cjs`],
ignoreEmptySearchPlaces: true,
stopDir: _os.default.homedir(),
cache: true,
transform: identity,
loaders: defaultLoadersSync,
metaConfigFilePath: null
};
const normalizedOptions = { ...defaults,
...options,
loaders: { ...defaults.loaders,
...options.loaders
}
};
return normalizedOptions;
}
exports.cosmiconfigSync = cosmiconfigSync;
//# sourceMappingURL=index.js.map

@@ -1,4 +0,8 @@

import { Loaders } from './types';
declare const loaders: Loaders;
export { loaders };
import { Loader, LoaderSync } from './types.js';
export declare const loadJsSync: LoaderSync;
export declare const loadJs: Loader;
export declare const loadJson: LoaderSync;
export declare const loadYaml: LoaderSync;
export declare const loadTsSync: LoaderSync;
export declare const loadTs: Loader;
//# sourceMappingURL=loaders.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.loaders = void 0;
var _url = require("url");
/* eslint-disable @typescript-eslint/no-require-imports */
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadTs = exports.loadTsSync = exports.loadYaml = exports.loadJson = exports.loadJs = exports.loadJsSync = void 0;
const node_fs_1 = require("node:fs");
const promises_1 = require("node:fs/promises");
const node_path_1 = __importDefault(require("node:path"));
const node_url_1 = require("node:url");
let importFresh;
const loadJsSync = function loadJsSync(filepath) {
if (importFresh === undefined) {
importFresh = require('import-fresh');
}
const result = importFresh(filepath);
return result;
if (importFresh === undefined) {
importFresh = require('import-fresh');
}
return importFresh(filepath);
};
exports.loadJsSync = loadJsSync;
const loadJs = async function loadJs(filepath) {
try {
const {
href
} = (0, _url.pathToFileURL)(filepath);
return (await import(href)).default;
} catch (error) {
return loadJsSync(filepath, '');
}
try {
const { href } = (0, node_url_1.pathToFileURL)(filepath);
return (await import(href)).default;
}
catch (error) {
return (0, exports.loadJsSync)(filepath, '');
}
};
exports.loadJs = loadJs;
let parseJson;
const loadJson = function loadJson(filepath, content) {
if (parseJson === undefined) {
parseJson = require('parse-json');
}
try {
const result = parseJson(content);
return result;
} catch (error) {
error.message = `JSON Error in ${filepath}:\n${error.message}`;
throw error;
}
if (parseJson === undefined) {
parseJson = require('parse-json');
}
try {
return parseJson(content);
}
catch (error) {
error.message = `JSON Error in ${filepath}:\n${error.message}`;
throw error;
}
};
exports.loadJson = loadJson;
let yaml;
const loadYaml = function loadYaml(filepath, content) {
if (yaml === undefined) {
yaml = require('js-yaml');
}
try {
const result = yaml.load(content);
return result;
} catch (error) {
error.message = `YAML Error in ${filepath}:\n${error.message}`;
throw error;
}
if (yaml === undefined) {
yaml = require('js-yaml');
}
try {
return yaml.load(content);
}
catch (error) {
error.message = `YAML Error in ${filepath}:\n${error.message}`;
throw error;
}
};
const loaders = {
loadJs,
loadJsSync,
loadJson,
loadYaml
exports.loadYaml = loadYaml;
let typescript;
const loadTsSync = function loadTsSync(filepath, content) {
/* istanbul ignore next -- @preserve */
if (typescript === undefined) {
typescript = require('typescript');
}
const compiledFilepath = `${filepath.slice(0, -2)}js`;
try {
const config = resolveTsConfig(node_path_1.default.dirname(filepath)) ?? {};
config.compilerOptions = {
...config.compilerOptions,
module: typescript.ModuleKind.NodeNext,
moduleResolution: typescript.ModuleResolutionKind.NodeNext,
target: typescript.ScriptTarget.ES2022,
noEmit: false,
};
content = typescript.transpileModule(content, config).outputText;
(0, node_fs_1.writeFileSync)(compiledFilepath, content);
return (0, exports.loadJsSync)(compiledFilepath, content).default;
}
catch (error) {
error.message = `TypeScript Error in ${filepath}:\n${error.message}`;
throw error;
}
finally {
if ((0, node_fs_1.existsSync)(compiledFilepath)) {
(0, node_fs_1.rmSync)(compiledFilepath);
}
}
};
exports.loaders = loaders;
exports.loadTsSync = loadTsSync;
const loadTs = async function loadTs(filepath, content) {
if (typescript === undefined) {
typescript = await import('typescript');
}
const compiledFilepath = `${filepath.slice(0, -2)}mjs`;
try {
const config = resolveTsConfig(node_path_1.default.dirname(filepath)) ?? {};
config.compilerOptions = {
...config.compilerOptions,
module: typescript.ModuleKind.ES2022,
moduleResolution: typescript.ModuleResolutionKind.Bundler,
target: typescript.ScriptTarget.ES2022,
noEmit: false,
};
content = typescript.transpileModule(content, config).outputText;
await (0, promises_1.writeFile)(compiledFilepath, content);
const { href } = (0, node_url_1.pathToFileURL)(compiledFilepath);
return (await import(href)).default;
}
catch (error) {
error.message = `TypeScript Error in ${filepath}:\n${error.message}`;
throw error;
}
finally {
if ((0, node_fs_1.existsSync)(compiledFilepath)) {
await (0, promises_1.rm)(compiledFilepath);
}
}
};
exports.loadTs = loadTs;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function resolveTsConfig(directory) {
const filePath = typescript.findConfigFile(directory, (fileName) => {
return typescript.sys.fileExists(fileName);
});
if (filePath !== undefined) {
const { config, error } = typescript.readConfigFile(filePath, (path) => typescript.sys.readFile(path));
if (error) {
throw new Error(`Error in ${filePath}: ${error.messageText.toString()}`);
}
return config;
}
return;
}
//# sourceMappingURL=loaders.js.map

@@ -1,3 +0,8 @@

import { Loader, LoaderSync, Options, OptionsSync } from './index';
/**
* @public
*/
export type Config = any;
/**
* @public
*/
export type CosmiconfigResult = {

@@ -8,18 +13,80 @@ config: Config;

} | null;
export interface InternalOptions {
usePackagePropInConfigFiles?: boolean;
metaConfigFilePath: string | null;
/**
* @public
*/
export type LoaderResult = Config | null;
/**
* @public
*/
export type Loader = ((filepath: string, content: string) => Promise<LoaderResult>) | LoaderSync;
/**
* @public
*/
export type LoaderSync = (filepath: string, content: string) => LoaderResult;
/**
* @public
*/
export type Transform = ((CosmiconfigResult: CosmiconfigResult) => Promise<CosmiconfigResult>) | TransformSync;
/**
* @public
*/
export type TransformSync = (CosmiconfigResult: CosmiconfigResult) => CosmiconfigResult;
/**
* @public
*/
export interface CommonOptions {
packageProp?: string | Array<string>;
searchPlaces?: Array<string>;
ignoreEmptySearchPlaces?: boolean;
stopDir?: string;
cache?: boolean;
}
export interface ExplorerOptions extends Required<Options>, InternalOptions {
/**
* @public
*/
export interface Options extends CommonOptions {
loaders?: Loaders;
transform?: Transform;
}
export interface ExplorerOptionsSync extends Required<OptionsSync>, InternalOptions {
/**
* @public
*/
export interface OptionsSync extends CommonOptions {
loaders?: LoadersSync;
transform?: TransformSync;
}
export type Cache = Map<string, CosmiconfigResult>;
export type LoadedFileContent = Config | null | undefined;
/**
* @public
*/
export interface Loaders {
[key: string]: Loader;
}
/**
* @public
*/
export interface LoadersSync {
[key: string]: LoaderSync;
}
/**
* @public
*/
export interface PublicExplorerBase {
clearLoadCache: () => void;
clearSearchCache: () => void;
clearCaches: () => void;
}
/**
* @public
*/
export interface PublicExplorer extends PublicExplorerBase {
search: (searchFrom?: string) => Promise<CosmiconfigResult>;
load: (filepath: string) => Promise<CosmiconfigResult>;
}
/**
* @public
*/
export interface PublicExplorerSync extends PublicExplorerBase {
search: (searchFrom?: string) => CosmiconfigResult;
load: (filepath: string) => CosmiconfigResult;
}
//# sourceMappingURL=types.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
{
"name": "cosmiconfig",
"version": "8.2.0",
"description": "Find and load configuration from a package.json property, rc file, or CommonJS module",
"version": "8.3.0",
"description": "Find and load configuration from a package.json property, rc file, TypeScript module, and more!",
"main": "dist/index.js",

@@ -11,8 +11,7 @@ "types": "dist/index.d.ts",

"scripts": {
"clean": "del-cli --dot=true \"./dist/**/*\"",
"build": "npm run clean && npm run build:compile && npm run build:types",
"build:compile": "cross-env NODE_ENV=production babel src -d dist --verbose --extensions .js,.ts --ignore \"**/**/*.test.js\",\"**/**/*.test.ts\" --source-maps",
"build:types": "cross-env NODE_ENV=production tsc --project tsconfig.types.json",
"dev": "npm run clean && npm run build:compile -- --watch",
"lint": "eslint --ext .js,.ts . && npm run lint:md",
"clean": "git clean -Xdf -e '!node_modules' .",
"build": "npm run build:tsc",
"build:tsc": "cross-env NODE_ENV=production tsc -b",
"dev": "npm run build:tsc -- --watch",
"lint": "eslint --ext .js,.ts .",
"lint:fix": "eslint --ext .js,.ts . --fix",

@@ -23,14 +22,8 @@ "lint:md": "remark-preset-davidtheclark",

"format:check": "prettier \"**/*.{js,ts,json,yml,yaml}\" --check",
"typescript": "tsc",
"test": "vitest run --coverage",
"test:watch": "vitest",
"check:all": "npm run test && npm run typescript && npm run lint && npm run format:check",
"prepublishOnly": "npm run check:all && npm run build"
"check:all": "npm run test && npm run lint && npm run format:check",
"prepublishOnly": "npm run check:all && npm run build",
"prepare": "husky install"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged && npm run typescript && npm run test",
"pre-push": "npm run check:all"
}
},
"lint-staged": {

@@ -60,2 +53,3 @@ "*.{js,ts}": [

"contributors": [
"Randolf J <jrandolf@google.com>",
"David Clark <david.dave.clark@gmail.com>",

@@ -71,64 +65,45 @@ "Bogdan Chadkin <trysound@yandex.ru>",

"homepage": "https://github.com/cosmiconfig/cosmiconfig#readme",
"prettier": {
"trailingComma": "all",
"arrowParens": "always",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
"peerDependencies": {
"typescript": ">=4.9.5"
},
"babel": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "14"
},
"exclude": [
"proposal-dynamic-import"
]
}
],
"@babel/preset-typescript"
]
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
},
"dependencies": {
"import-fresh": "^3.2.1",
"import-fresh": "^3.3.0",
"js-yaml": "^4.1.0",
"parse-json": "^5.0.0",
"parse-json": "^5.2.0",
"path-type": "^4.0.0"
},
"devDependencies": {
"@babel/cli": "^7.19.3",
"@babel/core": "^7.20.2",
"@babel/preset-env": "^7.20.2",
"@babel/preset-typescript": "^7.18.6",
"@types/js-yaml": "^4.0.5",
"@types/node": "^14.0.22",
"@types/node": "~18",
"@types/parse-json": "^4.0.0",
"@typescript-eslint/eslint-plugin": "^5.54.1",
"@typescript-eslint/parser": "^5.54.1",
"@vitest/coverage-istanbul": "^0.29.2",
"cross-env": "^7.0.2",
"del": "^5.1.0",
"del-cli": "^3.0.1",
"eslint": "^8.36.0",
"@typescript-eslint/eslint-plugin": "^6.5.0",
"@typescript-eslint/parser": "^6.5.0",
"@vitest/coverage-istanbul": "^0.34.3",
"cross-env": "^7.0.3",
"del": "^7.1.0",
"del-cli": "^5.1.0",
"eslint": "^8.48.0",
"eslint-config-davidtheclark-node": "^0.2.2",
"eslint-config-prettier": "^6.11.0",
"eslint-import-resolver-typescript": "^3.5.3",
"eslint-plugin-import": "^2.22.0",
"eslint-config-prettier": "^9.0.0",
"eslint-import-resolver-typescript": "^3.6.0",
"eslint-plugin-import": "^2.28.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-vitest": "^0.0.54",
"husky": "^4.2.5",
"lint-staged": "^10.2.11",
"make-dir": "^3.1.0",
"parent-module": "^2.0.0",
"prettier": "^2.0.5",
"eslint-plugin-vitest": "^0.2.8",
"husky": "^8.0.3",
"lint-staged": "^14.0.1",
"make-dir": "^4.0.0",
"parent-module": "^3.0.0",
"prettier": "^3.0.3",
"remark-preset-davidtheclark": "^0.12.0",
"typescript": "^4.9.5",
"vitest": "^0.29.2"
"typescript": "^5.2.2",
"vitest": "^0.34.3"
},
"engines": {
"node": ">=14"
"node": ">=18"
}
}

@@ -14,5 +14,5 @@ # cosmiconfig

- a JSON or YAML, extensionless "rc file"
- an "rc file" with the extensions `.json`, `.yaml`, `.yml`, `.js`, `.mjs`, or `.cjs`
- an "rc file" with the extensions `.json`, `.yaml`, `.yml`, `.js`, `.ts`, `.mjs`, or `.cjs`
- any of the above two inside a `.config` subdirectory
- a `.config.js`, `.config.mjs`, or `.config.cjs` file
- a `.config.js`, `.config.ts`, `.config.mjs`, or `.config.cjs` file

@@ -23,5 +23,5 @@ For example, if your module's name is "myapp", cosmiconfig will search up the directory tree for configuration in the following places:

- a `.myapprc` file in JSON or YAML format
- a `.myapprc.json`, `.myapprc.yaml`, `.myapprc.yml`, `.myapprc.js`, `.myapprc.mjs`, or `.myapprc.cjs` file
- a `myapprc`, `myapprc.json`, `myapprc.yaml`, `myapprc.yml`, `myapprc.js` or `myapprc.cjs` file inside a `.config` subdirectory
- a `myapp.config.js`, `myapp.config.mjs`, or `myapp.config.cjs` file
- a `.myapprc.json`, `.myapprc.yaml`, `.myapprc.yml`, `.myapprc.js`, `.myapprc.ts`, `.myapprc.mjs`, or `.myapprc.cjs` file
- a `myapprc`, `myapprc.json`, `myapprc.yaml`, `myapprc.yml`, `myapprc.js`, `myapprc.ts` or `myapprc.cjs` file inside a `.config` subdirectory
- a `myapp.config.js`, `myapp.config.ts`, `myapp.config.mjs`, or `myapp.config.cjs` file

@@ -153,5 +153,5 @@ Cosmiconfig continues to search up the directory tree, checking each of these places in each directory, until it finds some acceptable configuration (or hits the home directory).

2. A `.goldengrahamsrc` file with JSON or YAML syntax.
3. A `.goldengrahamsrc.json`, `.goldengrahamsrc.yaml`, `.goldengrahamsrc.yml`, `.goldengrahamsrc.js`, or `.goldengrahamsrc.cjs` file. (To learn more about how JS files are loaded, see ["Loading JS modules"].)
4. A `goldengrahamsrc`, `goldengrahamsrc.json`, `goldengrahamsrc.yaml`, `goldengrahamsrc.yml`, `goldengrahamsrc.js`, or `goldengrahamsrc.cjs` file in the `.config` subdirectory.
5. A `goldengrahams.config.js`, `goldengrahams.config.mjs`, or `goldengrahams.config.cjs` file. (To learn more about how JS files are loaded, see ["Loading JS modules"].)
3. A `.goldengrahamsrc.json`, `.goldengrahamsrc.yaml`, `.goldengrahamsrc.yml`, `.goldengrahamsrc.js`, `.goldengrahamsrc.ts`, or `.goldengrahamsrc.cjs` file. (To learn more about how JS files are loaded, see ["Loading JS modules"].)
4. A `goldengrahamsrc`, `goldengrahamsrc.json`, `goldengrahamsrc.yaml`, `goldengrahamsrc.yml`, `goldengrahamsrc.js`, `goldengrahamsrc.ts`, or `goldengrahamsrc.cjs` file in the `.config` subdirectory.
5. A `goldengrahams.config.js`, `goldengrahams.config.ts`, `goldengrahams.config.mjs`, or `goldengrahams.config.cjs` file. (To learn more about how JS files are loaded, see ["Loading JS modules"].)
- If none of those searches reveal a configuration object, move up one directory level and try again.

@@ -282,2 +282,3 @@ So the search continues in `./`, `../`, `../../`, `../../../`, etc., checking the same places in each directory.

`.${moduleName}rc.js`,
`.${moduleName}rc.ts`,
`.${moduleName}rc.mjs`,

@@ -290,7 +291,9 @@ `.${moduleName}rc.cjs`,

`.config/${moduleName}rc.js`,
`.config/${moduleName}rc.ts`,
`.config/${moduleName}rc.cjs`,
`${moduleName}.config.js`,
`${moduleName}.config.ts`,
`${moduleName}.config.mjs`,
`${moduleName}.config.cjs`,
]
];
```

@@ -313,32 +316,22 @@

// Disallow extensions on rc files:
[
'package.json',
'.porgyrc',
'porgy.config.js'
]
// Limit the options dramatically:
[
'package.json',
'.porgyrc'
]
// Maybe you want to look for a wide variety of JS flavors:
[
'porgy.config.js',
['package.json', '.porgyrc', 'porgy.config.js'][
// Limit the options dramatically:
('package.json', '.porgyrc')
][
// Maybe you want to look for a wide variety of JS flavors:
('porgy.config.js',
'porgy.config.mjs',
'porgy.config.ts',
'porgy.config.coffee'
]
// ^^ You will need to designate custom loaders to tell
// Cosmiconfig how to handle `.ts` and `.coffee` files.
'porgy.config.coffee')
][
// ^^ You will need to designate custom loaders to tell
// Cosmiconfig how to handle `.ts` and `.coffee` files.
// Look within a .config/ subdirectory of every searched directory:
[
'package.json',
// Look within a .config/ subdirectory of every searched directory:
('package.json',
'.porgyrc',
'.config/.porgyrc',
'.porgyrc.json',
'.config/.porgyrc.json'
]
'.config/.porgyrc.json')
];
```

@@ -360,3 +353,3 @@

console.log(Object.entries(defaultLoaders))
console.log(Object.entries(defaultLoaders));
// [

@@ -366,2 +359,3 @@ // [ '.mjs', [Function: loadJs] ],

// [ '.js', [Function: loadJs] ],
// [ '.ts', [Function: loadTs] ],
// [ '.json', [Function: loadJson] ],

@@ -373,6 +367,7 @@ // [ '.yaml', [Function: loadYaml] ],

console.log(Object.entries(defaultLoadersSync))
console.log(Object.entries(defaultLoadersSync));
// [
// [ '.cjs', [Function: loadJsSync] ],
// [ '.js', [Function: loadJsSync] ],
// [ '.ts', [Function: loadTsSync] ],
// [ '.json', [Function: loadJson] ],

@@ -399,3 +394,3 @@ // [ '.yaml', [Function: loadYaml] ],

{
noExt: defaultLoaders['.json']
noExt: defaultLoaders['.json'];
}

@@ -451,3 +446,2 @@ ```

{
'.ts': typeScriptLoader,
'.coffee': coffeeScriptLoader

@@ -458,3 +452,2 @@ }

{
'.ts': defaultLoaders['.js'],
'.coffee': defaultLoaders['.js']

@@ -551,3 +544,3 @@ }

With cosmiconfig's [asynchronous API](#asynchronous-api), the default [`searchPlaces`] include `.js`, `.mjs`, and `.cjs` files. Cosmiconfig loads all these file types with the [dynamic `import` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports).
With cosmiconfig's [asynchronous API](#asynchronous-api), the default [`searchPlaces`] include `.js`, `.ts`, `.mjs`, and `.cjs` files. Cosmiconfig loads all these file types with the [dynamic `import` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports).

@@ -590,2 +583,3 @@ With the [synchronous API](#synchronous-api), JS configuration files are always treated as CommonJS, and `.mjs` files are ignored, because there is no synchronous API for the dynamic `import` function.

.{NAME}rc.js
.{NAME}rc.ts
.{NAME}rc.cjs

@@ -597,4 +591,6 @@ .config/{NAME}rc

.config/{NAME}rc.js
.config/{NAME}rc.ts
.config/{NAME}rc.cjs
{NAME}.config.js
{NAME}.config.ts
{NAME}.config.cjs

@@ -635,2 +631,3 @@ ```

.config.js
.config.ts
.config.cjs

@@ -637,0 +634,0 @@ ```

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc