UNPKG

sinch-rtc

Version:

RTC JavaScript/Web SDK

79 lines 2.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Base64Helper = void 0; const CryptoJS = require("crypto-js"); const _1 = require("./"); const Errors_1 = require("./Errors"); /** * Helps to work with Base64 transforms */ class Base64Helper { /** * Encodes input into Base64 string * @param v - input value, can be string, array or object */ static encode(v) { let str; // ensure input is a string if (typeof v !== "string") { if (_1.TypeHelper.isPlainObject(v) || _1.TypeHelper.isArray(v)) { str = JSON.stringify(v); } else { throw new Errors_1.ArgumentError("String to encode must be a string, a plain object or an array", (0, _1.nameof)(v)); } } else { str = v; } const wordsArray = CryptoJS.enc.Utf8.parse(str); const base64 = CryptoJS.enc.Base64.stringify(wordsArray); return this.makeURLSafe(base64); } /** * Encodes UTF8 value to Base64 not caring about URL safeness * @param s - input string to be encoded */ static encodeUnsafe(s) { const wordsArray = CryptoJS.enc.Utf8.parse(s); return CryptoJS.enc.Base64.stringify(wordsArray); } /** * * @param b - Input base64-encoded value as a string representation * @returns Crypto-JS specific structure of byte array */ static decode(b) { return CryptoJS.enc.Base64.parse(b); } /** * * @param b - Input base64-encoded value as a string representation * @returns Decoded UTF-8 string */ static decodeToString(b) { return CryptoJS.enc.Base64.parse(b).toString(CryptoJS.enc.Utf8); } /** * Removes padding from Base64 encoded string * @param u - */ static makeURLSafe(u) { // JWT RFC 7515 specifies that base64 encoding without padding should be used. return u.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } static decodeUrlSafeToUint8Array(base64) { const padding = "=".repeat((4 - (base64.length % 4)) % 4); return this.decodeToUint8Array(base64.replace(/-/g, "+").replace(/_/g, "/") + padding); } static decodeToUint8Array(base64) { const rawData = atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } } exports.Base64Helper = Base64Helper; //# sourceMappingURL=Base64.helper.js.map