mirror of
https://github.com/ReVanced/revanced-bots.git
synced 2026-01-11 21:56:17 +00:00
feat(packages/shared): add logger factory
- @revanced/websocket-api now also utilizes the new logger from the shared package - @revanced/websocket-api/utils/checkEnv has been renamed to its full form - It also no longer returns anything as it's no longer needed
This commit is contained in:
@@ -5,5 +5,5 @@
|
|||||||
"port": 3000,
|
"port": 3000,
|
||||||
"ocrConcurrentQueues": 1,
|
"ocrConcurrentQueues": 1,
|
||||||
"clientHeartbeatInterval": 5000,
|
"clientHeartbeatInterval": 5000,
|
||||||
"debugLogsInProduction": false
|
"consoleLogLevel": "silly"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,10 +22,11 @@
|
|||||||
"type": "integer",
|
"type": "integer",
|
||||||
"default": 60000
|
"default": 60000
|
||||||
},
|
},
|
||||||
"debugLogsInProduction": {
|
"consoleLogLevel": {
|
||||||
"description": "Whether to print debug logs in production",
|
"description": "The log level to print to console",
|
||||||
"type": "boolean",
|
"type": "string",
|
||||||
"default": false
|
"enum": ["error", "warn", "info", "verbose", "debug", "silly", "none"],
|
||||||
|
"default": "info"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,43 +47,29 @@ export default class Client {
|
|||||||
this.#emitter.emit('ready')
|
this.#emitter.emit('ready')
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
if (this.disconnected === false)
|
if (this.disconnected === false) this.disconnect(DisconnectReason.ServerError)
|
||||||
this.disconnect(DisconnectReason.ServerError)
|
|
||||||
else this.forceDisconnect(DisconnectReason.ServerError)
|
else this.forceDisconnect(DisconnectReason.ServerError)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
on<TOpName extends keyof ClientEventHandlers>(
|
on<TOpName extends keyof ClientEventHandlers>(name: TOpName, handler: ClientEventHandlers[typeof name]) {
|
||||||
name: TOpName,
|
|
||||||
handler: ClientEventHandlers[typeof name],
|
|
||||||
) {
|
|
||||||
this.#emitter.on(name, handler)
|
this.#emitter.on(name, handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
once<TOpName extends keyof ClientEventHandlers>(
|
once<TOpName extends keyof ClientEventHandlers>(name: TOpName, handler: ClientEventHandlers[typeof name]) {
|
||||||
name: TOpName,
|
|
||||||
handler: ClientEventHandlers[typeof name],
|
|
||||||
) {
|
|
||||||
this.#emitter.once(name, handler)
|
this.#emitter.once(name, handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
off<TOpName extends keyof ClientEventHandlers>(
|
off<TOpName extends keyof ClientEventHandlers>(name: TOpName, handler: ClientEventHandlers[typeof name]) {
|
||||||
name: TOpName,
|
|
||||||
handler: ClientEventHandlers[typeof name],
|
|
||||||
) {
|
|
||||||
this.#emitter.off(name, handler)
|
this.#emitter.off(name, handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
send<TOp extends ServerOperation>(packet: Packet<TOp>) {
|
send<TOp extends ServerOperation>(packet: Packet<TOp>) {
|
||||||
return new Promise<void>((resolve, reject) => {
|
return new Promise<void>((resolve, reject) => {
|
||||||
try {
|
try {
|
||||||
this.#throwIfDisconnected(
|
this.#throwIfDisconnected('Cannot send packet to client that has already disconnected')
|
||||||
'Cannot send packet to client that has already disconnected',
|
|
||||||
)
|
|
||||||
|
|
||||||
this.#socket.send(serializePacket(packet), err =>
|
this.#socket.send(serializePacket(packet), err => (err ? reject(err) : resolve()))
|
||||||
err ? reject(err) : resolve(),
|
|
||||||
)
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
reject(e)
|
reject(e)
|
||||||
}
|
}
|
||||||
@@ -91,16 +77,12 @@ export default class Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async disconnect(reason: DisconnectReason = DisconnectReason.Generic) {
|
async disconnect(reason: DisconnectReason = DisconnectReason.Generic) {
|
||||||
this.#throwIfDisconnected(
|
this.#throwIfDisconnected('Cannot disconnect client that has already disconnected')
|
||||||
'Cannot disconnect client that has already disconnected',
|
|
||||||
)
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.send({ op: ServerOperation.Disconnect, d: { reason } })
|
await this.send({ op: ServerOperation.Disconnect, d: { reason } })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new Error(
|
throw new Error(`Cannot send disconnect reason to client ${this.id}: ${err}`)
|
||||||
`Cannot send disconnect reason to client ${this.id}: ${err}`,
|
|
||||||
)
|
|
||||||
} finally {
|
} finally {
|
||||||
this.forceDisconnect(reason)
|
this.forceDisconnect(reason)
|
||||||
}
|
}
|
||||||
@@ -173,10 +155,7 @@ export default class Client {
|
|||||||
if (Date.now() - this.lastHeartbeat > 0) {
|
if (Date.now() - this.lastHeartbeat > 0) {
|
||||||
// TODO: put into config
|
// TODO: put into config
|
||||||
// 5000 is extra time to account for latency
|
// 5000 is extra time to account for latency
|
||||||
const interval = setTimeout(
|
const interval = setTimeout(() => this.disconnect(DisconnectReason.TimedOut), 5000)
|
||||||
() => this.disconnect(DisconnectReason.TimedOut),
|
|
||||||
5000,
|
|
||||||
)
|
|
||||||
|
|
||||||
this.once('heartbeat', () => clearTimeout(interval))
|
this.once('heartbeat', () => clearTimeout(interval))
|
||||||
// This should never happen but it did in my testing so I'm adding this just in case
|
// This should never happen but it did in my testing so I'm adding this just in case
|
||||||
@@ -208,11 +187,9 @@ export type ClientEventName = keyof typeof ClientOperation
|
|||||||
export type ClientEventHandlers = {
|
export type ClientEventHandlers = {
|
||||||
[K in Uncapitalize<ClientEventName>]: (
|
[K in Uncapitalize<ClientEventName>]: (
|
||||||
packet: ClientPacketObject<typeof ClientOperation[Capitalize<K>]>,
|
packet: ClientPacketObject<typeof ClientOperation[Capitalize<K>]>,
|
||||||
) => Promise<void> | void
|
) => Promise<unknown> | unknown
|
||||||
} & {
|
} & {
|
||||||
ready: () => Promise<void> | void
|
ready: () => Promise<unknown> | unknown
|
||||||
packet: (
|
packet: (packet: ClientPacketObject<ClientOperation>) => Promise<unknown> | unknown
|
||||||
packet: ClientPacketObject<ClientOperation>,
|
disconnect: (reason: DisconnectReason) => Promise<unknown> | unknown
|
||||||
) => Promise<void> | void
|
|
||||||
disconnect: (reason: DisconnectReason) => Promise<void> | void
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import type { Wit } from 'node-wit'
|
|||||||
import type { Worker as TesseractWorker } from 'tesseract.js'
|
import type { Worker as TesseractWorker } from 'tesseract.js'
|
||||||
import { ClientPacketObject } from '../classes/Client.js'
|
import { ClientPacketObject } from '../classes/Client.js'
|
||||||
import type { Config } from '../utils/getConfig.js'
|
import type { Config } from '../utils/getConfig.js'
|
||||||
import type { Logger } from '../utils/logger.js'
|
import type { Logger } from '@revanced/bot-shared'
|
||||||
|
|
||||||
export { default as parseTextEventHandler } from './parseText.js'
|
export { default as parseTextEventHandler } from './parseText.js'
|
||||||
export { default as parseImageEventHandler } from './parseImage.js'
|
export { default as parseImageEventHandler } from './parseImage.js'
|
||||||
|
|||||||
@@ -14,13 +14,8 @@ const parseImageEventHandler: EventHandler<ClientOperation.ParseImage> = async (
|
|||||||
d: { image_url: imageUrl, id },
|
d: { image_url: imageUrl, id },
|
||||||
} = packet
|
} = packet
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(`Client ${client.id} requested to parse image from URL:`, imageUrl)
|
||||||
`Client ${client.id} requested to parse image from URL:`,
|
logger.debug(`Queue currently has ${queue.remaining}/${config.ocrConcurrentQueues} items in it`)
|
||||||
imageUrl,
|
|
||||||
)
|
|
||||||
logger.debug(
|
|
||||||
`Queue currently has ${queue.remaining}/${config.ocrConcurrentQueues} items in it`,
|
|
||||||
)
|
|
||||||
|
|
||||||
if (queue.remaining < config.ocrConcurrentQueues) queue.shift()
|
if (queue.remaining < config.ocrConcurrentQueues) queue.shift()
|
||||||
await queue.wait()
|
await queue.wait()
|
||||||
@@ -30,10 +25,7 @@ const parseImageEventHandler: EventHandler<ClientOperation.ParseImage> = async (
|
|||||||
|
|
||||||
const { data, jobId } = await tesseractWorker.recognize(imageUrl)
|
const { data, jobId } = await tesseractWorker.recognize(imageUrl)
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(`Recognized image from URL for client ${client.id} (job ${jobId}):`, data.text)
|
||||||
`Recognized image from URL for client ${client.id} (job ${jobId}):`,
|
|
||||||
data.text,
|
|
||||||
)
|
|
||||||
await client.send({
|
await client.send({
|
||||||
op: ServerOperation.ParsedImage,
|
op: ServerOperation.ParsedImage,
|
||||||
d: {
|
d: {
|
||||||
@@ -42,10 +34,7 @@ const parseImageEventHandler: EventHandler<ClientOperation.ParseImage> = async (
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
} catch {
|
} catch {
|
||||||
logger.error(
|
logger.error(`Failed to parse image from URL for client ${client.id}:`, imageUrl)
|
||||||
`Failed to parse image from URL for client ${client.id}:`,
|
|
||||||
imageUrl,
|
|
||||||
)
|
|
||||||
await client.send({
|
await client.send({
|
||||||
op: ServerOperation.ParseImageFailed,
|
op: ServerOperation.ParseImageFailed,
|
||||||
d: {
|
d: {
|
||||||
|
|||||||
@@ -4,10 +4,7 @@ import { inspect as inspectObject } from 'node:util'
|
|||||||
|
|
||||||
import type { EventHandler } from './index.js'
|
import type { EventHandler } from './index.js'
|
||||||
|
|
||||||
const parseTextEventHandler: EventHandler<ClientOperation.ParseText> = async (
|
const parseTextEventHandler: EventHandler<ClientOperation.ParseText> = async (packet, { witClient, logger }) => {
|
||||||
packet,
|
|
||||||
{ witClient, logger },
|
|
||||||
) => {
|
|
||||||
const {
|
const {
|
||||||
client,
|
client,
|
||||||
d: { text, id },
|
d: { text, id },
|
||||||
|
|||||||
@@ -9,25 +9,21 @@ import { inspect as inspectObject } from 'node:util'
|
|||||||
|
|
||||||
import Client from './classes/Client.js'
|
import Client from './classes/Client.js'
|
||||||
|
|
||||||
import {
|
import { EventContext, parseImageEventHandler, parseTextEventHandler } from './events/index.js'
|
||||||
EventContext,
|
|
||||||
parseImageEventHandler,
|
|
||||||
parseTextEventHandler,
|
|
||||||
} from './events/index.js'
|
|
||||||
|
|
||||||
import {
|
import { DisconnectReason, HumanizedDisconnectReason, createLogger } from '@revanced/bot-shared'
|
||||||
DisconnectReason,
|
|
||||||
HumanizedDisconnectReason,
|
|
||||||
} from '@revanced/bot-shared'
|
|
||||||
import { WebSocket } from 'ws'
|
import { WebSocket } from 'ws'
|
||||||
import { checkEnv, getConfig, logger } from './utils/index.js'
|
import { checkEnvironment, getConfig } from './utils/index.js'
|
||||||
|
|
||||||
|
// Load config, init logger, check environment
|
||||||
|
|
||||||
// Check environment variables and load config
|
|
||||||
const environment = checkEnv(logger)
|
|
||||||
const config = getConfig()
|
const config = getConfig()
|
||||||
|
const logger = createLogger('websocket-api', {
|
||||||
|
level: config.consoleLogLevel === 'none' ? 'error' : config.consoleLogLevel,
|
||||||
|
silent: config.consoleLogLevel === 'none',
|
||||||
|
})
|
||||||
|
|
||||||
if (!config.debugLogsInProduction && environment === 'production')
|
checkEnvironment(logger)
|
||||||
logger.debug = () => {}
|
|
||||||
|
|
||||||
// Workers and API clients
|
// Workers and API clients
|
||||||
|
|
||||||
@@ -71,46 +67,25 @@ const server = fastify()
|
|||||||
clients.add(client)
|
clients.add(client)
|
||||||
|
|
||||||
logger.debug(`Client ${client.id}'s instance has been added`)
|
logger.debug(`Client ${client.id}'s instance has been added`)
|
||||||
logger.info(
|
logger.info(`New client connected (now ${clients.size} clients) with ID:`, client.id)
|
||||||
`New client connected (now ${clients.size} clients) with ID:`,
|
|
||||||
client.id,
|
|
||||||
)
|
|
||||||
|
|
||||||
client.on('disconnect', reason => {
|
client.on('disconnect', reason => {
|
||||||
clients.delete(client)
|
clients.delete(client)
|
||||||
logger.info(
|
logger.info(`Client ${client.id} disconnected because client ${HumanizedDisconnectReason[reason]}`)
|
||||||
`Client ${client.id} disconnected because client ${HumanizedDisconnectReason[reason]}`,
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
client.on('parseText', async packet =>
|
client.on('parseText', async packet => parseTextEventHandler(packet, eventContext))
|
||||||
parseTextEventHandler(packet, eventContext),
|
|
||||||
)
|
|
||||||
|
|
||||||
client.on('parseImage', async packet =>
|
client.on('parseImage', async packet => parseImageEventHandler(packet, eventContext))
|
||||||
parseImageEventHandler(packet, eventContext),
|
|
||||||
)
|
if (['debug', 'silly'].includes(config.consoleLogLevel)) {
|
||||||
|
logger.debug('Debug logs enabled, attaching debug events...')
|
||||||
|
|
||||||
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 }) =>
|
client.on('packet', ({ client, ...rawPacket }) =>
|
||||||
logger.debug(
|
logger.debug(`Packet received from client ${client.id}: ${inspectObject(rawPacket)}`),
|
||||||
`Packet received from client ${client.id}:`,
|
|
||||||
inspectObject(rawPacket),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
client.on('heartbeat', () =>
|
client.on('heartbeat', () => logger.debug('Heartbeat received from client', client.id))
|
||||||
logger.debug(
|
|
||||||
'Heartbeat received from client',
|
|
||||||
client.id,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof Error) logger.error(e.stack ?? e.message)
|
if (e instanceof Error) logger.error(e.stack ?? e.message)
|
||||||
@@ -125,22 +100,19 @@ const server = fastify()
|
|||||||
return connection.socket.terminate()
|
return connection.socket.terminate()
|
||||||
}
|
}
|
||||||
|
|
||||||
if (client.disconnected === false)
|
if (client.disconnected === false) client.disconnect(DisconnectReason.ServerError)
|
||||||
client.disconnect(DisconnectReason.ServerError)
|
|
||||||
else client.forceDisconnect()
|
else client.forceDisconnect()
|
||||||
|
|
||||||
clients.delete(client)
|
clients.delete(client)
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(`Client ${client.id} disconnected because of an internal error`)
|
||||||
`Client ${client.id} disconnected because of an internal error`,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
// Start the server
|
// Start the server
|
||||||
|
|
||||||
logger.debug('Starting with these configurations:', inspectObject(config))
|
logger.debug(`Starting with these configurations: ${inspectObject(config)}`, )
|
||||||
|
|
||||||
await server.listen({
|
await server.listen({
|
||||||
host: config.address ?? '0.0.0.0',
|
host: config.address ?? '0.0.0.0',
|
||||||
@@ -150,8 +122,4 @@ await server.listen({
|
|||||||
const addressInfo = server.server.address()
|
const addressInfo = server.server.address()
|
||||||
if (!addressInfo || typeof addressInfo !== 'object')
|
if (!addressInfo || typeof addressInfo !== 'object')
|
||||||
logger.debug('Server started, but cannot determine address information')
|
logger.debug('Server started, but cannot determine address information')
|
||||||
else
|
else logger.info(`Server started at: ${addressInfo.address}:${addressInfo.port}`)
|
||||||
logger.info(
|
|
||||||
'Server started at:',
|
|
||||||
`${addressInfo.address}:${addressInfo.port}`,
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
23
apis/websocket/src/utils/checkEnvironment.ts
Executable file
23
apis/websocket/src/utils/checkEnvironment.ts
Executable file
@@ -0,0 +1,23 @@
|
|||||||
|
import type { Logger } from '@revanced/bot-shared'
|
||||||
|
|
||||||
|
export default function checkEnvironment(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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,17 +22,14 @@ type BaseTypeOf<T> = T extends (infer U)[]
|
|||||||
? { [K in keyof T]: T[K] }
|
? { [K in keyof T]: T[K] }
|
||||||
: T
|
: T
|
||||||
|
|
||||||
export type Config = Omit<
|
export type Config = Omit<BaseTypeOf<typeof import('../../config.json')>, '$schema'>
|
||||||
BaseTypeOf<typeof import('../../config.json')>,
|
|
||||||
'$schema'
|
|
||||||
>
|
|
||||||
|
|
||||||
export const defaultConfig: Config = {
|
export const defaultConfig: Config = {
|
||||||
address: '127.0.0.1',
|
address: '127.0.0.1',
|
||||||
port: 80,
|
port: 80,
|
||||||
ocrConcurrentQueues: 1,
|
ocrConcurrentQueues: 1,
|
||||||
clientHeartbeatInterval: 60000,
|
clientHeartbeatInterval: 60000,
|
||||||
debugLogsInProduction: false,
|
consoleLogLevel: 'info',
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function getConfig() {
|
export default function getConfig() {
|
||||||
|
|||||||
@@ -1,3 +1,2 @@
|
|||||||
export { default as getConfig } from './getConfig.js'
|
export { default as getConfig } from './getConfig.js'
|
||||||
export { default as checkEnv } from './checkEnv.js'
|
export { default as checkEnvironment } from './checkEnvironment.js'
|
||||||
export { default as logger } from './logger.js'
|
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
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
|
|
||||||
58
package.json
58
package.json
@@ -1,38 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "revanced-helper",
|
"name": "revanced-helper",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"description": "🤖 Bots assisting ReVanced on multiple platforms",
|
"author": "Palm <palmpasuthorn@gmail.com> (https://github.com/PalmDevs)",
|
||||||
"private": true,
|
|
||||||
"workspaces": [
|
|
||||||
"apis/*",
|
|
||||||
"bots/*",
|
|
||||||
"packages/*"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"build": "turbo run build",
|
|
||||||
"watch": "turbo run watch",
|
|
||||||
"format": "prettier --ignore-path .gitignore --write .",
|
|
||||||
"format:check": "prettier --ignore-path .gitignore --cache --check .",
|
|
||||||
"lint": "eslint --ignore-path .gitignore --cache .",
|
|
||||||
"lint:apply": "eslint --ignore-path .gitignore --fix .",
|
|
||||||
"commitlint": "commitlint --edit",
|
|
||||||
"t": "turbo run",
|
|
||||||
"prepare": "lefthook install"
|
|
||||||
},
|
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/revanced/revanced-helper.git"
|
"url": "git+https://github.com/revanced/revanced-helper.git"
|
||||||
},
|
},
|
||||||
"author": "Palm <palmpasuthorn@gmail.com> (https://github.com/PalmDevs)",
|
|
||||||
"contributors": [
|
|
||||||
"Palm <palmpasuthorn@gmail.com> (https://github.com/PalmDevs)",
|
|
||||||
"ReVanced <nosupport@revanced.app> (https://github.com/revanced)"
|
|
||||||
],
|
|
||||||
"license": "GPL-3.0-or-later",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/revanced/revanced-helper/issues"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/revanced/revanced-helper#readme",
|
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@biomejs/biome": "1.3.3",
|
"@biomejs/biome": "1.3.3",
|
||||||
"@commitlint/cli": "^18.4.3",
|
"@commitlint/cli": "^18.4.3",
|
||||||
@@ -48,9 +21,36 @@
|
|||||||
"turbo": "^1.10.16",
|
"turbo": "^1.10.16",
|
||||||
"typescript": "^5.3.2"
|
"typescript": "^5.3.2"
|
||||||
},
|
},
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://github.com/revanced/revanced-helper/issues"
|
||||||
|
},
|
||||||
|
"contributors": [
|
||||||
|
"Palm <palmpasuthorn@gmail.com> (https://github.com/PalmDevs)",
|
||||||
|
"ReVanced <nosupport@revanced.app> (https://github.com/revanced)"
|
||||||
|
],
|
||||||
|
"description": "🤖 Bots assisting ReVanced on multiple platforms",
|
||||||
|
"homepage": "https://github.com/revanced/revanced-helper#readme",
|
||||||
|
"license": "GPL-3.0-or-later",
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"uuid": ">=9.0.0",
|
"uuid": ">=9.0.0",
|
||||||
"isomorphic-fetch": ">=3.0.0"
|
"isomorphic-fetch": ">=3.0.0"
|
||||||
},
|
},
|
||||||
"trustedDependencies": ["lefthook", "biome", "turbo"]
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"build": "turbo run build",
|
||||||
|
"watch": "turbo run watch",
|
||||||
|
"format": "prettier --ignore-path .gitignore --write .",
|
||||||
|
"format:check": "prettier --ignore-path .gitignore --cache --check .",
|
||||||
|
"lint": "eslint --ignore-path .gitignore --cache .",
|
||||||
|
"lint:apply": "eslint --ignore-path .gitignore --fix .",
|
||||||
|
"commitlint": "commitlint --edit",
|
||||||
|
"t": "turbo run",
|
||||||
|
"prepare": "lefthook install"
|
||||||
|
},
|
||||||
|
"trustedDependencies": ["lefthook", "biome", "turbo"],
|
||||||
|
"workspaces": [
|
||||||
|
"apis/*",
|
||||||
|
"bots/*",
|
||||||
|
"packages/*"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,9 @@
|
|||||||
"homepage": "https://github.com/revanced/revanced-helper#readme",
|
"homepage": "https://github.com/revanced/revanced-helper#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bson": "^6.2.0",
|
"bson": "^6.2.0",
|
||||||
|
"chalk": "^5.3.0",
|
||||||
"valibot": "^0.21.0",
|
"valibot": "^0.21.0",
|
||||||
|
"winston": "^3.11.0",
|
||||||
"zod": "^3.22.4"
|
"zod": "^3.22.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,7 @@ const HumanizedDisconnectReason = {
|
|||||||
[DisconnectReason.InvalidPacket]: 'has sent invalid packet',
|
[DisconnectReason.InvalidPacket]: 'has sent invalid packet',
|
||||||
[DisconnectReason.Generic]: 'has been disconnected for unknown reasons',
|
[DisconnectReason.Generic]: 'has been disconnected for unknown reasons',
|
||||||
[DisconnectReason.TimedOut]: 'has timed out',
|
[DisconnectReason.TimedOut]: 'has timed out',
|
||||||
[DisconnectReason.ServerError]:
|
[DisconnectReason.ServerError]: 'has been disconnected due to an internal server error',
|
||||||
'has been disconnected due to an internal server error',
|
|
||||||
[DisconnectReason.NeverConnected]: 'had never connected to the server',
|
[DisconnectReason.NeverConnected]: 'had never connected to the server',
|
||||||
} as const satisfies Record<DisconnectReason, string>
|
} as const satisfies Record<DisconnectReason, string>
|
||||||
|
|
||||||
|
|||||||
@@ -15,11 +15,7 @@ import {
|
|||||||
// merge
|
// merge
|
||||||
} from 'valibot'
|
} from 'valibot'
|
||||||
import DisconnectReason from '../constants/DisconnectReason.js'
|
import DisconnectReason from '../constants/DisconnectReason.js'
|
||||||
import {
|
import { ClientOperation, Operation, ServerOperation } from '../constants/Operation.js'
|
||||||
ClientOperation,
|
|
||||||
Operation,
|
|
||||||
ServerOperation,
|
|
||||||
} from '../constants/Operation.js'
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Schema to validate packets
|
* Schema to validate packets
|
||||||
@@ -59,10 +55,7 @@ export const PacketDataSchemas = {
|
|||||||
labels: array(
|
labels: array(
|
||||||
object({
|
object({
|
||||||
name: string(),
|
name: string(),
|
||||||
confidence: special<number>(
|
confidence: special<number>(input => typeof input === 'number' && input >= 0 && input <= 1),
|
||||||
input =>
|
|
||||||
typeof input === 'number' && input >= 0 && input <= 1,
|
|
||||||
),
|
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -1,8 +1,4 @@
|
|||||||
import {
|
import { ClientOperation, Operation, ServerOperation } from '../constants/Operation.js'
|
||||||
ClientOperation,
|
|
||||||
Operation,
|
|
||||||
ServerOperation,
|
|
||||||
} from '../constants/Operation.js'
|
|
||||||
import { Packet } from '../schemas/Packet.js'
|
import { Packet } from '../schemas/Packet.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -11,10 +7,7 @@ import { Packet } from '../schemas/Packet.js'
|
|||||||
* @param packet A packet
|
* @param packet A packet
|
||||||
* @returns Whether this packet is trying to do the operation given
|
* @returns Whether this packet is trying to do the operation given
|
||||||
*/
|
*/
|
||||||
export function packetMatchesOperation<TOp extends Operation>(
|
export function packetMatchesOperation<TOp extends Operation>(op: TOp, packet: Packet): packet is Packet<TOp> {
|
||||||
op: TOp,
|
|
||||||
packet: Packet,
|
|
||||||
): packet is Packet<TOp> {
|
|
||||||
return packet.op === op
|
return packet.op === op
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,9 +16,7 @@ export function packetMatchesOperation<TOp extends Operation>(
|
|||||||
* @param packet A packet
|
* @param packet A packet
|
||||||
* @returns Whether this packet is a client packet
|
* @returns Whether this packet is a client packet
|
||||||
*/
|
*/
|
||||||
export function isClientPacket(
|
export function isClientPacket(packet: Packet): packet is Packet<ClientOperation> {
|
||||||
packet: Packet,
|
|
||||||
): packet is Packet<ClientOperation> {
|
|
||||||
return packet.op in ClientOperation
|
return packet.op in ClientOperation
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,8 +25,6 @@ export function isClientPacket(
|
|||||||
* @param packet A packet
|
* @param packet A packet
|
||||||
* @returns Whether this packet is a server packet
|
* @returns Whether this packet is a server packet
|
||||||
*/
|
*/
|
||||||
export function isServerPacket(
|
export function isServerPacket(packet: Packet): packet is Packet<ServerOperation> {
|
||||||
packet: Packet,
|
|
||||||
): packet is Packet<ServerOperation> {
|
|
||||||
return packet.op in ServerOperation
|
return packet.op in ServerOperation
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
export * from './guard.js'
|
export * from './guard.js'
|
||||||
|
export * from './logger.js'
|
||||||
export * from './serialization.js'
|
export * from './serialization.js'
|
||||||
export * from './string.js'
|
export * from './string.js'
|
||||||
|
|||||||
66
packages/shared/src/utils/logger.ts
Normal file
66
packages/shared/src/utils/logger.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import { createLogger as createWinstonLogger, LoggerOptions, transports, format } from 'winston'
|
||||||
|
import { Chalk, ChalkInstance } from 'chalk'
|
||||||
|
|
||||||
|
const chalk = new Chalk()
|
||||||
|
|
||||||
|
const LevelPrefixes = {
|
||||||
|
error: `${chalk.bgRed.whiteBright(' ERR! ')} `,
|
||||||
|
warn: `${chalk.bgYellow.black(' WARN ')} `,
|
||||||
|
info: `${chalk.bgBlue.whiteBright(' INFO ')} `,
|
||||||
|
log: chalk.reset(''),
|
||||||
|
debug: chalk.gray('DEBUG: '),
|
||||||
|
silly: chalk.gray('SILLY: '),
|
||||||
|
} as Record<string, string>
|
||||||
|
|
||||||
|
const LevelColorFunctions = {
|
||||||
|
error: chalk.redBright,
|
||||||
|
warn: chalk.yellowBright,
|
||||||
|
info: chalk.cyanBright,
|
||||||
|
log: chalk.reset,
|
||||||
|
debug: chalk.gray,
|
||||||
|
silly: chalk.gray,
|
||||||
|
} as Record<string, ChalkInstance>
|
||||||
|
|
||||||
|
export function createLogger(
|
||||||
|
serviceName: string,
|
||||||
|
config: SafeOmit<
|
||||||
|
LoggerOptions,
|
||||||
|
| 'defaultMeta'
|
||||||
|
| 'exceptionHandlers'
|
||||||
|
| 'exitOnError'
|
||||||
|
| 'handleExceptions'
|
||||||
|
| 'handleRejections'
|
||||||
|
| 'levels'
|
||||||
|
| 'rejectionHandlers'
|
||||||
|
>,
|
||||||
|
) {
|
||||||
|
const logger = createWinstonLogger({
|
||||||
|
exitOnError: false,
|
||||||
|
defaultMeta: { serviceName },
|
||||||
|
handleExceptions: true,
|
||||||
|
handleRejections: true,
|
||||||
|
transports: config.transports ?? [
|
||||||
|
new transports.Console(),
|
||||||
|
new transports.File({
|
||||||
|
dirname: 'logs',
|
||||||
|
filename: `${serviceName}-${Date.now()}.log`,
|
||||||
|
format: format.combine(
|
||||||
|
format.uncolorize(),
|
||||||
|
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
||||||
|
format.printf(
|
||||||
|
({ level, message, timestamp }) => `[${timestamp}] ${level.toUpperCase()}: ${message}`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
format: format.printf(({ level, message }) => LevelPrefixes[level] + LevelColorFunctions[level]!(message)),
|
||||||
|
...config,
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.silly(`Logger for ${serviceName} created at ${Date.now()}`)
|
||||||
|
|
||||||
|
return logger
|
||||||
|
}
|
||||||
|
|
||||||
|
type SafeOmit<T, K extends keyof T> = Omit<T, K>
|
||||||
|
export type Logger = ReturnType<typeof createLogger>
|
||||||
Reference in New Issue
Block a user