| 1 |
// Copyright 2021-2026 Buf Technologies, Inc. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
// Native Uint8Array.prototype.setFromBase64, if the runtime provides it. |
| 15 |
const nativeSetFromBase64 = Uint8Array.prototype.setFromBase64; |
| 16 |
/** |
| 17 |
* Decodes a base64 string to a byte array. |
| 18 |
* |
| 19 |
* - ignores white-space, including line breaks and tabs |
| 20 |
* - allows inner padding (can decode concatenated base64 strings) |
| 21 |
* - does not require padding |
| 22 |
* - understands base64url encoding: |
| 23 |
* "-" instead of "+", |
| 24 |
* "_" instead of "/", |
| 25 |
* no padding |
| 26 |
*/ |
| 27 |
export function base64Decode(base64Str) { |
| 28 |
const len = base64Str.length; |
| 29 |
// Decoded size, assuming a well-formed string: three bytes per group of |
| 30 |
// four characters, minus one byte for each padding character. |
| 31 |
let size = len - ((len + 3) >> 2); |
| 32 |
if ((len & 3) == 0 && base64Str[len - 1] == "=") { |
| 33 |
size -= base64Str[len - 2] == "=" ? 2 : 1; |
| 34 |
} |
| 35 |
const bytes = new Uint8Array(size); |
| 36 |
let written = -1; |
| 37 |
if (nativeSetFromBase64) { |
| 38 |
try { |
| 39 |
const result = nativeSetFromBase64.call(bytes, base64Str); |
| 40 |
if (result.read == len) { |
| 41 |
written = result.written; |
| 42 |
} |
| 43 |
} |
| 44 |
catch (_a) { |
| 45 |
// The native decoder rejects base64url and inner padding, which we accept. |
| 46 |
} |
| 47 |
} |
| 48 |
if (written < 0) { |
| 49 |
written = setFromBase64(bytes, base64Str); |
| 50 |
} |
| 51 |
return written == size ? bytes : bytes.subarray(0, written); |
| 52 |
} |
| 53 |
/** Writes into `bytes` from index 0 and returns the number of bytes written. */ |
| 54 |
function setFromBase64(bytes, base64Str) { |
| 55 |
const table = getDecodeTable(); |
| 56 |
let bytePos = 0, // position in byte array |
| 57 |
groupPos = 0, // position in base64 group |
| 58 |
b, // current byte |
| 59 |
p = 0; // previous byte |
| 60 |
for (let i = 0; i < base64Str.length; i++) { |
| 61 |
b = table[base64Str.charCodeAt(i)]; |
| 62 |
if (b === undefined) { |
| 63 |
switch (base64Str[i]) { |
| 64 |
// @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true |
| 65 |
case "=": |
| 66 |
groupPos = 0; // reset state when padding found |
| 67 |
case "\n": |
| 68 |
case "\r": |
| 69 |
case "\t": |
| 70 |
case " ": |
| 71 |
continue; // skip white-space, and padding |
| 72 |
default: |
| 73 |
throw Error("invalid base64 string"); |
| 74 |
} |
| 75 |
} |
| 76 |
switch (groupPos) { |
| 77 |
case 0: |
| 78 |
p = b; |
| 79 |
groupPos = 1; |
| 80 |
break; |
| 81 |
case 1: |
| 82 |
bytes[bytePos++] = (p << 2) | ((b & 48) >> 4); |
| 83 |
p = b; |
| 84 |
groupPos = 2; |
| 85 |
break; |
| 86 |
case 2: |
| 87 |
bytes[bytePos++] = ((p & 15) << 4) | ((b & 60) >> 2); |
| 88 |
p = b; |
| 89 |
groupPos = 3; |
| 90 |
break; |
| 91 |
case 3: |
| 92 |
bytes[bytePos++] = ((p & 3) << 6) | b; |
| 93 |
groupPos = 0; |
| 94 |
break; |
| 95 |
} |
| 96 |
} |
| 97 |
if (groupPos == 1) |
| 98 |
throw Error("invalid base64 string"); |
| 99 |
return bytePos; |
| 100 |
} |
| 101 |
const nativeToBase64 = Uint8Array.prototype.toBase64; |
| 102 |
const toBase64OptionsMap = { |
| 103 |
std: { alphabet: "base64", omitPadding: false }, |
| 104 |
std_raw: { alphabet: "base64", omitPadding: true }, |
| 105 |
url: { alphabet: "base64url", omitPadding: true }, |
| 106 |
}; |
| 107 |
/** |
| 108 |
* Encode a byte array to a base64 string. |
| 109 |
* |
| 110 |
* By default, this function uses the standard base64 encoding with padding. |
| 111 |
* |
| 112 |
* To encode without padding, use encoding = "std_raw". |
| 113 |
* |
| 114 |
* To encode with the URL encoding, use encoding = "url", which replaces the |
| 115 |
* characters +/ by their URL-safe counterparts -_, and omits padding. |
| 116 |
*/ |
| 117 |
export function base64Encode(bytes, encoding = "std") { |
| 118 |
if (nativeToBase64) { |
| 119 |
return nativeToBase64.call(bytes, toBase64OptionsMap[encoding]); |
| 120 |
} |
| 121 |
const table = getEncodeTable(encoding); |
| 122 |
const pad = encoding == "std"; |
| 123 |
let base64 = "", groupPos = 0, // position in base64 group |
| 124 |
b, // current byte |
| 125 |
p = 0; // carry over from previous byte |
| 126 |
for (let i = 0; i < bytes.length; i++) { |
| 127 |
b = bytes[i]; |
| 128 |
switch (groupPos) { |
| 129 |
case 0: |
| 130 |
base64 += table[b >> 2]; |
| 131 |
p = (b & 3) << 4; |
| 132 |
groupPos = 1; |
| 133 |
break; |
| 134 |
case 1: |
| 135 |
base64 += table[p | (b >> 4)]; |
| 136 |
p = (b & 15) << 2; |
| 137 |
groupPos = 2; |
| 138 |
break; |
| 139 |
case 2: |
| 140 |
base64 += table[p | (b >> 6)]; |
| 141 |
base64 += table[b & 63]; |
| 142 |
groupPos = 0; |
| 143 |
break; |
| 144 |
} |
| 145 |
} |
| 146 |
// add output padding |
| 147 |
if (groupPos) { |
| 148 |
base64 += table[p]; |
| 149 |
if (pad) { |
| 150 |
base64 += "="; |
| 151 |
if (groupPos == 1) |
| 152 |
base64 += "="; |
| 153 |
} |
| 154 |
} |
| 155 |
return base64; |
| 156 |
} |
| 157 |
// lookup table from base64 character to byte |
| 158 |
let encodeTableStd; |
| 159 |
let encodeTableUrl; |
| 160 |
// lookup table from base64 character *code* to byte because lookup by number is fast |
| 161 |
let decodeTable; |
| 162 |
function getEncodeTable(encoding) { |
| 163 |
if (!encodeTableStd) { |
| 164 |
encodeTableStd = |
| 165 |
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); |
| 166 |
encodeTableUrl = encodeTableStd.slice(0, -2).concat("-", "_"); |
| 167 |
} |
| 168 |
return encoding == "url" |
| 169 |
? // biome-ignore lint/style/noNonNullAssertion: TS fails to narrow down |
| 170 |
encodeTableUrl |
| 171 |
: encodeTableStd; |
| 172 |
} |
| 173 |
function getDecodeTable() { |
| 174 |
if (!decodeTable) { |
| 175 |
decodeTable = []; |
| 176 |
const encodeTable = getEncodeTable("std"); |
| 177 |
for (let i = 0; i < encodeTable.length; i++) |
| 178 |
decodeTable[encodeTable[i].charCodeAt(0)] = i; |
| 179 |
// support base64url variants |
| 180 |
decodeTable["-".charCodeAt(0)] = encodeTable.indexOf("+"); |
| 181 |
decodeTable["_".charCodeAt(0)] = encodeTable.indexOf("/"); |
| 182 |
} |
| 183 |
return decodeTable; |
| 184 |
} |