Skip to content

Commit

Permalink
Fix #91
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelXF committed Jul 3, 2023
1 parent 5013a4f commit bc9b441
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
14 changes: 14 additions & 0 deletions src/templates/functionLength.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import Template from "./template";

/**
* Helper function to set `function.length` property.
*/
export const FunctionLengthTemplate = Template(`
function {name}(functionObject, functionLength){
Object["defineProperty"](functionObject, "length", {
"value": functionLength,
"configurable": true
});
return functionObject;
}
`);
13 changes: 11 additions & 2 deletions src/transforms/minify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
isForInitialize,
append,
isVarContext,
computeFunctionLength,
} from "../util/insert";
import { isValidIdentifier, isEquivalent } from "../util/compare";
import { walk, isBlock } from "../traverse";
Expand Down Expand Up @@ -258,8 +259,15 @@ export default class Minify extends Transform {
append(
parents[parents.length - 1] || object,
Template(`
function ${this.arrowFunctionName}(arrowFn){
return function(){ return arrowFn(...arguments) }
function ${this.arrowFunctionName}(arrowFn, functionLength){
var functionObject = function(){ return arrowFn(...arguments) };
Object["defineProperty"](functionObject, "length", {
"value": functionLength,
"configurable": true
});
return functionObject;
}
`).single()
);
Expand All @@ -268,6 +276,7 @@ export default class Minify extends Transform {
const wrap = (object: Node) => {
return CallExpression(Identifier(this.arrowFunctionName), [
clone(object),
Literal(computeFunctionLength(object.params)),
]);
};

Expand Down
19 changes: 19 additions & 0 deletions test/transforms/minify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,3 +517,22 @@ test("Variant #26: Don't break nested redefined function declaration", async ()

expect(TEST_OUTPUT).toStrictEqual(1);
});

// https://github.com/MichaelXF/js-confuser/issues/91
test("Variant #27: Preserve function.length property", async () => {
var output = await JsConfuser(
`
function oneParameter(a){};
var twoParameters = function({a},{b,c},...d){};
function threeParameters(a,b,c,d = 1,{e},...f){};
TEST_OUTPUT = oneParameter.length + twoParameters.length + threeParameters.length;
`,
{ target: "node", minify: true }
);

var TEST_OUTPUT;
eval(output);

expect(TEST_OUTPUT).toStrictEqual(6);
});

0 comments on commit bc9b441

Please sign in to comment.