From ccb2065d1147af56b5c1a929635f63443e469205 Mon Sep 17 00:00:00 2001 From: Alex Potsides Date: Wed, 1 Mar 2023 15:18:40 +0000 Subject: [PATCH] fix: make pbStream function polymorphic (#40) What we want to say is that the type returned from `unwrap` will be the original duplex passed in, but it's source will have changed to return `Uint8ArrayList`s. We can still pass duplexes that source `Uint8Array`s though, so make the exported function polymorphic. --- src/index.ts | 20 ++++++++++++-------- test/index.spec.ts | 2 +- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/index.ts b/src/index.ts index 503cfb6..f6991a5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -43,7 +43,7 @@ export interface Encoder { /** * Convenience methods for working with protobuf streams */ -export interface ProtobufStream { +export interface ProtobufStream = Duplex> { /** * Read a set number of bytes from the stream */ @@ -82,7 +82,7 @@ export interface ProtobufStream { /** * Returns the underlying stream */ - unwrap: () => Duplex + unwrap: () => Stream } export interface Opts { @@ -97,14 +97,16 @@ export interface Opts { maxDataLength: number } -export function pbStream (duplex: Duplex, opts = {}): ProtobufStream { - const shake = handshake(duplex) +export function pbStream > (duplex: Stream, opts?: Partial): ProtobufStream +export function pbStream > (duplex: Duplex, opts?: Partial): ProtobufStream +export function pbStream (duplex: any, opts = {}): ProtobufStream { + const shake = handshake(duplex) const lpReader = lp.decode.fromReader( shake.reader, opts ) - const W: ProtobufStream = { + const W: ProtobufStream = { read: async (bytes) => { // just read const { value } = await shake.reader.next(bytes) @@ -142,10 +144,8 @@ export function pbStream (duplex: Du write: (data) => { // just write if (data instanceof Uint8Array) { - // @ts-expect-error writer should always accept pushing Uint8Arrays shake.writer.push(data) } else { - // @ts-expect-error writer should always accept pushing Uint8Arrays shake.writer.push(data.subarray()) } }, @@ -166,7 +166,11 @@ export function pbStream (duplex: Du unwrap: () => { // returns vanilla duplex again, terminates all reads/writes from this object shake.rest() - return shake.stream + + duplex.source = shake.stream.source + duplex.sink = shake.stream.sink + + return duplex } } diff --git a/test/index.spec.ts b/test/index.spec.ts index 7f66d02..b747a52 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -65,7 +65,7 @@ Object.keys(tests).forEach(key => { const test = tests[key] describe(`it-pb-rpc ${key}`, () => { - let w: ProtobufStream + let w: ProtobufStream before(async () => { w = pbStream(pair())