chore: apply code fixes with biome

This commit is contained in:
PalmDevs
2023-11-28 22:03:41 +07:00
parent c80bd068fa
commit f2d85c32a4
32 changed files with 1384 additions and 1383 deletions

View File

@@ -1,218 +1,218 @@
import {
ClientOperation,
DisconnectReason,
Packet,
ServerOperation,
deserializePacket,
isClientPacket,
serializePacket,
uncapitalize,
} from '@revanced/bot-shared'
import { EventEmitter } from 'node:events'
import type TypedEmitter from 'typed-emitter'
import type { RawData, WebSocket } from 'ws'
export default class Client {
id: string
disconnected: DisconnectReason | false = false
ready: boolean = false
lastHeartbeat: number = null!
heartbeatInterval: number
#hbTimeout: NodeJS.Timeout = null!
#emitter = new EventEmitter() as TypedEmitter<ClientEventHandlers>
#socket: WebSocket
constructor(options: ClientOptions) {
this.#socket = options.socket
this.heartbeatInterval = options.heartbeatInterval ?? 60000
this.id = options.id
this.#socket.on('error', () => this.forceDisconnect())
this.#socket.on('close', () => this.forceDisconnect())
this.#socket.on('unexpected-response', () => this.forceDisconnect())
this.send({
op: ServerOperation.Hello,
d: {
heartbeatInterval: this.heartbeatInterval,
},
})
.then(() => {
this.#listen()
this.#listenHeartbeat()
this.ready = true
this.#emitter.emit('ready')
})
.catch(() => {
if (this.disconnected === false)
this.disconnect(DisconnectReason.ServerError)
else this.forceDisconnect(DisconnectReason.ServerError)
})
}
on<TOpName extends keyof ClientEventHandlers>(
name: TOpName,
handler: ClientEventHandlers[typeof name]
) {
this.#emitter.on(name, handler)
}
once<TOpName extends keyof ClientEventHandlers>(
name: TOpName,
handler: ClientEventHandlers[typeof name]
) {
this.#emitter.once(name, handler)
}
off<TOpName extends keyof ClientEventHandlers>(
name: TOpName,
handler: ClientEventHandlers[typeof name]
) {
this.#emitter.off(name, handler)
}
send<TOp extends ServerOperation>(packet: Packet<TOp>) {
return new Promise<void>((resolve, reject) => {
try {
this.#throwIfDisconnected(
'Cannot send packet to client that has already disconnected'
)
this.#socket.send(serializePacket(packet), err =>
err ? reject(err) : resolve()
)
} catch (e) {
reject(e)
}
})
}
async disconnect(reason: DisconnectReason = DisconnectReason.Generic) {
this.#throwIfDisconnected(
'Cannot disconnect client that has already disconnected'
)
try {
await this.send({ op: ServerOperation.Disconnect, d: { reason } })
} catch (err) {
throw new Error(
`Cannot send disconnect reason to client ${this.id}: ${err}`
)
} finally {
this.forceDisconnect(reason)
}
}
forceDisconnect(reason: DisconnectReason = DisconnectReason.Generic) {
if (this.disconnected !== false) return
if (this.#hbTimeout) clearTimeout(this.#hbTimeout)
this.#socket.terminate()
this.ready = false
this.disconnected = reason
this.#emitter.emit('disconnect', reason)
}
#throwIfDisconnected(errorMessage: string) {
if (this.disconnected !== false) throw new Error(errorMessage)
if (this.#socket.readyState !== this.#socket.OPEN) {
this.forceDisconnect(DisconnectReason.Generic)
throw new Error(errorMessage)
}
}
#listen() {
this.#socket.on('message', data => {
try {
const rawPacket = deserializePacket(this._toBuffer(data))
if (!isClientPacket(rawPacket)) throw null
const packet: ClientPacketObject<ClientOperation> = {
...rawPacket,
client: this,
}
this.#emitter.emit('packet', packet)
this.#emitter.emit(
uncapitalize(ClientOperation[packet.op] as ClientEventName),
// @ts-expect-error TypeScript doesn't know that the above line will negate the type enough
packet
)
} catch (e) {
// TODO: add error fields to sent packet so we can log what went wrong
this.disconnect(DisconnectReason.InvalidPacket)
}
})
}
#listenHeartbeat() {
this.lastHeartbeat = Date.now()
this.#startHeartbeatTimeout()
this.on('heartbeat', () => {
this.lastHeartbeat = Date.now()
this.#hbTimeout.refresh()
this.send({
op: ServerOperation.HeartbeatAck,
d: {
nextHeartbeat: this.lastHeartbeat + this.heartbeatInterval,
},
}).catch(() => {})
})
}
#startHeartbeatTimeout() {
this.#hbTimeout = setTimeout(() => {
if (Date.now() - this.lastHeartbeat > 0) {
// TODO: put into config
// 5000 is extra time to account for latency
const interval = setTimeout(
() => this.disconnect(DisconnectReason.TimedOut),
5000
)
this.once('heartbeat', () => clearTimeout(interval))
// This should never happen but it did in my testing so I'm adding this just in case
this.once('disconnect', () => clearTimeout(interval))
// Technically we don't have to do this, but JUST IN CASE!
} else this.#hbTimeout.refresh()
}, this.heartbeatInterval)
}
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 ClientOptions {
id: string
socket: WebSocket
heartbeatInterval?: number
}
export type ClientPacketObject<TOp extends ClientOperation> = Packet<TOp> & {
client: Client
}
export type ClientEventName = keyof typeof ClientOperation
export type ClientEventHandlers = {
[K in Uncapitalize<ClientEventName>]: (
packet: ClientPacketObject<(typeof ClientOperation)[Capitalize<K>]>
) => Promise<void> | void
} & {
ready: () => Promise<void> | void
packet: (
packet: ClientPacketObject<ClientOperation>
) => Promise<void> | void
disconnect: (reason: DisconnectReason) => Promise<void> | void
}
import { EventEmitter } from 'node:events'
import {
ClientOperation,
DisconnectReason,
Packet,
ServerOperation,
deserializePacket,
isClientPacket,
serializePacket,
uncapitalize,
} from '@revanced/bot-shared'
import type TypedEmitter from 'typed-emitter'
import type { RawData, WebSocket } from 'ws'
export default class Client {
id: string
disconnected: DisconnectReason | false = false
ready = false
lastHeartbeat: number = null!
heartbeatInterval: number
#hbTimeout: NodeJS.Timeout = null!
#emitter = new EventEmitter() as TypedEmitter<ClientEventHandlers>
#socket: WebSocket
constructor(options: ClientOptions) {
this.#socket = options.socket
this.heartbeatInterval = options.heartbeatInterval ?? 60000
this.id = options.id
this.#socket.on('error', () => this.forceDisconnect())
this.#socket.on('close', () => this.forceDisconnect())
this.#socket.on('unexpected-response', () => this.forceDisconnect())
this.send({
op: ServerOperation.Hello,
d: {
heartbeatInterval: this.heartbeatInterval,
},
})
.then(() => {
this.#listen()
this.#listenHeartbeat()
this.ready = true
this.#emitter.emit('ready')
})
.catch(() => {
if (this.disconnected === false)
this.disconnect(DisconnectReason.ServerError)
else this.forceDisconnect(DisconnectReason.ServerError)
})
}
on<TOpName extends keyof ClientEventHandlers>(
name: TOpName,
handler: ClientEventHandlers[typeof name],
) {
this.#emitter.on(name, handler)
}
once<TOpName extends keyof ClientEventHandlers>(
name: TOpName,
handler: ClientEventHandlers[typeof name],
) {
this.#emitter.once(name, handler)
}
off<TOpName extends keyof ClientEventHandlers>(
name: TOpName,
handler: ClientEventHandlers[typeof name],
) {
this.#emitter.off(name, handler)
}
send<TOp extends ServerOperation>(packet: Packet<TOp>) {
return new Promise<void>((resolve, reject) => {
try {
this.#throwIfDisconnected(
'Cannot send packet to client that has already disconnected',
)
this.#socket.send(serializePacket(packet), err =>
err ? reject(err) : resolve(),
)
} catch (e) {
reject(e)
}
})
}
async disconnect(reason: DisconnectReason = DisconnectReason.Generic) {
this.#throwIfDisconnected(
'Cannot disconnect client that has already disconnected',
)
try {
await this.send({ op: ServerOperation.Disconnect, d: { reason } })
} catch (err) {
throw new Error(
`Cannot send disconnect reason to client ${this.id}: ${err}`,
)
} finally {
this.forceDisconnect(reason)
}
}
forceDisconnect(reason: DisconnectReason = DisconnectReason.Generic) {
if (this.disconnected !== false) return
if (this.#hbTimeout) clearTimeout(this.#hbTimeout)
this.#socket.terminate()
this.ready = false
this.disconnected = reason
this.#emitter.emit('disconnect', reason)
}
#throwIfDisconnected(errorMessage: string) {
if (this.disconnected !== false) throw new Error(errorMessage)
if (this.#socket.readyState !== this.#socket.OPEN) {
this.forceDisconnect(DisconnectReason.Generic)
throw new Error(errorMessage)
}
}
#listen() {
this.#socket.on('message', data => {
try {
const rawPacket = deserializePacket(this._toBuffer(data))
if (!isClientPacket(rawPacket)) throw null
const packet: ClientPacketObject<ClientOperation> = {
...rawPacket,
client: this,
}
this.#emitter.emit('packet', packet)
this.#emitter.emit(
uncapitalize(ClientOperation[packet.op] as ClientEventName),
// @ts-expect-error TypeScript doesn't know that the above line will negate the type enough
packet,
)
} catch (e) {
// TODO: add error fields to sent packet so we can log what went wrong
this.disconnect(DisconnectReason.InvalidPacket)
}
})
}
#listenHeartbeat() {
this.lastHeartbeat = Date.now()
this.#startHeartbeatTimeout()
this.on('heartbeat', () => {
this.lastHeartbeat = Date.now()
this.#hbTimeout.refresh()
this.send({
op: ServerOperation.HeartbeatAck,
d: {
nextHeartbeat: this.lastHeartbeat + this.heartbeatInterval,
},
}).catch(() => {})
})
}
#startHeartbeatTimeout() {
this.#hbTimeout = setTimeout(() => {
if (Date.now() - this.lastHeartbeat > 0) {
// TODO: put into config
// 5000 is extra time to account for latency
const interval = setTimeout(
() => this.disconnect(DisconnectReason.TimedOut),
5000,
)
this.once('heartbeat', () => clearTimeout(interval))
// This should never happen but it did in my testing so I'm adding this just in case
this.once('disconnect', () => clearTimeout(interval))
// Technically we don't have to do this, but JUST IN CASE!
} else this.#hbTimeout.refresh()
}, this.heartbeatInterval)
}
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 ClientOptions {
id: string
socket: WebSocket
heartbeatInterval?: number
}
export type ClientPacketObject<TOp extends ClientOperation> = Packet<TOp> & {
client: Client
}
export type ClientEventName = keyof typeof ClientOperation
export type ClientEventHandlers = {
[K in Uncapitalize<ClientEventName>]: (
packet: ClientPacketObject<typeof ClientOperation[Capitalize<K>]>,
) => Promise<void> | void
} & {
ready: () => Promise<void> | void
packet: (
packet: ClientPacketObject<ClientOperation>,
) => Promise<void> | void
disconnect: (reason: DisconnectReason) => Promise<void> | void
}

View File

@@ -1,20 +1,20 @@
import type { ClientOperation } from '@revanced/bot-shared'
import type { Wit } from 'node-wit'
import { ClientPacketObject } from '../classes/Client.js'
import type { Config } from '../utils/getConfig.js'
import type { Logger } from '../utils/logger.js'
import type { Worker as TesseractWorker } from 'tesseract.js'
export { default as parseTextEventHandler } from './parseText.js'
export { default as parseImageEventHandler } from './parseImage.js'
export type EventHandler<POp extends ClientOperation> = (
packet: ClientPacketObject<POp>,
context: EventContext
) => void | Promise<void>
export type EventContext = {
witClient: Wit
tesseractWorker: TesseractWorker
logger: Logger
config: Config
}
import type { ClientOperation } from '@revanced/bot-shared'
import type { Wit } from 'node-wit'
import type { Worker as TesseractWorker } from 'tesseract.js'
import { ClientPacketObject } from '../classes/Client.js'
import type { Config } from '../utils/getConfig.js'
import type { Logger } from '../utils/logger.js'
export { default as parseTextEventHandler } from './parseText.js'
export { default as parseImageEventHandler } from './parseImage.js'
export type EventHandler<POp extends ClientOperation> = (
packet: ClientPacketObject<POp>,
context: EventContext,
) => void | Promise<void>
export type EventContext = {
witClient: Wit
tesseractWorker: TesseractWorker
logger: Logger
config: Config
}

View File

@@ -1,63 +1,63 @@
import { ClientOperation, ServerOperation } from '@revanced/bot-shared'
import { AsyncQueue } from '@sapphire/async-queue'
import type { EventHandler } from './index.js'
const queue = new AsyncQueue()
const parseImageEventHandler: EventHandler<ClientOperation.ParseImage> = async (
packet,
{ tesseractWorker, logger, config }
) => {
const {
client,
d: { image_url: imageUrl, id },
} = packet
logger.debug(
`Client ${client.id} requested to parse image from URL:`,
imageUrl
)
logger.debug(
`Queue currently has ${queue.remaining}/${config.ocrConcurrentQueues} items in it`
)
if (queue.remaining < config.ocrConcurrentQueues) queue.shift()
await queue.wait()
try {
logger.debug(`Recognizing image from URL for client ${client.id}`)
const { data, jobId } = await tesseractWorker.recognize(imageUrl)
logger.debug(
`Recognized image from URL for client ${client.id} (job ${jobId}):`,
data.text
)
await client.send({
op: ServerOperation.ParsedImage,
d: {
id,
text: data.text,
},
})
} catch {
logger.error(
`Failed to parse image from URL for client ${client.id}:`,
imageUrl
)
await client.send({
op: ServerOperation.ParseImageFailed,
d: {
id,
},
})
} finally {
queue.shift()
logger.debug(
`Finished processing image from URL for client ${client.id}, queue has ${queue.remaining}/${config.ocrConcurrentQueues} remaining items in it`
)
}
}
export default parseImageEventHandler
import { ClientOperation, ServerOperation } from '@revanced/bot-shared'
import { AsyncQueue } from '@sapphire/async-queue'
import type { EventHandler } from './index.js'
const queue = new AsyncQueue()
const parseImageEventHandler: EventHandler<ClientOperation.ParseImage> = async (
packet,
{ tesseractWorker, logger, config },
) => {
const {
client,
d: { image_url: imageUrl, id },
} = packet
logger.debug(
`Client ${client.id} requested to parse image from URL:`,
imageUrl,
)
logger.debug(
`Queue currently has ${queue.remaining}/${config.ocrConcurrentQueues} items in it`,
)
if (queue.remaining < config.ocrConcurrentQueues) queue.shift()
await queue.wait()
try {
logger.debug(`Recognizing image from URL for client ${client.id}`)
const { data, jobId } = await tesseractWorker.recognize(imageUrl)
logger.debug(
`Recognized image from URL for client ${client.id} (job ${jobId}):`,
data.text,
)
await client.send({
op: ServerOperation.ParsedImage,
d: {
id,
text: data.text,
},
})
} catch {
logger.error(
`Failed to parse image from URL for client ${client.id}:`,
imageUrl,
)
await client.send({
op: ServerOperation.ParseImageFailed,
d: {
id,
},
})
} finally {
queue.shift()
logger.debug(
`Finished processing image from URL for client ${client.id}, queue has ${queue.remaining}/${config.ocrConcurrentQueues} remaining items in it`,
)
}
}
export default parseImageEventHandler

View File

@@ -1,43 +1,43 @@
import { ClientOperation, ServerOperation } from '@revanced/bot-shared'
import { inspect as inspectObject } from 'node:util'
import type { EventHandler } from './index.js'
const parseTextEventHandler: EventHandler<ClientOperation.ParseText> = async (
packet,
{ witClient, logger }
) => {
const {
client,
d: { text, id },
} = packet
logger.debug(`Client ${client.id} requested to parse text:`, text)
try {
const { intents } = await witClient.message(text, {})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const intentsWithoutIds = intents.map(({ id, ...rest }) => rest)
await client.send({
op: ServerOperation.ParsedText,
d: {
id,
labels: intentsWithoutIds,
},
})
} catch (e) {
await client.send({
op: ServerOperation.ParseTextFailed,
d: {
id,
},
})
if (e instanceof Error) logger.error(e.stack ?? e.message)
else logger.error(inspectObject(e))
}
}
export default parseTextEventHandler
import { ClientOperation, ServerOperation } from '@revanced/bot-shared'
import { inspect as inspectObject } from 'node:util'
import type { EventHandler } from './index.js'
const parseTextEventHandler: EventHandler<ClientOperation.ParseText> = async (
packet,
{ witClient, logger },
) => {
const {
client,
d: { text, id },
} = packet
logger.debug(`Client ${client.id} requested to parse text:`, text)
try {
const { intents } = await witClient.message(text, {})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const intentsWithoutIds = intents.map(({ id, ...rest }) => rest)
await client.send({
op: ServerOperation.ParsedText,
d: {
id,
labels: intentsWithoutIds,
},
})
} catch (e) {
await client.send({
op: ServerOperation.ParseTextFailed,
d: {
id,
},
})
if (e instanceof Error) logger.error(e.stack ?? e.message)
else logger.error(inspectObject(e))
}
}
export default parseTextEventHandler

View File

@@ -1,157 +1,157 @@
import { fastify } from 'fastify'
import fastifyWebsocket from '@fastify/websocket'
import { createWorker as createTesseractWorker } from 'tesseract.js'
import witPkg from 'node-wit'
const { Wit } = witPkg
import { inspect as inspectObject } from 'node:util'
import Client from './classes/Client.js'
import {
EventContext,
parseImageEventHandler,
parseTextEventHandler,
} from './events/index.js'
import { getConfig, checkEnv, logger } from './utils/index.js'
import { WebSocket } from 'ws'
import {
DisconnectReason,
HumanizedDisconnectReason,
} from '@revanced/bot-shared'
// Check environment variables and load config
const environment = checkEnv(logger)
const config = getConfig()
if (!config.debugLogsInProduction && environment === 'production')
logger.debug = () => {}
// Workers and API clients
const tesseractWorker = await createTesseractWorker('eng')
const witClient = new Wit({
accessToken: process.env['WIT_AI_TOKEN']!,
})
process.on('beforeExit', () => tesseractWorker.terminate())
// Server logic
const clients = new Set<Client>()
const clientSocketMap = new WeakMap<WebSocket, Client>()
const eventContext: EventContext = {
tesseractWorker,
logger,
witClient,
config,
}
const server = fastify()
.register(fastifyWebsocket, {
options: {
// 16 KiB max payload
// A Discord message can not be longer than 4000 characters
// OCR should not be longer than 16000 characters
maxPayload: 16 * 1024,
},
})
.register(async instance => {
instance.get('/', { websocket: true }, async (connection, request) => {
try {
const client = new Client({
socket: connection.socket,
id: request.hostname,
heartbeatInterval: config.clientHeartbeatInterval,
})
clientSocketMap.set(connection.socket, client)
clients.add(client)
logger.debug(`Client ${client.id}'s instance has been added`)
logger.info(
`New client connected (now ${clients.size} clients) with ID:`,
client.id
)
client.on('disconnect', reason => {
clients.delete(client)
logger.info(
`Client ${client.id} disconnected because client ${HumanizedDisconnectReason[reason]}`
)
})
client.on('parseText', async packet =>
parseTextEventHandler(packet, eventContext)
)
client.on('parseImage', async packet =>
parseImageEventHandler(packet, eventContext)
)
if (
environment === 'development' &&
!config.debugLogsInProduction
) {
logger.debug(
'Running development mode or debug logs in production is enabled, attaching debug events...'
)
client.on('packet', ({ client, ...rawPacket }) =>
logger.debug(
`Packet received from client ${client.id}:`,
inspectObject(rawPacket)
)
)
client.on('heartbeat', () =>
logger.debug(
'Heartbeat received from client',
client.id
)
)
}
} catch (e) {
if (e instanceof Error) logger.error(e.stack ?? e.message)
else logger.error(inspectObject(e))
const client = clientSocketMap.get(connection.socket)
if (!client) {
logger.error(
'Missing client instance when encountering an error. If the instance still exists in memory, it will NOT be removed!'
)
return connection.socket.terminate()
}
if (client.disconnected === false)
client.disconnect(DisconnectReason.ServerError)
else client.forceDisconnect()
clients.delete(client)
logger.debug(
`Client ${client.id} disconnected because of an internal error`
)
}
})
})
// Start the server
logger.debug('Starting with these configurations:', inspectObject(config))
await server.listen({
host: config.address ?? '0.0.0.0',
port: config.port ?? 80,
})
const addressInfo = server.server.address()
if (!addressInfo || typeof addressInfo !== 'object')
logger.debug('Server started, but cannot determine address information')
else
logger.info(
'Server started at:',
`${addressInfo.address}:${addressInfo.port}`
)
import fastifyWebsocket from '@fastify/websocket'
import { fastify } from 'fastify'
import witPkg from 'node-wit'
import { createWorker as createTesseractWorker } from 'tesseract.js'
const { Wit } = witPkg
import { inspect as inspectObject } from 'node:util'
import Client from './classes/Client.js'
import {
EventContext,
parseImageEventHandler,
parseTextEventHandler,
} from './events/index.js'
import {
DisconnectReason,
HumanizedDisconnectReason,
} from '@revanced/bot-shared'
import { WebSocket } from 'ws'
import { checkEnv, getConfig, logger } from './utils/index.js'
// Check environment variables and load config
const environment = checkEnv(logger)
const config = getConfig()
if (!config.debugLogsInProduction && environment === 'production')
logger.debug = () => {}
// Workers and API clients
const tesseractWorker = await createTesseractWorker('eng')
const witClient = new Wit({
accessToken: process.env['WIT_AI_TOKEN']!,
})
process.on('beforeExit', () => tesseractWorker.terminate())
// Server logic
const clients = new Set<Client>()
const clientSocketMap = new WeakMap<WebSocket, Client>()
const eventContext: EventContext = {
tesseractWorker,
logger,
witClient,
config,
}
const server = fastify()
.register(fastifyWebsocket, {
options: {
// 16 KiB max payload
// A Discord message can not be longer than 4000 characters
// OCR should not be longer than 16000 characters
maxPayload: 16 * 1024,
},
})
.register(async instance => {
instance.get('/', { websocket: true }, async (connection, request) => {
try {
const client = new Client({
socket: connection.socket,
id: request.hostname,
heartbeatInterval: config.clientHeartbeatInterval,
})
clientSocketMap.set(connection.socket, client)
clients.add(client)
logger.debug(`Client ${client.id}'s instance has been added`)
logger.info(
`New client connected (now ${clients.size} clients) with ID:`,
client.id,
)
client.on('disconnect', reason => {
clients.delete(client)
logger.info(
`Client ${client.id} disconnected because client ${HumanizedDisconnectReason[reason]}`,
)
})
client.on('parseText', async packet =>
parseTextEventHandler(packet, eventContext),
)
client.on('parseImage', async packet =>
parseImageEventHandler(packet, eventContext),
)
if (
environment === 'development' &&
!config.debugLogsInProduction
) {
logger.debug(
'Running development mode or debug logs in production is enabled, attaching debug events...',
)
client.on('packet', ({ client, ...rawPacket }) =>
logger.debug(
`Packet received from client ${client.id}:`,
inspectObject(rawPacket),
),
)
client.on('heartbeat', () =>
logger.debug(
'Heartbeat received from client',
client.id,
),
)
}
} catch (e) {
if (e instanceof Error) logger.error(e.stack ?? e.message)
else logger.error(inspectObject(e))
const client = clientSocketMap.get(connection.socket)
if (!client) {
logger.error(
'Missing client instance when encountering an error. If the instance still exists in memory, it will NOT be removed!',
)
return connection.socket.terminate()
}
if (client.disconnected === false)
client.disconnect(DisconnectReason.ServerError)
else client.forceDisconnect()
clients.delete(client)
logger.debug(
`Client ${client.id} disconnected because of an internal error`,
)
}
})
})
// Start the server
logger.debug('Starting with these configurations:', inspectObject(config))
await server.listen({
host: config.address ?? '0.0.0.0',
port: config.port ?? 80,
})
const addressInfo = server.server.address()
if (!addressInfo || typeof addressInfo !== 'object')
logger.debug('Server started, but cannot determine address information')
else
logger.info(
'Server started at:',
`${addressInfo.address}:${addressInfo.port}`,
)

View File

@@ -1,9 +1,9 @@
declare global {
namespace NodeJS {
interface ProcessEnv {
WIT_AI_TOKEN?: string
}
}
}
declare type NodeEnvironment = 'development' | 'production'
declare global {
namespace NodeJS {
interface ProcessEnv {
WIT_AI_TOKEN?: string
}
}
}
declare type NodeEnvironment = 'development' | 'production'

View File

@@ -1,31 +1,31 @@
import type { Logger } from './logger.js'
export default function checkEnv(logger: Logger) {
if (!process.env['NODE_ENV'])
logger.warn('NODE_ENV not set, defaulting to `development`')
const environment = (process.env['NODE_ENV'] ??
'development') as NodeEnvironment
if (!['development', 'production'].includes(environment)) {
logger.error(
'NODE_ENV is neither `development` nor `production`, unable to determine environment'
)
logger.info('Set NODE_ENV to blank to use `development` mode')
process.exit(1)
}
logger.info(`Running in ${environment} mode...`)
if (environment === 'production' && process.env['IS_USING_DOT_ENV']) {
logger.warn(
'You seem to be using .env files, this is generally not a good idea in production...'
)
}
if (!process.env['WIT_AI_TOKEN']) {
logger.error('WIT_AI_TOKEN is not defined in the environment variables')
process.exit(1)
}
return environment
}
import type { Logger } from './logger.js'
export default function checkEnv(logger: Logger) {
if (!process.env['NODE_ENV'])
logger.warn('NODE_ENV not set, defaulting to `development`')
const environment = (process.env['NODE_ENV'] ??
'development') as NodeEnvironment
if (!['development', 'production'].includes(environment)) {
logger.error(
'NODE_ENV is neither `development` nor `production`, unable to determine environment',
)
logger.info('Set NODE_ENV to blank to use `development` mode')
process.exit(1)
}
logger.info(`Running in ${environment} mode...`)
if (environment === 'production' && process.env['IS_USING_DOT_ENV']) {
logger.warn(
'You seem to be using .env files, this is generally not a good idea in production...',
)
}
if (!process.env['WIT_AI_TOKEN']) {
logger.error('WIT_AI_TOKEN is not defined in the environment variables')
process.exit(1)
}
return environment
}

View File

@@ -1,40 +1,40 @@
import { existsSync } from 'node:fs'
import { resolve as resolvePath } from 'node:path'
import { pathToFileURL } from 'node:url'
const configPath = resolvePath(process.cwd(), 'config.json')
const userConfig: Partial<Config> = existsSync(configPath)
? (
await import(pathToFileURL(configPath).href, {
assert: {
type: 'json',
},
})
).default
: {}
type BaseTypeOf<T> = T extends (infer U)[]
? U[]
: T extends (...args: unknown[]) => infer U
? (...args: unknown[]) => U
: T extends object
? { [K in keyof T]: T[K] }
: T
export type Config = Omit<
BaseTypeOf<typeof import('../../config.json')>,
'$schema'
>
export const defaultConfig: Config = {
address: '127.0.0.1',
port: 80,
ocrConcurrentQueues: 1,
clientHeartbeatInterval: 60000,
debugLogsInProduction: false,
}
export default function getConfig() {
return Object.assign(defaultConfig, userConfig) satisfies Config
}
import { existsSync } from 'node:fs'
import { resolve as resolvePath } from 'node:path'
import { pathToFileURL } from 'node:url'
const configPath = resolvePath(process.cwd(), 'config.json')
const userConfig: Partial<Config> = existsSync(configPath)
? (
await import(pathToFileURL(configPath).href, {
assert: {
type: 'json',
},
})
).default
: {}
type BaseTypeOf<T> = T extends (infer U)[]
? U[]
: T extends (...args: unknown[]) => infer U
? (...args: unknown[]) => U
: T extends object
? { [K in keyof T]: T[K] }
: T
export type Config = Omit<
BaseTypeOf<typeof import('../../config.json')>,
'$schema'
>
export const defaultConfig: Config = {
address: '127.0.0.1',
port: 80,
ocrConcurrentQueues: 1,
clientHeartbeatInterval: 60000,
debugLogsInProduction: false,
}
export default function getConfig() {
return Object.assign(defaultConfig, userConfig) satisfies Config
}

View File

@@ -1,3 +1,3 @@
export { default as getConfig } from './getConfig.js'
export { default as checkEnv } from './checkEnv.js'
export { default as logger } from './logger.js'
export { default as getConfig } from './getConfig.js'
export { default as checkEnv } from './checkEnv.js'
export { default as logger } from './logger.js'

View File

@@ -1,25 +1,25 @@
import { Chalk } from 'chalk'
const chalk = new Chalk()
const logger = {
debug: (...args) => console.debug(chalk.gray('DEBUG:', ...args)),
info: (...args) =>
console.info(chalk.bgBlue.whiteBright(' INFO '), ...args),
warn: (...args) =>
console.warn(
chalk.bgYellow.blackBright.bold(' WARN '),
chalk.yellowBright(...args)
),
error: (...args) =>
console.error(
chalk.bgRed.whiteBright.bold(' ERROR '),
chalk.redBright(...args)
),
log: console.log,
} satisfies Logger
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'log'
export type LogFunction = (...x: unknown[]) => void
export type Logger = Record<LogLevel, LogFunction>
export default logger
import { Chalk } from 'chalk'
const chalk = new Chalk()
const logger = {
debug: (...args) => console.debug(chalk.gray('DEBUG:', ...args)),
info: (...args) =>
console.info(chalk.bgBlue.whiteBright(' INFO '), ...args),
warn: (...args) =>
console.warn(
chalk.bgYellow.blackBright.bold(' WARN '),
chalk.yellowBright(...args),
),
error: (...args) =>
console.error(
chalk.bgRed.whiteBright.bold(' ERROR '),
chalk.redBright(...args),
),
log: console.log,
} satisfies Logger
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'log'
export type LogFunction = (...x: unknown[]) => void
export type Logger = Record<LogLevel, LogFunction>
export default logger