Skip to content

Support characters outside of the Latin1 range in Browser #154

@curran

Description

@curran

I came across this issue where if the source code passed into magic-string contains characters outside of the Latin1 range, e.g. Cyrillic, and the execution context is a browser (works fine in Node), then an error is thrown:

InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

I did some research and found a solution (in the context of a Rollup use case):

const rollupBundle = await rollup(inputOptions);
const { code, map } = await rollupBundle.generate(outputOptions);

// Monkey patch magic-string internals
// to support characters outside of the Latin1 range, e.g. Cyrillic.
const toString = map.toString.bind(map);
map.toString = () => unescape(encodeURIComponent(toString()));

// Inspired by https://github.com/rollup/rollup/issues/121
const codeWithSourceMap = code + '\n//# sourceMappingURL=' + map.toUrl();

Related reading:

I'd be happy to submit a PR incorporating this into magic-string, if there's interest.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions