Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(fix): introduce errors and parse message data func #247

Merged
merged 2 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ export * from './lib/useMicrophone';
export * from './lib/useSoundPlayer';
export * from './lib/useVoiceClient';
export * from './lib/VoiceProvider';
export * from './lib/errors';
export * from './lib/messages';

export {
AudioEncoding,
Expand Down
31 changes: 31 additions & 0 deletions packages/react/src/lib/audio-message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import z from 'zod';

export const AudioMessageSchema = z
.object({
type: z.literal('audio'),
data: z.instanceof(ArrayBuffer),
})
.transform((obj) => {
return Object.assign(obj, {
receivedAt: new Date(),
});
});

export type AudioMessage = z.infer<typeof AudioMessageSchema>;

export const parseAudioMessage = async (
blob: Blob,
): Promise<AudioMessage | null> => {
return blob
.arrayBuffer()
.then((buffer) => {
return {
type: 'audio' as const,
data: buffer,
receivedAt: new Date(),
};
})
.catch(() => {
return null;
});
};
55 changes: 55 additions & 0 deletions packages/react/src/lib/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
export class SocketUnknownMessageError extends Error {
constructor(message?: string) {
super(`Unknown message type.${message ? ' ' + message : ''}`);
this.name = 'SocketUnknownMessageError';
}
}

/**
* @name isSocketUnknownMessageError
* @description
* Check if an error is a SocketUnknownMessageError.
* @param err - The error to check.
* @returns
* `true` if the error is a SocketUnknownMessageError.
* @example
* ```ts
* if (isSocketUnknownMessageError(err)) {
* console.error('Unknown message type');
* }
* ```
*/
export const isSocketUnknownMessageError = (
err: unknown,
): err is SocketUnknownMessageError => {
return err instanceof SocketUnknownMessageError;
};

export class SocketFailedToParseMessageError extends Error {
constructor(message?: string) {
super(
`Failed to parse message from socket.${message ? ' ' + message : ''}`,
);
this.name = 'SocketFailedToParseMessageError';
}
}

/**
* @name isSocketFailedToParseMessageError
* @description
* Check if an error is a SocketFailedToParseMessageError.
* @param err - The error to check.
* @returns
* `true` if the error is a SocketFailedToParseMessageError.
* @example
* ```ts
* if (isSocketFailedToParseMessageError(err)) {
* console.error('Failed to parse message from socket');
* }
* ```
*/
export const isSocketFailedToParseMessageError = (
err: unknown,
): err is SocketFailedToParseMessageError => {
return err instanceof SocketFailedToParseMessageError;
};
104 changes: 104 additions & 0 deletions packages/react/src/lib/messages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { type Hume } from 'hume';
import * as serializers from 'hume/serialization';

import { type AudioMessage, parseAudioMessage } from './audio-message';
import {
SocketFailedToParseMessageError,
SocketUnknownMessageError,
} from './errors';

/**
* @name parseMessageData
* @description
* Parse the data of a message from the socket.
* @param data - The data to parse.
* @returns
* The parsed message data.
* @example
* ```ts
* const message = await parseMessageData(data);
* ```
*/
export const parseMessageData = async (
data: unknown,
): Promise<
| {
success: true;
message: Hume.empathicVoice.SubscribeEvent | AudioMessage;
}
| {
success: false;
error: Error;
}
> => {
if (data instanceof Blob) {
const message = await parseAudioMessage(data);

if (message) {
return {
success: true,
message,
};
} else {
return {
success: false,
error: new SocketFailedToParseMessageError(
`Received blob was unable to be converted to ArrayBuffer.`,
),
};
}
}

if (typeof data !== 'string') {
return {
success: false,
error: new SocketFailedToParseMessageError(
`Expected a string but received ${typeof data}.`,
),
};
}

const parseResponse = serializers.empathicVoice.SubscribeEvent.parse(data);

if (!parseResponse.ok) {
return {
success: false,
error: new SocketUnknownMessageError(
`Received JSON was not a known message type.`,
),
};
}

return {
success: true,
message: parseResponse.value,
};
};

/**
* @name parseMessageType
* @description
* Parse the type of a message from the socket.
* @param event - The event to parse.
* @returns
* The parsed message type.
* @example
* ```ts
* const message = await parseMessageType(event);
* ```
*/
export const parseMessageType = async (
event: MessageEvent,
): Promise<
| {
success: true;
message: Hume.empathicVoice.SubscribeEvent | AudioMessage;
}
| {
success: false;
error: Error;
}
> => {
const data: unknown = event.data;
return parseMessageData(data);
};
Loading