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