Skip to content

Commit 28418ff

Browse files
committed
Fix safeBtoa fallback for Unicode binary payloads
Applied via @cursor push command
1 parent 4850e33 commit 28418ff

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/codegen/codegen.test.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -816,5 +816,36 @@ describe('Code generation', () => {
816816
expect(snippet).toContain('`{"user": "test"}`')
817817
expect(snippet).not.toContain('encoding.b64decode')
818818
})
819+
820+
it('should base64 encode binary content when btoa cannot handle input', () => {
821+
const binaryContent = "\x00\u0100'data"
822+
const bytes = new TextEncoder().encode(binaryContent)
823+
let utf8Binary = ''
824+
for (const byte of bytes) {
825+
utf8Binary += String.fromCharCode(byte)
826+
}
827+
const expectedBase64Content = btoa(utf8Binary)
828+
const schema = {
829+
data: createProxyData({
830+
id: '1',
831+
request: createRequest({
832+
method: 'POST',
833+
url: '/api/v1/upload',
834+
content: binaryContent,
835+
headers: [['content-type', 'application/octet-stream']],
836+
}),
837+
}),
838+
before: [],
839+
after: [],
840+
checks: [],
841+
}
842+
843+
const result = generateRequestSnippetsFromSchemas([schema], thinkTime)
844+
const snippet = result[0]?.snippet ?? ''
845+
846+
expect(snippet).toContain(
847+
`encoding.b64decode('${expectedBase64Content}')`
848+
)
849+
})
819850
})
820851
})

src/utils/format.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,14 @@ export function safeBtoa(content: string) {
3838
try {
3939
return btoa(content)
4040
} catch {
41-
return content
41+
const bytes = new TextEncoder().encode(content)
42+
let binary = ''
43+
44+
for (const byte of bytes) {
45+
binary += String.fromCharCode(byte)
46+
}
47+
48+
return btoa(binary)
4249
}
4350
}
4451

0 commit comments

Comments
 (0)