import { NativeModules, NativeEventEmitter, Platform, type EmitterSubscription } from 'react-native'; import LazyMoveSdk from './components/LazyMoveSdk'; import type { AuthState, DrivingService, ErrorListType, ErrorReasons, HealthListItem, IssueListService, MoveSdkDeviceFilter, SdkState, ShutdownReturnType, TimelineDetectionService, TripState, WalkingService, WarningListType, WarningReasons, AuthStateEvent, IssueListItem, MoveScanResult, MoveSdkAndroidConfig, MoveSdkAuth, MoveSdkConfig, MoveSdkDevice, MoveSdkDeviceDiscovery, MoveSdkOptions, MoveSdkLog, NotificationConfig, HealthPermissionsResult, } from './NativeMoveSdk'; export type { AuthState, DrivingService, ErrorListType, ErrorReasons, HealthListItem, IssueListService, MoveSdkDeviceFilter, SdkState, ShutdownReturnType, TimelineDetectionService, TripState, WalkingService, WarningListType, WarningReasons, AuthStateEvent, IssueListItem, MoveScanResult, MoveSdkAndroidConfig, MoveSdkAuth, MoveSdkConfig, MoveSdkDevice, MoveSdkDeviceDiscovery, MoveSdkOptions, MoveSdkLog, NotificationConfig, HealthPermissionsResult, }; export { LazyMoveSdk }; const LINKING_ERROR = `The package 'react-native-move-sdk' doesn't seem to be linked. Make sure: \n\n` + Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go\n'; // @ts-expect-error const isTurboModuleEnabled = global.__turboModuleProxy != null; const MoveSdkModule = isTurboModuleEnabled ? require('./NativeMoveSdk').default : NativeModules.MoveSdk; const eventEmitter = new NativeEventEmitter(MoveSdkModule); const NativeMoveSdk = MoveSdkModule ? MoveSdkModule : new Proxy( {}, { get() { throw new Error(LINKING_ERROR); }, } ); export default class MoveSdk { static READY: SdkState = 'READY'; static RUNNING: SdkState = 'RUNNING'; static UNINITIALIZED: SdkState = 'UNINITIALIZED'; static AUTH_EXPIRED: AuthState = 'EXPIRED'; static AUTH_VALID: AuthState = 'VALID'; static AUTH_UNKNOWN: AuthState = 'UNKNOWN'; static AUTH_INVALID: AuthState = 'INVALID'; static UNKNOWN: TripState = 'UNKNOWN'; static DRIVING: TripState = 'DRIVING'; static HALT: TripState = 'HALT'; static IDLE: TripState = 'IDLE'; static IGNORED: TripState = 'IGNORED'; static sdkStateFromNative(sdkState: SdkState): SdkState { if ([MoveSdk.UNINITIALIZED, MoveSdk.READY, MoveSdk.RUNNING, MoveSdk.UNINITIALIZED].includes(sdkState)) { return sdkState; } return MoveSdk.UNINITIALIZED; } static tripStateFromNative(nativeTripState: TripState): TripState { if ([MoveSdk.UNKNOWN, MoveSdk.DRIVING, MoveSdk.HALT, MoveSdk.IDLE, MoveSdk.IGNORED].includes(nativeTripState)) { return nativeTripState; } return MoveSdk.UNKNOWN; } static authStateFromNative(nativeAuthState: AuthState): AuthState { if ([MoveSdk.AUTH_VALID, MoveSdk.AUTH_EXPIRED, MoveSdk.AUTH_INVALID].includes(nativeAuthState)) { return nativeAuthState; } return MoveSdk.AUTH_UNKNOWN; } /** * @deprecated Use setupWithCode(...) instead. */ static async setup(config: MoveSdkConfig, auth: MoveSdkAuth, android: MoveSdkAndroidConfig, options?: MoveSdkOptions): Promise { let platformParams: Array = []; if (Platform.OS === 'android') { const { notifications } = android; const { tripNotification, recognitionNotification } = notifications; if (!tripNotification || !recognitionNotification) { throw new Error('MOVE SDK needs notification configuration for Android'); } platformParams = [ recognitionNotification.title, recognitionNotification.text, tripNotification.title, tripNotification.text, ]; } return await NativeMoveSdk.setup( auth, // Config config, options ?? {}, // Platform config platformParams ); } static async setupWithCode(code: string, config: MoveSdkConfig, android: MoveSdkAndroidConfig, options?: MoveSdkOptions): Promise { let platformParams: Array = []; if (Platform.OS === 'android') { const { notifications } = android; const { tripNotification, recognitionNotification } = notifications; if (!tripNotification || !recognitionNotification) { throw new Error('MOVE SDK needs notification configuration for Android'); } platformParams = [ recognitionNotification.title, recognitionNotification.text, tripNotification.title, tripNotification.text, ]; } return await NativeMoveSdk.setupWithCode( code, // Config config, options ?? {}, // Platform config platformParams ); } static allowMockLocations(allowMockLocations: boolean) { if (isTurboModuleEnabled) { NativeMoveSdk.allowMockLocations(allowMockLocations); } else { NativeMoveSdk.mockLocations(allowMockLocations); } } static resolveError() { NativeMoveSdk.resolveError(); } /** * @deprecated Relies on deprecated setup(auth: ...). */ static async updateAuth(auth: MoveSdkAuth): Promise { const { userId, projectId, accessToken, refreshToken } = auth; return await NativeMoveSdk.updateAuth(userId, accessToken, refreshToken, projectId); } static async startAutomaticDetection(): Promise { return await NativeMoveSdk.startAutomaticDetection(); } static async stopAutomaticDetection(): Promise { return await NativeMoveSdk.stopAutomaticDetection(); } static forceTripRecognition(duration: number = 60000) { NativeMoveSdk.forceTripRecognition(duration); } static keepInForeground(enabled: boolean) { if (Platform.OS === 'android') { NativeMoveSdk.keepInForeground(enabled); } else { console.warn('MoveSdk.keepInForeground() is Android OS only.'); } } static keepActive(enabled: boolean) { if (Platform.OS === 'android') { NativeMoveSdk.keepActive(enabled); } else { console.warn('MoveSdk.keepActive() is Android OS only.'); } } static async synchronizeUserData(): Promise { return await NativeMoveSdk.synchronizeUserData(); } static async getAuthState(): Promise { const authState = await NativeMoveSdk.getAuthState(); return MoveSdk.authStateFromNative(authState); } static async getState(): Promise { const state = await NativeMoveSdk.getState(); return MoveSdk.sdkStateFromNative(state); } static async getTripState(): Promise { const tripState = await NativeMoveSdk.getTripState(); return MoveSdk.tripStateFromNative(tripState); } static async getErrors(): Promise { return await NativeMoveSdk.getErrors(); } static async getWarnings(): Promise { return await NativeMoveSdk.getWarnings(); } static async initiateAssistanceCall(): Promise { return await NativeMoveSdk.initiateAssistanceCall(); } static setAssistanceMetaData(data: string) { NativeMoveSdk.setAssistanceMetaData(data); } static addTripStateListener(tripStateChanged: (state: TripState) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_TRIP_STATE', (event) => tripStateChanged(MoveSdk.tripStateFromNative(event.state))); } static addTripStartListener(tripStartTriggered: (start: Date) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_TRIP_START', (start) => tripStartTriggered(new Date(Number(start)))); } static addSdkStateListener(sdkStateChanged: (state: SdkState) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_STATE', (event) => { sdkStateChanged(MoveSdk.sdkStateFromNative(event.state)); }); } static addAuthStateListener(authStateChanged: (event: AuthStateEvent) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_AUTH_STATE', (event) => { const transformedEvent = { ...event, state: MoveSdk.authStateFromNative(event.state), }; authStateChanged(transformedEvent); }); } static addErrorsListener(errorsReceived: (errors: ErrorListType) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_ERRORS', (event) => { errorsReceived(event.errors); }); } static addWarningsListener(warningsReceived: (warnings: WarningListType) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_WARNINGS', (event) => { warningsReceived(event.warnings); }); } static addAppEventListener(appEventReceived: (event: string) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_APP_EVENT', (event) => { appEventReceived(event); }); } static addLogListener(logReceived: (event: MoveSdkLog) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_LOG', (event) => { logReceived(event); }); } static addRemoteConfigChangeListener(configChangeReceived: (config: Array) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_CONFIG_UPDATE', (config) => { configChangeReceived(config.services); }); } static addHealthListener(scoreReceived: (health: Array) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_HEALTH', (health) => { scoreReceived(health); }); } static version(): string { return Platform.OS === 'android' ? NativeMoveSdk.getConstants().version : 'Unknown'; } static finishCurrentTrip() { NativeMoveSdk.finishCurrentTrip(); } static ignoreCurrentTrip() { NativeMoveSdk.ignoreCurrentTrip(); } static requestMotionPermission() { if (Platform.OS === 'ios') { NativeMoveSdk.requestMotionPermission(); } else { console.warn('MoveSdk.requestMotionPermission() is iOS only.'); } } static async shutdown(force: boolean = true, timeout?: number): Promise { return await NativeMoveSdk.shutdown(force, timeout); } static async getDeviceQualifier(): Promise { return NativeMoveSdk.getDeviceQualifier(); } static async getMoveConfig(): Promise { return await NativeMoveSdk.getMoveConfig(); } static async geocode(latitude: number, longitude: number): Promise { return await NativeMoveSdk.geocode(latitude, longitude); } static async isAuthValid(): Promise { return await NativeMoveSdk.isAuthValid(); } // **** PERMISSIONS MODULE START ***** static async canDrawOverlays(): Promise { return await NativeMoveSdk.canDrawOverlays(); } static requestDrawOverlaysPermission() { if (Platform.OS === 'android') { NativeMoveSdk.requestDrawOverlaysPermission(); } else { console.warn('MoveSdk.requestDrawOverlaysPermission() is Android OS only.'); } } static async isAppIgnoringBatteryOptimization(): Promise { return await NativeMoveSdk.isAppIgnoringBatteryOptimization(); } static requestAppIgnoringBatteryOptimization() { if (Platform.OS === 'android') { NativeMoveSdk.requestAppIgnoringBatteryOptimization(); } else { console.warn('MoveSdk.requestAppIgnoringBatteryOptimization() is Android OS only.'); } } // **** PERMISSIONS MODULE END ***** static startScanningDevices(sdkDevicesDetected: (state: Array) => void, filter: MoveSdkDeviceFilter[] = ['paired'], uuid?: string, manufacturerId?: number): EmitterSubscription { const subscription = eventEmitter.addListener('MOVE_SDK_DEVICES', (devices) => { sdkDevicesDetected(devices); }); const subscriptionRemove = subscription.remove; subscription.remove = () => { NativeMoveSdk.stopScanningDevices(); subscriptionRemove(); }; NativeMoveSdk.startScanningDevices(filter, uuid, manufacturerId ?? -1); return subscription; } static async getRegisteredDevices(): Promise> { return await NativeMoveSdk.getRegisteredDevices(); } static async registerDevices(devices: Array): Promise { return await NativeMoveSdk.registerDevices(devices); } static async unregisterDevices(devices: Array): Promise { return await NativeMoveSdk.unregisterDevices(devices); } static requestBluetoothAlwaysUsagePermission() { NativeMoveSdk.requestBluetoothAlwaysUsagePermission(); } static async getBluetoothPermission() { return await NativeMoveSdk.getBluetoothPermission(); } static async getBluetoothState() { return await NativeMoveSdk.getBluetoothState(); } static addDeviceDiscoveryListener(onScanResult: (state: Array) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_SCAN_RESULT', (results) => { onScanResult(results); }); } static addDeviceStateListener(onScanResult: (results: Array) => void): EmitterSubscription { return eventEmitter.addListener('MOVE_SDK_DEVICE_STATE', results => { onScanResult(results); }); } static setTimer(callback: () => void, delay: number = 60000): string { if (Platform.OS === 'android') { const key = Date.now().toString(); NativeMoveSdk.setTimer(delay, key, callback); return key; } else { console.warn('MoveSdk.setTimer() is Android OS only.'); return ''; } } static cancelTimer(key: string) { if (Platform.OS === 'android') { NativeMoveSdk.cancelTimer(key); } else { console.warn('MoveSdk.cancelTimer() is Android OS only.'); } } static async startTrip(metadata?: { [key: string]: string }): Promise { return await NativeMoveSdk.startTrip(metadata); } static updateConfig(config: MoveSdkConfig, options?: MoveSdkOptions) { NativeMoveSdk.updateConfig(config, options ?? {}); } static setTripMetadata(metadata?: { [key: string]: string }) { NativeMoveSdk.setTripMetadata(metadata); } /** * @deprecated May be removed in future versions. */ static async setLiveLocationTag(tag?: string): Promise { return await NativeMoveSdk.setLiveLocationTag(tag); } static startNativeSdkStateListener() { NativeMoveSdk.startNativeSdkStateListener(); } static async requestHealthPermissions(): Promise { return await NativeMoveSdk.requestHealthPermissions(); } static beaconDevices(serviceUUID: string): MoveSdkDevice { const name = `Beacons ${serviceUUID}` return { id: serviceUUID, name: name, displayName: name, data: JSON.stringify({ id: serviceUUID, name: name, uuid: serviceUUID, displayName: name }) }; } }