textlint
Version:
The pluggable linting tool for text and markdown.
79 lines • 2.81 kB
JavaScript
import { moduleInterop } from "@textlint/module-interop";
import * as fs from "fs";
import * as path from "path";
import { dynamicImport } from "@textlint/resolver";
import { isTextlintRuleModule } from "@textlint/config-loader";
/**
* Load all rule modules from specified directory.
* These are filtered by [extname]
* @param {String} [rulesDir] Path to rules directory, may be relative. Defaults to `lib/rules`.
* @param {String | String[]} [extnames] extension names
* @returns {Object} Loaded rule modules by rule ids (file names).
*/
export function loadFromDir(rulesDir, extnames = [".js", ".ts"]) {
let rulesDirAbsolutePath;
if (!rulesDir) {
rulesDirAbsolutePath = path.join(__dirname, "rules");
}
else {
rulesDirAbsolutePath = path.resolve(process.cwd(), rulesDir);
}
const rules = Object.create(null);
fs.readdirSync(rulesDirAbsolutePath).forEach((file) => {
if (Array.isArray(extnames)) {
if (!extnames.includes(path.extname(file))) {
return;
}
}
else {
if (path.extname(file) !== extnames) {
return;
}
}
const withoutExt = path.basename(file, path.extname(file));
rules[withoutExt] = moduleInterop(require(path.join(rulesDirAbsolutePath, file)));
});
return rules;
}
export async function loadFromDirAsESM(rulesDir, extnames = [".js", ".ts"]) {
let rulesDirAbsolutePath;
if (!rulesDir) {
rulesDirAbsolutePath = path.join(__dirname, "rules");
}
else {
rulesDirAbsolutePath = path.resolve(process.cwd(), rulesDir);
}
const files = await fs.promises.readdir(rulesDirAbsolutePath);
const ruleFiles = files.filter((file) => {
if (Array.isArray(extnames)) {
if (!extnames.includes(path.extname(file))) {
return false;
}
}
else {
if (path.extname(file) !== extnames) {
return false;
}
}
return true;
});
return Promise.all(ruleFiles.map(async (ruleFile) => {
var _a;
const withoutExt = path.basename(ruleFile, path.extname(ruleFile));
const mod = await dynamicImport(path.join(rulesDirAbsolutePath, ruleFile), {
parentModule: "textlint"
});
const ruleModule = moduleInterop((_a = mod.exports) === null || _a === void 0 ? void 0 : _a.default);
if (!isTextlintRuleModule(ruleModule)) {
throw new Error(`Loaded Module ${ruleFile} should export rule module`);
}
const ret = {
rule: ruleModule,
ruleId: withoutExt,
options: true
};
return ret;
}));
}
//# sourceMappingURL=rule-loader.js.map
;