Skip to content
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- Fix JS rewriting of `this.<prop>` so it reliably detects a leading newline (and prepends the needed `;`) regardless of the amount of whitespace, and no longer wrongly rewrites `this` when preceded by `.`/`$` and several spaces (#381)

## [5.5.2] - 2026-11-06

### Fixed
Expand Down
45 changes: 31 additions & 14 deletions src/zimscraperlib/rewriting/js.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,19 +123,38 @@ def replace_this_prop() -> TransformationAction:
"""
Create a rewrite_function replacing "this" by `this_rw`.

Replacement happen only if "this" is not a property of an object.
Replacement happens only if "this" is not a property of an object, i.e. if there
is a previous token, and it is not "." or "$", once whitespace (including
newlines) in between is skipped over. The previous token is looked up in the
full original string rather than just the match, because another rule earlier
in `create_js_rules` may already have consumed (as part of an unrelated match)
whatever directly preceded that whitespace, e.g. the "=" in
`const location = this.location` is consumed by the `let/const location =`
passthrough rule.

If that skipped whitespace contains a newline, a semi-colon is also prepended.
This guards against a JavaScript Automatic Semicolon Insertion (ASI) pitfall:
`this_rw` starts with an identifier immediately followed by `(`, so if it
starts a new line right after a statement with no trailing `;`, JS would
otherwise parse it as a call of whatever the previous statement evaluated to
(e.g. `a = 5\nthis.x = 1` would silently become `a = 5(this.x = 1)`).
"""

def f(m_object: re.Match[str], _opts: dict[str, Any] | None) -> str:
offset = m_object.start()
first_char = m_object.string[offset - 1] if offset > 0 else ""
if first_char == "\n":
# This detection of new line is probably buggy, plus it is hard to get the
# intent of this, see https://github.com/openzim/warc2zim/issues/410
full_string = m_object.string
pos = m_object.start() - 1
has_newline = False
while pos >= 0 and full_string[pos].isspace():
has_newline = has_newline or full_string[pos] == "\n"
pos -= 1
if pos < 0 or full_string[pos] in ".$":
# No real previous token (start of script) is treated like "." or "$":
# kept as-is, consistent with this rule never firing on the very first
# token of a script.
return m_object[0]
if has_newline:
return m_object[0].replace("this", ";" + this_rw)
if first_char not in ".$":
return m_object[0].replace("this", this_rw)
return m_object[0]
return m_object[0].replace("this", this_rw)

return f

Expand Down Expand Up @@ -208,12 +227,10 @@ def create_js_rules() -> list[TransformationRule]:
),
# rewriting `return this`
(re.compile(r"\breturn\s+this\b\s*(?![\s\w.$])"), replace_this()),
# rewriting `this.` special porperties access on new line, with ; perpended
# if prev chars is `\n`, or if prev is not `.` or `$`, no semi
# rewriting `this.` special properties access: see replace_this_prop for
# when it does or does not rewrite
(
re.compile(
rf"[^$.]\s?\bthis\b(?=(?:\.(?:{'|'.join(GLOBAL_OVERRIDES)})\b))"
),
re.compile(rf"\bthis\b(?=(?:\.(?:{'|'.join(GLOBAL_OVERRIDES)})\b))"),
replace_this_prop(),
),
# rewrite `= this` or `, this`
Expand Down
16 changes: 11 additions & 5 deletions tests/rewriting/test_js_rewriting.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ def test_this_js_rewrite(
params=[
"aaa.this.window=red",
"aaa. this.window=red",
"aaa. this.window=red",
"aaa$this.window=red",
"aaa$ this.window=red",
"a = this.color;",
"return this.color",
'func(Function("return this.color"));',
Expand All @@ -79,12 +81,16 @@ def test_this_no_js_rewrite(
)


# This test probably has to be fixed but spec is blurry
# See https://github.com/openzim/warc2zim/issues/410
def test_this_js_rewrite_newline(simple_js_rewriter: JsRewriter):
@pytest.mark.parametrize(
"spaces",
[0, 1, 2, 3, 4],
)
def test_this_js_rewrite_newline(simple_js_rewriter: JsRewriter, spaces: int):
padding = " " * spaces
assert (
simple_js_rewriter.rewrite("aaa\n this.window=red")
== "aaa\n ;_____WB$wombat$check$this$function_____(this).window=red"
simple_js_rewriter.rewrite(f"aaa\n{padding}this.window=red")
== f"aaa\n{padding};_____WB$wombat$check$this$function_____(this)"
".window=red"
)


Expand Down