1import { requireOptionalNativeModule } from "expo";
2import { AppState, Platform } from "react-native";
3
4const NativeControls = requireOptionalNativeModule<{
5 readonly isProtectedDataAvailable?: () => Promise<boolean>;
6}>("T3NativeControls");
7
8let protectedDataAvailable: Promise<void> | undefined;
9
10// A locked iOS background launch cannot read startup storage. Cache readiness
11// for this launch only; later device locks do not pause an initialized runtime.
12export function whenProtectedDataAvailable(): Promise<void> {
13 protectedDataAvailable ??= new Promise((resolve) => {
14 const isAvailable = NativeControls?.isProtectedDataAvailable;
15 if (Platform.OS !== "ios" || AppState.currentState === "active") {
16 resolve();
17 return;
18 }
19 const subscription = AppState.addEventListener("change", (state) => {
20 if (state === "active") done();
21 });
22 function done() {
23 subscription.remove();
24 resolve();
25 }
26 isAvailable?.().then(
27 (available) => {
28 if (available) done();
29 },
30 () => {
31 // A failed check does not establish readiness; activation still can.
32 },
33 );
34 });
35 return protectedDataAvailable;
36}