1import { CodedError, uuid } from 'expo-modules-core';
2
3import { ServerRegistrationModule } from './ServerRegistrationModule.types';
4
5const INSTALLATION_ID_KEY = 'EXPO_NOTIFICATIONS_INSTALLATION_ID';
6const REGISTRATION_INFO_KEY = 'EXPO_NOTIFICATIONS_REGISTRATION_INFO';
7
8// Lazy fallback installationId per session initializer
9let getFallbackInstallationId = () => {
10  const sessionInstallationId = uuid.v4();
11  getFallbackInstallationId = () => sessionInstallationId;
12};
13
14export default {
15  getInstallationIdAsync: async () => {
16    let installationId;
17
18    try {
19      installationId = localStorage.getItem(INSTALLATION_ID_KEY);
20      if (!installationId || typeof installationId !== 'string') {
21        installationId = uuid.v4();
22        localStorage.setItem(INSTALLATION_ID_KEY, installationId);
23      }
24    } catch {
25      installationId = getFallbackInstallationId();
26    }
27
28    return installationId;
29  },
30  getRegistrationInfoAsync: async () => {
31    if (typeof localStorage === 'undefined') {
32      return null;
33    }
34    return localStorage.getItem(REGISTRATION_INFO_KEY);
35  },
36  setRegistrationInfoAsync: async (registrationInfo: string | null) => {
37    if (typeof localStorage === 'undefined') {
38      return;
39    }
40    try {
41      if (registrationInfo) {
42        localStorage.setItem(REGISTRATION_INFO_KEY, registrationInfo);
43      } else {
44        localStorage.removeItem(REGISTRATION_INFO_KEY);
45      }
46    } catch (error) {
47      throw new CodedError(
48        'ERR_NOTIFICATIONS_STORAGE_ERROR',
49        `Could not modify localStorage to persist auto-registration information: ${error}`
50      );
51    }
52  },
53  // mock implementations
54  addListener: () => {},
55  removeListeners: () => {},
56} as ServerRegistrationModule;
57