mirror of
https://github.com/ReVanced/revanced-bots.git
synced 2026-01-11 13:56:15 +00:00
chore: apply code fixes with biome
This commit is contained in:
@@ -1,177 +1,177 @@
|
||||
import { ClientOperation, Packet, ServerOperation } from '@revanced/bot-shared'
|
||||
import ClientGateway, { ClientGatewayEventHandlers } from './ClientGateway.js'
|
||||
|
||||
/**
|
||||
* The client that connects to the API.
|
||||
*/
|
||||
export default class Client {
|
||||
ready: boolean = false
|
||||
gateway: ClientGateway
|
||||
#parseId: number = 0
|
||||
|
||||
constructor(options: ClientOptions) {
|
||||
this.gateway = new ClientGateway({
|
||||
url: options.api.gatewayUrl,
|
||||
})
|
||||
|
||||
this.gateway.on('ready', () => {
|
||||
this.ready = true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the WebSocket API
|
||||
* @returns A promise that resolves when the client is ready
|
||||
*/
|
||||
connect() {
|
||||
return this.gateway.connect()
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the client is ready
|
||||
* @returns Whether the client is ready
|
||||
*/
|
||||
isReady(): this is ReadiedClient {
|
||||
return this.ready
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the API to parse the given text
|
||||
* @param text The text to parse
|
||||
* @returns An object containing the ID of the request and the labels
|
||||
*/
|
||||
async parseText(text: string) {
|
||||
this.#throwIfNotReady()
|
||||
|
||||
const currentId = (this.#parseId++).toString()
|
||||
|
||||
this.gateway.send({
|
||||
op: ClientOperation.ParseText,
|
||||
d: {
|
||||
text,
|
||||
id: currentId,
|
||||
},
|
||||
})
|
||||
|
||||
type CorrectPacket = Packet<ServerOperation.ParsedText>
|
||||
|
||||
const promise = new Promise<CorrectPacket['d']>((rs, rj) => {
|
||||
const parsedTextListener = (packet: CorrectPacket) => {
|
||||
if (packet.d.id !== currentId) return
|
||||
this.gateway.off('parsedText', parsedTextListener)
|
||||
rs(packet.d)
|
||||
}
|
||||
|
||||
const parseTextFailedListener = (
|
||||
packet: Packet<ServerOperation.ParseTextFailed>
|
||||
) => {
|
||||
if (packet.d.id !== currentId) return
|
||||
this.gateway.off('parseTextFailed', parseTextFailedListener)
|
||||
rj()
|
||||
}
|
||||
|
||||
this.gateway.on('parsedText', parsedTextListener)
|
||||
this.gateway.on('parseTextFailed', parseTextFailedListener)
|
||||
})
|
||||
|
||||
return await promise
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the API to parse the given image and return the text
|
||||
* @param url The URL of the image
|
||||
* @returns An object containing the ID of the request and the parsed text
|
||||
*/
|
||||
async parseImage(url: string) {
|
||||
this.#throwIfNotReady()
|
||||
|
||||
const currentId = (this.#parseId++).toString()
|
||||
|
||||
this.gateway.send({
|
||||
op: ClientOperation.ParseImage,
|
||||
d: {
|
||||
image_url: url,
|
||||
id: currentId,
|
||||
},
|
||||
})
|
||||
|
||||
type CorrectPacket = Packet<ServerOperation.ParsedImage>
|
||||
|
||||
const promise = new Promise<CorrectPacket['d']>((rs, rj) => {
|
||||
const parsedImageListener = (packet: CorrectPacket) => {
|
||||
if (packet.d.id !== currentId) return
|
||||
this.gateway.off('parsedImage', parsedImageListener)
|
||||
rs(packet.d)
|
||||
}
|
||||
|
||||
const parseImageFailedListener = (
|
||||
packet: Packet<ServerOperation.ParseImageFailed>
|
||||
) => {
|
||||
if (packet.d.id !== currentId) return
|
||||
this.gateway.off('parseImageFailed', parseImageFailedListener)
|
||||
rj()
|
||||
}
|
||||
|
||||
this.gateway.on('parsedImage', parsedImageListener)
|
||||
this.gateway.on('parseImageFailed', parseImageFailedListener)
|
||||
})
|
||||
|
||||
return await promise
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an event listener
|
||||
* @param name The event name to listen for
|
||||
* @param handler The event handler
|
||||
* @returns The event handler function
|
||||
*/
|
||||
on<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[TOpName]
|
||||
) {
|
||||
this.gateway.on(name, handler)
|
||||
return handler
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an event listener
|
||||
* @param name The event name to remove a listener from
|
||||
* @param handler The event handler to remove
|
||||
* @returns The removed event handler function
|
||||
*/
|
||||
off<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[TOpName]
|
||||
) {
|
||||
this.gateway.off(name, handler)
|
||||
return handler
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an event listener that will only be called once
|
||||
* @param name The event name to listen for
|
||||
* @param handler The event handler
|
||||
* @returns The event handler function
|
||||
*/
|
||||
once<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[TOpName]
|
||||
) {
|
||||
this.gateway.once(name, handler)
|
||||
return handler
|
||||
}
|
||||
|
||||
#throwIfNotReady() {
|
||||
if (!this.isReady()) throw new Error('Client is not ready')
|
||||
}
|
||||
}
|
||||
|
||||
export type ReadiedClient = Client & { ready: true }
|
||||
|
||||
export interface ClientOptions {
|
||||
api: ClientApiOptions
|
||||
}
|
||||
|
||||
export interface ClientApiOptions {
|
||||
gatewayUrl: string
|
||||
}
|
||||
import { ClientOperation, Packet, ServerOperation } from '@revanced/bot-shared'
|
||||
import ClientGateway, { ClientGatewayEventHandlers } from './ClientGateway.js'
|
||||
|
||||
/**
|
||||
* The client that connects to the API.
|
||||
*/
|
||||
export default class Client {
|
||||
ready = false
|
||||
gateway: ClientGateway
|
||||
#parseId = 0
|
||||
|
||||
constructor(options: ClientOptions) {
|
||||
this.gateway = new ClientGateway({
|
||||
url: options.api.gatewayUrl,
|
||||
})
|
||||
|
||||
this.gateway.on('ready', () => {
|
||||
this.ready = true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the WebSocket API
|
||||
* @returns A promise that resolves when the client is ready
|
||||
*/
|
||||
connect() {
|
||||
return this.gateway.connect()
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the client is ready
|
||||
* @returns Whether the client is ready
|
||||
*/
|
||||
isReady(): this is ReadiedClient {
|
||||
return this.ready
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the API to parse the given text
|
||||
* @param text The text to parse
|
||||
* @returns An object containing the ID of the request and the labels
|
||||
*/
|
||||
async parseText(text: string) {
|
||||
this.#throwIfNotReady()
|
||||
|
||||
const currentId = (this.#parseId++).toString()
|
||||
|
||||
this.gateway.send({
|
||||
op: ClientOperation.ParseText,
|
||||
d: {
|
||||
text,
|
||||
id: currentId,
|
||||
},
|
||||
})
|
||||
|
||||
type CorrectPacket = Packet<ServerOperation.ParsedText>
|
||||
|
||||
const promise = new Promise<CorrectPacket['d']>((rs, rj) => {
|
||||
const parsedTextListener = (packet: CorrectPacket) => {
|
||||
if (packet.d.id !== currentId) return
|
||||
this.gateway.off('parsedText', parsedTextListener)
|
||||
rs(packet.d)
|
||||
}
|
||||
|
||||
const parseTextFailedListener = (
|
||||
packet: Packet<ServerOperation.ParseTextFailed>,
|
||||
) => {
|
||||
if (packet.d.id !== currentId) return
|
||||
this.gateway.off('parseTextFailed', parseTextFailedListener)
|
||||
rj()
|
||||
}
|
||||
|
||||
this.gateway.on('parsedText', parsedTextListener)
|
||||
this.gateway.on('parseTextFailed', parseTextFailedListener)
|
||||
})
|
||||
|
||||
return await promise
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the API to parse the given image and return the text
|
||||
* @param url The URL of the image
|
||||
* @returns An object containing the ID of the request and the parsed text
|
||||
*/
|
||||
async parseImage(url: string) {
|
||||
this.#throwIfNotReady()
|
||||
|
||||
const currentId = (this.#parseId++).toString()
|
||||
|
||||
this.gateway.send({
|
||||
op: ClientOperation.ParseImage,
|
||||
d: {
|
||||
image_url: url,
|
||||
id: currentId,
|
||||
},
|
||||
})
|
||||
|
||||
type CorrectPacket = Packet<ServerOperation.ParsedImage>
|
||||
|
||||
const promise = new Promise<CorrectPacket['d']>((rs, rj) => {
|
||||
const parsedImageListener = (packet: CorrectPacket) => {
|
||||
if (packet.d.id !== currentId) return
|
||||
this.gateway.off('parsedImage', parsedImageListener)
|
||||
rs(packet.d)
|
||||
}
|
||||
|
||||
const parseImageFailedListener = (
|
||||
packet: Packet<ServerOperation.ParseImageFailed>,
|
||||
) => {
|
||||
if (packet.d.id !== currentId) return
|
||||
this.gateway.off('parseImageFailed', parseImageFailedListener)
|
||||
rj()
|
||||
}
|
||||
|
||||
this.gateway.on('parsedImage', parsedImageListener)
|
||||
this.gateway.on('parseImageFailed', parseImageFailedListener)
|
||||
})
|
||||
|
||||
return await promise
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an event listener
|
||||
* @param name The event name to listen for
|
||||
* @param handler The event handler
|
||||
* @returns The event handler function
|
||||
*/
|
||||
on<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[TOpName],
|
||||
) {
|
||||
this.gateway.on(name, handler)
|
||||
return handler
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an event listener
|
||||
* @param name The event name to remove a listener from
|
||||
* @param handler The event handler to remove
|
||||
* @returns The removed event handler function
|
||||
*/
|
||||
off<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[TOpName],
|
||||
) {
|
||||
this.gateway.off(name, handler)
|
||||
return handler
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an event listener that will only be called once
|
||||
* @param name The event name to listen for
|
||||
* @param handler The event handler
|
||||
* @returns The event handler function
|
||||
*/
|
||||
once<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[TOpName],
|
||||
) {
|
||||
this.gateway.once(name, handler)
|
||||
return handler
|
||||
}
|
||||
|
||||
#throwIfNotReady() {
|
||||
if (!this.isReady()) throw new Error('Client is not ready')
|
||||
}
|
||||
}
|
||||
|
||||
export type ReadiedClient = Client & { ready: true }
|
||||
|
||||
export interface ClientOptions {
|
||||
api: ClientApiOptions
|
||||
}
|
||||
|
||||
export interface ClientApiOptions {
|
||||
gatewayUrl: string
|
||||
}
|
||||
|
||||
@@ -1,234 +1,235 @@
|
||||
import { type RawData, WebSocket } from 'ws'
|
||||
import type TypedEmitter from 'typed-emitter'
|
||||
import {
|
||||
ClientOperation,
|
||||
DisconnectReason,
|
||||
Packet,
|
||||
ServerOperation,
|
||||
deserializePacket,
|
||||
isServerPacket,
|
||||
serializePacket,
|
||||
uncapitalize,
|
||||
} from '@revanced/bot-shared'
|
||||
import { EventEmitter } from 'events'
|
||||
|
||||
/**
|
||||
* The class that handles the WebSocket connection to the server.
|
||||
* This is the only relevant class for the time being. But in the future, there may be more classes to handle different protocols of the API.
|
||||
*/
|
||||
export default class ClientGateway {
|
||||
readonly url: string
|
||||
ready: boolean = false
|
||||
disconnected: boolean | DisconnectReason = DisconnectReason.NeverConnected
|
||||
config: Readonly<Packet<ServerOperation.Hello>['d']> | null = null!
|
||||
|
||||
#hbTimeout: NodeJS.Timeout = null!
|
||||
#socket: WebSocket = null!
|
||||
#emitter = new EventEmitter() as TypedEmitter<ClientGatewayEventHandlers>
|
||||
|
||||
constructor(options: ClientGatewayOptions) {
|
||||
this.url = options.url
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the WebSocket API
|
||||
* @returns A promise that resolves when the client is ready
|
||||
*/
|
||||
connect() {
|
||||
return new Promise<void>((rs, rj) => {
|
||||
try {
|
||||
this.#socket = new WebSocket(this.url)
|
||||
|
||||
this.#socket.on('open', () => {
|
||||
this.disconnected = false
|
||||
rs()
|
||||
})
|
||||
|
||||
this.#socket.on('close', () =>
|
||||
this.#handleDisconnect(DisconnectReason.Generic)
|
||||
)
|
||||
|
||||
this.#listen()
|
||||
this.ready = true
|
||||
this.#emitter.emit('ready')
|
||||
} catch (e) {
|
||||
rj(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an event listener
|
||||
* @param name The event name to listen for
|
||||
* @param handler The event handler
|
||||
* @returns The event handler function
|
||||
*/
|
||||
on<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[typeof name]
|
||||
) {
|
||||
this.#emitter.on(name, handler)
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an event listener
|
||||
* @param name The event name to remove a listener from
|
||||
* @param handler The event handler to remove
|
||||
* @returns The removed event handler function
|
||||
*/
|
||||
off<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[typeof name]
|
||||
) {
|
||||
this.#emitter.off(name, handler)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an event listener that will only be called once
|
||||
* @param name The event name to listen for
|
||||
* @param handler The event handler
|
||||
* @returns The event handler function
|
||||
*/
|
||||
once<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[typeof name]
|
||||
) {
|
||||
this.#emitter.once(name, handler)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a packet to the server
|
||||
* @param packet The packet to send
|
||||
* @returns A promise that resolves when the packet has been sent
|
||||
*/
|
||||
send<TOp extends ClientOperation>(packet: Packet<TOp>) {
|
||||
this.#throwIfDisconnected(
|
||||
'Cannot send a packet when already disconnected from the server'
|
||||
)
|
||||
|
||||
return new Promise<void>((resolve, reject) =>
|
||||
this.#socket.send(serializePacket(packet), err =>
|
||||
err ? reject(err) : resolve()
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the WebSocket API
|
||||
*/
|
||||
disconnect() {
|
||||
this.#throwIfDisconnected(
|
||||
'Cannot disconnect when already disconnected from the server'
|
||||
)
|
||||
|
||||
this.#handleDisconnect(DisconnectReason.Generic)
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the client is ready
|
||||
* @returns Whether the client is ready
|
||||
*/
|
||||
isReady(): this is ReadiedClientGateway {
|
||||
return this.ready
|
||||
}
|
||||
|
||||
#listen() {
|
||||
this.#socket.on('message', data => {
|
||||
const packet = deserializePacket(this._toBuffer(data))
|
||||
// TODO: maybe log this?
|
||||
// Just ignore the invalid packet, we don't have to disconnect
|
||||
if (!isServerPacket(packet)) return
|
||||
|
||||
this.#emitter.emit('packet', packet)
|
||||
|
||||
switch (packet.op) {
|
||||
case ServerOperation.Hello:
|
||||
// eslint-disable-next-line no-case-declarations
|
||||
const data = Object.freeze(
|
||||
(packet as Packet<ServerOperation.Hello>).d
|
||||
)
|
||||
this.config = data
|
||||
this.#emitter.emit('hello', data)
|
||||
this.#startHeartbeating()
|
||||
break
|
||||
case ServerOperation.Disconnect:
|
||||
return this.#handleDisconnect(
|
||||
(packet as Packet<ServerOperation.Disconnect>).d.reason
|
||||
)
|
||||
default:
|
||||
return this.#emitter.emit(
|
||||
uncapitalize(
|
||||
ServerOperation[
|
||||
packet.op
|
||||
] as ClientGatewayServerEventName
|
||||
),
|
||||
// @ts-expect-error TypeScript doesn't know that the lines above negate the type enough
|
||||
packet
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#throwIfDisconnected(errorMessage: string) {
|
||||
if (this.disconnected !== false) throw new Error(errorMessage)
|
||||
if (this.#socket.readyState !== this.#socket.OPEN)
|
||||
throw new Error(errorMessage)
|
||||
}
|
||||
|
||||
#handleDisconnect(reason: DisconnectReason) {
|
||||
clearTimeout(this.#hbTimeout)
|
||||
this.disconnected = reason
|
||||
this.#socket.close()
|
||||
|
||||
this.#emitter.emit('disconnect', reason)
|
||||
}
|
||||
|
||||
#startHeartbeating() {
|
||||
this.on('heartbeatAck', packet => {
|
||||
this.#hbTimeout = setTimeout(() => {
|
||||
this.send({
|
||||
op: ClientOperation.Heartbeat,
|
||||
d: null,
|
||||
})
|
||||
}, packet.d.nextHeartbeat - Date.now())
|
||||
})
|
||||
|
||||
// Immediately send a heartbeat so we can get when to send the next one
|
||||
this.send({
|
||||
op: ClientOperation.Heartbeat,
|
||||
d: null,
|
||||
})
|
||||
}
|
||||
|
||||
protected _toBuffer(data: RawData) {
|
||||
if (data instanceof Buffer) return data
|
||||
else if (data instanceof ArrayBuffer) return Buffer.from(data)
|
||||
else return Buffer.concat(data)
|
||||
}
|
||||
}
|
||||
|
||||
export interface ClientGatewayOptions {
|
||||
/**
|
||||
* The gateway URL to connect to
|
||||
*/
|
||||
url: string
|
||||
}
|
||||
|
||||
export type ClientGatewayServerEventName = keyof typeof ServerOperation
|
||||
|
||||
export type ClientGatewayEventHandlers = {
|
||||
[K in Uncapitalize<ClientGatewayServerEventName>]: (
|
||||
packet: Packet<(typeof ServerOperation)[Capitalize<K>]>
|
||||
) => Promise<void> | void
|
||||
} & {
|
||||
hello: (
|
||||
config: NonNullable<ClientGateway['config']>
|
||||
) => Promise<void> | void
|
||||
ready: () => Promise<void> | void
|
||||
packet: (packet: Packet<ServerOperation>) => Promise<void> | void
|
||||
disconnect: (reason: DisconnectReason) => Promise<void> | void
|
||||
}
|
||||
|
||||
export type ReadiedClientGateway = RequiredProperty<
|
||||
InstanceType<typeof ClientGateway>
|
||||
>
|
||||
import { EventEmitter } from 'events'
|
||||
import {
|
||||
ClientOperation,
|
||||
DisconnectReason,
|
||||
Packet,
|
||||
ServerOperation,
|
||||
deserializePacket,
|
||||
isServerPacket,
|
||||
serializePacket,
|
||||
uncapitalize,
|
||||
} from '@revanced/bot-shared'
|
||||
import type TypedEmitter from 'typed-emitter'
|
||||
import { type RawData, WebSocket } from 'ws'
|
||||
|
||||
/**
|
||||
* The class that handles the WebSocket connection to the server.
|
||||
* This is the only relevant class for the time being. But in the future, there may be more classes to handle different protocols of the API.
|
||||
*/
|
||||
export default class ClientGateway {
|
||||
readonly url: string
|
||||
ready = false
|
||||
disconnected: boolean | DisconnectReason = DisconnectReason.NeverConnected
|
||||
config: Readonly<Packet<ServerOperation.Hello>['d']> | null = null!
|
||||
|
||||
#hbTimeout: NodeJS.Timeout = null!
|
||||
#socket: WebSocket = null!
|
||||
#emitter = new EventEmitter() as TypedEmitter<ClientGatewayEventHandlers>
|
||||
|
||||
constructor(options: ClientGatewayOptions) {
|
||||
this.url = options.url
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the WebSocket API
|
||||
* @returns A promise that resolves when the client is ready
|
||||
*/
|
||||
connect() {
|
||||
return new Promise<void>((rs, rj) => {
|
||||
try {
|
||||
this.#socket = new WebSocket(this.url)
|
||||
|
||||
this.#socket.on('open', () => {
|
||||
this.disconnected = false
|
||||
rs()
|
||||
})
|
||||
|
||||
this.#socket.on('close', () =>
|
||||
this.#handleDisconnect(DisconnectReason.Generic),
|
||||
)
|
||||
|
||||
this.#listen()
|
||||
this.ready = true
|
||||
this.#emitter.emit('ready')
|
||||
} catch (e) {
|
||||
rj(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an event listener
|
||||
* @param name The event name to listen for
|
||||
* @param handler The event handler
|
||||
* @returns The event handler function
|
||||
*/
|
||||
on<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[typeof name],
|
||||
) {
|
||||
this.#emitter.on(name, handler)
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an event listener
|
||||
* @param name The event name to remove a listener from
|
||||
* @param handler The event handler to remove
|
||||
* @returns The removed event handler function
|
||||
*/
|
||||
off<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[typeof name],
|
||||
) {
|
||||
this.#emitter.off(name, handler)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an event listener that will only be called once
|
||||
* @param name The event name to listen for
|
||||
* @param handler The event handler
|
||||
* @returns The event handler function
|
||||
*/
|
||||
once<TOpName extends keyof ClientGatewayEventHandlers>(
|
||||
name: TOpName,
|
||||
handler: ClientGatewayEventHandlers[typeof name],
|
||||
) {
|
||||
this.#emitter.once(name, handler)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a packet to the server
|
||||
* @param packet The packet to send
|
||||
* @returns A promise that resolves when the packet has been sent
|
||||
*/
|
||||
send<TOp extends ClientOperation>(packet: Packet<TOp>) {
|
||||
this.#throwIfDisconnected(
|
||||
'Cannot send a packet when already disconnected from the server',
|
||||
)
|
||||
|
||||
return new Promise<void>((resolve, reject) =>
|
||||
this.#socket.send(serializePacket(packet), err =>
|
||||
err ? reject(err) : resolve(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the WebSocket API
|
||||
*/
|
||||
disconnect() {
|
||||
this.#throwIfDisconnected(
|
||||
'Cannot disconnect when already disconnected from the server',
|
||||
)
|
||||
|
||||
this.#handleDisconnect(DisconnectReason.Generic)
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the client is ready
|
||||
* @returns Whether the client is ready
|
||||
*/
|
||||
isReady(): this is ReadiedClientGateway {
|
||||
return this.ready
|
||||
}
|
||||
|
||||
#listen() {
|
||||
this.#socket.on('message', data => {
|
||||
const packet = deserializePacket(this._toBuffer(data))
|
||||
// TODO: maybe log this?
|
||||
// Just ignore the invalid packet, we don't have to disconnect
|
||||
if (!isServerPacket(packet)) return
|
||||
|
||||
this.#emitter.emit('packet', packet)
|
||||
|
||||
switch (packet.op) {
|
||||
case ServerOperation.Hello: {
|
||||
// eslint-disable-next-line no-case-declarations
|
||||
const data = Object.freeze(
|
||||
(packet as Packet<ServerOperation.Hello>).d,
|
||||
)
|
||||
this.config = data
|
||||
this.#emitter.emit('hello', data)
|
||||
this.#startHeartbeating()
|
||||
break
|
||||
}
|
||||
case ServerOperation.Disconnect:
|
||||
return this.#handleDisconnect(
|
||||
(packet as Packet<ServerOperation.Disconnect>).d.reason,
|
||||
)
|
||||
default:
|
||||
return this.#emitter.emit(
|
||||
uncapitalize(
|
||||
ServerOperation[
|
||||
packet.op
|
||||
] as ClientGatewayServerEventName,
|
||||
),
|
||||
// @ts-expect-error TypeScript doesn't know that the lines above negate the type enough
|
||||
packet,
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#throwIfDisconnected(errorMessage: string) {
|
||||
if (this.disconnected !== false) throw new Error(errorMessage)
|
||||
if (this.#socket.readyState !== this.#socket.OPEN)
|
||||
throw new Error(errorMessage)
|
||||
}
|
||||
|
||||
#handleDisconnect(reason: DisconnectReason) {
|
||||
clearTimeout(this.#hbTimeout)
|
||||
this.disconnected = reason
|
||||
this.#socket.close()
|
||||
|
||||
this.#emitter.emit('disconnect', reason)
|
||||
}
|
||||
|
||||
#startHeartbeating() {
|
||||
this.on('heartbeatAck', packet => {
|
||||
this.#hbTimeout = setTimeout(() => {
|
||||
this.send({
|
||||
op: ClientOperation.Heartbeat,
|
||||
d: null,
|
||||
})
|
||||
}, packet.d.nextHeartbeat - Date.now())
|
||||
})
|
||||
|
||||
// Immediately send a heartbeat so we can get when to send the next one
|
||||
this.send({
|
||||
op: ClientOperation.Heartbeat,
|
||||
d: null,
|
||||
})
|
||||
}
|
||||
|
||||
protected _toBuffer(data: RawData) {
|
||||
if (data instanceof Buffer) return data
|
||||
else if (data instanceof ArrayBuffer) return Buffer.from(data)
|
||||
else return Buffer.concat(data)
|
||||
}
|
||||
}
|
||||
|
||||
export interface ClientGatewayOptions {
|
||||
/**
|
||||
* The gateway URL to connect to
|
||||
*/
|
||||
url: string
|
||||
}
|
||||
|
||||
export type ClientGatewayServerEventName = keyof typeof ServerOperation
|
||||
|
||||
export type ClientGatewayEventHandlers = {
|
||||
[K in Uncapitalize<ClientGatewayServerEventName>]: (
|
||||
packet: Packet<typeof ServerOperation[Capitalize<K>]>,
|
||||
) => Promise<void> | void
|
||||
} & {
|
||||
hello: (
|
||||
config: NonNullable<ClientGateway['config']>,
|
||||
) => Promise<void> | void
|
||||
ready: () => Promise<void> | void
|
||||
packet: (packet: Packet<ServerOperation>) => Promise<void> | void
|
||||
disconnect: (reason: DisconnectReason) => Promise<void> | void
|
||||
}
|
||||
|
||||
export type ReadiedClientGateway = RequiredProperty<
|
||||
InstanceType<typeof ClientGateway>
|
||||
>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export { default as Client } from './Client.js'
|
||||
export * from './Client.js'
|
||||
export { default as ClientGateway } from './ClientGateway.js'
|
||||
export * from './ClientGateway.js'
|
||||
export { default as Client } from './Client.js'
|
||||
export * from './Client.js'
|
||||
export { default as ClientGateway } from './ClientGateway.js'
|
||||
export * from './ClientGateway.js'
|
||||
|
||||
@@ -1 +1 @@
|
||||
export * from './classes/index.js'
|
||||
export * from './classes/index.js'
|
||||
|
||||
2
packages/api/utility-types.d.ts
vendored
2
packages/api/utility-types.d.ts
vendored
@@ -1 +1 @@
|
||||
type RequiredProperty<T> = { [P in keyof T]: Required<NonNullable<T[P]>> }
|
||||
type RequiredProperty<T> = { [P in keyof T]: Required<NonNullable<T[P]>> }
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
/**
|
||||
* Disconnect reasons for clients
|
||||
*/
|
||||
enum DisconnectReason {
|
||||
/**
|
||||
* Unknown reason
|
||||
*/
|
||||
Generic = 1,
|
||||
/**
|
||||
* The client did not respond in time
|
||||
*/
|
||||
TimedOut,
|
||||
/**
|
||||
* The client sent an invalid packet (unserializable or invalid JSON)
|
||||
*/
|
||||
InvalidPacket,
|
||||
/**
|
||||
* The server has encountered an internal error
|
||||
*/
|
||||
ServerError,
|
||||
/**
|
||||
* The client had never connected to the server (**CLIENT-ONLY**)
|
||||
*/
|
||||
NeverConnected,
|
||||
}
|
||||
|
||||
export default DisconnectReason
|
||||
/**
|
||||
* Disconnect reasons for clients
|
||||
*/
|
||||
enum DisconnectReason {
|
||||
/**
|
||||
* Unknown reason
|
||||
*/
|
||||
Generic = 1,
|
||||
/**
|
||||
* The client did not respond in time
|
||||
*/
|
||||
TimedOut = 2,
|
||||
/**
|
||||
* The client sent an invalid packet (unserializable or invalid JSON)
|
||||
*/
|
||||
InvalidPacket = 3,
|
||||
/**
|
||||
* The server has encountered an internal error
|
||||
*/
|
||||
ServerError = 4,
|
||||
/**
|
||||
* The client had never connected to the server (**CLIENT-ONLY**)
|
||||
*/
|
||||
NeverConnected = 5,
|
||||
}
|
||||
|
||||
export default DisconnectReason
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import DisconnectReason from './DisconnectReason.js'
|
||||
|
||||
/**
|
||||
* Humanized disconnect reasons for logs
|
||||
*/
|
||||
const HumanizedDisconnectReason = {
|
||||
[DisconnectReason.InvalidPacket]: 'has sent invalid packet',
|
||||
[DisconnectReason.Generic]: 'has been disconnected for unknown reasons',
|
||||
[DisconnectReason.TimedOut]: 'has timed out',
|
||||
[DisconnectReason.ServerError]:
|
||||
'has been disconnected due to an internal server error',
|
||||
[DisconnectReason.NeverConnected]: 'had never connected to the server',
|
||||
} as const satisfies Record<DisconnectReason, string>
|
||||
|
||||
export default HumanizedDisconnectReason
|
||||
import DisconnectReason from './DisconnectReason.js'
|
||||
|
||||
/**
|
||||
* Humanized disconnect reasons for logs
|
||||
*/
|
||||
const HumanizedDisconnectReason = {
|
||||
[DisconnectReason.InvalidPacket]: 'has sent invalid packet',
|
||||
[DisconnectReason.Generic]: 'has been disconnected for unknown reasons',
|
||||
[DisconnectReason.TimedOut]: 'has timed out',
|
||||
[DisconnectReason.ServerError]:
|
||||
'has been disconnected due to an internal server error',
|
||||
[DisconnectReason.NeverConnected]: 'had never connected to the server',
|
||||
} as const satisfies Record<DisconnectReason, string>
|
||||
|
||||
export default HumanizedDisconnectReason
|
||||
|
||||
@@ -1,57 +1,57 @@
|
||||
/**
|
||||
* Client operation codes for the gateway
|
||||
*/
|
||||
export enum ClientOperation {
|
||||
/**
|
||||
* Client's heartbeat (to check if the connection is dead or not)
|
||||
*/
|
||||
Heartbeat = 100,
|
||||
|
||||
/**
|
||||
* Client's request to parse text
|
||||
*/
|
||||
ParseText = 110,
|
||||
/**
|
||||
* Client's request to parse image
|
||||
*/
|
||||
ParseImage,
|
||||
}
|
||||
|
||||
/**
|
||||
* Server operation codes for the gateway
|
||||
*/
|
||||
export enum ServerOperation {
|
||||
/**
|
||||
* Server's acknowledgement of a client's heartbeat
|
||||
*/
|
||||
HeartbeatAck = 1,
|
||||
/**
|
||||
* Server's initial response to a client's connection
|
||||
*/
|
||||
Hello,
|
||||
|
||||
/**
|
||||
* Server's response to client's request to parse text
|
||||
*/
|
||||
ParsedText = 10,
|
||||
/**
|
||||
* Server's response to client's request to parse image
|
||||
*/
|
||||
ParsedImage,
|
||||
/**
|
||||
* Server's failure response to client's request to parse text
|
||||
*/
|
||||
ParseTextFailed,
|
||||
/**
|
||||
* Server's failure response to client's request to parse image
|
||||
*/
|
||||
ParseImageFailed,
|
||||
|
||||
/**
|
||||
* Server's disconnect message
|
||||
*/
|
||||
Disconnect = 20,
|
||||
}
|
||||
|
||||
export const Operation = { ...ClientOperation, ...ServerOperation } as const
|
||||
export type Operation = ClientOperation | ServerOperation
|
||||
/**
|
||||
* Client operation codes for the gateway
|
||||
*/
|
||||
export enum ClientOperation {
|
||||
/**
|
||||
* Client's heartbeat (to check if the connection is dead or not)
|
||||
*/
|
||||
Heartbeat = 100,
|
||||
|
||||
/**
|
||||
* Client's request to parse text
|
||||
*/
|
||||
ParseText = 110,
|
||||
/**
|
||||
* Client's request to parse image
|
||||
*/
|
||||
ParseImage = 111,
|
||||
}
|
||||
|
||||
/**
|
||||
* Server operation codes for the gateway
|
||||
*/
|
||||
export enum ServerOperation {
|
||||
/**
|
||||
* Server's acknowledgement of a client's heartbeat
|
||||
*/
|
||||
HeartbeatAck = 1,
|
||||
/**
|
||||
* Server's initial response to a client's connection
|
||||
*/
|
||||
Hello = 2,
|
||||
|
||||
/**
|
||||
* Server's response to client's request to parse text
|
||||
*/
|
||||
ParsedText = 10,
|
||||
/**
|
||||
* Server's response to client's request to parse image
|
||||
*/
|
||||
ParsedImage = 11,
|
||||
/**
|
||||
* Server's failure response to client's request to parse text
|
||||
*/
|
||||
ParseTextFailed = 12,
|
||||
/**
|
||||
* Server's failure response to client's request to parse image
|
||||
*/
|
||||
ParseImageFailed = 13,
|
||||
|
||||
/**
|
||||
* Server's disconnect message
|
||||
*/
|
||||
Disconnect = 20,
|
||||
}
|
||||
|
||||
export const Operation = { ...ClientOperation, ...ServerOperation } as const
|
||||
export type Operation = ClientOperation | ServerOperation
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export { default as DisconnectReason } from './DisconnectReason.js'
|
||||
export { default as HumanizedDisconnectReason } from './HumanizedDisconnectReason.js'
|
||||
export * from './Operation.js'
|
||||
export { default as DisconnectReason } from './DisconnectReason.js'
|
||||
export { default as HumanizedDisconnectReason } from './HumanizedDisconnectReason.js'
|
||||
export * from './Operation.js'
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export * from './constants/index.js'
|
||||
export * from './schemas/index.js'
|
||||
export * from './utils/index.js'
|
||||
export * from './constants/index.js'
|
||||
export * from './schemas/index.js'
|
||||
export * from './utils/index.js'
|
||||
|
||||
@@ -1,101 +1,101 @@
|
||||
import DisconnectReason from '../constants/DisconnectReason.js'
|
||||
import {
|
||||
ClientOperation,
|
||||
Operation,
|
||||
ServerOperation,
|
||||
} from '../constants/Operation.js'
|
||||
import {
|
||||
object,
|
||||
enum_,
|
||||
special,
|
||||
ObjectSchema,
|
||||
number,
|
||||
string,
|
||||
Output,
|
||||
AnySchema,
|
||||
null_,
|
||||
NullSchema,
|
||||
array,
|
||||
url,
|
||||
parse,
|
||||
// merge
|
||||
} from 'valibot'
|
||||
|
||||
/**
|
||||
* Schema to validate packets
|
||||
*/
|
||||
export const PacketSchema = special<Packet>(input => {
|
||||
if (
|
||||
typeof input === 'object' &&
|
||||
input &&
|
||||
'op' in input &&
|
||||
typeof input.op === 'number' &&
|
||||
input.op in Operation &&
|
||||
'd' in input &&
|
||||
typeof input.d === 'object'
|
||||
) {
|
||||
try {
|
||||
parse(PacketDataSchemas[input.op as Operation], input.d)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}, 'Invalid packet data')
|
||||
|
||||
/**
|
||||
* Schema to validate packet data for each possible operations
|
||||
*/
|
||||
export const PacketDataSchemas = {
|
||||
[ServerOperation.Hello]: object({
|
||||
heartbeatInterval: number(),
|
||||
}),
|
||||
[ServerOperation.HeartbeatAck]: object({
|
||||
nextHeartbeat: number(),
|
||||
}),
|
||||
[ServerOperation.ParsedText]: object({
|
||||
id: string(),
|
||||
labels: array(
|
||||
object({
|
||||
name: string(),
|
||||
confidence: special<number>(
|
||||
input =>
|
||||
typeof input === 'number' && input >= 0 && input <= 1
|
||||
),
|
||||
})
|
||||
),
|
||||
}),
|
||||
[ServerOperation.ParsedImage]: object({
|
||||
id: string(),
|
||||
text: string(),
|
||||
}),
|
||||
[ServerOperation.ParseTextFailed]: object({
|
||||
id: string(),
|
||||
}),
|
||||
[ServerOperation.ParseImageFailed]: object({
|
||||
id: string(),
|
||||
}),
|
||||
[ServerOperation.Disconnect]: object({
|
||||
reason: enum_(DisconnectReason),
|
||||
}),
|
||||
|
||||
[ClientOperation.Heartbeat]: null_(),
|
||||
[ClientOperation.ParseText]: object({
|
||||
id: string(),
|
||||
text: string(),
|
||||
}),
|
||||
[ClientOperation.ParseImage]: object({
|
||||
id: string(),
|
||||
image_url: string([url()]),
|
||||
}),
|
||||
} as const satisfies Record<
|
||||
Operation,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
ObjectSchema<any> | AnySchema | NullSchema
|
||||
>
|
||||
|
||||
export type Packet<TOp extends Operation = Operation> = {
|
||||
op: TOp
|
||||
d: Output<(typeof PacketDataSchemas)[TOp]>
|
||||
}
|
||||
import {
|
||||
url,
|
||||
AnySchema,
|
||||
NullSchema,
|
||||
ObjectSchema,
|
||||
Output,
|
||||
array,
|
||||
enum_,
|
||||
null_,
|
||||
number,
|
||||
object,
|
||||
parse,
|
||||
special,
|
||||
string,
|
||||
// merge
|
||||
} from 'valibot'
|
||||
import DisconnectReason from '../constants/DisconnectReason.js'
|
||||
import {
|
||||
ClientOperation,
|
||||
Operation,
|
||||
ServerOperation,
|
||||
} from '../constants/Operation.js'
|
||||
|
||||
/**
|
||||
* Schema to validate packets
|
||||
*/
|
||||
export const PacketSchema = special<Packet>(input => {
|
||||
if (
|
||||
typeof input === 'object' &&
|
||||
input &&
|
||||
'op' in input &&
|
||||
typeof input.op === 'number' &&
|
||||
input.op in Operation &&
|
||||
'd' in input &&
|
||||
typeof input.d === 'object'
|
||||
) {
|
||||
try {
|
||||
parse(PacketDataSchemas[input.op as Operation], input.d)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}, 'Invalid packet data')
|
||||
|
||||
/**
|
||||
* Schema to validate packet data for each possible operations
|
||||
*/
|
||||
export const PacketDataSchemas = {
|
||||
[ServerOperation.Hello]: object({
|
||||
heartbeatInterval: number(),
|
||||
}),
|
||||
[ServerOperation.HeartbeatAck]: object({
|
||||
nextHeartbeat: number(),
|
||||
}),
|
||||
[ServerOperation.ParsedText]: object({
|
||||
id: string(),
|
||||
labels: array(
|
||||
object({
|
||||
name: string(),
|
||||
confidence: special<number>(
|
||||
input =>
|
||||
typeof input === 'number' && input >= 0 && input <= 1,
|
||||
),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
[ServerOperation.ParsedImage]: object({
|
||||
id: string(),
|
||||
text: string(),
|
||||
}),
|
||||
[ServerOperation.ParseTextFailed]: object({
|
||||
id: string(),
|
||||
}),
|
||||
[ServerOperation.ParseImageFailed]: object({
|
||||
id: string(),
|
||||
}),
|
||||
[ServerOperation.Disconnect]: object({
|
||||
reason: enum_(DisconnectReason),
|
||||
}),
|
||||
|
||||
[ClientOperation.Heartbeat]: null_(),
|
||||
[ClientOperation.ParseText]: object({
|
||||
id: string(),
|
||||
text: string(),
|
||||
}),
|
||||
[ClientOperation.ParseImage]: object({
|
||||
id: string(),
|
||||
image_url: string([url()]),
|
||||
}),
|
||||
} as const satisfies Record<
|
||||
Operation,
|
||||
// biome-ignore lint/suspicious/noExplicitAny: This is a schema, it's not possible to type it
|
||||
ObjectSchema<any> | AnySchema | NullSchema
|
||||
>
|
||||
|
||||
export type Packet<TOp extends Operation = Operation> = {
|
||||
op: TOp
|
||||
d: Output<typeof PacketDataSchemas[TOp]>
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
export * from './Packet.js'
|
||||
export * from './Packet.js'
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
import { Packet } from '../schemas/Packet.js'
|
||||
import {
|
||||
ClientOperation,
|
||||
Operation,
|
||||
ServerOperation,
|
||||
} from '../constants/Operation.js'
|
||||
|
||||
/**
|
||||
* Checks whether a packet is trying to do the given operation
|
||||
* @param op Operation code to check
|
||||
* @param packet A packet
|
||||
* @returns Whether this packet is trying to do the operation given
|
||||
*/
|
||||
export function packetMatchesOperation<TOp extends Operation>(
|
||||
op: TOp,
|
||||
packet: Packet
|
||||
): packet is Packet<TOp> {
|
||||
return packet.op === op
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this packet is a client packet **(this does NOT validate the data)**
|
||||
* @param packet A packet
|
||||
* @returns Whether this packet is a client packet
|
||||
*/
|
||||
export function isClientPacket(
|
||||
packet: Packet
|
||||
): packet is Packet<ClientOperation> {
|
||||
return packet.op in ClientOperation
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this packet is a server packet **(this does NOT validate the data)**
|
||||
* @param packet A packet
|
||||
* @returns Whether this packet is a server packet
|
||||
*/
|
||||
export function isServerPacket(
|
||||
packet: Packet
|
||||
): packet is Packet<ServerOperation> {
|
||||
return packet.op in ServerOperation
|
||||
}
|
||||
import {
|
||||
ClientOperation,
|
||||
Operation,
|
||||
ServerOperation,
|
||||
} from '../constants/Operation.js'
|
||||
import { Packet } from '../schemas/Packet.js'
|
||||
|
||||
/**
|
||||
* Checks whether a packet is trying to do the given operation
|
||||
* @param op Operation code to check
|
||||
* @param packet A packet
|
||||
* @returns Whether this packet is trying to do the operation given
|
||||
*/
|
||||
export function packetMatchesOperation<TOp extends Operation>(
|
||||
op: TOp,
|
||||
packet: Packet,
|
||||
): packet is Packet<TOp> {
|
||||
return packet.op === op
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this packet is a client packet **(this does NOT validate the data)**
|
||||
* @param packet A packet
|
||||
* @returns Whether this packet is a client packet
|
||||
*/
|
||||
export function isClientPacket(
|
||||
packet: Packet,
|
||||
): packet is Packet<ClientOperation> {
|
||||
return packet.op in ClientOperation
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this packet is a server packet **(this does NOT validate the data)**
|
||||
* @param packet A packet
|
||||
* @returns Whether this packet is a server packet
|
||||
*/
|
||||
export function isServerPacket(
|
||||
packet: Packet,
|
||||
): packet is Packet<ServerOperation> {
|
||||
return packet.op in ServerOperation
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export * from './guard.js'
|
||||
export * from './serialization.js'
|
||||
export * from './string.js'
|
||||
export * from './guard.js'
|
||||
export * from './serialization.js'
|
||||
export * from './string.js'
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import * as BSON from 'bson'
|
||||
import { Packet, PacketSchema } from '../schemas/index.js'
|
||||
import { Operation } from '../constants/index.js'
|
||||
import { parse } from 'valibot'
|
||||
|
||||
/**
|
||||
* Compresses a packet into a buffer
|
||||
* @param packet The packet to compress
|
||||
* @returns A buffer of the compressed packet
|
||||
*/
|
||||
export function serializePacket<TOp extends Operation>(packet: Packet<TOp>) {
|
||||
return BSON.serialize(packet)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompresses a buffer into a packet
|
||||
* @param buffer The buffer to decompress
|
||||
* @returns A packet
|
||||
*/
|
||||
export function deserializePacket(buffer: Buffer) {
|
||||
const data = BSON.deserialize(buffer)
|
||||
return parse(PacketSchema, data) as Packet
|
||||
}
|
||||
import * as BSON from 'bson'
|
||||
import { parse } from 'valibot'
|
||||
import { Operation } from '../constants/index.js'
|
||||
import { Packet, PacketSchema } from '../schemas/index.js'
|
||||
|
||||
/**
|
||||
* Compresses a packet into a buffer
|
||||
* @param packet The packet to compress
|
||||
* @returns A buffer of the compressed packet
|
||||
*/
|
||||
export function serializePacket<TOp extends Operation>(packet: Packet<TOp>) {
|
||||
return BSON.serialize(packet)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompresses a buffer into a packet
|
||||
* @param buffer The buffer to decompress
|
||||
* @returns A packet
|
||||
*/
|
||||
export function deserializePacket(buffer: Buffer) {
|
||||
const data = BSON.deserialize(buffer)
|
||||
return parse(PacketSchema, data) as Packet
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* Uncapitalizes the first letter of a string
|
||||
* @param str The string to uncapitalize
|
||||
* @returns The uncapitalized string
|
||||
*/
|
||||
export function uncapitalize<T extends string>(str: T): Uncapitalize<T> {
|
||||
return (str.charAt(0).toLowerCase() + str.slice(1)) as Uncapitalize<T>
|
||||
}
|
||||
/**
|
||||
* Uncapitalizes the first letter of a string
|
||||
* @param str The string to uncapitalize
|
||||
* @returns The uncapitalized string
|
||||
*/
|
||||
export function uncapitalize<T extends string>(str: T): Uncapitalize<T> {
|
||||
return (str.charAt(0).toLowerCase() + str.slice(1)) as Uncapitalize<T>
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user