withastro / prettier-plugin-astro

Prettier plugin for Astro
Other
479 stars 36 forks source link

πŸ› BUG: <script> formatting broken in files containing multi-byte characters #405

Closed Garmelon closed 8 months ago

Garmelon commented 9 months ago

Describe the Bug

When trying to format an utf-8 encoded file that contains characters above code point 0x7f and that contains a multi-line <script> tag, formatting fails with a SyntaxError. The error shows lines that differ from the lines in the file.

Note that a single-line script tag like <script></script> does not necessarily trigger the issue.

Steps to Reproduce

  1. Create the following astro file:
    
    Hello wΓΆrld.

2. Try formatting it with `prettier` and `prettier-plugin-astro`
3. Observe the following error:

src/example.astro [error] src/example.astro: SyntaxError: Unterminated regular expression. (3:2) [error] 1 | [error] 2 | [error] > 3 | /script> [error] | ^ [error] 4 |


Expected outcome: The file is formatted and looks like this:
```astro
Hello wΓΆrld.

<script></script>
Garmelon commented 9 months ago

A character seems to be replaced by a newline. Exactly which character depends on the amount of "extra bytes" in the file. With a single extra byte, the first character of </script> is affected. With two extra characters, the second character of </script> is affected, and so on.

We can confirm this using the ΓΆ and € characters. In utf-8, ΓΆ is two bytes large while € is three bytes large. Thus, a file containing € (2 extra bytes) and a file containing ΓΆΓΆ (2 extra bytes) should result in the same error message, and they do:

€
<script>
</script>
ΓΆΓΆ
<script>
</script>
[error] src/example.astro: SyntaxError: Unterminated JSX contents. (3:8)
[error]   1 |
[error]   2 | <
[error] > 3 | script>
[error]     |        ^
[error]   4 |

Adding more extra bytes moves the affected character along further:

ΓΆΓΆΓΆΓΆΓΆΓΆΓΆ
<script>
</script>
[error] src/example.astro: SyntaxError: Unexpected token (2:2)
[error]   1 |
[error] > 2 | </scri
[error]     |  ^
[error]   3 | t>
[error]   4 |

If the script tag is not empty, its contents are similarly affected:

ΓΆΓΆΓΆ
<script>
"hello"
"world"
</script>
[error] src/example.astro: SyntaxError: Unterminated string constant. (2:1)
[error]   1 |
[error] > 2 | "h
[error]     | ^
[error]   3 | "hello"
[error]   4 | "world"
[error]   5 | cript>
Princesseuh commented 9 months ago

Weird, not too sure where that comes from. Quite likely to be a Astro compiler bug.

Thank you for reporting this issue! I'll investigate asap.

Garmelon commented 8 months ago

This appears to be the fault of the latest version of the https://github.com/neokidev/prettier-plugin-astro-organize-imports plugin. Without it, or with version 0.3.3, everything formats correctly. Closing this issue in favor of https://github.com/neokidev/prettier-plugin-astro-organize-imports/issues/105.