chore: format and remove unneccessary code

This commit is contained in:
PalmDevs
2023-11-25 22:45:27 +07:00
parent 72adec51b4
commit 306f627cef
39 changed files with 690 additions and 647 deletions

View File

@@ -1,6 +1,7 @@
{
"root": true,
"extends": ["prettier"],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"sourceType": "module",
"ecmaVersion": "latest"

View File

@@ -39,4 +39,3 @@ bun bundle
```
The files will be placed in the `dist` directory. **Configurations and `.env` files will NOT be copied automatically.**

View File

@@ -141,7 +141,7 @@ export default class Client {
this.#emitter.emit('packet', packet)
this.#emitter.emit(
uncapitalize(ClientOperation[packet.op] as ClientEventName),
// @ts-expect-error
// @ts-expect-error TypeScript doesn't know that the above line will negate the type enough
packet
)
} catch (e) {

View File

@@ -8,7 +8,10 @@ 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 EventHandler<POp extends ClientOperation> = (
packet: ClientPacketObject<POp>,
context: EventContext
) => void | Promise<void>
export type EventContext = {
witClient: Wit
tesseractWorker: TesseractWorker

View File

@@ -17,16 +17,17 @@ import {
import { getConfig, checkEnv, logger } from './utils/index.js'
import { WebSocket } from 'ws'
import { DisconnectReason, HumanizedDisconnectReason } from '@revanced/bot-shared'
// Load environment variables and config
(async () => {
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 = () => {}
if (!config.debugLogsInProduction && environment === 'production')
logger.debug = () => {}
// Workers and API clients
@@ -90,9 +91,14 @@ const server = fastify()
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 }) =>
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)
@@ -100,7 +106,10 @@ const server = fastify()
)
client.on('heartbeat', () =>
logger.debug('Heartbeat received from client', client.id)
logger.debug(
'Heartbeat received from client',
client.id
)
)
}
} catch (e) {
@@ -146,5 +155,3 @@ else
'Server started at:',
`${addressInfo.address}:${addressInfo.port}`
)
})()

View File

@@ -1,7 +1,8 @@
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`')
if (!process.env['NODE_ENV'])
logger.warn('NODE_ENV not set, defaulting to `development`')
const environment = (process.env['NODE_ENV'] ??
'development') as NodeEnvironment
@@ -16,7 +17,9 @@ export default function checkEnv(logger: Logger) {
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...')
logger.warn(
'You seem to be using .env files, this is generally not a good idea in production...'
)
}
if (!process.env['WIT_AI_TOKEN']) {

View File

@@ -2,28 +2,31 @@ 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 configPath = resolvePath(process.cwd(), 'config.json')
const userConfig: Partial<Config> = existsSync(configPath)
? (await import(pathToFileURL(configPath).href, {
? (
await import(pathToFileURL(configPath).href, {
assert: {
type: 'json',
},
})).default
})
).default
: {}
type BaseTypeOf<T> = T extends (infer U)[]
? U[]
: T extends (...args: any[]) => infer U
? (...args: any[]) => 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 type Config = Omit<
BaseTypeOf<typeof import('../../config.json')>,
'$schema'
>
export const defaultConfig: Config = {
address: '127.0.0.1',
port: 80,

View File

@@ -3,14 +3,23 @@ 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)),
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: any[]) => void
export type LogFunction = (...x: unknown[]) => void
export type Logger = Record<LogLevel, LogFunction>
export default logger

View File

@@ -4,7 +4,7 @@
"baseUrl": ".",
"outDir": "dist",
"module": "ESNext",
"composite": false,
"composite": false
},
"exclude": ["node_modules", "dist"],
"include": ["./*.json", "src/**/*.ts"]

BIN
bun.lockb

Binary file not shown.

View File

@@ -49,7 +49,9 @@ export default class Client {
rs(packet)
}
const parseTextFailedListener = (packet: Packet<ServerOperation.ParseTextFailed>) => {
const parseTextFailedListener = (
packet: Packet<ServerOperation.ParseTextFailed>
) => {
if (packet.d.id !== currentId) return
this.gateway.off('parseTextFailed', parseTextFailedListener)
rj(packet)
@@ -84,7 +86,9 @@ export default class Client {
rs(packet)
}
const parseImageFailedListener = (packet: Packet<ServerOperation.ParseImageFailed>) => {
const parseImageFailedListener = (
packet: Packet<ServerOperation.ParseImageFailed>
) => {
if (packet.d.id !== currentId) return
this.gateway.off('parseImageFailed', parseImageFailedListener)
rj(packet)

View File

@@ -24,8 +24,7 @@ export default class ClientGateway {
#hbTimeout: NodeJS.Timeout = null!
#socket: WebSocket = null!
#emitter =
new EventEmitter() as TypedEmitter<ClientGatewayEventHandlers>
#emitter = new EventEmitter() as TypedEmitter<ClientGatewayEventHandlers>
constructor(options: ClientGatewayOptions) {
this.url = options.url
@@ -110,6 +109,7 @@ export default class ClientGateway {
switch (packet.op) {
case ServerOperation.Hello:
// eslint-disable-next-line no-case-declarations
const data = Object.freeze(
(packet as Packet<ServerOperation.Hello>).d
)
@@ -124,9 +124,11 @@ export default class ClientGateway {
default:
return this.#emitter.emit(
uncapitalize(
ServerOperation[packet.op] as ClientGatewayServerEventName
ServerOperation[
packet.op
] as ClientGatewayServerEventName
),
// @ts-expect-error
// @ts-expect-error TypeScript doesn't know that the lines above negate the type enough
packet
)
}

View File

@@ -5,7 +5,7 @@
"rootDir": "./src",
"outDir": "dist",
"module": "ESNext",
"composite": true,
"composite": true
},
"exclude": ["node_modules", "dist"]
}

View File

@@ -1 +1 @@
type RequiredProperty<T> = { [P in keyof T]: Required<NonNullable<T[P]>>; };
type RequiredProperty<T> = { [P in keyof T]: Required<NonNullable<T[P]>> }

View File

@@ -21,7 +21,7 @@ enum DisconnectReason {
/**
* The client had never connected to the server (**CLIENT-ONLY**)
*/
NeverConnected
NeverConnected,
}
export default DisconnectReason

View File

@@ -4,8 +4,9 @@ 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'
[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

View File

@@ -50,8 +50,8 @@ export enum ServerOperation {
/**
* Server's disconnect message
*/
Disconnect = 20
Disconnect = 20,
}
export const Operation = { ...ClientOperation, ...ServerOperation } as const
export type Operation = (ClientOperation | ServerOperation)
export type Operation = ClientOperation | ServerOperation

View File

@@ -1,5 +1,9 @@
import { Packet } from '../schemas/Packet.js'
import { ClientOperation, Operation, ServerOperation } from '../constants/Operation.js'
import {
ClientOperation,
Operation,
ServerOperation,
} from '../constants/Operation.js'
/**
* Checks whether a packet is trying to do the given operation
@@ -7,7 +11,10 @@ import { ClientOperation, Operation, ServerOperation } from '../constants/Operat
* @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> {
export function packetMatchesOperation<TOp extends Operation>(
op: TOp,
packet: Packet
): packet is Packet<TOp> {
return packet.op === op
}
@@ -16,7 +23,9 @@ export function packetMatchesOperation<TOp extends Operation>(op: TOp, packet: P
* @param packet A packet
* @returns Whether this packet is a client packet
*/
export function isClientPacket(packet: Packet): packet is Packet<ClientOperation> {
export function isClientPacket(
packet: Packet
): packet is Packet<ClientOperation> {
return packet.op in ClientOperation
}
@@ -25,6 +34,8 @@ export function isClientPacket(packet: Packet): packet is Packet<ClientOperation
* @param packet A packet
* @returns Whether this packet is a server packet
*/
export function isServerPacket(packet: Packet): packet is Packet<ServerOperation> {
export function isServerPacket(
packet: Packet
): packet is Packet<ServerOperation> {
return packet.op in ServerOperation
}

View File

@@ -1,3 +1,3 @@
export function uncapitalize<T extends string>(str: T): Uncapitalize<T> {
return str.charAt(0).toLowerCase() + str.slice(1) as Uncapitalize<T>
return (str.charAt(0).toLowerCase() + str.slice(1)) as Uncapitalize<T>
}

View File

@@ -5,7 +5,7 @@
"rootDir": "./src",
"outDir": "dist",
"module": "ESNext",
"composite": true,
"composite": true
},
"exclude": ["node_modules", "dist"]
}

View File

@@ -1,3 +1,3 @@
{
"extends": "./tsconfig.base.json",
"extends": "./tsconfig.base.json"
}

View File

@@ -1,6 +1,6 @@
{
// `bun-types` will not be added until https://github.com/oven-sh/bun/issues/7247 is fixed
"extends": ["@tsconfig/strictest", /* "bun-types" */],
"extends": ["@tsconfig/strictest" /* "bun-types" */],
"compilerOptions": {
"lib": ["ESNext"],
"module": "NodeNext",
@@ -12,6 +12,6 @@
"esModuleInterop": true,
"declaration": false,
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
},
"isolatedModules": true
}
}

View File

@@ -2,7 +2,7 @@
"extends": "./tsconfig.base.json",
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"declarationMap": true
},
"references": [
{
@@ -10,6 +10,6 @@
},
{
"path": "./packages/api"
},
}
]
}