Open History to see the last commit
1/**
2 * Encoding and decoding helpers for Base64, Base64Url, and hexadecimal text.
3 * The functions convert between strings, UTF-8 text, and `Uint8Array` bytes.
4 * Encode functions return strings directly, while decode functions return
5 * `Result.Result` so invalid input is reported as an `EncodingError` instead of
6 * being thrown.
7 *
8 * @since 4.0.0
9 */
10import * as Data from "./Data.ts"
11import { hasProperty } from "./Predicate.ts"
12import * as Result from "./Result.ts"
13
14// -------------------------------------------------------------------------------------
15// EncodingError
16// -------------------------------------------------------------------------------------
17
18/**
19 * Type identifier stored on `EncodingError` values and used by
20 * `isEncodingError`.
21 *
22 * **When to use**
23 *
24 * Use when implementing low-level `EncodingError`-compatible values that need
25 * to carry the runtime marker.
26 *
27 * **Details**
28 *
29 * This marker is part of the runtime representation of `EncodingError`. Prefer
30 * `isEncodingError` when narrowing unknown values.
31 *
32 * @see {@link isEncodingError} for the public guard that checks this marker
33 *
34 * @category type IDs
35 * @since 4.0.0
36 */
37export const EncodingErrorTypeId = "~effect/encoding/EncodingError" as const
38
39/**
40 * Literal type of the `EncodingErrorTypeId` marker.
41 *
42 * **When to use**
43 *
44 * Use to type the marker carried by `EncodingError` values.
45 *
46 * @category type IDs
47 * @since 4.0.0
48 */
49export type EncodingErrorTypeId = typeof EncodingErrorTypeId
50
51/**
52 * Error returned when an encoding or decoding operation cannot process its
53 * input.
54 *
55 * **When to use**
56 *
57 * Use when you need to handle or inspect failures from encoding or decoding
58 * operations.
59 *
60 * **Details**
61 *
62 * The error records whether the failure happened during encoding or decoding,
63 * which encoding module reported it, the original input, and a human-readable
64 * message.
65 *
66 * @see {@link isEncodingError} for checking whether a value is an EncodingError
67 * @category errors
68 * @since 4.0.0
69 */
70export class EncodingError extends Data.TaggedError("EncodingError")<{
71 kind: "Decode" | "Encode"
72 module: string
73 input: unknown
74 message: string
75}> {
76 /**
77 * Marks this value as an encoding or decoding error for runtime guards.
78 *
79 * **When to use**
80 *
81 * Use to identify `EncodingError` instances through `isEncodingError`.
82 *
83 * @since 4.0.0
84 */
85 readonly [EncodingErrorTypeId]: EncodingErrorTypeId = EncodingErrorTypeId
86}
87
88/**
89 * Checks whether a value is an `EncodingError`.
90 *
91 * **When to use**
92 *
93 * Use to narrow an unknown value before handling it as an `EncodingError` from
94 * encoding or decoding code.
95 *
96 * **Details**
97 *
98 * Returns `true` when the value carries the `EncodingErrorTypeId` marker and
99 * narrows the value to `EncodingError`.
100 *
101 * @see {@link EncodingError} for the structured error produced by failed
102 * encoding and decoding operations
103 *
104 * @category guards
105 * @since 4.0.0
106 */
107export const isEncodingError = (u: unknown): u is EncodingError => hasProperty(u, EncodingErrorTypeId)
108
109// -------------------------------------------------------------------------------------
110// Base64
111// -------------------------------------------------------------------------------------
112
113/**
114 * Encodes the given value into a base64 (RFC4648) `string`.
115 *
116 * **When to use**
117 *
118 * Use to encode text or bytes as a standard padded Base64 string for storage or
119 * transport.
120 *
121 * **Details**
122 *
123 * String inputs are encoded as UTF-8 bytes before Base64 encoding.
124 * `Uint8Array` inputs are encoded directly. The output uses the standard
125 * RFC4648 alphabet with `=` padding.
126 *
127 * **Example** (Encoding Base64 strings and bytes)
128 *
129 * ```ts import.meta.vitest
130 * import { Encoding } from "effect"
131 *
132 * // Encode a string
133 * Encoding.encodeBase64("hello") // => "aGVsbG8="
134 *
135 * // Encode binary data
136 * const bytes = new Uint8Array([72, 101, 108, 108, 111])
137 * Encoding.encodeBase64(bytes) // => "SGVsbG8="
138 * ```
139 *
140 * @see {@link decodeBase64} for decoding standard Base64 to bytes
141 * @see {@link decodeBase64String} for decoding standard Base64 to UTF-8 text
142 * @see {@link encodeBase64Url} for URL-safe unpadded Base64 output
143 *
144 * @category encoding
145 * @since 2.0.0
146 */
147export const encodeBase64: (input: Uint8Array | string) => string = (input) =>
148 typeof input === "string" ? base64EncodeUint8Array(encoder.encode(input)) : base64EncodeUint8Array(input)
149
150/**
151 * Decodes a base64 (RFC4648) string into bytes safely.
152 *
153 * **When to use**
154 *
155 * Use to decode a standard padded Base64 string into bytes without throwing on
156 * invalid input.
157 *
158 * **Details**
159 *
160 * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or
161 * `Result.fail` with an `EncodingError` when the input is not valid base64.
162 *
163 * **Example** (Decoding Base64 bytes)
164 *
165 * ```ts import.meta.vitest
166 * import { Encoding, Result } from "effect"
167 *
168 * Encoding.decodeBase64("SGVsbG8=") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111]))
169 * ```
170 *
171 * @category decoding
172 * @since 2.0.0
173 */
174export 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.
229 *
230 * **When to use**
231 *
232 * Use to decode a standard padded Base64 string into UTF-8 text without
233 * throwing on invalid input.
234 *
235 * **Details**
236 *
237 * Returns `Result.succeed` with the decoded text when decoding succeeds, or
238 * `Result.fail` with an `EncodingError` when the input is not valid base64.
239 *
240 * **Example** (Decoding Base64 strings)
241 *
242 * ```ts import.meta.vitest
243 * import { Encoding, Result } from "effect"
244 *
245 * Encoding.decodeBase64String("aGVsbG8=") // => Result.succeed("hello")
246 * ```
247 *
248 * @category decoding
249 * @since 2.0.0
250 */
251export const decodeBase64String = (str: string) => Result.map(decodeBase64(str), (_) => decoder.decode(_))
252
253// -------------------------------------------------------------------------------------
254// Base64Url
255// -------------------------------------------------------------------------------------
256
257/**
258 * Encodes the given value into a base64 (URL) `string`.
259 *
260 * **When to use**
261 *
262 * Use to encode text or bytes as an unpadded Base64Url string for contexts that
263 * require the URL-safe alphabet.
264 *
265 * **Details**
266 *
267 * String inputs are encoded as UTF-8 bytes before Base64Url encoding.
268 * `Uint8Array` inputs are encoded directly. The output removes `=` padding and
269 * replaces `+` with `-` and `/` with `_`.
270 *
271 * **Example** (Encoding URL-safe Base64)
272 *
273 * ```ts import.meta.vitest
274 * import { Encoding } from "effect"
275 *
276 * // URL-safe base64 encoding (uses - and _ instead of + and /)
277 * Encoding.encodeBase64Url("hello?") // => "aGVsbG8_"
278 *
279 * const bytes = new Uint8Array([72, 101, 108, 108, 111, 63])
280 * Encoding.encodeBase64Url(bytes) // => "SGVsbG8_"
281 * ```
282 *
283 * @see {@link decodeBase64Url} for decoding URL-safe Base64 to bytes
284 * @see {@link decodeBase64UrlString} for decoding URL-safe Base64 to UTF-8 text
285 * @see {@link encodeBase64} for standard padded Base64 output
286 *
287 * @category encoding
288 * @since 2.0.0
289 */
290export const encodeBase64Url: (input: Uint8Array | string) => string = (input) =>
291 typeof input === "string" ? base64UrlEncodeUint8Array(encoder.encode(input)) : base64UrlEncodeUint8Array(input)
292
293/**
294 * Decodes a URL-safe base64 string into bytes safely.
295 *
296 * **When to use**
297 *
298 * Use to decode padded or unpadded Base64Url text into bytes without throwing
299 * on invalid input.
300 *
301 * **Details**
302 *
303 * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or
304 * `Result.fail` with an `EncodingError` when the input is not valid URL-safe
305 * base64. Both padded and unpadded URL-safe base64 forms are accepted when
306 * otherwise valid.
307 *
308 * **Example** (Decoding URL-safe Base64 bytes)
309 *
310 * ```ts import.meta.vitest
311 * import { Encoding, Result } from "effect"
312 *
313 * Encoding.decodeBase64Url("SGVsbG8_") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111, 63]))
314 * ```
315 *
316 * @category decoding
317 * @since 2.0.0
318 */
319export const decodeBase64Url = (str: string): Result.Result<Uint8Array, EncodingError> => {
320 const stripped = stripCrlf(str)
321 const length = stripped.length
322 if (length % 4 === 1) {
323 return Result.fail(
324 new EncodingError({
325 module: "Base64Url",
326 kind: "Decode",
327 input: stripped,
328 message: `Length should be a multiple of 4, but is ${length}`
329 })
330 )
331 }
332
333 if (!/^[-_A-Z0-9]*?={0,2}$/i.test(stripped)) {
334 return Result.fail(
335 new EncodingError({
336 module: "Base64Url",
337 kind: "Decode",
338 input: stripped,
339 message: "Invalid input"
340 })
341 )
342 }
343
344 // Some variants allow or require omitting the padding '=' signs
345 let sanitized = length % 4 === 2 ? `${stripped}==` : length % 4 === 3 ? `${stripped}=` : stripped
346 sanitized = sanitized.replace(/-/g, "+").replace(/_/g, "/")
347
348 return decodeBase64(sanitized)
349}
350
351/**
352 * Decodes a URL-safe base64 string into a UTF-8 string safely.
353 *
354 * **When to use**
355 *
356 * Use to decode padded or unpadded Base64Url text into UTF-8 text without
357 * throwing on invalid input.
358 *
359 * **Details**
360 *
361 * Returns `Result.succeed` with the decoded text when decoding succeeds, or
362 * `Result.fail` with an `EncodingError` when the input is not valid URL-safe
363 * base64.
364 *
365 * **Example** (Decoding URL-safe Base64 strings)
366 *
367 * ```ts import.meta.vitest
368 * import { Encoding, Result } from "effect"
369 *
370 * Encoding.decodeBase64UrlString("aGVsbG8_") // => Result.succeed("hello?")
371 * ```
372 *
373 * @category decoding
374 * @since 2.0.0
375 */
376export const decodeBase64UrlString = (str: string) => Result.map(decodeBase64Url(str), (_) => decoder.decode(_))
377
378// -------------------------------------------------------------------------------------
379// Hex
380// -------------------------------------------------------------------------------------
381
382/**
383 * Encodes the given value into a hex `string`.
384 *
385 * **When to use**
386 *
387 * Use to encode text or bytes as lowercase hexadecimal text.
388 *
389 * **Example** (Encoding hex strings and bytes)
390 *
391 * ```ts import.meta.vitest
392 * import { Encoding } from "effect"
393 *
394 * // Encode a string to hex
395 * Encoding.encodeHex("hello") // => "68656c6c6f"
396 *
397 * // Encode binary data to hex
398 * const bytes = new Uint8Array([72, 101, 108, 108, 111])
399 * Encoding.encodeHex(bytes) // => "48656c6c6f"
400 * ```
401 *
402 * @category encoding
403 * @since 2.0.0
404 */
405export const encodeHex: (input: Uint8Array | string) => string = (input) =>
406 typeof input === "string" ? hexEncodeUint8Array(encoder.encode(input)) : hexEncodeUint8Array(input)
407
408/**
409 * Generates a random lowercase hexadecimal string, optimized for lengths that
410 * are multiples of 8.
411 *
412 * `length` is not validated. The function generates `length >>> 3` random
413 * 8-character words, so non-negative lengths below `2 ** 32` are rounded down
414 * to a multiple of 8 and other values follow JavaScript's unsigned 32-bit
415 * coercion rules.
416 *
417 * This function uses `Math.random()` and is not cryptographically secure. For
418 * security-sensitive values, use the `Crypto.Crypto` service's `randomBytes`
419 * method and encode the result with {@link encodeHex}.
420 *
421 * @category encoding
422 * @since 4.0.0
423 */
424export const randomHex = (length: number): string => {
425 let result = ""
426 for (let i = length >>> 3; i > 0; i--) {
427 const word = (Math.random() * 0x100000000) >>> 0
428 result += byteToHex[word >>> 24] + byteToHex[(word >>> 16) & 0xff] + byteToHex[(word >>> 8) & 0xff] +
429 byteToHex[word & 0xff]
430 }
431 return result
432}
433
434/**
435 * Decodes a hexadecimal string into bytes safely.
436 *
437 * **When to use**
438 *
439 * Use to decode hexadecimal text into bytes without throwing on invalid input.
440 *
441 * **Details**
442 *
443 * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or
444 * `Result.fail` with an `EncodingError` when the input has an odd length or
445 * contains invalid hex characters.
446 *
447 * **Example** (Decoding hex bytes)
448 *
449 * ```ts import.meta.vitest
450 * import { Encoding, Result } from "effect"
451 *
452 * Encoding.decodeHex("48656c6c6f") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111]))
453 * ```
454 *
455 * @category decoding
456 * @since 2.0.0
457 */
458export const decodeHex = (str: string): Result.Result<Uint8Array, EncodingError> => {
459 const bytes = new TextEncoder().encode(str)
460 if (bytes.length % 2 !== 0) {
461 return Result.fail(
462 new EncodingError({
463 module: "Hex",
464 kind: "Decode",
465 input: str,
466 message: `Length must be a multiple of 2, but is ${bytes.length}`
467 })
468 )
469 }
470
471 try {
472 const length = bytes.length / 2
473 const result = new Uint8Array(length)
474 for (let i = 0; i < length; i++) {
475 const a = fromHexChar(bytes[i * 2])
476 const b = fromHexChar(bytes[i * 2 + 1])
477 result[i] = (a << 4) | b
478 }
479
480 return Result.succeed(result)
481 } catch (e) {
482 return Result.fail(
483 new EncodingError({
484 module: "Hex",
485 kind: "Decode",
486 input: str,
487 message: e instanceof Error ? e.message : "Invalid input"
488 })
489 )
490 }
491}
492
493/**
494 * Decodes a hexadecimal string into a UTF-8 string safely.
495 *
496 * **When to use**
497 *
498 * Use to decode hexadecimal text into UTF-8 text without throwing on invalid
499 * input.
500 *
501 * **Details**
502 *
503 * Returns `Result.succeed` with the decoded text when decoding succeeds, or
504 * `Result.fail` with an `EncodingError` when the input is not valid hex.
505 *
506 * **Example** (Decoding hex strings)
507 *
508 * ```ts import.meta.vitest
509 * import { Encoding, Result } from "effect"
510 *
511 * Encoding.decodeHexString("68656c6c6f") // => Result.succeed("hello")
512 * ```
513 *
514 * @category decoding
515 * @since 2.0.0
516 */
517export const decodeHexString = (str: string) => Result.map(decodeHex(str), (_) => decoder.decode(_))
518
519// -------------------------------------------------------------------------------------
520// internals
521// -------------------------------------------------------------------------------------
522
523const encoder = new TextEncoder()
524const decoder = new TextDecoder()
525
526const stripCrlf = (str: string) => str.replace(/[\n\r]/g, "")
527
528// Base64 internals
529
530const base64EncodeUint8Array = (bytes: Uint8Array) => {
531 const length = bytes.length
532
533 let result = ""
534 let i: number
535
536 for (i = 2; i < length; i += 3) {
537 result += base64abc[bytes[i - 2] >> 2]
538 result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]
539 result += base64abc[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)]
540 result += base64abc[bytes[i] & 0x3f]
541 }
542
543 if (i === length + 1) {
544 result += base64abc[bytes[i - 2] >> 2]
545 result += base64abc[(bytes[i - 2] & 0x03) << 4]
546 result += "=="
547 }
548
549 if (i === length) {
550 result += base64abc[bytes[i - 2] >> 2]
551 result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]
552 result += base64abc[(bytes[i - 1] & 0x0f) << 2]
553 result += "="
554 }
555
556 return result
557}
558
559function getBase64Code(charCode: number) {
560 if (charCode >= base64codes.length) {
561 throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`)
562 }
563
564 const code = base64codes[charCode]
565 if (code === 255) {
566 throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`)
567 }
568
569 return code
570}
571
572const base64abc = [
573 "A",
574 "B",
575 "C",
576 "D",
577 "E",
578 "F",
579 "G",
580 "H",
581 "I",
582 "J",
583 "K",
584 "L",
585 "M",
586 "N",
587 "O",
588 "P",
589 "Q",
590 "R",
591 "S",
592 "T",
593 "U",
594 "V",
595 "W",
596 "X",
597 "Y",
598 "Z",
599 "a",
600 "b",
601 "c",
602 "d",
603 "e",
604 "f",
605 "g",
606 "h",
607 "i",
608 "j",
609 "k",
610 "l",
611 "m",
612 "n",
613 "o",
614 "p",
615 "q",
616 "r",
617 "s",
618 "t",
619 "u",
620 "v",
621 "w",
622 "x",
623 "y",
624 "z",
625 "0",
626 "1",
627 "2",
628 "3",
629 "4",
630 "5",
631 "6",
632 "7",
633 "8",
634 "9",
635 "+",
636 "/"
637]
638
639const base64codes = [
640 255,
641 255,
642 255,
643 255,
644 255,
645 255,
646 255,
647 255,
648 255,
649 255,
650 255,
651 255,
652 255,
653 255,
654 255,
655 255,
656 255,
657 255,
658 255,
659 255,
660 255,
661 255,
662 255,
663 255,
664 255,
665 255,
666 255,
667 255,
668 255,
669 255,
670 255,
671 255,
672 255,
673 255,
674 255,
675 255,
676 255,
677 255,
678 255,
679 255,
680 255,
681 255,
682 255,
683 62,
684 255,
685 255,
686 255,
687 63,
688 52,
689 53,
690 54,
691 55,
692 56,
693 57,
694 58,
695 59,
696 60,
697 61,
698 255,
699 255,
700 255,
701 0,
702 255,
703 255,
704 255,
705 0,
706 1,
707 2,
708 3,
709 4,
710 5,
711 6,
712 7,
713 8,
714 9,
715 10,
716 11,
717 12,
718 13,
719 14,
720 15,
721 16,
722 17,
723 18,
724 19,
725 20,
726 21,
727 22,
728 23,
729 24,
730 25,
731 255,
732 255,
733 255,
734 255,
735 255,
736 255,
737 26,
738 27,
739 28,
740 29,
741 30,
742 31,
743 32,
744 33,
745 34,
746 35,
747 36,
748 37,
749 38,
750 39,
751 40,
752 41,
753 42,
754 43,
755 44,
756 45,
757 46,
758 47,
759 48,
760 49,
761 50,
762 51
763]
764
765// Base64Url internals
766
767const base64UrlEncodeUint8Array = (data: Uint8Array) =>
768 base64EncodeUint8Array(data).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")
769
770// Hex internals
771
772const byteToHex: Array<string> = []
773for (let i = 0; i < 256; i++) {
774 byteToHex.push(i.toString(16).padStart(2, "0"))
775}
776
777const hexEncodeUint8Array = (bytes: Uint8Array): string => {
778 let result = ""
779 for (let i = 0; i < bytes.length; i++) {
780 result += byteToHex[bytes[i]]
781 }
782 return result
783}
784
785const fromHexChar = (byte: number) => {
786 if (48 <= byte && byte <= 57) {
787 return byte - 48
788 }
789
790 if (97 <= byte && byte <= 102) {
791 return byte - 97 + 10
792 }
793
794 if (65 <= byte && byte <= 70) {
795 return byte - 65 + 10
796 }
797
798 throw new TypeError("Invalid input")
799}