Skip to content
Open
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
9 changes: 8 additions & 1 deletion src/internal/utils/base64.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@ export const toBase64 = (data: string | Uint8Array | null | undefined): string =
}

if (typeof btoa !== 'undefined') {
return btoa(String.fromCharCode.apply(null, data as any));
// Process in chunks to avoid stack overflow with large inputs.
// String.fromCharCode.apply has a max argument count (~65536).
let binary = '';
const chunkSize = 8192;
for (let i = 0; i < data.length; i += chunkSize) {
binary += String.fromCharCode(...data.subarray(i, Math.min(i + chunkSize, data.length)));
}
return btoa(binary);
}

throw new AnthropicError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined');
Expand Down
18 changes: 18 additions & 0 deletions tests/base64.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,24 @@ describe.each(['Buffer', 'atob'])('with %s', (mode) => {
});
});

test('toBase64 handles large input without stack overflow', () => {
// 200KB of data - would cause "Maximum call stack size exceeded"
// with the old String.fromCharCode.apply/spread approach
const size = 200 * 1024;
const largeData = new Uint8Array(size);
for (let i = 0; i < size; i++) {
largeData[i] = i % 256;
}

const encoded = toBase64(largeData);
expect(typeof encoded).toBe('string');
expect(encoded.length).toBeGreaterThan(0);

// Round-trip: decode and verify it matches
const decoded = fromBase64(encoded);
expect(decoded).toEqual(largeData);
});

test('fromBase64', () => {
const testCases = [
{
Expand Down