Skip to content

Commit

Permalink
use unwrap in type guards
Browse files Browse the repository at this point in the history
  • Loading branch information
turbocrime authored and grod220 committed Jun 28, 2024
1 parent 842b138 commit 4da58ad
Showing 1 changed file with 11 additions and 16 deletions.
27 changes: 11 additions & 16 deletions apps/extension/src/content-scripts/message-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,36 +6,31 @@ import { PraxConnection } from '../message/prax';
export type PraxMessage<T = unknown> = { [PRAX]: T };
export type PraxMessageEvent<T = unknown> = MessageEvent<PraxMessage<T>>;

export const unwrapPraxMessageEvent = <T>(ev: PraxMessageEvent<T>): T =>
// @ts-expect-error - ts can't understand the injected string
ev.data[PRAX] as T;

export const isPraxMessageEvent = (ev: MessageEvent<unknown>): ev is PraxMessageEvent =>
typeof ev.data === 'object' && ev.data !== null && PRAX in ev.data;

export const isPraxPortMessageEvent = (
ev: MessageEvent<unknown>,
): ev is PraxMessageEvent<MessagePort> =>
// @ts-expect-error - ts can't understand the injected string
isPraxMessageEvent(ev) && ev.data[PRAX] instanceof MessagePort;
isPraxMessageEvent(ev) && unwrapPraxMessageEvent(ev) instanceof MessagePort;

export const isPraxRequestMessageEvent = (
ev: MessageEvent<unknown>,
): ev is PraxMessageEvent<PraxConnection.Request> =>
// @ts-expect-error - ts can't understand the injected string
isPraxMessageEvent(ev) && ev.data[PRAX] === PraxConnection.Request;
isPraxMessageEvent(ev) && unwrapPraxMessageEvent(ev) === PraxConnection.Request;

export const isPraxEndMessageEvent = (
ev: MessageEvent<unknown>,
): ev is PraxMessageEvent<PraxConnection.Disconnect> =>
// @ts-expect-error - ts can't understand the injected string
isPraxMessageEvent(ev) && ev.data[PRAX] === PraxConnection.Disconnect;
isPraxMessageEvent(ev) && unwrapPraxMessageEvent(ev) === PraxConnection.Disconnect;

export const isPraxFailureMessageEvent = (
ev: MessageEvent<unknown>,
): ev is PraxMessageEvent<PenumbraRequestFailure> => {
if (!isPraxMessageEvent(ev)) return false;
// @ts-expect-error - ts can't understand the injected string
const status = ev.data[PRAX] as unknown;
return typeof status === 'string' && status in PenumbraRequestFailure;
};

export const unwrapPraxMessageEvent = <T>(ev: PraxMessageEvent<T>): T =>
// @ts-expect-error - ts can't understand the injected string
ev.data[PRAX] as T;
): ev is PraxMessageEvent<PenumbraRequestFailure> =>
isPraxMessageEvent(ev) &&
typeof unwrapPraxMessageEvent(ev) === 'string' &&
unwrapPraxMessageEvent<string>(ev) in PenumbraRequestFailure;

0 comments on commit 4da58ad

Please sign in to comment.