From 497787bb2ec7e517928b94aae3917f1d4787653b Mon Sep 17 00:00:00 2001 From: fraxken Date: Sun, 21 Jul 2024 22:07:22 +0200 Subject: [PATCH] fix(isOneLineRequire): must return true for a one line require with no export --- src/utils/isOneLineExpressionExport.js | 18 ++++++++++++------ .../283-oneline-require-minified.spec.js | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) create mode 100644 test/issues/283-oneline-require-minified.spec.js diff --git a/src/utils/isOneLineExpressionExport.js b/src/utils/isOneLineExpressionExport.js index 3c133d8..0ea1ca4 100644 --- a/src/utils/isOneLineExpressionExport.js +++ b/src/utils/isOneLineExpressionExport.js @@ -2,17 +2,23 @@ import { exportAssignmentHasRequireLeave } from "./exportAssignmentHasRequireLeave.js"; export function isOneLineExpressionExport(body) { - if (body.length > 1) { + if (body.length === 0 || body.length > 1) { return false; } - if (body[0].type !== "ExpressionStatement") { + const [firstNode] = body; + if (firstNode.type !== "ExpressionStatement") { return false; } - if (body[0].expression.type !== "AssignmentExpression") { - return false; + switch (firstNode.expression.type) { + // module.exports = require('...'); + case "AssignmentExpression": + return exportAssignmentHasRequireLeave(firstNode.expression.right); + // require('...'); + case "CallExpression": + return exportAssignmentHasRequireLeave(firstNode.expression); + default: + return false; } - - return exportAssignmentHasRequireLeave(body[0].expression.right); } diff --git a/test/issues/283-oneline-require-minified.spec.js b/test/issues/283-oneline-require-minified.spec.js new file mode 100644 index 0000000..4843168 --- /dev/null +++ b/test/issues/283-oneline-require-minified.spec.js @@ -0,0 +1,19 @@ +// Import Node.js Dependencies +import { test } from "node:test"; +import assert from "node:assert"; + +// Import Internal Dependencies +import { runASTAnalysis } from "../../index.js"; + +// Regression test for https://github.com/NodeSecure/js-x-ray/issues/283 +test("Given a one line require (with no module.exports) then isOneLineRequire must equal true", () => { + const { isOneLineRequire } = runASTAnalysis(`require('foo.js');`); + + assert.ok(isOneLineRequire); +}); + +test("Given an empty code then isOneLineRequire must equal false", () => { + const { isOneLineRequire } = runASTAnalysis(``); + + assert.strictEqual(isOneLineRequire, false); +});