| 1 | /** |
| 2 | * Base64 encoding and decoding helpers. |
| 3 | * |
| 4 | * @since 4.0.0 |
| 5 | */ |
| 6 | import * as Result from "../Result.ts" |
| 7 | import { EncodingError } from "./EncodingError.ts" |
| 8 | |
| 9 | /** |
| 10 | * Encodes the given value into a Base64 (RFC 4648) string. |
| 11 | * |
| 12 | * **When to use** |
| 13 | * |
| 14 | * Use to encode text or bytes as a standard padded Base64 string for storage or |
| 15 | * transport. |
| 16 | * |
| 17 | * **Details** |
| 18 | * |
| 19 | * String inputs are encoded as UTF-8 bytes before Base64 encoding. |
| 20 | * `Uint8Array` inputs are encoded directly. The output uses the standard |
| 21 | * RFC 4648 alphabet with `=` padding. |
| 22 | * |
| 23 | * **Example** (Encoding Base64 strings and bytes) |
| 24 | * |
| 25 | * ```ts import.meta.vitest |
| 26 | * import { Base64 } from "effect/encoding" |
| 27 | * |
| 28 | * Base64.encode("hello") // => "aGVsbG8=" |
| 29 | * |
| 30 | * const bytes = new Uint8Array([72, 101, 108, 108, 111]) |
| 31 | * Base64.encode(bytes) // => "SGVsbG8=" |
| 32 | * ``` |
| 33 | * |
| 34 | * @see {@link decode} for decoding standard Base64 to bytes |
| 35 | * @see {@link decodeString} for decoding standard Base64 to UTF-8 text |
| 36 | * |
| 37 | * @category encoding |
| 38 | * @since 4.0.0 |
| 39 | */ |
| 40 | export const encode: (input: Uint8Array | string) => string = (input) => |
| 41 | encodeBytes(typeof input === "string" ? encoder.encode(input) : input) |
| 42 | |
| 43 | /** |
| 44 | * Decodes a Base64 (RFC 4648) string into bytes safely. |
| 45 | * |
| 46 | * **When to use** |
| 47 | * |
| 48 | * Use to decode a standard padded Base64 string into bytes without throwing on |
| 49 | * invalid input. |
| 50 | * |
| 51 | * **Details** |
| 52 | * |
| 53 | * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or |
| 54 | * `Result.fail` with an `EncodingError` when the input is not valid Base64. |
| 55 | * |
| 56 | * **Example** (Decoding Base64 bytes) |
| 57 | * |
| 58 | * ```ts import.meta.vitest |
| 59 | * import { Result } from "effect" |
| 60 | * import { Base64 } from "effect/encoding" |
| 61 | * |
| 62 | * Base64.decode("SGVsbG8=") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111])) |
| 63 | * ``` |
| 64 | * |
| 65 | * @category decoding |
| 66 | * @since 4.0.0 |
| 67 | */ |
| 68 | export const decode = (str: string): Result.Result<Uint8Array, EncodingError> => { |
| 69 | const stripped = stripCrlf(str) |
| 70 | const length = stripped.length |
| 71 | if (length % 4 !== 0) { |
| 72 | return Result.fail( |
| 73 | new EncodingError({ |
| 74 | kind: "Decode", |
| 75 | module: "Base64", |
| 76 | input: stripped, |
| 77 | message: `Length must be a multiple of 4, but is ${length}` |
| 78 | }) |
| 79 | ) |
| 80 | } |
| 81 | |
| 82 | const index = stripped.indexOf("=") |
| 83 | if (index !== -1 && ((index < length - 2) || (index === length - 2 && stripped[length - 1] !== "="))) { |
| 84 | return Result.fail( |
| 85 | new EncodingError({ |
| 86 | kind: "Decode", |
| 87 | module: "Base64", |
| 88 | input: stripped, |
| 89 | message: "Found a '=' character, but it is not at the end" |
| 90 | }) |
| 91 | ) |
| 92 | } |
| 93 | |
| 94 | try { |
| 95 | const missingOctets = stripped.endsWith("==") ? 2 : stripped.endsWith("=") ? 1 : 0 |
| 96 | const result = new Uint8Array(3 * (length / 4) - missingOctets) |
| 97 | for (let i = 0, j = 0; i < length; i += 4, j += 3) { |
| 98 | const buffer = getCode(stripped.charCodeAt(i)) << 18 | |
| 99 | getCode(stripped.charCodeAt(i + 1)) << 12 | |
| 100 | getCode(stripped.charCodeAt(i + 2)) << 6 | |
| 101 | getCode(stripped.charCodeAt(i + 3)) |
| 102 | result[j] = buffer >> 16 |
| 103 | result[j + 1] = (buffer >> 8) & 0xff |
| 104 | result[j + 2] = buffer & 0xff |
| 105 | } |
| 106 | return Result.succeed(result) |
| 107 | } catch (cause) { |
| 108 | return Result.fail( |
| 109 | new EncodingError({ |
| 110 | kind: "Decode", |
| 111 | module: "Base64", |
| 112 | input: stripped, |
| 113 | message: cause instanceof Error ? cause.message : "Invalid input" |
| 114 | }) |
| 115 | ) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /** |
| 120 | * Decodes a Base64 (RFC 4648) string into UTF-8 text safely. |
| 121 | * |
| 122 | * **When to use** |
| 123 | * |
| 124 | * Use to decode a standard padded Base64 string into UTF-8 text without |
| 125 | * throwing on invalid input. |
| 126 | * |
| 127 | * **Details** |
| 128 | * |
| 129 | * Returns `Result.succeed` with the decoded text when decoding succeeds, or |
| 130 | * `Result.fail` with an `EncodingError` when the input is not valid Base64. |
| 131 | * |
| 132 | * **Example** (Decoding Base64 strings) |
| 133 | * |
| 134 | * ```ts import.meta.vitest |
| 135 | * import { Result } from "effect" |
| 136 | * import { Base64 } from "effect/encoding" |
| 137 | * |
| 138 | * Base64.decodeString("aGVsbG8=") // => Result.succeed("hello") |
| 139 | * ``` |
| 140 | * |
| 141 | * @category decoding |
| 142 | * @since 4.0.0 |
| 143 | */ |
| 144 | export const decodeString = (str: string) => Result.map(decode(str), (_) => decoder.decode(_)) |
| 145 | |
| 146 | const encodeBytes = (bytes: Uint8Array): string => { |
| 147 | const length = bytes.length |
| 148 | let result = "" |
| 149 | let i: number |
| 150 | for (i = 2; i < length; i += 3) { |
| 151 | result += alphabet[bytes[i - 2] >> 2] |
| 152 | result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)] |
| 153 | result += alphabet[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)] |
| 154 | result += alphabet[bytes[i] & 0x3f] |
| 155 | } |
| 156 | if (i === length + 1) { |
| 157 | result += alphabet[bytes[i - 2] >> 2] |
| 158 | result += alphabet[(bytes[i - 2] & 0x03) << 4] |
| 159 | result += "==" |
| 160 | } |
| 161 | if (i === length) { |
| 162 | result += alphabet[bytes[i - 2] >> 2] |
| 163 | result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)] |
| 164 | result += alphabet[(bytes[i - 1] & 0x0f) << 2] |
| 165 | result += "=" |
| 166 | } |
| 167 | return result |
| 168 | } |
| 169 | |
| 170 | const encoder = new TextEncoder() |
| 171 | const decoder = new TextDecoder() |
| 172 | const stripCrlf = (str: string) => str.replace(/[\n\r]/g, "") |
| 173 | const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" |
| 174 | const codes = new Uint8Array(123).fill(255) |
| 175 | for (let i = 0; i < alphabet.length; i++) codes[alphabet.charCodeAt(i)] = i |
| 176 | codes["=".charCodeAt(0)] = 0 |
| 177 | |
| 178 | const getCode = (charCode: number): number => { |
| 179 | if (charCode >= codes.length || codes[charCode] === 255) { |
| 180 | throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`) |
| 181 | } |
| 182 | return codes[charCode] |
| 183 | } |