Rich-Harris / magic-string

Manipulate strings like a wizard

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

feat: Allow to edit sourcemap to move caret to a correct place.

hyrious opened this issue · comments

Originally evanw/esbuild#1886

Abstract
Sourcemap is about strings, it is not strictly bound to some language. However, tools that processing sourcemaps are expecting some mapping rules to be followed. If we can move the corresponding caret of source code in the generated code, we may be able to follow those rules.

Reproduction

  1. Consider we have a file written: (the | represents our caret).

    |<div>hello</div>

  2. We edit that source into the form export default templ(…).

    export default templ(`|<div>hello</div>`)

  3. Now something bad happens: if templ throws any error or just print something to the console, Chrome, Firefox and node won't generate correct location.

    This is easy to explain: the runtime captures an error thrown from templ, it then look for the source location from the sourcemap. However, it can not find a location because it did not find a caret around the templ token, either at left ( |templ ) or at right ( templ| ).

  4. The solution is moving that caret to the left of templ, or even more left to export. Because the runtime has the whole AST, it knows where to stop searching.

API Advice
I currently have no good design to this feature. Ideally the carets may increase if we split the input into parts. It's not obvious to find a way to manipulate them.