| 1 | // atob / btoa. |
| 2 | // Own IIFE: captures the host ops it needs, attaches to |
| 3 | // globalThis, exits. The $$-prefixed host ops stay defined |
| 4 | // for the life of the isolate — non-enumerable (see the ops |
| 5 | // macro in js.rs), not removed. DOMException is installed |
| 6 | // later, by harness.js, and is only referenced at call time. |
| 7 | (function () { |
| 8 | const _atob = $$atob; |
| 9 | const _btoa = $$btoa; |
| 10 | |
| 11 | // WHATWG infra: atob strips ASCII whitespace |
| 12 | // (U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, |
| 13 | // U+0020 SPACE) from input before decoding, and |
| 14 | // throws DOMException("InvalidCharacterError") on |
| 15 | // bad input (not a plain Error). The Rust op does |
| 16 | // neither — preprocess and re-wrap here. |
| 17 | globalThis.atob = (s) => { |
| 18 | s = String(s).replace(/[\t\n\f\r ]/g, ""); |
| 19 | try { |
| 20 | return _atob(s); |
| 21 | } catch (e) { |
| 22 | throw new DOMException( |
| 23 | e && e.message |
| 24 | ? String(e.message) |
| 25 | : "atob: invalid base64", |
| 26 | "InvalidCharacterError", |
| 27 | ); |
| 28 | } |
| 29 | }; |
| 30 | globalThis.btoa = (s) => { |
| 31 | s = String(s); |
| 32 | for (let i = 0; i < s.length; i++) { |
| 33 | if (s.charCodeAt(i) > 0xff) { |
| 34 | throw new DOMException( |
| 35 | "String contains a code point > U+00FF", |
| 36 | "InvalidCharacterError", |
| 37 | ); |
| 38 | } |
| 39 | } |
| 40 | return _btoa(s); |
| 41 | }; |
| 42 | })(); |