Skip to content

Commit d4bf990

Browse files
Merge pull request #250 from SarahIsWeird/main
Fail script processing when reassignment to const variable is detected
2 parents 2ac9caf + 1bfca54 commit d4bf990

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/processScript/index.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,4 +444,9 @@ if (import.meta.vitest) {
444444
(0, eval)(`(${script})`)(import.meta.vitest)
445445
})
446446
}
447+
448+
const reassignmentTestSource = `export default () => { const i = 0; i = 1; }`
449+
expect(async (): Promise<any> => await processScript(reassignmentTestSource, { scriptName: true, minify: false }))
450+
.rejects
451+
.toThrowError(`Reassignment to const variable i is not allowed!`)
447452
}

src/processScript/transform.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -881,8 +881,22 @@ export function transform(
881881
parent.superClass = t.identifier(`Object`)
882882
},
883883
VariableDeclaration({ node: variableDeclaration }) {
884-
if (variableDeclaration.kind == `const`)
884+
if (variableDeclaration.kind == `const`) {
885885
variableDeclaration.kind = `let`
886+
variableDeclaration.extra = {
887+
...variableDeclaration.extra,
888+
usedToBeConst: true,
889+
}
890+
}
891+
},
892+
AssignmentExpression({ node: assignment, scope }) {
893+
const lhs = assignment.left
894+
if (lhs.type != `Identifier`) return
895+
896+
const binding = scope.getBinding(lhs.name)
897+
if (binding?.path?.parentPath?.node?.extra?.usedToBeConst) {
898+
throw new Error(`Reassignment to const variable ${lhs.name} is not allowed!`);
899+
}
886900
},
887901
ThisExpression: path => {
888902
path.replaceWith(t.identifier(`undefined`))

0 commit comments

Comments
 (0)