Skip to content

Commit

Permalink
fix(bun): Rewrite TextEncoderStream polyfill implementation for Bun m…
Browse files Browse the repository at this point in the history
…iddleware (#6309)

Co-authored-by: PatrickJS <[email protected]>
Co-authored-by: PatrickJS <[email protected]>
  • Loading branch information
3 people authored May 14, 2024
1 parent bb8b7a9 commit 45ba302
Showing 1 changed file with 29 additions and 35 deletions.
64 changes: 29 additions & 35 deletions packages/qwik-city/middleware/bun/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,45 +16,39 @@ import { MIME_TYPES } from '../request-handler/mime-types';
import { join, extname } from 'node:path';

// @builder.io/qwik-city/middleware/bun

const resolved = Promise.resolve();
class TextEncoderStream {
// minimal polyfill implementation of TextEncoderStream
// since bun does not yet support TextEncoderStream
_writer: any;
readable: any;
writable: any;

constructor() {
this._writer = null;
this.readable = {
pipeTo: (writableStream: any) => {
this._writer = writableStream.getWriter();
},
};
this.writable = {
getWriter: () => {
if (!this._writer) {
throw new Error('No writable stream');
}
const encoder = new TextEncoder();
return {
write: async (chunk: any) => {
if (chunk != null) {
await this._writer.write(encoder.encode(chunk));
}
},
close: () => this._writer.close(),
ready: resolved,
};
},
};
}
// still missing from bun: last check was bun version 1.1.8
class TextEncoderStream_polyfill {
private _encoder = new TextEncoder();
private _reader: ReadableStreamDefaultController<any> | null = null;
public ready = Promise.resolve();
public closed = false;
public readable = new ReadableStream({
start: (controller) => {
this._reader = controller;
},
});

public writable = new WritableStream({
write: async (chunk) => {
if (chunk != null && this._reader) {
const encoded = this._encoder.encode(chunk);
this._reader.enqueue(encoded);
}
},
close: () => {
this._reader?.close();
this.closed = true;
},
abort: (reason) => {
this._reader?.error(reason);
this.closed = true;
},
});
}

/** @public */
export function createQwikCity(opts: QwikCityBunOptions) {
globalThis.TextEncoderStream ||= TextEncoderStream as any;
globalThis.TextEncoderStream = TextEncoderStream || (TextEncoderStream_polyfill as any);

const qwikSerializer = {
_deserializeData,
Expand Down

0 comments on commit 45ba302

Please sign in to comment.