Skip to content

Commit

Permalink
fix(util-base64): allow arrays to stand in for Uint8Array (runtime only)
Browse files Browse the repository at this point in the history
  • Loading branch information
kuhe committed Mar 12, 2024
1 parent 511206e commit b370b7a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/old-kangaroos-rhyme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@smithy/util-base64": patch
---

allow arrays to stand in for Uint8Array in toBase64
8 changes: 8 additions & 0 deletions packages/util-base64/src/toBase64.browser.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import type { Encoder } from "@smithy/types";

import testCases from "./__mocks__/testCases.json";
import { fromBase64 } from "./fromBase64.browser";
import { toBase64 } from "./toBase64.browser";

describe(toBase64.name, () => {
Expand All @@ -19,4 +20,11 @@ describe(toBase64.name, () => {
expect(() => (toBase64 as Encoder)(new Date())).toThrow();
expect(() => (toBase64 as Encoder)({})).toThrow();
});

it("allows array to stand in for Uint8Array", () => {
expect(() => (toBase64 as Encoder)([])).not.toThrow();

const helloUtf8Array = fromBase64("aGVsbG8=");
expect(toBase64(([...helloUtf8Array] as unknown) as Uint8Array)).toEqual("aGVsbG8=");
});
});
10 changes: 9 additions & 1 deletion packages/util-base64/src/toBase64.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,17 @@ export function toBase64(_input: Uint8Array | string): string {
} else {
input = _input as Uint8Array;
}
if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {

const isArrayLike = typeof input === "object" && typeof input.length === "number";
const isUint8Array =
typeof input === "object" &&
typeof (input as Uint8Array).byteOffset === "number" &&
typeof (input as Uint8Array).byteLength === "number";

if (!isArrayLike && !isUint8Array) {
throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
}

let str = "";
for (let i = 0; i < input.length; i += 3) {
let bits = 0;
Expand Down

0 comments on commit b370b7a

Please sign in to comment.