Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve handling when file is matched but empty #11

Merged
merged 1 commit into from
Mar 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/swift-clouds-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@proload/core": patch
---

Improve handling when matched file is empty
Empty file added fixtures/empty/test.config.mjs
Empty file.
105 changes: 71 additions & 34 deletions packages/core/lib/esm/index.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import escalade from "escalade";
import { join, dirname, extname, resolve } from "path";
import deepmerge from 'deepmerge';
import deepmerge from "deepmerge";

import { existsSync, readdir, readFile, stat } from "fs";
import { promisify } from "util";
Expand All @@ -15,23 +15,35 @@ const toRead = promisify(readdir);
const toReadFile = promisify(readFile);

let merge = deepmerge;
const defaultExtensions = ['js', 'cjs', 'mjs'];
const defaultFileNames = ['[name].config'];
const defaultExtensions = ["js", "cjs", "mjs"];
const defaultFileNames = ["[name].config"];

const validNames = (namespace) => {
const extensionPlugins = load.plugins.filter(p => Array.isArray(p.extensions));
const fileNamePlugins = load.plugins.filter(p => Array.isArray(p.fileNames));
const validExtensions = [...defaultExtensions].concat(...extensionPlugins.map(p => p.extensions));
const validFileNames = [...defaultFileNames].concat(...fileNamePlugins.map(p => p.fileNames));
const extensionPlugins = load.plugins.filter((p) =>
Array.isArray(p.extensions)
);
const fileNamePlugins = load.plugins.filter((p) =>
Array.isArray(p.fileNames)
);
const validExtensions = [...defaultExtensions].concat(
...extensionPlugins.map((p) => p.extensions)
);
const validFileNames = [...defaultFileNames].concat(
...fileNamePlugins.map((p) => p.fileNames)
);

const result = validFileNames
.map(fileName => fileName.replace('[name]', namespace))
.map((fileName) => fileName.replace("[name]", namespace))
.reduce((acc, fileName) => {
return [...acc].concat(...validExtensions.map(ext => `${fileName}${ext ? '.' + ext.replace(/^\./, '') : ''}`))
return [...acc].concat(
...validExtensions.map(
(ext) => `${fileName}${ext ? "." + ext.replace(/^\./, "") : ""}`
)
);
}, []);

return result;
}
};

/**
* @param {any} val
Expand All @@ -48,13 +60,14 @@ const requireOrImportWithMiddleware = (filePath) => {
(plugin) => typeof plugin.transform !== "undefined"
);
return requireOrImport(filePath, { middleware: registerPlugins }).then(
async (mdl) => Promise.all(
transformPlugins.map((plugin) => {
return Promise.resolve(plugin.transform(mdl)).then((result) => {
if (result) mdl = result;
});
})
).then(() => mdl)
async (mdl) =>
Promise.all(
transformPlugins.map((plugin) => {
return Promise.resolve(plugin.transform(mdl)).then((result) => {
if (result) mdl = result;
});
})
).then(() => mdl)
);
};

Expand All @@ -68,7 +81,10 @@ async function resolveExtension(namespace, { filePath, extension }) {
let resolvedPath;
if (extension.startsWith("./") || extension.startsWith("../")) {
if (extname(extension) === "") {
resolvedPath = resolve(dirname(filePath), `${extension}${extname(filePath)}`);
resolvedPath = resolve(
dirname(filePath),
`${extension}${extname(filePath)}`
);
}
if (!existsSync(resolvedPath)) resolvedPath = null;

Expand All @@ -88,15 +104,15 @@ async function resolveExtension(namespace, { filePath, extension }) {
if (resolvedPath && existsSync(resolvedPath)) {
break;
} else {
resolvedPath = null
resolvedPath = null;
}
} catch (e) {}
}
}
if (!resolvedPath) {
resolvedPath = resolvePkg(extension, { cwd: dirname(filePath) });
}
if (!resolvedPath) return
if (!resolvedPath) return;
const value = await requireOrImportWithMiddleware(resolvedPath);

return { filePath: resolvedPath, value };
Expand All @@ -109,7 +125,6 @@ async function resolveExtensions(
) {
let value = typeof raw === "function" ? await raw(context) : raw;
if (Array.isArray(value)) return value;

assert(
isObject(value),
`${namespace} configuration expects an "object" but encountered ${value}`
Expand Down Expand Up @@ -140,28 +155,29 @@ async function resolveExtensions(
}

/**
*
* @param {string} namespace
*
* @param {string} namespace
* @param {import('../index').LoadOptions} opts
*/
async function load(namespace, opts = {}) {
// if (opts)
const accepted = validNames(namespace);
const { context, accept } = opts;
const input = opts.cwd || process.cwd();

let mustExist = true;
if (typeof opts.mustExist !== 'undefined') {
mustExist = opts.mustExist
if (typeof opts.mustExist !== "undefined") {
mustExist = opts.mustExist;
}
if (typeof opts.merge === 'function') {
if (typeof opts.merge === "function") {
merge = opts.merge;
}

let filePath;

if (typeof opts.filePath === 'string') {
const absPath = opts.filePath.startsWith('.') ? resolve(opts.filePath, input) : opts.filePath;
if (typeof opts.filePath === "string") {
const absPath = opts.filePath.startsWith(".")
? resolve(opts.filePath, input)
: opts.filePath;
if (existsSync(absPath)) {
filePath = absPath;
}
Expand Down Expand Up @@ -192,20 +208,40 @@ async function load(namespace, opts = {}) {

if (names.includes("package.json")) {
let file = join(dir, "package.json");
let _, contents = await toReadFile(file).then((r) => JSON.parse(r.toString()));
let _,
contents = await toReadFile(file).then((r) =>
JSON.parse(r.toString())
);
if (contents[namespace]) return "package.json";
}
});
}

if (mustExist) {
assert(!!filePath, `Unable to resolve a ${namespace} configuration`, 'ERR_PROLOAD_NOT_FOUND');
assert(
!!filePath,
`Unable to resolve a ${namespace} configuration`,
"ERR_PROLOAD_NOT_FOUND"
);
} else if (!filePath) {
return;
}

let rawValue = await requireOrImportWithMiddleware(filePath);
if (filePath.endsWith('package.json')) rawValue = rawValue[namespace];
if (filePath.endsWith("package.json")) rawValue = rawValue[namespace];
const hasExport = ('default' in rawValue);
if (!hasExport) {
if (mustExist) {
assert(
true,
`Resolved a ${namespace} configuration, but no configuration was exported`,
"ERR_PROLOAD_NOT_FOUND"
);
} else {
return;
}
}

const resolvedValue = await resolveExtensions(namespace, {
filePath,
value: rawValue,
Expand All @@ -223,9 +259,10 @@ const defaultPlugins = [
{
name: "@proload/extract-default",
transform(mdl) {
if (typeof mdl === "undefined") return mdl;
if (mdl.default && Object.keys(mdl).length === 1) {
return mdl.default;
};
}

return mdl;
},
Expand Down
15 changes: 15 additions & 0 deletions packages/core/test/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ test('missing but mustExist (default)', async () => {
is(err, 1);
});

test('empty but not mustExist', async () => {
let mdl = await load('test', { cwd: resolve(`fixtures/empty`), mustExist: false });
type(mdl, 'undefined')
});

test('empty but mustExist (default)', async () => {
let err = 0;
try {
let mdl = await load('test', { cwd: resolve(`fixtures/empty`) });
} catch (e) {
err += 1;
}
is(err, 1);
});

test('missing but not mustExist', async () => {
let mdl = await load('test', { cwd: resolve(`fixtures/missing`), mustExist: false });
type(mdl, 'undefined')
Expand Down