@ton.js/core
Version:
TonWeb - JavaScript API for TON blockchain
82 lines • 2.86 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.stringToBase64 = exports.base64toString = exports.isValidBase64 = exports.base64ToBytes = exports.bytesToBase64 = void 0;
const text_encoding_1 = require("./text-encoding");
/**
* Non-URL safe with optional padding.
* Taken from the JOI library sources.
*/
const validationRegex = (/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/);
/* istanbul ignore next */
const hasNodeBuffer = (typeof Buffer !== 'undefined' && (Buffer === null || Buffer === void 0 ? void 0 : Buffer.from));
function bytesToBase64(bytes) {
/* istanbul ignore else */
if (hasNodeBuffer) {
const proto = Buffer.prototype;
/* istanbul ignore else */
if (proto.base64Slice) {
// Using internal function, which performs much faster
return proto.base64Slice
.call(bytes, 0, bytes.length);
}
else {
// Using safe, but slower approach as a fallback
return Buffer.from(bytes)
.toString('base64');
}
}
else {
// Browser
return btoa(String.fromCharCode(...bytes));
}
}
exports.bytesToBase64 = bytesToBase64;
function base64ToBytes(base64) {
// [RFC 4648]:
// Implementations MUST reject the encoded data if it
// contains characters outside the base alphabet when
// interpreting base-encoded data.
validateBase64orThrow(base64);
/* istanbul ignore else */
if (hasNodeBuffer) {
// 1.6 times faster than browser implementation
return new Uint8Array(Buffer.from(base64, 'base64'));
}
else {
// Browser
const binaryString = atob(base64);
const length = binaryString.length;
const bytes = new Uint8Array(length);
for (let i = 0; i < length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
}
exports.base64ToBytes = base64ToBytes;
function isValidBase64(base64string) {
return validationRegex.test(base64string);
}
exports.isValidBase64 = isValidBase64;
/**
* @deprecated this function is no longer used by the library
* and will be removed in the future
*/
function base64toString(base64) {
return (0, text_encoding_1.bytesToString)(base64ToBytes(base64));
}
exports.base64toString = base64toString;
/**
* @deprecated this function is no longer used by the library
* and will be removed in the future
*/
function stringToBase64(text) {
return bytesToBase64((0, text_encoding_1.stringToBytes)(text));
}
exports.stringToBase64 = stringToBase64;
function validateBase64orThrow(base64string) {
if (!isValidBase64(base64string)) {
throw new Error(`Incorrect Base64 string`);
}
}
//# sourceMappingURL=base64.js.map