Skip to content

Commit

Permalink
encoding: Fix unicode base64 encode/decode (#1599)
Browse files Browse the repository at this point in the history
  • Loading branch information
Procybit committed Aug 5, 2024
1 parent 44ad6f2 commit eafceab
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions extensions/encoding.js
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@
arguments: {
string: {
type: Scratch.ArgumentType.STRING,
defaultValue: btoa("apple"), // don't translate because btoa() will error in Chinese ...
defaultValue: this._btoa("apple"),
},
code: {
type: Scratch.ArgumentType.STRING,
Expand Down Expand Up @@ -572,7 +572,7 @@
string = Scratch.Cast.toString(string);
switch (code) {
case "Base64":
return btoa(string);
return this._btoa(string);
case "URL":
return encodeURIComponent(string);
}
Expand All @@ -583,7 +583,7 @@
switch (code) {
case "Base64":
try {
return atob(string);
return this._atob(string);
} catch (error) {
console.error("invalid base 64", error);
return "";
Expand Down Expand Up @@ -636,6 +636,18 @@
}
return string;
}
_btoa(unicode) {
let bytes = new TextEncoder().encode(unicode);
let binString = Array.from(bytes, (byte) =>
String.fromCodePoint(byte)
).join("");
return btoa(binString);
}
_atob(base64) {
let binString = atob(base64);
let bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
return new TextDecoder().decode(bytes);
}
}
Scratch.extensions.register(new Encoding());
})(Scratch);

0 comments on commit eafceab

Please sign in to comment.