chore: switch coding style to JS standard
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIServerUtils.ts
1 import type { IncomingMessage } from 'node:http'
2
3 import { Protocol, ProtocolVersion } from '../../types/index.js'
4 import { logPrefix, logger } from '../../utils/index.js'
5
6 // eslint-disable-next-line @typescript-eslint/no-extraneous-class
7 export class UIServerUtils {
8 private constructor () {
9 // This is intentional
10 }
11
12 public static handleProtocols = (
13 protocols: Set<string>,
14 request: IncomingMessage
15 ): string | false => {
16 let protocol: Protocol | undefined
17 let version: ProtocolVersion | undefined
18 if (protocols.size === 0) {
19 return false
20 }
21 for (const fullProtocol of protocols) {
22 if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol)) {
23 return fullProtocol
24 }
25 }
26 logger.error(
27 `${logPrefix(
28 ' UI WebSocket Server |'
29 )} Unsupported protocol: '${protocol}' or protocol version: '${version}'`
30 )
31 return false
32 }
33
34 public static isProtocolAndVersionSupported = (protocolStr: string): boolean => {
35 const [protocol, version] = UIServerUtils.getProtocolAndVersion(protocolStr)
36 return (
37 Object.values(Protocol).includes(protocol) && Object.values(ProtocolVersion).includes(version)
38 )
39 }
40
41 public static getProtocolAndVersion = (protocolStr: string): [Protocol, ProtocolVersion] => {
42 const protocolIndex = protocolStr.indexOf(Protocol.UI)
43 const protocol = protocolStr.substring(
44 protocolIndex,
45 protocolIndex + Protocol.UI.length
46 ) as Protocol
47 const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion
48 return [protocol, version]
49 }
50
51 public static isLoopback (address: string): boolean {
52 // eslint-disable-next-line prefer-regex-literals
53 const isLoopbackRegExp = new RegExp(
54 // eslint-disable-next-line no-useless-escape
55 /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/,
56 'i'
57 )
58 return isLoopbackRegExp.test(address)
59 }
60 }