text-decoder-stream.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2016 Google Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Polyfill for TextEncoderStream and TextDecoderStream
  15. // Modified by Sukka (https://skk.moe) to increase compatibility and performance with Bun.
  16. export class PolyfillTextDecoderStream extends TransformStream<Uint8Array, string> {
  17. readonly encoding: string;
  18. readonly fatal: boolean;
  19. readonly ignoreBOM: boolean;
  20. constructor(
  21. encoding: Encoding = 'utf-8',
  22. { fatal = false, ignoreBOM = false }: ConstructorParameters<typeof TextDecoder>[1] = {},
  23. ) {
  24. const decoder = new TextDecoder(encoding, { fatal, ignoreBOM });
  25. super({
  26. transform(chunk: Uint8Array, controller: TransformStreamDefaultController<string>) {
  27. const decoded = decoder.decode(chunk);
  28. if (decoded.length > 0) {
  29. controller.enqueue(decoded);
  30. }
  31. },
  32. flush(controller: TransformStreamDefaultController<string>) {
  33. // If {fatal: false} is in options (the default), then the final call to
  34. // decode() can produce extra output (usually the unicode replacement
  35. // character 0xFFFD). When fatal is true, this call is just used for its
  36. // side-effect of throwing a TypeError exception if the input is
  37. // incomplete.
  38. const output = decoder.decode();
  39. if (output.length > 0) {
  40. controller.enqueue(output);
  41. }
  42. }
  43. });
  44. this.encoding = encoding;
  45. this.fatal = fatal;
  46. this.ignoreBOM = ignoreBOM;
  47. }
  48. }