diff --git a/src/engine.ts b/src/engine.ts index 4934f165..edbb03d5 100644 --- a/src/engine.ts +++ b/src/engine.ts @@ -935,7 +935,9 @@ function dynamicReplacement( const _pipe = _config_rr.pipedData, _text = _data_rr, _find = _config_rr.pattern, - code_rr = _config_rr.replacementOri, + // The code of the user is in a block of its own, so it can declare the same names with let and const. + // The value of the block is the value of its last statement, like before. The line break ends a comment at the end. + code_rr = '{' + _config_rr.replacementOri + '\n}', _cwd = process.cwd(), _now = _time, _ = ' ', diff --git a/test/fix/815.test.js b/test/fix/815.test.js new file mode 100644 index 00000000..3c882816 --- /dev/null +++ b/test/fix/815.test.js @@ -0,0 +1,23 @@ +// https://github.com/mathiasrw/rexreplace/issues/815 +// The numbers and the named groups were made with var in front of the code, so code that declared the same name with let or const did not run. +import {describe, test, expect} from 'bun:test'; +import {rr} from '../helper.js'; + +describe('#815 --js code can declare its own variables', () => { + test.each([ + ['a cousin with const', 'o', 'const $n00 = "C"; $n00', 'fCC'], + ['a number with var, as before', 'o', 'var $t = "V"; $t', 'fVV'], + ['a function', 'o', 'function $t() { return "F"; } $t()', 'fFF'], + ['a number with let', 'o', 'let $t = "T"; $t', 'fTT'], + ['a group with const', '(o)', 'const $1 = "X"; $1', 'fXX'], + ['a named group with let', '(?o)', 'let _o = "N"; _o', 'fNN'], + ])('with the name of %s', async (name, pattern, code, out) => { + expect((await rr(pattern, code, {pipedData: 'foo', replacementJs: true})).out).toBe(out); + }); + + test('the value is still the value of the last statement, also with a comment at the end', async () => { + expect( + (await rr('o', 'const a = 1; a + 1 // two', {pipedData: 'foo', replacementJs: true})).out + ).toBe('f22'); + }); +});