Skip to content

Commit

Permalink
fix(typescript): properly import the TransformStream type
Browse files Browse the repository at this point in the history
When compiling with TypeScript with module set to "node16" and
moduleResolution to "node16", the following error would be thrown:

> node_modules/engine.io-parser/build/cjs/index.d.ts:6:54 - error TS2304: Cannot find name 'TransformStream'.
> 6 export declare function createPacketEncoderStream(): TransformStream<Packet, any>;
>                                                        ~~~~~~~~~~~~~~~
> node_modules/engine.io-parser/build/cjs/index.d.ts:7:96 - error TS2304: Cannot find name 'TransformStream'.
> 7 export declare function createPacketDecoderStream(maxPayload: number, binaryType: BinaryType): TransformStream<Uint8Array, any>;
>                                                                                                  ~~~~~~~~~~~~~~~
> Found 2 errors in the same file, starting at: node_modules/engine.io-parser/build/cjs/index.d.ts:6

This is because the TransformStream object is not exposed in the global
scope in the `@types/node` package, even though it is since Node.js
`v18.0.0`.

Reference: https://nodejs.org/api/webstreams.html#class-transformstream

Note: we only import the TransformStream type (not value) because it
isn't defined on older Node.js versions.

Related:

- https://github.com/socketio/engine.io-parser/issues/136
- socketio/socket.io-client#1606
  • Loading branch information
darrachequesne committed Feb 5, 2024
1 parent 08cff77 commit 0305b4a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
5 changes: 5 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import {
BinaryType,
ERROR_PACKET,
} from "./commons.js";
// we can't import TransformStream as a value because it was added in Node.js v16.5.0, so it would break on older Node.js versions
// reference: https://nodejs.org/api/webstreams.html#class-transformstream
import type { TransformStream } from "node:stream/web";

const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text

Expand Down Expand Up @@ -47,6 +50,7 @@ const decodePayload = (
};

export function createPacketEncoderStream() {
// @ts-expect-error
return new TransformStream({
transform(packet: Packet, controller) {
encodePacketToBinary(packet, (encodedPacket) => {
Expand Down Expand Up @@ -122,6 +126,7 @@ export function createPacketDecoderStream(
let expectedLength = -1;
let isBinary = false;

// @ts-expect-error
return new TransformStream({
transform(chunk: Uint8Array, controller) {
chunks.push(chunk);
Expand Down
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 0305b4a

Please sign in to comment.