From 94feb062fdf9b91eed75cf8e27244895a98edc0b Mon Sep 17 00:00:00 2001 From: Ibrahim Ansari Date: Fri, 21 Jul 2023 05:37:01 +0530 Subject: [PATCH] Require explicit function return types w/ ESLint. --- .eslintrc.js | 1 - src/App.tsx | 10 +++++----- src/components/Dialog.tsx | 2 +- src/components/DisconnectDialog.tsx | 2 +- src/components/ElevatedView.tsx | 2 +- src/components/Text.tsx | 2 +- src/components/TextField.tsx | 2 +- src/components/TextFieldDialog.tsx | 6 +++--- src/components/accounts/AccountDisplay.tsx | 2 +- src/components/accounts/AddAccountDialog.tsx | 6 +++--- src/components/accounts/MicrosoftLogin.tsx | 8 ++++---- src/components/servers/EditServerDialog.tsx | 8 ++++---- src/components/servers/ServerDisplay.tsx | 2 +- src/components/settings/DarkModeSetting.tsx | 7 +++++-- src/components/settings/Setting.tsx | 4 ++-- src/context/useDarkMode.ts | 2 +- src/minecraft/api/microsoft.ts | 6 ++++-- src/minecraft/api/mojang.ts | 6 ++++-- src/minecraft/api/yggdrasil.ts | 15 ++++++++++++--- src/minecraft/chatToJsx.tsx | 8 ++++---- src/minecraft/connection/index.ts | 4 +++- src/minecraft/connection/javascript.ts | 6 ++++-- src/minecraft/connection/native.ts | 10 ++++++---- src/minecraft/connection/shared.ts | 8 +++++--- src/minecraft/packet.ts | 6 +++--- src/minecraft/pingServer.ts | 10 ++++++++-- src/minecraft/utils.ts | 13 ++++++++----- src/screens/AccountScreen.tsx | 4 ++-- src/screens/ServerScreen.tsx | 10 +++++----- src/screens/SettingScreen.tsx | 2 +- src/screens/chat/ChatScreen.tsx | 12 ++++++------ src/screens/chat/packetHandler.ts | 2 +- src/screens/chat/sessionBuilder.ts | 2 +- src/storage/useJsonAsyncStorage.ts | 2 +- 34 files changed, 112 insertions(+), 80 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 4d477ac..1e33862 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -33,7 +33,6 @@ module.exports = { '@typescript-eslint/restrict-plus-operands': 'off', '@typescript-eslint/no-dynamic-delete': 'off', '@typescript-eslint/no-var-requires': 'off', - '@typescript-eslint/explicit-function-return-type': 'off', // TODO: Enable later. // Adjust to Prettier's presence. (Maybe we should do away with it later.) '@typescript-eslint/space-before-function-paren': 'off', '@typescript-eslint/member-delimiter-style': 'off', diff --git a/src/App.tsx b/src/App.tsx index d14952c..141deff 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -43,9 +43,9 @@ export interface RootStackParamList { Home: undefined Chat: { serverName: string; version: number } } -type HomeNavigationProp = NativeStackNavigationProp +type HomeProp = NativeStackNavigationProp -const HomeScreen = ({ navigation }: { navigation: HomeNavigationProp }) => { +const HomeScreen = ({ navigation }: { navigation: HomeProp }): JSX.Element => { const { connection } = React.useContext(ConnectionContext) React.useEffect(() => { if (connection) { @@ -92,7 +92,7 @@ const HomeScreen = ({ navigation }: { navigation: HomeNavigationProp }) => { ) } -const App = () => { +const App = (): JSX.Element => { const [connection, setConnection] = React.useState< ServerConnection | undefined >() @@ -109,9 +109,9 @@ const App = () => { const [serversStore, setServersStore] = useAsyncStorage('@servers', '{}') const accounts: Accounts = JSON.parse(accountsStore) const servers: Servers = JSON.parse(serversStore) - const setAccounts = (newAccounts: Accounts) => + const setAccounts = (newAccounts: Accounts): void => setAccountsStore(JSON.stringify(newAccounts)) - const setServers = (newServers: Servers) => + const setServers = (newServers: Servers): void => setServersStore(JSON.stringify(newServers)) const colorScheme = useColorScheme() diff --git a/src/components/Dialog.tsx b/src/components/Dialog.tsx index 718cd70..f58faf4 100644 --- a/src/components/Dialog.tsx +++ b/src/components/Dialog.tsx @@ -17,7 +17,7 @@ const Dialog = ({ visible: boolean onRequestClose: () => void containerStyles?: ViewStyle -}>) => ( +}>): JSX.Element => ( { +const DisconnectDialog = (): JSX.Element => { const darkMode = useDarkMode() const { disconnectReason, setDisconnectReason } = useContext(ConnectionContext) diff --git a/src/components/ElevatedView.tsx b/src/components/ElevatedView.tsx index df54687..e0b8da9 100644 --- a/src/components/ElevatedView.tsx +++ b/src/components/ElevatedView.tsx @@ -4,7 +4,7 @@ import useDarkMode from '../context/useDarkMode' const ElevatedView = ( props: React.PropsWithChildren<{ style?: ViewStyle }> -) => ( +): JSX.Element => ( ) => ( +const Text = (props: React.PropsWithChildren): JSX.Element => ( { +const TextField = (props: TextInputProps & { red?: boolean }): JSX.Element => { const style = props.style?.valueOf() const darkMode = useDarkMode() return ( diff --git a/src/components/TextFieldDialog.tsx b/src/components/TextFieldDialog.tsx index e9bcbbf..644ca34 100644 --- a/src/components/TextFieldDialog.tsx +++ b/src/components/TextFieldDialog.tsx @@ -24,13 +24,13 @@ const TextFieldDialog = ({ closeModal: () => void initialState: string setFinalState: (state: string) => void -}) => { +}): JSX.Element => { const [modalContent, setModalContent] = useState(initialState) - const closeModalAndSaveState = () => { + const closeModalAndSaveState = (): void => { setFinalState(modalContent) closeModal() } - const closeModalAndReset = () => { + const closeModalAndReset = (): void => { setModalContent(initialState) closeModal() } diff --git a/src/components/accounts/AccountDisplay.tsx b/src/components/accounts/AccountDisplay.tsx index 5fbc1dd..04acb16 100644 --- a/src/components/accounts/AccountDisplay.tsx +++ b/src/components/accounts/AccountDisplay.tsx @@ -16,7 +16,7 @@ const AccountDisplay = ({ darkMode: boolean setActiveAccount: (uuid: string) => void setDeleteAccount: (uuid: string) => void -}) => ( +}): JSX.Element => ( setActiveAccount(uuid)} diff --git a/src/components/accounts/AddAccountDialog.tsx b/src/components/accounts/AddAccountDialog.tsx index feb6bf9..0d74901 100644 --- a/src/components/accounts/AddAccountDialog.tsx +++ b/src/components/accounts/AddAccountDialog.tsx @@ -16,7 +16,7 @@ const AddAccountDialog = ({ }: { open: boolean setOpen: React.Dispatch> -}) => { +}): JSX.Element => { const darkMode = useDarkMode() const { accounts, setAccounts } = useContext(UsersContext) @@ -32,7 +32,7 @@ const AddAccountDialog = ({ !/^[A-Za-z0-9_]{3,16}$/.test(newUser) && (password === null ? true : !/^[^\s@]+@[^\s@]+$/.test(newUser)) - const cancelAddAccount = () => { + const cancelAddAccount = (): void => { setMicrosoftLogin(false) setOpen(false) setUserRed(false) @@ -41,7 +41,7 @@ const AddAccountDialog = ({ setPassword(null) // setPassword('') setDialogError('') } - const addAccount = () => { + const addAccount = (): void => { const accountExists = !!accounts[newUser] || !!Object.keys(accounts).find(id => accounts[id].email === newUser) diff --git a/src/components/accounts/MicrosoftLogin.tsx b/src/components/accounts/MicrosoftLogin.tsx index b07d1ab..075ad42 100644 --- a/src/components/accounts/MicrosoftLogin.tsx +++ b/src/components/accounts/MicrosoftLogin.tsx @@ -17,7 +17,7 @@ import { } from '../../minecraft/api/microsoft' import config from '../../../config.json' -const MicrosoftLogin = ({ close }: { close: () => void }) => { +const MicrosoftLogin = ({ close }: { close: () => void }): JSX.Element => { const darkMode = useDarkMode() const style = darkMode ? '' @@ -27,7 +27,7 @@ const MicrosoftLogin = ({ close }: { close: () => void }) => { const webview = useRef(null) const [loading, setLoading] = useState(false) const [html, setRawHtml] = useState('') - const setHtml = (newHtml: string) => setRawHtml(style + newHtml) + const setHtml = (newHtml: string): void => setRawHtml(style + newHtml) const addAccount = ( id: string, @@ -54,12 +54,12 @@ const MicrosoftLogin = ({ close }: { close: () => void }) => { return alreadyExists } - const onRequestClose = () => { + const onRequestClose = (): void => { if (!loading) close() } const handleNavigationStateChange = async ( newNavState: WebViewNavigation - ) => { + ): Promise => { // LOW-TODO: Parse errors. if (!webview.current || !newNavState.url) return if ( diff --git a/src/components/servers/EditServerDialog.tsx b/src/components/servers/EditServerDialog.tsx index 326ce1e..e457cee 100644 --- a/src/components/servers/EditServerDialog.tsx +++ b/src/components/servers/EditServerDialog.tsx @@ -27,7 +27,7 @@ const EditServerDialog = ({ deleteServer: (server: string) => void editServerDialogOpen: string | boolean setEditServerDialogOpen: (server: string | boolean) => void -}) => { +}): JSX.Element => { const [ipAddr, setIpAddr] = useState('') const [ipAddrRed, setIpAddrRed] = useState(false) const [newServerName, setNewServerName] = useState('') @@ -54,15 +54,15 @@ const EditServerDialog = ({ } }, [editServerDialogOpen, server]) - const closeDialog = () => setEditServerDialogOpen(false) + const closeDialog = (): void => setEditServerDialogOpen(false) - const handleDeleteServer = () => { + const handleDeleteServer = (): void => { if (typeof editServerDialogOpen !== 'string') return deleteServer(editServerDialogOpen) closeDialog() } - const handleEditServer = () => { + const handleEditServer = (): void => { const edit = typeof editServerDialogOpen === 'string' if ( !newServerName || diff --git a/src/components/servers/ServerDisplay.tsx b/src/components/servers/ServerDisplay.tsx index b0d01c7..4a8cc5a 100644 --- a/src/components/servers/ServerDisplay.tsx +++ b/src/components/servers/ServerDisplay.tsx @@ -29,7 +29,7 @@ const ServerDisplay = ({ darkMode: boolean connectToServer: (server: string) => void openEditServerDialog: (server: string) => void -}) => ( +}): JSX.Element => ( connectToServer(server)} diff --git a/src/components/settings/DarkModeSetting.tsx b/src/components/settings/DarkModeSetting.tsx index 5fddb83..35ab002 100644 --- a/src/components/settings/DarkModeSetting.tsx +++ b/src/components/settings/DarkModeSetting.tsx @@ -15,7 +15,7 @@ import useDarkMode from '../../context/useDarkMode' const RadioButton = (props: { style?: StyleProp selected: boolean -}) => { +}): JSX.Element => { const darkMode = useDarkMode() return ( void } -const DarkModeSetting = ({ value, setValue }: DarkModeSettingProps) => { +const DarkModeSetting = ({ + value, + setValue +}: DarkModeSettingProps): JSX.Element => { const [modalOpen, setModalOpen] = useState(false) const ripple = { color: '#aaa' } const dark = useDarkMode() diff --git a/src/components/settings/Setting.tsx b/src/components/settings/Setting.tsx index 6b0b3ce..7944726 100644 --- a/src/components/settings/Setting.tsx +++ b/src/components/settings/Setting.tsx @@ -20,7 +20,7 @@ const Setting = ({ setValue?: (newValue: T) => void multiline?: boolean maxLength?: number -}) => { +}): JSX.Element => { const da = useDarkMode() const [modalOpen, setModalOpen] = useState(false) const [modalContent, setModalContent] = useState( @@ -30,7 +30,7 @@ const Setting = ({ const [toggleValue, setToggleValue] = useState(value) const Wrapper = setValue ?? onClick ? Pressable : React.Fragment - const wrapperPress = () => { + const wrapperPress = (): void => { if (onClick) onClick() else if (typeof value === 'boolean' && setValue) { setValue(!toggleValue as T) diff --git a/src/context/useDarkMode.ts b/src/context/useDarkMode.ts index 1d6bfcf..3289714 100644 --- a/src/context/useDarkMode.ts +++ b/src/context/useDarkMode.ts @@ -2,6 +2,6 @@ import { createContext, useContext } from 'react' export const ColorSchemeContext = createContext(false) -const useDarkMode = () => useContext(ColorSchemeContext) +const useDarkMode = (): boolean => useContext(ColorSchemeContext) export default useDarkMode diff --git a/src/minecraft/api/microsoft.ts b/src/minecraft/api/microsoft.ts index e7b65ae..6d7eb6b 100644 --- a/src/minecraft/api/microsoft.ts +++ b/src/minecraft/api/microsoft.ts @@ -115,7 +115,9 @@ export const authenticateWithXsts = async ( return res.access_token } -export const checkGameOwnership = async (accessToken: string) => { +export const checkGameOwnership = async ( + accessToken: string +): Promise => { const req = await fetch(mcStoreUrl, { headers: { Accept: 'application/json', @@ -125,7 +127,7 @@ export const checkGameOwnership = async (accessToken: string) => { if (!req.ok) throw new Error('Failed to check if user owns Minecraft game!') const res = await req.json() const items = res.items as Array<{ name: string }> - return ( + return !!( items?.length >= 2 && items.find(item => item.name === 'game_minecraft') && items.find(item => item.name === 'product_minecraft') diff --git a/src/minecraft/api/mojang.ts b/src/minecraft/api/mojang.ts index 77fe9d6..2f20df6 100644 --- a/src/minecraft/api/mojang.ts +++ b/src/minecraft/api/mojang.ts @@ -19,14 +19,16 @@ export const joinMinecraftSession = async ( accessToken: string, selectedProfile: string, serverId: string -) => +): Promise => await fetch(joinMinecraftSessionUrl, { body: JSON.stringify({ accessToken, selectedProfile, serverId }), headers: { 'content-type': 'application/json' }, method: 'POST' }) -export const getPlayerCertificates = async (accessToken: string) => +export const getPlayerCertificates = async ( + accessToken: string +): Promise => await fetch(getPlayerCertificatesUrl, { headers: { Authorization: 'Bearer ' + accessToken }, method: 'POST' diff --git a/src/minecraft/api/yggdrasil.ts b/src/minecraft/api/yggdrasil.ts index 5a3c6d6..5d2014c 100644 --- a/src/minecraft/api/yggdrasil.ts +++ b/src/minecraft/api/yggdrasil.ts @@ -51,7 +51,10 @@ export const refresh = async ( return await request.json() } -export const validate = async (accessToken: string, clientToken?: string) => { +export const validate = async ( + accessToken: string, + clientToken?: string +): Promise => { const request = await fetch('https://authserver.mojang.com/validate', { method: 'POST', headers: { 'content-type': 'application/json' }, @@ -64,7 +67,10 @@ export const validate = async (accessToken: string, clientToken?: string) => { } } -export const signout = async (username: string, password: string) => { +export const signout = async ( + username: string, + password: string +): Promise => { const request = await fetch('https://authserver.mojang.com/signout', { method: 'POST', headers: { 'content-type': 'application/json' }, @@ -75,7 +81,10 @@ export const signout = async (username: string, password: string) => { } } -export const invalidate = async (accessToken: string, clientToken: string) => { +export const invalidate = async ( + accessToken: string, + clientToken: string +): Promise => { const request = await fetch('https://authserver.mojang.com/invalidate', { method: 'POST', headers: { 'content-type': 'application/json' }, diff --git a/src/minecraft/chatToJsx.tsx b/src/minecraft/chatToJsx.tsx index 365f592..e055eb1 100644 --- a/src/minecraft/chatToJsx.tsx +++ b/src/minecraft/chatToJsx.tsx @@ -91,7 +91,7 @@ export interface HoverEvent { value: MinecraftChat } -const hasColorCodes = (s: string) => /§[0-9a-fk-orx]/.test(s) +const hasColorCodes = (s: string): boolean => /§[0-9a-fk-orx]/.test(s) // const stripColorCodes = (s: string) => s.replace(/§[0-9a-fk-orx]/g, '').trim() const parseColorCodes = (arg: string | PlainTextChat): PlainTextChat[] => { let s: string @@ -253,7 +253,7 @@ const parseChatToJsx = ( clickEventHandler: (clickEvent: ClickEvent) => void = () => {}, componentProps?: Record, trim = false -) => { +): JSX.Element => { let flat = sanitizeComponents(flattenComponents(chat)) if (trim) flat = trimComponentsByLine(flat) return ( @@ -296,7 +296,7 @@ export const ChatToJsx = (props: { componentProps?: Record clickEventHandler?: (clickEvent: ClickEvent) => void trim?: boolean -}) => +}): JSX.Element => parseChatToJsx( props.chat ?? { text: '' }, props.component, @@ -306,7 +306,7 @@ export const ChatToJsx = (props: { props.trim ) -export const parseValidJson = (text: string) => { +export const parseValidJson = (text: string): any => { try { return JSON.parse(text) } catch (e) { diff --git a/src/minecraft/connection/index.ts b/src/minecraft/connection/index.ts index 7bfa8d5..06b9df2 100644 --- a/src/minecraft/connection/index.ts +++ b/src/minecraft/connection/index.ts @@ -37,7 +37,9 @@ export interface ServerConnection extends events.EventEmitter { ((event: string, listener: Function) => this) // eslint-disable-line @typescript-eslint/ban-types } -const initiateConnection = async (opts: ConnectionOptions) => { +const initiateConnection = async ( + opts: ConnectionOptions +): Promise => { if (isNativeConnectionAvailable()) { return await initiateNativeConnection(opts) } diff --git a/src/minecraft/connection/javascript.ts b/src/minecraft/connection/javascript.ts index 14c3a27..0a75795 100644 --- a/src/minecraft/connection/javascript.ts +++ b/src/minecraft/connection/javascript.ts @@ -67,7 +67,7 @@ export class JavaScriptServerConnection } onlyOneCloseCall = false - close() { + close(): void { if (this.onlyOneCloseCall) return else this.onlyOneCloseCall = true @@ -81,7 +81,9 @@ export class JavaScriptServerConnection } } -const initiateJavaScriptConnection = async (opts: ConnectionOptions) => { +const initiateJavaScriptConnection = async ( + opts: ConnectionOptions +): Promise => { const [host, port] = await resolveHostname(opts.host, opts.port) const socket = net.createConnection({ host, port }) const conn = new JavaScriptServerConnection(socket, opts) diff --git a/src/minecraft/connection/native.ts b/src/minecraft/connection/native.ts index 5a6b5f9..48b04a5 100644 --- a/src/minecraft/connection/native.ts +++ b/src/minecraft/connection/native.ts @@ -12,7 +12,7 @@ import packetIds from '../packets/ids' const { ConnectionModule } = NativeModules -export const isNativeConnectionAvailable = () => +export const isNativeConnectionAvailable = (): boolean => !!ConnectionModule?.openConnection interface NativeEvent { @@ -148,7 +148,7 @@ export class NativeServerConnection return ConnectionModule.writePacket(this.id, packetId, toWrite) } - internalClose(closeConnection: boolean) { + internalClose(closeConnection: boolean): void { if (this.closed) return this.closed = true if (closeConnection) ConnectionModule.closeConnection(this.id) @@ -160,12 +160,14 @@ export class NativeServerConnection this.emit('close') } - close() { + close(): void { this.internalClose(true) } } -const initiateNativeConnection = async (opts: ConnectionOptions) => { +const initiateNativeConnection = async ( + opts: ConnectionOptions +): Promise => { const [host, port] = await resolveHostname(opts.host, opts.port) const id = await ConnectionModule.openConnection({ loginPacket: getLoginPacket(opts).toString('base64'), diff --git a/src/minecraft/connection/shared.ts b/src/minecraft/connection/shared.ts index 9b23b7a..8f3fdf8 100644 --- a/src/minecraft/connection/shared.ts +++ b/src/minecraft/connection/shared.ts @@ -10,7 +10,9 @@ import { writeVarInt } from '../utils' -export const parseEncryptionRequestPacket = (packet: Packet) => { +export const parseEncryptionRequestPacket = ( + packet: Packet +): [Buffer, Buffer, Buffer] => { // ASCII encoding of the server id string let data = packet.data const [sidLen, sidLenLen] = readVarInt(data) @@ -27,7 +29,7 @@ export const parseEncryptionRequestPacket = (packet: Packet) => { return [serverId, publicKey, verifyToken] } -export const getLoginPacket = (opts: ConnectionOptions) => { +export const getLoginPacket = (opts: ConnectionOptions): Buffer => { const data: PacketDataTypes[] = [opts.username] if ( opts.protocolVersion >= protocolMap[1.19] && @@ -69,7 +71,7 @@ export const handleEncryptionRequest = ( selectedProfile: string, connection: ServerConnection, callback: (secret: Buffer, response: Buffer) => Promise -) => { +): void => { // https://wiki.vg/Protocol_Encryption const [serverId, publicKey, verifyToken] = parseEncryptionRequestPacket(packet) diff --git a/src/minecraft/packet.ts b/src/minecraft/packet.ts index 67c3a16..9907eb8 100644 --- a/src/minecraft/packet.ts +++ b/src/minecraft/packet.ts @@ -2,7 +2,7 @@ import { Buffer } from 'buffer' import { compressData, decompressData } from './compression' import { toggleEndian, encodeString, readVarInt, writeVarInt } from './utils' -export const makeBasePacket = (packetId: number, data: Buffer) => { +export const makeBasePacket = (packetId: number, data: Buffer): Buffer => { const finalData = Buffer.concat([writeVarInt(packetId), data]) const finalDataLength = writeVarInt(finalData.byteLength) // VarInt Length(Packet ID + Data) + VarInt Packet ID + Byte Array Data @@ -13,7 +13,7 @@ export const makeBaseCompressedPacket = async ( threshold: number, packetId: number, data: Buffer -) => { +): Promise => { // VarInt Packet Length | Length of Data Length + compressed length of (Packet ID + Data) // VarInt Data Length | Length of uncompressed (Packet ID + Data) or 0 // VarInt Packet ID | zlib compressed packet ID (see the sections below) @@ -30,7 +30,7 @@ export const makeBaseCompressedPacket = async ( export type PacketDataTypes = string | boolean | number | Buffer -export const concatPacketData = (data: PacketDataTypes[]) => +export const concatPacketData = (data: PacketDataTypes[]): Buffer => Buffer.concat( data.map(field => { if (typeof field === 'string') return encodeString(field) diff --git a/src/minecraft/pingServer.ts b/src/minecraft/pingServer.ts index a0990b4..a3d0577 100644 --- a/src/minecraft/pingServer.ts +++ b/src/minecraft/pingServer.ts @@ -39,7 +39,10 @@ export interface Ping { description: string | PlainTextChat } -export const legacyPing = async (opts: { host: string; port: number }) => { +export const legacyPing = async (opts: { + host: string + port: number +}): Promise => { const [host, port] = await resolveHostname(opts.host, opts.port) return await new Promise((resolve, reject) => { const socket = net.createConnection({ host, port }) @@ -98,7 +101,10 @@ export const legacyPing = async (opts: { host: string; port: number }) => { }) } -export const modernPing = async (opts: { host: string; port: number }) => { +export const modernPing = async (opts: { + host: string + port: number +}): Promise => { const [host, port] = await resolveHostname(opts.host, opts.port) return await new Promise((resolve, reject) => { const socket = net.createConnection({ host, port }) diff --git a/src/minecraft/utils.ts b/src/minecraft/utils.ts index ec9ac02..4c36bc2 100644 --- a/src/minecraft/utils.ts +++ b/src/minecraft/utils.ts @@ -21,7 +21,7 @@ export const protocolMap = { auto: -1 } -export const padBufferToLength = (buffer: Buffer, length: number) => +export const padBufferToLength = (buffer: Buffer, length: number): Buffer => length <= buffer.byteLength ? buffer : Buffer.concat([ @@ -29,7 +29,10 @@ export const padBufferToLength = (buffer: Buffer, length: number) => buffer ]) -export const toggleEndian = (buffer: Buffer, bytes: number = buffer.length) => { +export const toggleEndian = ( + buffer: Buffer, + bytes: number = buffer.length +): Buffer => { const output = Buffer.alloc(buffer.length) if (buffer.length % bytes !== 0) { throw new Error( @@ -79,7 +82,7 @@ export const resolveHostname = async ( } else return [hostname, port] } -export const getRandomBytes = async (size: number) => +export const getRandomBytes = async (size: number): Promise => await new Promise((resolve, reject) => { randomBytes(size, (err, buf) => { if (err) reject(err) @@ -88,7 +91,7 @@ export const getRandomBytes = async (size: number) => }) // Credits for following 2 functions: https://gist.github.com/andrewrk/4425843 -export function mcHexDigest(hash: Buffer) { +export function mcHexDigest(hash: Buffer): string { // check for negative hashes const negative = hash.readInt8(0) < 0 if (negative) performTwosCompliment(hash) @@ -99,7 +102,7 @@ export function mcHexDigest(hash: Buffer) { return digest } -function performTwosCompliment(buffer: Buffer) { +function performTwosCompliment(buffer: Buffer): void { let carry = true let newByte, value for (let i = buffer.length - 1; i >= 0; --i) { diff --git a/src/screens/AccountScreen.tsx b/src/screens/AccountScreen.tsx index da0cb63..22b1ca2 100644 --- a/src/screens/AccountScreen.tsx +++ b/src/screens/AccountScreen.tsx @@ -13,14 +13,14 @@ import { invalidate } from '../minecraft/api/yggdrasil' // LOW-TODO: Reload to update account info for online mode using /refresh. // Also, to reload all the skin images? -const AccountScreen = () => { +const AccountScreen = (): JSX.Element => { const darkMode = useDarkMode() const { accounts, setAccounts } = useContext(UsersContext) const [addAccountDialogOpen, setAddAccountDialogOpen] = useState(false) const [deleteAccount, setDeleteAccount] = useState('') - const setActiveAccount = (uuid: string) => { + const setActiveAccount = (uuid: string): void => { const newAccounts = accounts for (const key in newAccounts) { if (newAccounts[key].active) { diff --git a/src/screens/ServerScreen.tsx b/src/screens/ServerScreen.tsx index 63ef19d..416c638 100644 --- a/src/screens/ServerScreen.tsx +++ b/src/screens/ServerScreen.tsx @@ -21,7 +21,7 @@ import { parseIp, protocolMap } from '../minecraft/utils' type Props = NativeStackScreenProps -const ServerScreen = (props: Props) => { +const ServerScreen = (props: Props): JSX.Element => { const darkMode = useDarkMode() const { servers, setServers } = useContext(ServersContext) const { setDisconnectReason } = useContext(ConnectionContext) @@ -66,7 +66,7 @@ const ServerScreen = (props: Props) => { ) }, [servers, pingResponses]) - const openEditServerDialog = (server: string) => { + const openEditServerDialog = (server: string): void => { setEditServerDialogOpen(server) } @@ -74,7 +74,7 @@ const ServerScreen = (props: Props) => { serverName: string, version: keyof typeof protocolMap, address: string - ) => { + ): void => { const edit = typeof editServerDialogOpen === 'string' const newServers = { ...servers } if (edit) delete newServers[editServerDialogOpen] @@ -83,13 +83,13 @@ const ServerScreen = (props: Props) => { setPingResponses({}) } - const deleteServer = (server: string) => { + const deleteServer = (server: string): void => { const newServers = { ...servers } delete newServers[server] setServers(newServers) } - const connectToServer = (serverName: string) => { + const connectToServer = (serverName: string): void => { let version = protocolMap[servers[serverName].version] if (version === -1) { const ping = pingResponses[servers[serverName].address] diff --git a/src/screens/SettingScreen.tsx b/src/screens/SettingScreen.tsx index 39eca79..79308eb 100644 --- a/src/screens/SettingScreen.tsx +++ b/src/screens/SettingScreen.tsx @@ -16,7 +16,7 @@ import SettingsContext from '../context/settingsContext' type StackProps = NativeStackScreenProps type TabProps = MaterialTopTabScreenProps -const SettingScreen = ({ navigation }: StackProps | TabProps) => { +const SettingScreen = ({ navigation }: StackProps | TabProps): JSX.Element => { const darkModeApp = useDarkMode() const { settings, setSettings } = useContext(SettingsContext) diff --git a/src/screens/chat/ChatScreen.tsx b/src/screens/chat/ChatScreen.tsx index 5f027fa..640e51f 100644 --- a/src/screens/chat/ChatScreen.tsx +++ b/src/screens/chat/ChatScreen.tsx @@ -59,7 +59,7 @@ const ItemRenderer = (props: { item: Message colorMap: ColorMap clickEventHandler: (event: ClickEvent) => void -}) => ( +}): JSX.Element => ( void -}) => { +}): JSX.Element => { // If colorMap/clickEventHandler changes, this will change and cause a re-render. // If messages changes, FlatList will execute this function for all messages, and // ItemRendererMemo will check if props have changed instead of this useCallback. @@ -115,7 +115,7 @@ const handleError = } // TODO: Ability to copy text. -const ChatScreen = ({ navigation, route }: Props) => { +const ChatScreen = ({ navigation, route }: Props): JSX.Element => { const darkMode = useDarkMode() const { settings } = useContext(SettingsContext) const { servers } = useContext(ServersContext) @@ -138,9 +138,9 @@ const ChatScreen = ({ navigation, route }: Props) => { const { version, serverName } = route.params const charLimit = version >= 306 /* 16w38a */ ? 256 : 100 - const addMessage = (text: MinecraftChat) => + const addMessage = (text: MinecraftChat): number => messagesBufferRef.current.unshift({ key: idRef.current++, text }) - const closeChatScreen = (reason?: DisconnectReason) => { + const closeChatScreen = (reason?: DisconnectReason): void => { if (statusRef.current !== 'CLOSED') { if (navigation.canGoBack()) navigation.goBack() if (reason) setDisconnectReason(reason) @@ -248,7 +248,7 @@ const ChatScreen = ({ navigation, route }: Props) => { settings.sendSpawnCommand ]) - const sendMessage = (msg: string, saveHistory: boolean) => { + const sendMessage = (msg: string, saveHistory: boolean): void => { if (!connection || !msg) return setMessage('') if (msg.startsWith('/') && saveHistory) { diff --git a/src/screens/chat/packetHandler.ts b/src/screens/chat/packetHandler.ts index c68f925..78c712e 100644 --- a/src/screens/chat/packetHandler.ts +++ b/src/screens/chat/packetHandler.ts @@ -65,7 +65,7 @@ const handleSystemMessage = ( addMessage: (text: MinecraftChat) => void, handleError: HandleError, is1191: boolean -) => { +): void => { try { const [chatLength, chatVarIntLength] = readVarInt(packet.data) const chatJson = packet.data diff --git a/src/screens/chat/sessionBuilder.ts b/src/screens/chat/sessionBuilder.ts index fd311fd..f203cb1 100644 --- a/src/screens/chat/sessionBuilder.ts +++ b/src/screens/chat/sessionBuilder.ts @@ -128,7 +128,7 @@ export const createConnection = async ( accessToken: session?.accessToken, certificate: settings.enableChatSigning ? session?.certificate : undefined }) - const onCloseOrError = () => { + const onCloseOrError = (): void => { closeChatScreen( newConn.disconnectReason ? { server, reason: parseValidJson(newConn.disconnectReason) } diff --git a/src/storage/useJsonAsyncStorage.ts b/src/storage/useJsonAsyncStorage.ts index cdd4837..726cb22 100644 --- a/src/storage/useJsonAsyncStorage.ts +++ b/src/storage/useJsonAsyncStorage.ts @@ -3,7 +3,7 @@ import AsyncStorage from '@react-native-async-storage/async-storage' type SetJsonAsyncStorage = (value: Partial) => void -const useMemoisedValue = (value: T) => { +const useMemoisedValue = (value: T): T => { const ref = useRef(value) if (JSON.stringify(value) !== JSON.stringify(ref.current)) ref.current = value return ref.current