1import { Platform } from 'react-native';
2
3import { installationID, isDevice } from '../native-modules/DevLauncherInternal';
4import { queryDevSessionsAsync } from '../native-modules/DevMenu';
5import { DevSession } from '../types';
6
7// TODO -- move this into context / make it settable via JS
8const baseAddress = Platform.select({
9  ios: 'http://localhost',
10  android: 'http://10.0.0.2',
11});
12
13const statusPage = 'status';
14const portsToCheck = [8081, 8082, 19000, 19001, 19002, 19003, 19004, 19005];
15
16export async function getDevSessionsAsync(isAuthenticated = false): Promise<DevSession[]> {
17  let devSessions: DevSession[] = [];
18
19  if (isAuthenticated) {
20    const sessions = await queryDevSessionsAsync();
21    devSessions = devSessions.concat(sessions);
22  }
23
24  if (!devSessions.length && installationID) {
25    const sessions = await queryDevSessionsAsync(installationID);
26    devSessions = devSessions.concat(sessions);
27  }
28
29  if (!devSessions.length && !isDevice) {
30    const localPackagers = await getLocalPackagersAsync();
31    devSessions = devSessions.concat(localPackagers);
32  }
33
34  return devSessions;
35}
36
37export async function getLocalPackagersAsync(): Promise<DevSession[]> {
38  const onlineDevSessions: DevSession[] = [];
39
40  await Promise.all(
41    portsToCheck.map(async (port) => {
42      try {
43        const address = `${baseAddress}:${port}`;
44        const { status } = await fetch(`${address}/${statusPage}`);
45        if (status === 200) {
46          onlineDevSessions.push({
47            url: address,
48            description: address,
49            source: 'desktop',
50          });
51        }
52      } catch (e) {}
53    })
54  );
55
56  return onlineDevSessions;
57}
58