(str: string)
| 172 | * @since 2.0.0 |
| 173 | */ |
| 174 | export const decodeBase64 = (str: string): Result.Result<Uint8Array, EncodingError> => { |
| 175 | const stripped = stripCrlf(str) |
| 176 | const length = stripped.length |
| 177 | if (length % 4 !== 0) { |
| 178 | return Result.fail( |
| 179 | new EncodingError({ |
| 180 | kind: "Decode", |
| 181 | module: "Base64", |
| 182 | input: stripped, |
| 183 | message: `Length must be a multiple of 4, but is ${length}` |
| 184 | }) |
| 185 | ) |
| 186 | } |
| 187 | |
| 188 | const index = stripped.indexOf("=") |
| 189 | if (index !== -1 && ((index < length - 2) || (index === length - 2 && stripped[length - 1] !== "="))) { |
| 190 | return Result.fail( |
| 191 | new EncodingError({ |
| 192 | kind: "Decode", |
| 193 | module: "Base64", |
| 194 | input: stripped, |
| 195 | message: `Found a '=' character, but it is not at the end` |
| 196 | }) |
| 197 | ) |
| 198 | } |
| 199 | |
| 200 | try { |
| 201 | const missingOctets = stripped.endsWith("==") ? 2 : stripped.endsWith("=") ? 1 : 0 |
| 202 | const result = new Uint8Array(3 * (length / 4) - missingOctets) |
| 203 | for (let i = 0, j = 0; i < length; i += 4, j += 3) { |
| 204 | const buffer = getBase64Code(stripped.charCodeAt(i)) << 18 | |
| 205 | getBase64Code(stripped.charCodeAt(i + 1)) << 12 | |
| 206 | getBase64Code(stripped.charCodeAt(i + 2)) << 6 | |
| 207 | getBase64Code(stripped.charCodeAt(i + 3)) |
| 208 | |
| 209 | result[j] = buffer >> 16 |
| 210 | result[j + 1] = (buffer >> 8) & 0xff |
| 211 | result[j + 2] = buffer & 0xff |
| 212 | } |
| 213 | |
| 214 | return Result.succeed(result) |
| 215 | } catch (e) { |
| 216 | return Result.fail( |
| 217 | new EncodingError({ |
| 218 | kind: "Decode", |
| 219 | module: "Base64", |
| 220 | input: stripped, |
| 221 | message: e instanceof Error ? e.message : "Invalid input" |
| 222 | }) |
| 223 | ) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /** |
| 228 | * Decodes a base64 (RFC4648) string into a UTF-8 string safely. |
no test coverage detected