mswjs / interceptors

Low-level network interception library.
https://npm.im/@mswjs/interceptors
MIT License
537 stars 123 forks source link

[Bun] TextDecoder(undefined) doesn't work with Bun 1.0.0 #422

Closed mouhannad-sh closed 1 year ago

mouhannad-sh commented 1 year ago

Hi 👋🏻

As I reported this on Bun oven-sh/bun#5211 . it seems like the TextDecoder would throw a TypeError if the encoding passed in explicitly undefined. which seems to be the case in https://github.com/mswjs/interceptors/blob/45df4685cb31d2f66c37fcd60b0f53359d838c98/src/utils/bufferUtils.ts#L8

not sure why the encoding variable is undefined but it seems to work just fine when I don't pass anything into the decoder class

rest.all("/api/proposals", async (req, res, ctx) => {
    const textDecoder = new TextDecoder(); // this works 
    const body = textDecoder.decode(req._body); 
    console.log(JSON.parse(body)) // works as expected 
}

it might be a good idea to guard the TextDecoder class in BufferUtils

export function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string { // or maybe set a default encoding value ? 
  const decoder = encoding ? new TextDecoder(encoding) : new TextDecoder();
  return decoder.decode(buffer)
}

Happy to put up a PR if needed

kettanaito commented 1 year ago

Hey, @mouhannad-sh. Thanks for reporting this.

In Node.js, you the encoding argument to the TextDecoder is optional. You can construct TextDecoder without any arguments or with an explicit undefined as the first argument. Both scenarios will result in the default utf-8 encoding being used:

new TextDecoder()
// TextDecoder { encoding: 'utf-8' }

new TextDecoder(undefined)
// TextDecoder { encoding: 'utf-8' }

See TextDecoder.

This is a bug in Bun and must be addressed there. Interceptors use the Node.js APIs correctly so no changes are needed to this library.