This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

20
node_modules/postcss-loader/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1175
node_modules/postcss-loader/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

3
node_modules/postcss-loader/dist/cjs.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
"use strict";
module.exports = require("./index").default;

16
node_modules/postcss-loader/dist/config.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
import type { Config as PostCSSConfig } from "postcss-load-config";
import type { LoaderContext } from "webpack";
type PostCSSLoaderContext = LoaderContext<PostCSSConfig>;
interface PostCSSLoaderAPI {
mode: PostCSSLoaderContext["mode"];
file: PostCSSLoaderContext["resourcePath"];
webpackLoaderContext: PostCSSLoaderContext;
env: PostCSSLoaderContext["mode"];
options: PostCSSConfig;
}
export type PostCSSLoaderOptions =
| PostCSSConfig
| ((api: PostCSSLoaderAPI) => PostCSSConfig);

172
node_modules/postcss-loader/dist/index.js generated vendored Normal file
View File

@@ -0,0 +1,172 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loader;
var _path = _interopRequireDefault(require("path"));
var _package = _interopRequireDefault(require("postcss/package.json"));
var _options = _interopRequireDefault(require("./options.json"));
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
let hasExplicitDependencyOnPostCSS = false;
/**
* **PostCSS Loader**
*
* Loads && processes CSS with [PostCSS](https://github.com/postcss/postcss)
*
* @method loader
*
* @param {String} content Source
* @param {Object} sourceMap Source Map
* @param {Object} meta Meta
*
* @return {callback} callback Result
*/
async function loader(content, sourceMap, meta) {
const options = this.getOptions(_options.default);
const callback = this.async();
const configOption = typeof options.postcssOptions === "undefined" || typeof options.postcssOptions.config === "undefined" ? true : options.postcssOptions.config;
let implementation;
try {
implementation = (0, _utils.getPostcssImplementation)(this, options.implementation);
} catch (error) {
callback(error);
return;
}
if (!implementation) {
callback(new Error(`The Postcss implementation "${options.implementation}" not found`));
return;
}
let loadedConfig;
if (configOption) {
try {
loadedConfig = await (0, _utils.loadConfig)(this, configOption, options.postcssOptions);
} catch (error) {
callback(error);
return;
}
}
const {
plugins,
processOptions
} = await (0, _utils.getPostcssOptions)(this, loadedConfig, options.postcssOptions);
const useSourceMap = typeof options.sourceMap !== "undefined" ? options.sourceMap : this.sourceMap;
if (useSourceMap) {
processOptions.map = {
inline: false,
annotation: false,
...processOptions.map
};
}
if (sourceMap && processOptions.map) {
processOptions.map.prev = (0, _utils.normalizeSourceMap)(sourceMap, this.context);
}
let root;
// Reuse PostCSS AST from other loaders
if (meta && meta.ast && meta.ast.type === "postcss" &&
// eslint-disable-next-line global-require
require("semver").satisfies(meta.ast.version, `^${_package.default.version}`)) {
({
root
} = meta.ast);
}
if (!root && options.execute) {
// eslint-disable-next-line no-param-reassign
content = (0, _utils.exec)(content, this);
}
let result;
let processor;
try {
processor = implementation(plugins);
result = await processor.process(root || content, processOptions);
} catch (error) {
// Check postcss versions to avoid using PostCSS 7.
// For caching reasons, we use the readFileSync and existsSync functions from the context,
// not the functions from the `fs` module.
if (!hasExplicitDependencyOnPostCSS && processor && processor.version && processor.version.startsWith("7.")) {
// The `findPackageJsonDir` function returns `string` or `null`.
// This is used to do for caching, that is, an explicit comparison with `undefined`
// is used to make the condition body run once.
const packageJSONDir = (0, _utils.findPackageJSONDir)(process.cwd(), this.fs.statSync);
if (packageJSONDir) {
let bufferOfPackageJSON;
try {
bufferOfPackageJSON = this.fs.readFileSync(_path.default.resolve(packageJSONDir, "package.json"), "utf8");
} catch (_error) {
// Nothing
}
if (bufferOfPackageJSON) {
let pkg;
try {
pkg = JSON.parse(bufferOfPackageJSON);
} catch (_error) {
// Nothing
}
if (pkg) {
const {
dependencies = {},
devDependencies = {}
} = pkg;
if (!dependencies.postcss && !devDependencies.postcss) {
this.emitWarning(new Error("Add postcss as project dependency. postcss is not a peer dependency for postcss-loader. " + "Use `npm install postcss` or `yarn add postcss`"));
} else {
hasExplicitDependencyOnPostCSS = true;
}
}
}
}
}
(0, _utils.reportError)(this, callback, error);
return;
}
for (const warning of result.warnings()) {
this.emitWarning((0, _utils.warningFactory)(warning));
}
for (const message of result.messages) {
// eslint-disable-next-line default-case
switch (message.type) {
case "dependency":
this.addDependency(message.file);
break;
case "build-dependency":
this.addBuildDependency(message.file);
break;
case "missing-dependency":
this.addMissingDependency(message.file);
break;
case "context-dependency":
this.addContextDependency(message.file);
break;
case "dir-dependency":
this.addContextDependency(message.dir);
break;
case "asset":
if (message.content && message.file) {
this.emitFile(message.file, message.content, message.sourceMap, message.info);
}
}
}
// eslint-disable-next-line no-undefined
let map = result.map ? result.map.toJSON() : undefined;
if (map && useSourceMap) {
map = (0, _utils.normalizeSourceMapAfterPostcss)(map, this.context);
}
let ast;
try {
ast = {
type: "postcss",
version: result.processor.version,
root: result.root
};
} catch (error) {
(0, _utils.reportError)(this, callback, error);
return;
}
callback(null, result.css, map, {
ast
});
}

58
node_modules/postcss-loader/dist/options.json generated vendored Normal file
View File

@@ -0,0 +1,58 @@
{
"title": "PostCSS Loader options",
"type": "object",
"properties": {
"postcssOptions": {
"description": "Options to pass through to `Postcss`.",
"link": "https://github.com/webpack-contrib/postcss-loader#postcssOptions",
"anyOf": [
{
"type": "object",
"additionalProperties": true,
"properties": {
"config": {
"description": "Allows to specify PostCSS config path.",
"link": "https://github.com/webpack-contrib/postcss-loader#config",
"anyOf": [
{
"description": "Allows to specify the path to the configuration file",
"type": "string"
},
{
"description": "Enables/Disables autoloading config",
"type": "boolean"
}
]
}
}
},
{
"instanceof": "Function"
}
]
},
"execute": {
"description": "Enables/Disables PostCSS parser support in 'CSS-in-JS'.",
"link": "https://github.com/webpack-contrib/postcss-loader#execute",
"type": "boolean"
},
"sourceMap": {
"description": "Enables/Disables generation of source maps.",
"link": "https://github.com/webpack-contrib/postcss-loader#sourcemap",
"type": "boolean"
},
"implementation": {
"description": "The implementation of postcss to use, instead of the locally installed version",
"link": "https://github.com/webpack-contrib/postcss-loader#implementation",
"anyOf": [
{
"type": "string"
},
{
"instanceof": "Function"
}
]
}
},
"additionalProperties": false
}

458
node_modules/postcss-loader/dist/utils.js generated vendored Normal file
View File

@@ -0,0 +1,458 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.exec = exec;
exports.findPackageJSONDir = findPackageJSONDir;
exports.getPostcssImplementation = getPostcssImplementation;
exports.getPostcssOptions = getPostcssOptions;
exports.loadConfig = loadConfig;
exports.normalizeSourceMap = normalizeSourceMap;
exports.normalizeSourceMapAfterPostcss = normalizeSourceMapAfterPostcss;
exports.reportError = reportError;
exports.warningFactory = warningFactory;
var _path = _interopRequireDefault(require("path"));
var _url = _interopRequireDefault(require("url"));
var _module = _interopRequireDefault(require("module"));
var _cosmiconfig = require("cosmiconfig");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const parentModule = module;
const stat = (inputFileSystem, filePath) => new Promise((resolve, reject) => {
inputFileSystem.stat(filePath, (err, stats) => {
if (err) {
reject(err);
}
resolve(stats);
});
});
function exec(code, loaderContext) {
const {
resource,
context
} = loaderContext;
const module = new _module.default(resource, parentModule);
// eslint-disable-next-line no-underscore-dangle
module.paths = _module.default._nodeModulePaths(context);
module.filename = resource;
// eslint-disable-next-line no-underscore-dangle
module._compile(code, resource);
return module.exports;
}
let tsLoader;
async function loadConfig(loaderContext, config, postcssOptions) {
const searchPath = typeof config === "string" ? _path.default.resolve(config) : _path.default.dirname(loaderContext.resourcePath);
let stats;
try {
stats = await stat(loaderContext.fs, searchPath);
} catch (errorIgnore) {
throw new Error(`No PostCSS config found in: ${searchPath}`);
}
const moduleName = "postcss";
const searchPlaces = [
// Prefer popular format
"package.json", `${moduleName}.config.js`, `${moduleName}.config.mjs`, `${moduleName}.config.cjs`, `${moduleName}.config.ts`, `${moduleName}.config.mts`, `${moduleName}.config.cts`, `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.js`, `.${moduleName}rc.mjs`, `.${moduleName}rc.cjs`, `.${moduleName}rc.ts`, `.${moduleName}rc.mts`, `.${moduleName}rc.cts`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.config/${moduleName}rc`, `.config/${moduleName}rc.json`, `.config/${moduleName}rc.yaml`, `.config/${moduleName}rc.yml`, `.config/${moduleName}rc.js`, `.config/${moduleName}rc.mjs`, `.config/${moduleName}rc.cjs`, `.config/${moduleName}rc.ts`, `.config/${moduleName}rc.mts`, `.config/${moduleName}rc.cts`];
const loaders = {
".js": async (...args) => {
let result;
try {
result = _cosmiconfig.defaultLoadersSync[".js"](...args);
} catch (error) {
let importESM;
try {
// eslint-disable-next-line no-new-func
importESM = new Function("id", "return import(id);");
} catch (e) {
importESM = null;
}
if (error.code === "ERR_REQUIRE_ESM" && _url.default.pathToFileURL && importESM) {
const urlForConfig = _url.default.pathToFileURL(args[0]);
result = await importESM(urlForConfig);
} else {
throw error;
}
}
return result;
},
".cjs": _cosmiconfig.defaultLoadersSync[".cjs"],
".mjs": async (...args) => {
let result;
let importESM;
try {
// eslint-disable-next-line no-new-func
importESM = new Function("id", "return import(id);");
} catch (e) {
importESM = null;
}
if (_url.default.pathToFileURL && importESM) {
const urlForConfig = _url.default.pathToFileURL(args[0]);
result = await importESM(urlForConfig);
} else {
throw new Error("ESM is not supported");
}
return result;
}
};
if (!tsLoader) {
const opts = {
interopDefault: true
};
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
const jiti = require("jiti")(__filename, opts);
tsLoader = filepath => jiti(filepath);
}
loaders[".cts"] = tsLoader;
loaders[".mts"] = tsLoader;
loaders[".ts"] = tsLoader;
const explorer = (0, _cosmiconfig.cosmiconfig)(moduleName, {
searchPlaces,
loaders
});
let result;
try {
if (stats.isFile()) {
result = await explorer.load(searchPath);
} else {
result = await explorer.search(searchPath);
}
} catch (error) {
throw error;
}
if (!result) {
return {};
}
loaderContext.addBuildDependency(result.filepath);
loaderContext.addDependency(result.filepath);
if (result.isEmpty) {
return result;
}
if (typeof result.config === "function") {
const api = {
mode: loaderContext.mode,
file: loaderContext.resourcePath,
// For complex use
webpackLoaderContext: loaderContext,
// Partial compatibility with `postcss-cli`
env: loaderContext.mode,
options: postcssOptions || {}
};
return {
...result,
config: result.config(api)
};
}
return result;
}
function loadPlugin(plugin, options, file) {
try {
// eslint-disable-next-line global-require, import/no-dynamic-require
let loadedPlugin = require(plugin);
if (loadedPlugin.default) {
loadedPlugin = loadedPlugin.default;
}
if (!options || Object.keys(options).length === 0) {
return loadedPlugin;
}
return loadedPlugin(options);
} catch (error) {
throw new Error(`Loading PostCSS "${plugin}" plugin failed: ${error.message}\n\n(@${file})`);
}
}
function pluginFactory() {
const listOfPlugins = new Map();
return plugins => {
if (typeof plugins === "undefined") {
return listOfPlugins;
}
if (Array.isArray(plugins)) {
for (const plugin of plugins) {
if (Array.isArray(plugin)) {
const [name, options] = plugin;
listOfPlugins.set(name, options);
} else if (plugin && typeof plugin === "function") {
listOfPlugins.set(plugin);
} else if (plugin && Object.keys(plugin).length === 1 && (typeof plugin[Object.keys(plugin)[0]] === "object" || typeof plugin[Object.keys(plugin)[0]] === "boolean") && plugin[Object.keys(plugin)[0]] !== null) {
const [name] = Object.keys(plugin);
const options = plugin[name];
if (options === false) {
listOfPlugins.delete(name);
} else {
listOfPlugins.set(name, options);
}
} else if (plugin) {
listOfPlugins.set(plugin);
}
}
} else {
const objectPlugins = Object.entries(plugins);
for (const [name, options] of objectPlugins) {
if (options === false) {
listOfPlugins.delete(name);
} else {
listOfPlugins.set(name, options);
}
}
}
return listOfPlugins;
};
}
async function tryRequireThenImport(module) {
let exports;
try {
// eslint-disable-next-line import/no-dynamic-require, global-require
exports = require(module);
return exports;
} catch (requireError) {
let importESM;
try {
// eslint-disable-next-line no-new-func
importESM = new Function("id", "return import(id);");
} catch (e) {
importESM = null;
}
if (requireError.code === "ERR_REQUIRE_ESM" && importESM) {
exports = await importESM(module);
return exports.default;
}
throw requireError;
}
}
async function getPostcssOptions(loaderContext, loadedConfig = {}, postcssOptions = {}) {
const file = loaderContext.resourcePath;
let normalizedPostcssOptions = postcssOptions;
if (typeof normalizedPostcssOptions === "function") {
normalizedPostcssOptions = normalizedPostcssOptions(loaderContext);
}
let plugins = [];
try {
const factory = pluginFactory();
if (loadedConfig.config && loadedConfig.config.plugins) {
factory(loadedConfig.config.plugins);
}
factory(normalizedPostcssOptions.plugins);
plugins = [...factory()].map(item => {
const [plugin, options] = item;
if (typeof plugin === "string") {
return loadPlugin(plugin, options, file);
}
return plugin;
});
} catch (error) {
loaderContext.emitError(error);
}
const processOptionsFromConfig = {
...loadedConfig.config
} || {};
if (processOptionsFromConfig.from) {
processOptionsFromConfig.from = _path.default.resolve(_path.default.dirname(loadedConfig.filepath), processOptionsFromConfig.from);
}
if (processOptionsFromConfig.to) {
processOptionsFromConfig.to = _path.default.resolve(_path.default.dirname(loadedConfig.filepath), processOptionsFromConfig.to);
}
const processOptionsFromOptions = {
...normalizedPostcssOptions
};
if (processOptionsFromOptions.from) {
processOptionsFromOptions.from = _path.default.resolve(loaderContext.rootContext, processOptionsFromOptions.from);
}
if (processOptionsFromOptions.to) {
processOptionsFromOptions.to = _path.default.resolve(loaderContext.rootContext, processOptionsFromOptions.to);
}
// No need `plugins` and `config` for processOptions
const {
plugins: __plugins,
...optionsFromConfig
} = processOptionsFromConfig;
const {
config: _config,
plugins: _plugins,
...optionsFromOptions
} = processOptionsFromOptions;
const processOptions = {
from: file,
to: file,
map: false,
...optionsFromConfig,
...optionsFromOptions
};
if (typeof processOptions.parser === "string") {
try {
processOptions.parser = await tryRequireThenImport(processOptions.parser);
} catch (error) {
loaderContext.emitError(new Error(`Loading PostCSS "${processOptions.parser}" parser failed: ${error.message}\n\n(@${file})`));
}
}
if (typeof processOptions.stringifier === "string") {
try {
processOptions.stringifier = await tryRequireThenImport(processOptions.stringifier);
} catch (error) {
loaderContext.emitError(new Error(`Loading PostCSS "${processOptions.stringifier}" stringifier failed: ${error.message}\n\n(@${file})`));
}
}
if (typeof processOptions.syntax === "string") {
try {
processOptions.syntax = await tryRequireThenImport(processOptions.syntax);
} catch (error) {
loaderContext.emitError(new Error(`Loading PostCSS "${processOptions.syntax}" syntax failed: ${error.message}\n\n(@${file})`));
}
}
if (processOptions.map === true) {
// https://github.com/postcss/postcss/blob/master/docs/source-maps.md
processOptions.map = {
inline: true
};
}
return {
plugins,
processOptions
};
}
const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i;
function getURLType(source) {
if (source[0] === "/") {
if (source[1] === "/") {
return "scheme-relative";
}
return "path-absolute";
}
if (IS_NATIVE_WIN32_PATH.test(source)) {
return "path-absolute";
}
return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
}
function normalizeSourceMap(map, resourceContext) {
let newMap = map;
// Some loader emit source map as string
// Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
if (typeof newMap === "string") {
newMap = JSON.parse(newMap);
}
delete newMap.file;
const {
sourceRoot
} = newMap;
delete newMap.sourceRoot;
if (newMap.sources) {
newMap.sources = newMap.sources.map(source => {
const sourceType = getURLType(source);
// Do no touch `scheme-relative` and `absolute` URLs
if (sourceType === "path-relative" || sourceType === "path-absolute") {
const absoluteSource = sourceType === "path-relative" && sourceRoot ? _path.default.resolve(sourceRoot, _path.default.normalize(source)) : _path.default.normalize(source);
return _path.default.relative(resourceContext, absoluteSource);
}
return source;
});
}
return newMap;
}
function normalizeSourceMapAfterPostcss(map, resourceContext) {
const newMap = map;
// result.map.file is an optional property that provides the output filename.
// Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
// eslint-disable-next-line no-param-reassign
delete newMap.file;
// eslint-disable-next-line no-param-reassign
newMap.sourceRoot = "";
// eslint-disable-next-line no-param-reassign
newMap.sources = newMap.sources.map(source => {
if (source.indexOf("<") === 0) {
return source;
}
const sourceType = getURLType(source);
// Do no touch `scheme-relative`, `path-absolute` and `absolute` types
if (sourceType === "path-relative") {
return _path.default.resolve(resourceContext, source);
}
return source;
});
return newMap;
}
function findPackageJSONDir(cwd, statSync) {
let dir = cwd;
for (;;) {
try {
if (statSync(_path.default.join(dir, "package.json")).isFile()) {
break;
}
} catch (error) {
// Nothing
}
const parent = _path.default.dirname(dir);
if (dir === parent) {
dir = null;
break;
}
dir = parent;
}
return dir;
}
function getPostcssImplementation(loaderContext, implementation) {
let resolvedImplementation = implementation;
if (!implementation || typeof implementation === "string") {
const postcssImplPkg = implementation || "postcss";
// eslint-disable-next-line import/no-dynamic-require, global-require
resolvedImplementation = require(postcssImplPkg);
}
// eslint-disable-next-line consistent-return
return resolvedImplementation;
}
function reportError(loaderContext, callback, error) {
if (error.file) {
loaderContext.addDependency(error.file);
}
if (error.name === "CssSyntaxError") {
callback(syntaxErrorFactory(error));
} else {
callback(error);
}
}
function warningFactory(warning) {
let message = "";
if (typeof warning.line !== "undefined") {
message += `(${warning.line}:${warning.column}) `;
}
if (typeof warning.plugin !== "undefined") {
message += `from "${warning.plugin}" plugin: `;
}
message += warning.text;
if (warning.node) {
message += `\n\nCode:\n ${warning.node.toString()}\n`;
}
const obj = new Error(message, {
cause: warning
});
obj.stack = null;
return obj;
}
function syntaxErrorFactory(error) {
let message = "\nSyntaxError\n\n";
if (typeof error.line !== "undefined") {
message += `(${error.line}:${error.column}) `;
}
if (typeof error.plugin !== "undefined") {
message += `from "${error.plugin}" plugin: `;
}
message += error.file ? `${error.file} ` : "<css input> ";
message += `${error.reason}`;
const code = error.showSourceCode();
if (code) {
message += `\n\n${code}\n`;
}
const obj = new Error(message, {
cause: error
});
obj.stack = null;
return obj;
}

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 David Clark
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,685 @@
# cosmiconfig
[![codecov](https://codecov.io/gh/cosmiconfig/cosmiconfig/branch/main/graph/badge.svg)](https://codecov.io/gh/cosmiconfig/cosmiconfig)
Cosmiconfig searches for and loads configuration for your program.
It features smart defaults based on conventional expectations in the JavaScript ecosystem.
But it's also flexible enough to search wherever you'd like to search, and load whatever you'd like to load.
By default, Cosmiconfig will start where you tell it to start and search up the directory tree for the following:
- a `package.json` property
- a JSON or YAML, extensionless "rc file"
- 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.ts`, `.config.mjs`, or `.config.cjs` file
For example, if your module's name is "myapp", cosmiconfig will search up the directory tree for configuration in the following places:
- a `myapp` property in `package.json`
- a `.myapprc` file in JSON or YAML format
- 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
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).
## Table of contents
- [Installation](#installation)
- [Usage for tooling developers](#usage-for-tooling-developers)
- [Result](#result)
- [Asynchronous API](#asynchronous-api)
- [cosmiconfig()](#cosmiconfig-1)
- [explorer.search()](#explorersearch)
- [explorer.load()](#explorerload)
- [explorer.clearLoadCache()](#explorerclearloadcache)
- [explorer.clearSearchCache()](#explorerclearsearchcache)
- [explorer.clearCaches()](#explorerclearcaches)
- [Synchronous API](#synchronous-api)
- [cosmiconfigSync()](#cosmiconfigsync)
- [explorerSync.search()](#explorersyncsearch)
- [explorerSync.load()](#explorersyncload)
- [explorerSync.clearLoadCache()](#explorersyncclearloadcache)
- [explorerSync.clearSearchCache()](#explorersyncclearsearchcache)
- [explorerSync.clearCaches()](#explorersyncclearcaches)
- [cosmiconfigOptions](#cosmiconfigoptions)
- [searchPlaces](#searchplaces)
- [loaders](#loaders)
- [packageProp](#packageprop)
- [stopDir](#stopdir)
- [cache](#cache)
- [transform](#transform)
- [ignoreEmptySearchPlaces](#ignoreemptysearchplaces)
- [Loading JS modules](#loading-js-modules)
- [Caching](#caching)
- [Differences from rc](#differences-from-rc)
- [Usage for end users](#usage-for-end-users)
- [Contributing & Development](#contributing--development)
## Installation
```
npm install cosmiconfig
```
Tested in Node 14+.
## Usage for tooling developers
*If you are an end user (i.e. a user of a tool that uses cosmiconfig, like `prettier` or `stylelint`),
you can skip down to [the end user section](#usage-for-end-users).*
Create a Cosmiconfig explorer, then either `search` for or directly `load` a configuration file.
```js
const { cosmiconfig, cosmiconfigSync } = require('cosmiconfig');
// ...
const explorer = cosmiconfig(moduleName);
// Search for a configuration by walking up directories.
// See documentation for search, below.
explorer.search()
.then((result) => {
// result.config is the parsed configuration object.
// result.filepath is the path to the config file that was found.
// result.isEmpty is true if there was nothing to parse in the config file.
})
.catch((error) => {
// Do something constructive.
});
// Load a configuration directly when you know where it should be.
// The result object is the same as for search.
// See documentation for load, below.
explorer.load(pathToConfig).then(..);
// You can also search and load synchronously.
const explorerSync = cosmiconfigSync(moduleName);
const searchedFor = explorerSync.search();
const loaded = explorerSync.load(pathToConfig);
```
## Result
The result object you get from `search` or `load` has the following properties:
- **config:** The parsed configuration object. `undefined` if the file is empty.
- **filepath:** The path to the configuration file that was found.
- **isEmpty:** `true` if the configuration file is empty. This property will not be present if the configuration file is not empty.
## Asynchronous API
### cosmiconfig()
```js
const { cosmiconfig } = require('cosmiconfig');
const explorer = cosmiconfig(moduleName[, cosmiconfigOptions])
```
Creates a cosmiconfig instance ("explorer") configured according to the arguments, and initializes its caches.
#### moduleName
Type: `string`. **Required.**
Your module name. This is used to create the default [`searchPlaces`] and [`packageProp`].
If your [`searchPlaces`] value will include files, as it does by default (e.g. `${moduleName}rc`), your `moduleName` must consist of characters allowed in filenames. That means you should not copy scoped package names, such as `@my-org/my-package`, directly into `moduleName`.
**[`cosmiconfigOptions`] are documented below.**
You may not need them, and should first read about the functions you'll use.
### explorer.search()
```js
explorer.search([searchFrom]).then(result => {..})
```
Searches for a configuration file. Returns a Promise that resolves with a [result] or with `null`, if no configuration file is found.
You can do the same thing synchronously with [`explorerSync.search()`].
Let's say your module name is `goldengrahams` so you initialized with `const explorer = cosmiconfig('goldengrahams');`.
Here's how your default [`search()`] will work:
- Starting from `process.cwd()` (or some other directory defined by the `searchFrom` argument to [`search()`]), look for configuration objects in the following places:
1. A `goldengrahams` property in a `package.json` file.
2. A `.goldengrahamsrc` file with JSON or YAML syntax.
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.
So the search continues in `./`, `../`, `../../`, `../../../`, etc., checking the same places in each directory.
- Continue searching until arriving at your home directory (or some other directory defined by the cosmiconfig option [`stopDir`]).
- For JS files,
- If at any point a parsable configuration is found, the [`search()`] Promise resolves with its [result] \(or, with [`explorerSync.search()`], the [result] is returned).
- If no configuration object is found, the [`search()`] Promise resolves with `null` (or, with [`explorerSync.search()`], `null` is returned).
- If a configuration object is found *but is malformed* (causing a parsing error), the [`search()`] Promise rejects with that error (so you should `.catch()` it). (Or, with [`explorerSync.search()`], the error is thrown.)
**If you know exactly where your configuration file should be, you can use [`load()`], instead.**
**The search process is highly customizable.**
Use the cosmiconfig options [`searchPlaces`] and [`loaders`] to precisely define where you want to look for configurations and how you want to load them.
#### searchFrom
Type: `string`.
Default: `process.cwd()`.
A filename.
[`search()`] will start its search here.
If the value is a directory, that's where the search starts.
If it's a file, the search starts in that file's directory.
### explorer.load()
```js
explorer.load(loadPath).then(result => {..})
```
Loads a configuration file. Returns a Promise that resolves with a [result] or rejects with an error (if the file does not exist or cannot be loaded).
Use `load` if you already know where the configuration file is and you just need to load it.
```js
explorer.load('load/this/file.json'); // Tries to load load/this/file.json.
```
If you load a `package.json` file, the result will be derived from whatever property is specified as your [`packageProp`].
You can do the same thing synchronously with [`explorerSync.load()`].
### explorer.clearLoadCache()
Clears the cache used in [`load()`].
### explorer.clearSearchCache()
Clears the cache used in [`search()`].
### explorer.clearCaches()
Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
## Synchronous API
### cosmiconfigSync()
```js
const { cosmiconfigSync } = require('cosmiconfig');
const explorerSync = cosmiconfigSync(moduleName[, cosmiconfigOptions])
```
Creates a *synchronous* cosmiconfig instance ("explorerSync") configured according to the arguments, and initializes its caches.
See [`cosmiconfig()`](#cosmiconfig-1).
### explorerSync.search()
```js
const result = explorerSync.search([searchFrom]);
```
Synchronous version of [`explorer.search()`].
Returns a [result] or `null`.
### explorerSync.load()
```js
const result = explorerSync.load(loadPath);
```
Synchronous version of [`explorer.load()`].
Returns a [result].
### explorerSync.clearLoadCache()
Clears the cache used in [`load()`].
### explorerSync.clearSearchCache()
Clears the cache used in [`search()`].
### explorerSync.clearCaches()
Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
## cosmiconfigOptions
Type: `Object`.
Possible options are documented below.
### searchPlaces
Type: `Array<string>`.
Default: See below.
An array of places that [`search()`] will check in each directory as it moves up the directory tree.
Each place is relative to the directory being searched, and the places are checked in the specified order.
**Default `searchPlaces`:**
For the [asynchronous API](#asynchronous-api), these are the default `searchPlaces`:
```js
[
'package.json',
`.${moduleName}rc`,
`.${moduleName}rc.json`,
`.${moduleName}rc.yaml`,
`.${moduleName}rc.yml`,
`.${moduleName}rc.js`,
`.${moduleName}rc.ts`,
`.${moduleName}rc.mjs`,
`.${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.mjs`,
`${moduleName}.config.cjs`,
];
```
For the [synchronous API](#synchronous-api), the only difference is that `.mjs` files are not included. See ["Loading JS modules"] for more information.
Create your own array to search more, fewer, or altogether different places.
Every item in `searchPlaces` needs to have a loader in [`loaders`] that corresponds to its extension.
(Common extensions are covered by default loaders.)
Read more about [`loaders`] below.
`package.json` is a special value: When it is included in `searchPlaces`, Cosmiconfig will always parse it as JSON and load a property within it, not the whole file.
That property is defined with the [`packageProp`] option, and defaults to your module name.
Examples, with a module named `porgy`:
```js
// 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',
'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.
// Look within a .config/ subdirectory of every searched directory:
('package.json',
'.porgyrc',
'.config/.porgyrc',
'.porgyrc.json',
'.config/.porgyrc.json')
];
```
### loaders
Type: `Object`.
Default: See below.
An object that maps extensions to the loader functions responsible for loading and parsing files with those extensions.
Cosmiconfig exposes its default loaders on the named export `defaultLoaders` and `defaultLoadersSync`.
**Default `loaders`:**
```js
const { defaultLoaders, defaultLoadersSync } = require('cosmiconfig');
console.log(Object.entries(defaultLoaders));
// [
// [ '.mjs', [Function: loadJs] ],
// [ '.cjs', [Function: loadJs] ],
// [ '.js', [Function: loadJs] ],
// [ '.ts', [Function: loadTs] ],
// [ '.json', [Function: loadJson] ],
// [ '.yaml', [Function: loadYaml] ],
// [ '.yml', [Function: loadYaml] ],
// [ 'noExt', [Function: loadYaml] ]
// ]
console.log(Object.entries(defaultLoadersSync));
// [
// [ '.cjs', [Function: loadJsSync] ],
// [ '.js', [Function: loadJsSync] ],
// [ '.ts', [Function: loadTsSync] ],
// [ '.json', [Function: loadJson] ],
// [ '.yaml', [Function: loadYaml] ],
// [ '.yml', [Function: loadYaml] ],
// [ 'noExt', [Function: loadYaml] ]
// ]
```
(YAML is a superset of JSON; which means YAML parsers can parse JSON; which is how extensionless files can be either YAML *or* JSON with only one parser.)
**If you provide a `loaders` object, your object will be *merged* with the defaults.**
So you can override one or two without having to override them all.
**Keys in `loaders`** are extensions (starting with a period), or `noExt` to specify the loader for files *without* extensions, like `.myapprc`.
**Values in `loaders`** are a loader function (described below) whose values are loader functions.
**The most common use case for custom loaders value is to load extensionless `rc` files as strict JSON**, instead of JSON *or* YAML (the default).
To accomplish that, provide the following `loaders` value:
```js
{
noExt: defaultLoaders['.json'];
}
```
If you want to load files that are not handled by the loader functions Cosmiconfig exposes, you can write a custom loader function or use one from NPM if it exists.
**Third-party loaders:**
- [cosmiconfig-typescript-loader](https://github.com/codex-/cosmiconfig-typescript-loader)
**Use cases for custom loader function:**
- Allow configuration syntaxes that aren't handled by Cosmiconfig's defaults, like JSON5, INI, or XML.
- Allow ES2015 modules from `.mjs` configuration files.
- Parse JS files with Babel before deriving the configuration.
**Custom loader functions** have the following signature:
```js
// Sync
(filepath: string, content: string) => Object | null
// Async
(filepath: string, content: string) => Object | null | Promise<Object | null>
```
Cosmiconfig reads the file when it checks whether the file exists, so it will provide you with both the file's path and its content.
Do whatever you need to, and return either a configuration object or `null` (or, for async-only loaders, a Promise that resolves with one of those).
`null` indicates that no real configuration was found and the search should continue.
A few things to note:
- If you use a custom loader, be aware of whether it's sync or async: you cannot use async customer loaders with the sync API ([`cosmiconfigSync()`]).
- **Special JS syntax can also be handled by using a `require` hook**, because `defaultLoaders['.js']` just uses `require`.
Whether you use custom loaders or a `require` hook is up to you.
Examples:
```js
// Allow JSON5 syntax:
{
'.json': json5Loader
}
// Allow a special configuration syntax of your own creation:
{
'.special': specialLoader
}
// Allow many flavors of JS, using custom loaders:
{
'.coffee': coffeeScriptLoader
}
// Allow many flavors of JS but rely on require hooks:
{
'.coffee': defaultLoaders['.js']
}
```
### packageProp
Type: `string | Array<string>`.
Default: `` `${moduleName}` ``.
Name of the property in `package.json` to look for.
Use a period-delimited string or an array of strings to describe a path to nested properties.
For example, the value `'configs.myPackage'` or `['configs', 'myPackage']` will get you the `"myPackage"` value in a `package.json` like this:
```json
{
"configs": {
"myPackage": {..}
}
}
```
If nested property names within the path include periods, you need to use an array of strings. For example, the value `['configs', 'foo.bar', 'baz']` will get you the `"baz"` value in a `package.json` like this:
```json
{
"configs": {
"foo.bar": {
"baz": {..}
}
}
}
```
If a string includes period but corresponds to a top-level property name, it will not be interpreted as a period-delimited path. For example, the value `'one.two'` will get you the `"three"` value in a `package.json` like this:
```json
{
"one.two": "three",
"one": {
"two": "four"
}
}
```
### stopDir
Type: `string`.
Default: Absolute path to your home directory.
Directory where the search will stop.
### cache
Type: `boolean`.
Default: `true`.
If `false`, no caches will be used.
Read more about ["Caching"](#caching) below.
### transform
Type: `(Result) => Promise<Result> | Result`.
A function that transforms the parsed configuration. Receives the [result].
If using [`search()`] or [`load()`] \(which are async), the transform function can return the transformed result or return a Promise that resolves with the transformed result.
If using `cosmiconfigSync`, [`search()`] or [`load()`], the function must be synchronous and return the transformed result.
The reason you might use this option — instead of simply applying your transform function some other way — is that *the transformed result will be cached*. If your transformation involves additional filesystem I/O or other potentially slow processing, you can use this option to avoid repeating those steps every time a given configuration is searched or loaded.
### ignoreEmptySearchPlaces
Type: `boolean`.
Default: `true`.
By default, if [`search()`] encounters an empty file (containing nothing but whitespace) in one of the [`searchPlaces`], it will ignore the empty file and move on.
If you'd like to load empty configuration files, instead, set this option to `false`.
Why might you want to load empty configuration files?
If you want to throw an error, or if an empty configuration file means something to your program.
## Loading JS modules
Your end users can provide JS configuration files as ECMAScript modules (ESM) under the following conditions:
- You (the cosmiconfig user) use cosmiconfig's [asynchronous API](#asynchronous-api).
- Your end user runs a version of Node that supports ESM ([>=12.17.0](https://nodejs.org/en/blog/release/v12.17.0/), or earlier with the `--experimental-modules` flag).
- Your end user provides an `.mjs` configuration file, or a `.js` file whose nearest parent `package.json` file contains `"type": "module"`. (See [Node's method for determining a file's module system](https://nodejs.org/api/packages.html#packages_determining_module_system).)
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).
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.
## Caching
As of v2, cosmiconfig uses caching to reduce the need for repetitious reading of the filesystem or expensive transforms. Every new cosmiconfig instance (created with `cosmiconfig()`) has its own caches.
To avoid or work around caching, you can do the following:
- Set the `cosmiconfig` option [`cache`] to `false`.
- Use the cache-clearing methods [`clearLoadCache()`], [`clearSearchCache()`], and [`clearCaches()`].
- Create separate instances of cosmiconfig (separate "explorers").
## Differences from [rc](https://github.com/dominictarr/rc)
[rc](https://github.com/dominictarr/rc) serves its focused purpose well. cosmiconfig differs in a few key ways — making it more useful for some projects, less useful for others:
- Looks for configuration in some different places: in a `package.json` property, an rc file, a `.config.js` file, and rc files with extensions.
- Built-in support for JSON, YAML, and CommonJS formats.
- Stops at the first configuration found, instead of finding all that can be found up the directory tree and merging them automatically.
- Options.
- Asynchronous by default (though can be run synchronously).
## Usage for end users
When configuring a tool, you can use multiple file formats and put these in multiple places.
Usually, a tool would mention this in its own README file,
but by default, these are the following places, where `{NAME}` represents the name of the tool:
```
package.json
.{NAME}rc
.{NAME}rc.json
.{NAME}rc.yaml
.{NAME}rc.yml
.{NAME}rc.js
.{NAME}rc.ts
.{NAME}rc.cjs
.config/{NAME}rc
.config/{NAME}rc.json
.config/{NAME}rc.yaml
.config/{NAME}rc.yml
.config/{NAME}rc.js
.config/{NAME}rc.ts
.config/{NAME}rc.cjs
{NAME}.config.js
{NAME}.config.ts
{NAME}.config.cjs
```
The contents of these files are defined by the tool.
For example, you can configure prettier to enforce semicolons at the end of the line
using a file named `.config/prettierrc.yml`:
```yaml
semi: true
```
Additionally, you have the option to put a property named after the tool in your `package.json` file,
with the contents of that property being the same as the file contents. To use the same example as above:
```json
{
"name": "your-project",
"dependencies": {},
"prettier": {
"semi": true
}
}
```
This has the advantage that you can put the configuration of all tools
(at least the ones that use cosmiconfig) in one file.
You can also add a `cosmiconfig` key within your `package.json` file or create one of the following files
to configure `cosmiconfig` itself:
```
.config.json
.config.yaml
.config.yml
.config.js
.config.ts
.config.cjs
```
The following property is currently actively supported in these places:
```yaml
cosmiconfig:
# overrides where configuration files are being searched to enforce a custom naming convention and format
searchPlaces:
- .config/{name}.yml
```
> **Note:** technically, you can overwrite all options described in [cosmiconfigOptions](#cosmiconfigoptions) here,
> but everything not listed above should be used at your own risk, as it has not been tested explicitly.
You can also add more root properties outside the `cosmiconfig` property
to configure your tools, entirely eliminating the need to look for additional configuration files:
```yaml
cosmiconfig:
searchPlaces: []
prettier:
semi: true
```
## Contributing & Development
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
And please do participate!
[result]: #result
[`load()`]: #explorerload
[`search()`]: #explorersearch
[`clearloadcache()`]: #explorerclearloadcache
[`clearsearchcache()`]: #explorerclearsearchcache
[`cosmiconfig()`]: #cosmiconfig
[`cosmiconfigSync()`]: #cosmiconfigsync
[`clearcaches()`]: #explorerclearcaches
[`packageprop`]: #packageprop
[`cache`]: #cache
[`stopdir`]: #stopdir
[`searchplaces`]: #searchplaces
[`loaders`]: #loaders
[`cosmiconfigoptions`]: #cosmiconfigoptions
[`explorerSync.search()`]: #explorersyncsearch
[`explorerSync.load()`]: #explorersyncload
[`explorer.search()`]: #explorersearch
[`explorer.load()`]: #explorerload
["Loading JS modules"]: #loading-js-modules

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=Explorer.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Explorer.d.ts","sourceRoot":"","sources":["../src/Explorer.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,103 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Explorer = void 0;
const promises_1 = __importDefault(require("fs/promises"));
const path_1 = __importDefault(require("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 = 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();
}
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 = path_1.default.resolve(this.config.stopDir);
from = 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 = 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' ||
error.code === 'ENOTDIR') {
continue;
}
throw error;
}
}
}
const dir = 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 await this.config.transform(null);
};
if (this.searchCache) {
return await (0, util_js_1.emplace)(this.searchCache, from, search);
}
return await search();
}
async #readConfiguration(filepath) {
const contents = await promises_1.default.readFile(filepath, { encoding: 'utf-8' });
return this.toCosmiconfigResult(filepath, await this.#loadConfiguration(filepath, contents));
}
async #loadConfiguration(filepath, contents) {
if (contents.trim() === '') {
return;
}
if (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 = 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)}`);
}
}
exports.Explorer = Explorer;
//# sourceMappingURL=Explorer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Explorer.js","sourceRoot":"","sources":["../src/Explorer.ts"],"names":[],"mappings":";;;;;;AAAA,2DAA6B;AAC7B,gDAAwB;AACxB,yCAAwC;AACxC,uDAA0E;AAC1E,6CAAwC;AAExC,uCAAuD;AAEvD;;GAEG;AACH,MAAa,QAAS,SAAQ,8BAA6B;IAClD,KAAK,CAAC,IAAI,CAAC,QAAgB;QAChC,QAAQ,GAAG,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QAElC,MAAM,IAAI,GAAG,KAAK,IAAgC,EAAE;YAClD,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,CAChC,MAAM,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CACxC,CAAC;QACJ,CAAC,CAAC;QACF,IAAI,IAAI,CAAC,SAAS,EAAE;YAClB,OAAO,MAAM,IAAA,iBAAO,EAAC,IAAI,CAAC,SAAS,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;S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iB,EACf,IAAA,qBAAQ,EAAC,QAAQ,EAAE,QAAQ,CAAC,EAC5B,IAAI,CAAC,MAAM,CAAC,WAAW,CACxB,IAAI,IAAI,CACV,CAAC;SACH;QAED,MAAM,SAAS,GAAG,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACzC,IAAI;YACF,MAAM,MAAM,GACV,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC;gBACzC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YACjC,IAAI,MAAM,KAAK,SAAS,EAAE;gBACxB,2DAA2D;gBAC3D,OAAO,MAAM,MAAM,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;aACzC;SACF;QAAC,OAAO,KAAK,EAAE;YACd,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAC1B,MAAM,KAAK,CAAC;SACb;QACD,MAAM,IAAI,KAAK,CACb,2BAA2B,IAAA,yCAAuB,EAAC,SAAS,CAAC,EAAE,CAChE,CAAC;IACJ,CAAC;CACF;AA/GD,4BA+GC"}

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=ExplorerBase.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ExplorerBase.d.ts","sourceRoot":"","sources":["../src/ExplorerBase.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,82 @@
"use strict";
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 path_1 = __importDefault(require("path"));
const util_js_1 = require("./util.js");
/**
* @internal
*/
class ExplorerBase {
#loadingMetaConfig = false;
config;
loadCache;
searchCache;
constructor(options) {
this.config = options;
if (options.cache) {
this.loadCache = new Map();
this.searchCache = new Map();
}
this.#validateConfig();
}
set loadingMetaConfig(value) {
this.#loadingMetaConfig = value;
}
#validateConfig() {
const config = this.config;
for (const place of config.searchPlaces) {
const extension = 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}.`);
}
}
}
clearLoadCache() {
if (this.loadCache) {
this.loadCache.clear();
}
}
clearSearchCache() {
if (this.searchCache) {
this.searchCache.clear();
}
}
clearCaches() {
this.clearLoadCache();
this.clearSearchCache();
}
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 };
}
}
exports.ExplorerBase = ExplorerBase;
/**
* @internal
*/
function getExtensionDescription(extension) {
/* istanbul ignore next -- @preserve */
return extension ? `extension "${extension}"` : 'files without extensions';
}
exports.getExtensionDescription = getExtensionDescription;
//# sourceMappingURL=ExplorerBase.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ExplorerBase.js","sourceRoot":"","sources":["../src/ExplorerBase.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AASxB,uCAA8C;AAE9C;;GAEG;AACH,MAAsB,YAAY;IAGhC,kBAAkB,GAAG,KAAK,CAAC;IAER,MAAM,CAAI;IACV,SAAS,CAEb;IACI,WAAW,CAEf;IAEf,YAAmB,OAAoB;QACrC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC;QACtB,IAAI,OAAO,CAAC,KAAK,EAAE;YACjB,IAAI,CAAC,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;YAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;SAC9B;QACD,IAAI,CAAC,eAAe,EAAE,CAA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AAE,OAAO,EAAE,IAAI,EAAE,CAAC;SACvD;QACD,IACE,IAAI,CAAC,MAAM,CAAC,uCAAuC;YACnD,IAAI,CAAC,kBAAkB,EACvB;YACA,MAAM,GAAG,IAAA,2BAAiB,EAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;SAC7D;QACD,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;SACvD;QACD,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;IAC9B,CAAC;CACF;AAvFD,oCAuFC;AAED;;GAEG;AACH,SAAgB,uBAAuB,CAAC,SAAkB;IACxD,uCAAuC;IACvC,OAAO,SAAS,CAAC,CAAC,CAAC,cAAc,SAAS,GAAG,CAAC,CAAC,CAAC,0BAA0B,CAAC;AAC7E,CAAC;AAHD,0DAGC"}

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=ExplorerSync.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ExplorerSync.d.ts","sourceRoot":"","sources":["../src/ExplorerSync.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,116 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExplorerSync = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("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 = 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();
}
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 = path_1.default.resolve(this.config.stopDir);
from = 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 = 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' ||
error.code === 'ENOTDIR') {
continue;
}
throw error;
}
}
}
const dir = 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 this.config.transform(null);
};
if (this.searchCache) {
return (0, util_js_1.emplace)(this.searchCache, from, search);
}
return search();
}
#readConfiguration(filepath) {
const contents = fs_1.default.readFileSync(filepath, 'utf8');
return this.toCosmiconfigResult(filepath, this.#loadConfiguration(filepath, contents));
}
#loadConfiguration(filepath, contents) {
if (contents.trim() === '') {
return;
}
if (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 = 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)}`);
}
/**
* @deprecated Use {@link ExplorerSync.prototype.load}.
*/
/* istanbul ignore next */
loadSync(filepath) {
return this.load(filepath);
}
/**
* @deprecated Use {@link ExplorerSync.prototype.search}.
*/
/* istanbul ignore next */
searchSync(from = '') {
return this.search(from);
}
}
exports.ExplorerSync = Explor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CAAC,CAAC;IAC7B,CAAC;IAED;;OAEG;IACH,0BAA0B;IACnB,UAAU,CAAC,IAAI,GAAG,EAAE;QACzB,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC3B,CAAC;CACF;AAzHD,oCAyHC"}

View File

@@ -0,0 +1,25 @@
export * from './types.js';
import { Options, OptionsSync, PublicExplorer, PublicExplorerSync } from './types.js';
export declare const metaSearchPlaces: string[];
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;
}>;
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;
}>;
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

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,YAAY,CAAC;AAa3B,OAAO,EAGL,OAAO,EACP,WAAW,EACX,cAAc,EACd,kBAAkB,EAEnB,MAAM,YAAY,CAAC;AAIpB,eAAO,MAAM,gBAAgB,UAS5B,CAAC;AAGF,eAAO,MAAM,cAAc;;;;;;;;;EAShB,CAAC;AACZ,eAAO,MAAM,kBAAkB;;;;;;;;EAQpB,CAAC;AAuIZ,wBAAgB,WAAW,CACzB,UAAU,EAAE,MAAM,EAClB,OAAO,GAAE,QAAQ,CAAC,OAAO,CAAM,GAC9B,cAAc,CAWhB;AAED,wBAAgB,eAAe,CAC7B,UAAU,EAAE,MAAM,EAClB,OAAO,GAAE,QAAQ,CAAC,WAAW,CAAM,GAClC,kBAAkB,CAWpB"}

View File

@@ -0,0 +1,195 @@
"use strict";
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 os_1 = __importDefault(require("os"));
const Explorer_js_1 = require("./Explorer.js");
const ExplorerSync_js_1 = require("./ExplorerSync.js");
const loaders_js_1 = require("./loaders.js");
const util_1 = require("./util");
// this needs to be hardcoded, as this is intended for end users, who can't supply options at this point
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.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,
});
const identity = function identity(x) {
return x;
};
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, ...(0, util_1.removeUndefinedValuesFromObject)(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: os_1.default.homedir(),
cache: true,
transform: identity,
loaders: exports.defaultLoaders,
metaConfigFilePath: null,
};
return {
...defaults,
...(0, util_1.removeUndefinedValuesFromObject)(options),
loaders: {
...defaults.loaders,
...options.loaders,
},
};
}
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: os_1.default.homedir(),
cache: true,
transform: identity,
loaders: exports.defaultLoadersSync,
metaConfigFilePath: null,
};
return {
...defaults,
...(0, util_1.removeUndefinedValuesFromObject)(options),
loaders: {
...defaults.loaders,
...options.loaders,
},
};
}
function cosmiconfig(moduleName, options = {}) {
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 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),
};
}
exports.cosmiconfigSync = cosmiconfigSync;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,sEAAsE;AACtE,6CAA2B;AAE3B,4CAAoB;AACpB,+CAAyC;AACzC,uDAAiD;AACjD,6CAOsB;AAUtB,iCAAyD;AAEzD,wGAAwG;AAC3F,QAAA,gBAAgB,GAAG;IAC9B,cAAc;IACd,cAAc;IACd,cAAc;IACd,aAAa;IACb,YAAY;IACZ,YAAY;IACZ,aAAa;IACb,aAAa;CACd,CAAC;AAEF,+EAA+E;AAClE,QAAA,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1C,MAAM,EAAE,mBAAM;IACd,MAAM,EAAE,mBAAM;IACd,KAAK,EAAE,mBAAM;IACb,KAAK,EAAE,mBAAM;IACb,OAAO,EAAE,qBAAQ;IACjB,OAAO,EAAE,qBAAQ;IACjB,MAAM,EAAE,qBAAQ;IAChB,KAAK,EAAE,qBAAQ;CACP,CAAC,CAAC;AACC,QAAA,kBAAkB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC9C,MAAM,EAAE,uBAAU;IAClB,KAAK,EAAE,uBAAU;IACjB,KAAK,EAAE,uBAAU;IACjB,OAAO,EAAE,qBAAQ;IACjB,OAAO,EAAE,qBAAQ;IACjB,MAAM,EAAE,qBAAQ;IAChB,KAAK,EAAE,qBAAQ;CACP,CAAC,CAAC;AAEZ,MAAM,QAAQ,GAAkB,SAAS,QAAQ,CAAC,CAAC;IACjD,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AAEF,SAAS,kBAAkB,CACzB,UAAkB,EAClB,OAAoB;IAEpB,MAAM,YAAY,GAAG,IAAI,8BAAY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I,8BAAY,CAAC,iBAAiB,CAAC,CAAC;IACzD,OAAO;QACL,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC;QAC9C,IAAI,EAAE,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC;QAC1C,cAAc,EAAE,YAAY,CAAC,cAAc,CAAC,IAAI,CAAC,YAAY,CAAC;QAC9D,gBAAgB,EAAE,YAAY,CAAC,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC;QAClE,WAAW,EAAE,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC,YAAY,CAAC;KACzD,CAAC;AACJ,CAAC;AAdD,0CAcC"}

View File

@@ -0,0 +1,8 @@
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

View File

@@ -0,0 +1 @@
{"version":3,"file":"loaders.d.ts","sourceRoot":"","sources":["../src/loaders.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAGhD,eAAO,MAAM,UAAU,EAAE,UAMxB,CAAC;AAEF,eAAO,MAAM,MAAM,EAAE,MAOpB,CAAC;AAGF,eAAO,MAAM,QAAQ,EAAE,UAWtB,CAAC;AAGF,eAAO,MAAM,QAAQ,EAAE,UAWtB,CAAC;AAGF,eAAO,MAAM,UAAU,EAAE,UA0BxB,CAAC;AAEF,eAAO,MAAM,MAAM,EAAE,MA0BpB,CAAC"}

View File

@@ -0,0 +1,133 @@
"use strict";
/* 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 fs_1 = require("fs");
const promises_1 = require("fs/promises");
const path_1 = __importDefault(require("path"));
const url_1 = require("url");
let importFresh;
const loadJsSync = function loadJsSync(filepath) {
if (importFresh === undefined) {
importFresh = require('import-fresh');
}
return importFresh(filepath);
};
exports.loadJsSync = loadJsSync;
const loadJs = async function loadJs(filepath) {
try {
const { href } = (0, 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 {
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 {
return yaml.load(content);
}
catch (error) {
error.message = `YAML Error in ${filepath}:\n${error.message}`;
throw error;
}
};
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)}cjs`;
try {
const config = resolveTsConfig(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, 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, fs_1.existsSync)(compiledFilepath)) {
(0, fs_1.rmSync)(compiledFilepath);
}
}
};
exports.loadTsSync = loadTsSync;
const loadTs = async function loadTs(filepath, content) {
if (typescript === undefined) {
typescript = (await import('typescript')).default;
}
const compiledFilepath = `${filepath.slice(0, -2)}mjs`;
try {
const config = resolveTsConfig(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, 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, 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

View File

@@ -0,0 +1 @@
{"version":3,"file":"loaders.js","sourceRoot":"","sources":["../src/loaders.ts"],"names":[],"mappings":";AAAA,0DAA0D;;;;;;AAE1D,2BAAuD;AACvD,0CAA4C;AAC5C,gDAAwB;AACxB,6BAAoC;AAGpC,IAAI,WAA0C,CAAC;AACxC,MAAM,UAAU,GAAe,SAAS,UAAU,CAAC,QAAQ;IAChE,IAAI,WAAW,KAAK,SAAS,EAAE;QAC7B,WAAW,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;KACvC;IAED,OAAO,WAAW,CAAC,QAAQ,CAAC,CAAC;AAC/B,CAAC,CAAC;AANW,QAAA,UAAU,cAMrB;AAEK,MAAM,MAAM,GAAW,KAAK,UAAU,MAAM,CAAC,QAAQ;IAC1D,IAAI;QACF,MAAM,EAAE,IAAI,EAAE,GAAG,IAAA,mB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C,CAAC,CAAC,CAAC;IACH,IAAI,QAAQ,KAAK,SAAS,EAAE;QAC1B,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,UAAU,CAAC,cAAc,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE,CACrE,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAC9B,CAAC;QACF,IAAI,KAAK,EAAE;YACT,MAAM,IAAI,KAAK,CAAC,YAAY,QAAQ,KAAK,KAAK,CAAC,WAAW,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;SAC1E;QACD,OAAO,MAAM,CAAC;KACf;IACD,OAAO;AACT,CAAC"}

View File

@@ -0,0 +1,91 @@
/**
* @public
*/
export type Config = any;
/**
* @public
*/
export type CosmiconfigResult = {
config: Config;
filepath: string;
isEmpty?: boolean;
} | 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;
}
/**
* @public
*/
export interface Options extends CommonOptions {
loaders?: Loaders;
transform?: Transform;
}
/**
* @public
*/
export interface OptionsSync extends CommonOptions {
loaders?: LoadersSync;
transform?: TransformSync;
}
/**
* @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

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,MAAM,MAAM,GAAG,GAAG,CAAC;AAEzB;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GAAG,IAAI,CAAC;AAET;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,IAAI,CAAC;AAEzC;;GAEG;AACH,MAAM,MAAM,MAAM,GACd,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC,GAC9D,UAAU,CAAC;AAEf;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,YAAY,CAAC;AAE7E;;GAEG;AACH,MAAM,MAAM,SAAS,GACjB,CAAC,CAAC,iBAAiB,EAAE,iBAAiB,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC,GACtE,aAAa,CAAC;AAElB;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,CAC1B,iBAAiB,EAAE,iBAAiB,KACjC,iBAAiB,CAAC;AAEvB;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,WAAW,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IACrC,YAAY,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC7B,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,OAAQ,SAAQ,aAAa;IAC5C,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,SAAS,CAAC;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,WAAY,SAAQ,aAAa;IAChD,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,SAAS,CAAC,EAAE,aAAa,CAAC;CAC3B;AA4BD;;GAEG;AACH,MAAM,WAAW,OAAO;IACtB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,cAAc,EAAE,MAAM,IAAI,CAAC;IAC3B,gBAAgB,EAAE,MAAM,IAAI,CAAC;IAC7B,WAAW,EAAE,MAAM,IAAI,CAAC;CACzB;AAED;;GAEG;AACH,MAAM,WAAW,cAAe,SAAQ,kBAAkB;IACxD,MAAM,EAAE,CAAC,UAAU,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAC5D,IAAI,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC;CACxD;AAED;;GAEG;AACH,MAAM,WAAW,kBAAmB,SAAQ,kBAAkB;IAC5D,MAAM,EAAE,CAAC,UAAU,CAAC,EAAE,MAAM,KAAK,iBAAiB,CAAC;IACnD,IAAI,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,iBAAiB,CAAC;CAC/C"}

View File

@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=util.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeUndefinedValuesFromObject = exports.getPropertyByPath = exports.emplace = void 0;
/**
* @internal
*/
function emplace(map, key, fn) {
const cached = map.get(key);
if (cached !== undefined) {
return cached;
}
const result = fn();
map.set(key, result);
return result;
}
exports.emplace = emplace;
// Resolves property names or property paths defined with period-delimited
// strings or arrays of strings. Property names that are found on the source
// object are used directly (even if they include a period).
// Nested property names that include periods, within a path, are only
// understood in array paths.
/**
* @internal
*/
function getPropertyByPath(source, path) {
if (typeof path === 'string' &&
Object.prototype.hasOwnProperty.call(source, path)) {
return source[path];
}
const parsedPath = typeof path === 'string' ? path.split('.') : path;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return parsedPath.reduce((previous, key) => {
if (previous === undefined) {
return previous;
}
return previous[key];
}, source);
}
exports.getPropertyByPath = getPropertyByPath;
/** @internal */
function removeUndefinedValuesFromObject(options) {
/* istanbul ignore if -- @preserve */
if (!options) {
return undefined;
}
return Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined));
}
exports.removeUndefinedValuesFromObject = removeUndefinedValuesFromObject;
//# sourceMappingURL=util.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,SAAgB,OAAO,CAAO,GAAc,EAAE,GAAM,EAAE,EAAW;IAC/D,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC5B,IAAI,MAAM,KAAK,SAAS,EAAE;QACxB,OAAO,MAAM,CAAC;KACf;IACD,MAAM,MAAM,GAAG,EAAE,EAAE,CAAC;IACpB,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACrB,OAAO,MAAM,CAAC;AAChB,CAAC;AARD,0BAQC;AAED,0EAA0E;AAC1E,4EAA4E;AAC5E,4DAA4D;AAC5D,sEAAsE;AACtE,6BAA6B;AAC7B;;GAEG;AACH,SAAgB,iBAAiB,CAC/B,MAAkC,EAClC,IAA4B;IAE5B,IACE,OAAO,IAAI,KAAK,QAAQ;QACxB,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,EAClD;QACA,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC;KACrB;IAED,MAAM,UAAU,GAAG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACrE,8DAA8D;IAC9D,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,QAAa,EAAE,GAAG,EAAW,EAAE;QACvD,IAAI,QAAQ,KAAK,SAAS,EAAE;YAC1B,OAAO,QAAQ,CAAC;SACjB;QACD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC,EAAE,MAAM,CAAC,CAAC;AACb,CAAC;AAnBD,8CAmBC;AAED,gBAAgB;AAChB,SAAgB,+BAA+B,CAC7C,OAA4C;IAE5C,qCAAqC;IACrC,IAAI,CAAC,OAAO,EAAE;QACZ,OAAO,SAAS,CAAC;KAClB;IACD,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CACnE,CAAC;AACJ,CAAC;AAVD,0EAUC"}

View File

@@ -0,0 +1,105 @@
{
"name": "cosmiconfig",
"version": "8.3.6",
"description": "Find and load configuration from a package.json property, rc file, TypeScript module, and more!",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"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",
"lint:md": "remark-preset-davidtheclark",
"format": "prettier \"**/*.{js,ts,json,yml,yaml}\" --write",
"format:md": "remark-preset-davidtheclark --format",
"format:check": "prettier \"**/*.{js,ts,json,yml,yaml}\" --check",
"test": "vitest run --coverage",
"test:watch": "vitest",
"check:all": "npm run test && npm run lint && npm run format:check",
"prepublishOnly": "npm run check:all && npm run build",
"prepare": "husky install"
},
"lint-staged": {
"*.{js,ts}": [
"eslint --fix",
"prettier --write"
],
"*.{json,yml,yaml}": [
"prettier --write"
],
"*.md": [
"remark-preset-davidtheclark",
"remark-preset-davidtheclark --format"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/cosmiconfig/cosmiconfig.git"
},
"keywords": [
"load",
"configuration",
"config"
],
"author": "Daniel Fischer <daniel@d-fischer.dev>",
"contributors": [
"Randolf J <jrandolf@google.com>",
"David Clark <david.dave.clark@gmail.com>",
"Bogdan Chadkin <trysound@yandex.ru>",
"Suhas Karanth <sudo.suhas@gmail.com>"
],
"funding": "https://github.com/sponsors/d-fischer",
"license": "MIT",
"bugs": {
"url": "https://github.com/cosmiconfig/cosmiconfig/issues"
},
"homepage": "https://github.com/cosmiconfig/cosmiconfig#readme",
"peerDependencies": {
"typescript": ">=4.9.5"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
},
"dependencies": {
"import-fresh": "^3.3.0",
"js-yaml": "^4.1.0",
"parse-json": "^5.2.0",
"path-type": "^4.0.0"
},
"devDependencies": {
"@types/js-yaml": "^4.0.5",
"@types/node": "^14",
"@types/parse-json": "^4.0.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": "^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.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": "^5.2.2",
"vitest": "^0.34.3"
},
"engines": {
"node": ">=14"
}
}

100
node_modules/postcss-loader/package.json generated vendored Normal file
View File

@@ -0,0 +1,100 @@
{
"name": "postcss-loader",
"version": "7.3.4",
"description": "PostCSS loader for webpack",
"license": "MIT",
"repository": "webpack-contrib/postcss-loader",
"author": "Andrey Sitnik <andrey@sitnik.ru>",
"homepage": "https://github.com/webpack-contrib/postcss-loader",
"bugs": "https://github.com/webpack-contrib/postcss-loader/issues",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/webpack"
},
"main": "dist/cjs.js",
"engines": {
"node": ">= 14.15.0"
},
"scripts": {
"start": "npm run build -- -w",
"clean": "del-cli dist",
"prebuild": "npm run clean",
"build": "cross-env NODE_ENV=production babel src -d dist --copy-files",
"commitlint": "commitlint --from=master",
"security": "npm audit --production",
"lint:prettier": "prettier \"{**/*,*}.{js,json,md,yml,css,ts}\" --list-different",
"lint:js": "eslint --cache .",
"lint:spelling": "cspell \"**/*.*\"",
"lint": "npm-run-all -l -p \"lint:**\"",
"fix:js": "npm run lint:js -- --fix",
"fix:prettier": "npm run lint:prettier -- --write",
"fix": "npm-run-all -l fix:js fix:prettier",
"test:only": "cross-env NODE_ENV=test jest",
"test:watch": "npm run test:only -- --watch",
"test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage",
"pretest": "npm run lint",
"test": "npm run test:coverage",
"prepare": "husky install && npm run build",
"release": "standard-version"
},
"files": [
"dist"
],
"peerDependencies": {
"postcss": "^7.0.0 || ^8.0.1",
"webpack": "^5.0.0"
},
"dependencies": {
"cosmiconfig": "^8.3.5",
"jiti": "^1.20.0",
"semver": "^7.5.4"
},
"devDependencies": {
"@babel/cli": "^7.23.0",
"@babel/core": "^7.23.0",
"@babel/preset-env": "^7.22.20",
"@commitlint/cli": "^17.7.2",
"@commitlint/config-conventional": "^17.7.0",
"@webpack-contrib/eslint-config-webpack": "^3.0.0",
"babel-jest": "^29.7.0",
"cross-env": "^7.0.3",
"cspell": "^6.31.2",
"cssnano": "^6.0.0",
"del": "^6.1.1",
"del-cli": "^5.1.0",
"eslint": "^8.50.0",
"eslint-config-prettier": "^8.9.0",
"eslint-plugin-import": "^2.28.1",
"husky": "^8.0.3",
"jest": "^29.7.0",
"less": "^4.2.0",
"less-loader": "^11.1.0",
"lint-staged": "^13.2.3",
"memfs": "^3.4.13",
"midas": "^2.0.3",
"npm-run-all": "^4.1.5",
"postcss": "^8.4.29",
"postcss-dark-theme-class": "^0.7.3",
"postcss-import": "^15.1.0",
"postcss-js": "^4.0.1",
"postcss-load-config": "^4.0.1",
"postcss-nested": "^6.0.1",
"postcss-short": "^5.0.0",
"prettier": "^2.8.7",
"sass": "^1.69.0",
"sass-loader": "^13.2.2",
"standard-version": "^9.3.2",
"strip-ansi": "^6.0.0",
"sugarss": "^4.0.1",
"ts-jest": "^29.1.0",
"ts-node": "^10.9.1",
"webpack": "^5.88.2"
},
"keywords": [
"css",
"postcss",
"postcss-runner",
"webpack",
"webpack-loader"
]
}