1import * as Updates from './Updates'; 2import type { Manifest, UpdatesNativeStateMachineContext } from './Updates.types'; 3import { UpdateInfoType, type CurrentlyRunningInfo, type UpdateInfo } from './UseUpdates.types'; 4 5// The currently running info, constructed from Updates constants 6export const currentlyRunning: CurrentlyRunningInfo = { 7 updateId: Updates.updateId ?? undefined, 8 channel: Updates.channel ?? undefined, 9 createdAt: Updates.createdAt ?? undefined, 10 isEmbeddedLaunch: Updates.isEmbeddedLaunch, 11 isEmergencyLaunch: Updates.isEmergencyLaunch, 12 manifest: Updates.manifest ?? undefined, 13 runtimeVersion: Updates.runtimeVersion ?? undefined, 14}; 15 16// Type for the state managed by useUpdates(). 17// Used internally by this module and not exported publicly. 18export type UseUpdatesStateType = { 19 availableUpdate?: UpdateInfo; 20 downloadedUpdate?: UpdateInfo; 21 checkError?: Error; 22 downloadError?: Error; 23 initializationError?: Error; 24 isUpdateAvailable: boolean; 25 isUpdatePending: boolean; 26 isChecking: boolean; 27 isDownloading: boolean; 28 lastCheckForUpdateTimeSinceRestart?: Date; 29}; 30 31// Constructs an UpdateInfo from a manifest 32export const updateFromManifest: (manifest: NonNullable<Manifest>) => UpdateInfo = (manifest) => { 33 return { 34 type: UpdateInfoType.NEW, 35 updateId: manifest.id ?? '', 36 createdAt: 37 manifest && 'createdAt' in manifest && manifest.createdAt 38 ? new Date(manifest.createdAt) 39 : // We should never reach this if the manifest is valid and has a commit time, 40 // but leave this in so that createdAt is always defined 41 new Date(0), 42 manifest, 43 }; 44}; 45 46// Default useUpdates() state 47export const defaultUseUpdatesState: UseUpdatesStateType = { 48 isChecking: false, 49 isDownloading: false, 50 isUpdateAvailable: false, 51 isUpdatePending: false, 52}; 53 54// Transform the useUpdates() state based on native state machine context 55export const reduceUpdatesStateFromContext: ( 56 updatesState: UseUpdatesStateType, 57 context: UpdatesNativeStateMachineContext 58) => UseUpdatesStateType = (updatesState, context) => { 59 const availableUpdate = context?.latestManifest 60 ? updateFromManifest(context?.latestManifest) 61 : undefined; 62 const downloadedUpdate = context?.downloadedManifest 63 ? updateFromManifest(context?.downloadedManifest) 64 : undefined; 65 return { 66 ...updatesState, 67 isUpdateAvailable: context.isUpdateAvailable, 68 isUpdatePending: context.isUpdatePending, 69 isChecking: context.isChecking, 70 isDownloading: context.isDownloading, 71 availableUpdate, 72 downloadedUpdate, 73 checkError: context.checkError, 74 downloadError: context.downloadError, 75 lastCheckForUpdateTimeSinceRestart: context.lastCheckForUpdateTime, 76 }; 77}; 78