Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(util-base64): allow arrays to stand in for Uint8Array (runtime only) #1185

Merged
merged 1 commit into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading