Compare commits

...
1 Commits
Author SHA1 Message Date
Jose Olarte IIIandCursor 71694b2e11 fix New Activity taps that stayed pending until push was enabled
Capacitor holds the notification action until the first listener. Register that listener on every native startup, separately from permission and FCM token registration.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-27 15:08:01 +08:00
7 changed files with 634 additions and 63 deletions
+8 -31
View File
@@ -46,14 +46,9 @@ import "./utils/safeAreaInset";
import "@timesafari/daily-notification-plugin";
import {
configureNativeFetcherIfReady,
initializeNativePushAndFirebaseMessaging,
onNotificationAuthMayBeReady,
runLegacyApiNotificationsCleanupOnce,
} from "@/services/notifications";
import { serverPushTime } from "@/services/notifications/newActivityDelivery";
import { migrateDeviceNotificationsOnce } from "@/services/notifications/deviceNotifications";
import { serverPushSupported } from "@/services/notifications/firebaseMessagingClient";
import { retrieveSettingsForActiveAccount } from "@/db/databaseUtil";
import { runDeferredCapacitorStartup } from "./main.capacitorDeferredStartup";
logger.log("[Capacitor] 🚀 Starting initialization");
logger.log("[Capacitor] Platform:", process.env.VITE_PLATFORM);
@@ -358,31 +353,13 @@ if (
});
}
// Register deeplink listener and configure native notification fetcher after app is mounted
setTimeout(async () => {
try {
logger.info(
`[Main] ⏳ Delaying listener registration to ensure Capacitor is ready...`,
);
await registerDeepLinkListener();
logger.info(`[Main] 🎉 Deep link system fully initialized!`);
// One-time: remove persisted legacy api_* schedules from pre-retirement installs
await runLegacyApiNotificationsCleanupOnce();
// Firebase Messaging (JS) + Capacitor PushNotifications (FCM/APNs token,
// delivery listeners), only while the server push is on, so that
// otherwise the device is not registered with the notification service.
// The on-device New Activity schedule is independent of it.
const settings = await retrieveSettingsForActiveAccount();
const pushSupported = await serverPushSupported();
await migrateDeviceNotificationsOnce(pushSupported);
if (serverPushTime(settings, pushSupported)) {
await initializeNativePushAndFirebaseMessaging();
}
// Configure native fetcher for API-driven daily notifications (activeDid + JWT)
await configureNativeFetcherIfReady();
} catch (error) {
logger.error(`[Main] ❌ Deep link system initialization failed:`, error);
}
// Register deeplink listener and configure native notification fetcher after app is mounted.
// The tap listener, appUrlOpen, and server-push setup each have their own error boundary.
setTimeout(() => {
logger.info(
`[Main] ⏳ Delaying listener registration to ensure Capacitor is ready...`,
);
void runDeferredCapacitorStartup(registerDeepLinkListener);
}, 2000); // 2 second delay to ensure Capacitor is fully ready
// Log app initialization status
+131
View File
@@ -0,0 +1,131 @@
jest.mock("@/utils/logger", () => ({
logger: {
error: jest.fn(),
info: jest.fn(),
debug: jest.fn(),
warn: jest.fn(),
log: jest.fn(),
},
}));
jest.mock("@/services/notifications/firebaseMessagingClient", () => ({
ensurePushNotificationActionListener: () => mockEnsure(),
initializeNativePushAndFirebaseMessaging: () => mockInitialize(),
serverPushSupported: () => mockServerPushSupported(),
}));
jest.mock("@/services/notifications/deviceNotifications", () => ({
migrateDeviceNotificationsOnce: (supported: boolean) =>
mockMigrate(supported),
}));
jest.mock("@/db/databaseUtil", () => ({
retrieveSettingsForActiveAccount: () => mockRetrieve(),
}));
jest.mock("@/services/notifications/legacyApiNotificationsCleanup", () => ({
runLegacyApiNotificationsCleanupOnce: () => mockCleanup(),
}));
jest.mock("@/services/notifications/nativeFetcherConfig", () => ({
configureNativeFetcherIfReady: () => mockConfigure(),
}));
import { logger } from "@/utils/logger";
import { runDeferredCapacitorStartup } from "./main.capacitorDeferredStartup";
const mockEnsure = jest.fn();
const mockInitialize = jest.fn();
const mockServerPushSupported = jest.fn();
const mockMigrate = jest.fn();
const mockRetrieve = jest.fn();
const mockCleanup = jest.fn();
const mockConfigure = jest.fn();
describe("runDeferredCapacitorStartup", () => {
beforeEach(() => {
jest.clearAllMocks();
mockEnsure.mockResolvedValue(undefined);
mockInitialize.mockResolvedValue(undefined);
mockServerPushSupported.mockResolvedValue(true);
mockMigrate.mockResolvedValue(undefined);
mockRetrieve.mockResolvedValue({ notifyingNewActivityTime: "9:00 AM" });
mockCleanup.mockResolvedValue(undefined);
mockConfigure.mockResolvedValue(undefined);
});
it("registers the tap listener when server push is off and does not register FCM", async () => {
mockRetrieve.mockResolvedValue({ notifyingNewActivityTime: "" });
await runDeferredCapacitorStartup(async () => undefined);
expect(mockEnsure).toHaveBeenCalledTimes(1);
expect(mockInitialize).not.toHaveBeenCalled();
expect(mockConfigure).toHaveBeenCalledTimes(1);
});
it("registers the tap listener when the saved time is an on-device schedule", async () => {
mockRetrieve.mockResolvedValue({
notifyingNewActivityTime: "9:00 AM",
newActivityDelivery: "device",
});
await runDeferredCapacitorStartup(async () => undefined);
expect(mockEnsure).toHaveBeenCalledTimes(1);
expect(mockInitialize).not.toHaveBeenCalled();
});
it("still registers FCM when server push is on", async () => {
await runDeferredCapacitorStartup(async () => undefined);
expect(mockEnsure).toHaveBeenCalledTimes(1);
expect(mockInitialize).toHaveBeenCalledTimes(1);
});
it("still registers the tap listener when appUrlOpen registration throws", async () => {
const order: string[] = [];
mockEnsure.mockImplementation(async () => {
order.push("ensure");
});
mockInitialize.mockImplementation(async () => {
order.push("init");
});
await expect(
runDeferredCapacitorStartup(async () => {
order.push("deep-link");
throw new Error("appUrlOpen failed");
}),
).resolves.toBeUndefined();
expect(order).toEqual(["ensure", "deep-link", "init"]);
expect(logger.error).toHaveBeenCalled();
expect(mockInitialize).toHaveBeenCalledTimes(1);
});
it("still registers appUrlOpen when the tap listener fails", async () => {
mockEnsure.mockRejectedValue(new Error("listener failed"));
const registerDeepLink = jest.fn().mockResolvedValue(undefined);
await expect(
runDeferredCapacitorStartup(registerDeepLink),
).resolves.toBeUndefined();
expect(registerDeepLink).toHaveBeenCalledTimes(1);
expect(mockInitialize).toHaveBeenCalledTimes(1);
});
it("still registers the tap listener when settings hydration throws", async () => {
mockRetrieve.mockRejectedValue(new Error("database unavailable"));
const registerDeepLink = jest.fn().mockResolvedValue(undefined);
await expect(
runDeferredCapacitorStartup(registerDeepLink),
).resolves.toBeUndefined();
expect(mockEnsure).toHaveBeenCalledTimes(1);
expect(registerDeepLink).toHaveBeenCalledTimes(1);
expect(mockInitialize).not.toHaveBeenCalled();
});
});
+52
View File
@@ -0,0 +1,52 @@
/**
* Work that runs after the native WebView is up, in separate error boundaries.
*
* A failure while registering `appUrlOpen`, the notification-tap listener, or
* server-push setup must not skip the others. The tap listener does not wait
* on the server-push setting, permission, or an FCM token.
*/
import { retrieveSettingsForActiveAccount } from "@/db/databaseUtil";
import { logger } from "@/utils/logger";
import { migrateDeviceNotificationsOnce } from "@/services/notifications/deviceNotifications";
import {
ensurePushNotificationActionListener,
initializeNativePushAndFirebaseMessaging,
serverPushSupported,
} from "@/services/notifications/firebaseMessagingClient";
import { runLegacyApiNotificationsCleanupOnce } from "@/services/notifications/legacyApiNotificationsCleanup";
import { configureNativeFetcherIfReady } from "@/services/notifications/nativeFetcherConfig";
import { serverPushTime } from "@/services/notifications/newActivityDelivery";
export async function runDeferredCapacitorStartup(
registerDeepLinkListener: () => Promise<unknown>,
): Promise<void> {
try {
await ensurePushNotificationActionListener();
} catch (error) {
logger.error(`[Main] ❌ Push notification action listener failed:`, error);
}
try {
await registerDeepLinkListener();
logger.info(`[Main] 🎉 Deep link system fully initialized!`);
} catch (error) {
logger.error(`[Main] ❌ Deep link system initialization failed:`, error);
}
try {
await runLegacyApiNotificationsCleanupOnce();
// Token registration stays behind the server-push setting so a device
// that has not asked for New Activity pushes is not registered. The tap
// listener above is already attached either way.
const settings = await retrieveSettingsForActiveAccount();
const pushSupported = await serverPushSupported();
await migrateDeviceNotificationsOnce(pushSupported);
if (serverPushTime(settings, pushSupported)) {
await initializeNativePushAndFirebaseMessaging();
}
await configureNativeFetcherIfReady();
} catch (error) {
logger.error(`[Main] ❌ Server push setup failed:`, error);
}
}
@@ -0,0 +1,324 @@
jest.mock("@capacitor/core", () => ({
Capacitor: {
isNativePlatform: () => mockIsNativePlatform(),
getPlatform: () => mockGetPlatform(),
},
}));
jest.mock("@capacitor/push-notifications", () => ({
PushNotifications: {
addListener: (eventName: string, listener: (payload: unknown) => void) =>
mockAddListener(eventName, listener),
requestPermissions: () => mockRequestPermissions(),
register: () => mockRegister(),
},
}));
jest.mock("firebase/app", () => ({
getApps: () => [],
initializeApp: jest.fn(),
}));
jest.mock("firebase/messaging", () => ({
getMessaging: jest.fn(),
getToken: jest.fn(),
isSupported: jest.fn(async () => false),
onMessage: jest.fn(),
}));
jest.mock("@/utils/logger", () => ({
logger: {
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
log: jest.fn(),
},
}));
jest.mock("@/plugins/NotificationInspectorPlugin", () => ({
NotificationInspector: {
isFirebaseConfigured: jest.fn(async () => ({ configured: true })),
},
}));
jest.mock("./NativeNotificationService", () => ({
handleCapacitorPushNotificationReceived: (notification: unknown) =>
mockHandleReceived(notification),
}));
jest.mock("./notificationApiAuth", () => ({
getNotificationApiHeaders: jest.fn(),
}));
jest.mock("./notificationAuthLifecycle", () => ({
deferFcmRegistration: jest.fn(),
}));
jest.mock("./NotificationService", () => ({
registerToken: jest.fn(),
}));
jest.mock("@/services/QRNavigationService", () => ({
QRNavigationService: {
getInstance: () => ({
getQRScannerRoute: () => ({ name: "contact-qr" }),
}),
},
}));
jest.mock("./firebaseWebEnv", () => ({
readFirebaseWebEnv: () => ({}),
}));
jest.mock("@/router", () => ({
__esModule: true,
default: {
isReady: () => Promise.resolve(),
replace: (location: unknown) => mockReplace(location),
},
}));
import { resetAlertSearchNotificationTapState } from "./alertSearchNotificationTap";
import {
ensurePushNotificationActionListener,
initializeNativePushAndFirebaseMessaging,
resetNativePushMessagingStateForTests,
} from "./firebaseMessagingClient";
const mockIsNativePlatform = jest.fn();
const mockGetPlatform = jest.fn();
const mockAddListener = jest.fn();
const mockRequestPermissions = jest.fn();
const mockRegister = jest.fn();
const mockHandleReceived = jest.fn();
const mockReplace = jest.fn();
const listeners = new Map<string, (_payload: unknown) => void>();
const CURSORS = "1234567.45678-1234567";
function alertSearchAction(
c: string = CURSORS,
id = "msg-1",
actionId = "tap",
) {
return {
actionId,
notification: {
id,
data: { type: "alert_search", c },
},
};
}
async function waitForReplace(): Promise<void> {
for (let attempt = 0; attempt < 30; attempt += 1) {
if (mockReplace.mock.calls.length > 0) return;
await new Promise((resolve) => setImmediate(resolve));
}
}
describe("push notification action listener", () => {
beforeEach(() => {
resetNativePushMessagingStateForTests();
resetAlertSearchNotificationTapState();
listeners.clear();
mockIsNativePlatform.mockReset();
mockGetPlatform.mockReset();
mockAddListener.mockReset();
mockRequestPermissions.mockReset();
mockRegister.mockReset();
mockHandleReceived.mockReset();
mockReplace.mockReset();
mockIsNativePlatform.mockReturnValue(true);
mockGetPlatform.mockReturnValue("ios");
mockRequestPermissions.mockResolvedValue({ receive: "granted" });
mockRegister.mockResolvedValue(undefined);
mockHandleReceived.mockResolvedValue(undefined);
mockReplace.mockResolvedValue(undefined);
mockAddListener.mockImplementation(
(eventName: string, listener: (payload: unknown) => void) => {
listeners.set(eventName, listener);
return Promise.resolve({ remove: jest.fn() });
},
);
});
it("registers the tap listener without asking for permission or an FCM token", async () => {
await ensurePushNotificationActionListener();
expect(mockAddListener).toHaveBeenCalledTimes(1);
expect(mockAddListener).toHaveBeenCalledWith(
"pushNotificationActionPerformed",
expect.any(Function),
);
expect(mockRequestPermissions).not.toHaveBeenCalled();
expect(mockRegister).not.toHaveBeenCalled();
});
it("does not register a listener on web", async () => {
mockIsNativePlatform.mockReturnValue(false);
await ensurePushNotificationActionListener();
expect(mockAddListener).not.toHaveBeenCalled();
});
it("opens New Activity when a retained cold-start tap is delivered to the new listener", async () => {
const tap = alertSearchAction();
mockAddListener.mockImplementation(
(eventName: string, listener: (payload: unknown) => void) => {
if (eventName === "pushNotificationActionPerformed") {
listener(tap);
}
return Promise.resolve({ remove: jest.fn() });
},
);
await ensurePushNotificationActionListener();
await waitForReplace();
expect(mockReplace).toHaveBeenCalledWith({
name: "new-activity",
params: {},
query: { c: CURSORS },
});
});
it("keeps the cursor through encoding and the deep-link handler", async () => {
const cursors = "12 34/56";
mockAddListener.mockImplementation(
(eventName: string, listener: (payload: unknown) => void) => {
if (eventName === "pushNotificationActionPerformed") {
listener(alertSearchAction(cursors));
}
return Promise.resolve({ remove: jest.fn() });
},
);
await ensurePushNotificationActionListener();
await waitForReplace();
expect(mockReplace).toHaveBeenCalledWith({
name: "new-activity",
params: {},
query: { c: cursors },
});
});
it("opens New Activity when a warm-start tap arrives after the listener exists", async () => {
await ensurePushNotificationActionListener();
expect(mockReplace).not.toHaveBeenCalled();
listeners.get("pushNotificationActionPerformed")?.(alertSearchAction());
await waitForReplace();
expect(mockReplace).toHaveBeenCalledTimes(1);
expect(mockReplace).toHaveBeenCalledWith({
name: "new-activity",
params: {},
query: { c: CURSORS },
});
});
it("does not navigate when a notification arrives in the foreground", async () => {
await initializeNativePushAndFirebaseMessaging();
listeners.get("pushNotificationReceived")?.({
id: "msg-1",
data: { type: "alert_search", c: CURSORS },
});
await new Promise((resolve) => setImmediate(resolve));
expect(mockHandleReceived).toHaveBeenCalledTimes(1);
expect(mockReplace).not.toHaveBeenCalled();
});
it("does not navigate when the notification is dismissed", async () => {
await ensurePushNotificationActionListener();
listeners.get("pushNotificationActionPerformed")?.(
alertSearchAction(CURSORS, "msg-1", "dismiss"),
);
await new Promise((resolve) => setImmediate(resolve));
expect(mockReplace).not.toHaveBeenCalled();
});
it("does not register a second tap listener when server push is enabled later", async () => {
await ensurePushNotificationActionListener();
await initializeNativePushAndFirebaseMessaging();
const actionRegistrations = mockAddListener.mock.calls.filter(
(call) => call[0] === "pushNotificationActionPerformed",
);
expect(actionRegistrations).toHaveLength(1);
expect(mockRequestPermissions).toHaveBeenCalledTimes(1);
expect(mockRegister).toHaveBeenCalledTimes(1);
});
it("shares one in-flight registration among concurrent callers", async () => {
let release: (handle: { remove: jest.Mock }) => void = () => undefined;
mockAddListener.mockImplementation(
() =>
new Promise((resolve) => {
release = resolve;
}),
);
const first = ensurePushNotificationActionListener();
const second = ensurePushNotificationActionListener();
expect(mockAddListener).toHaveBeenCalledTimes(1);
release({ remove: jest.fn() });
await Promise.all([first, second]);
await ensurePushNotificationActionListener();
expect(mockAddListener).toHaveBeenCalledTimes(1);
});
it("retries listener registration after addListener fails", async () => {
mockAddListener.mockRejectedValueOnce(new Error("bridge down"));
await expect(ensurePushNotificationActionListener()).rejects.toThrow(
"bridge down",
);
await ensurePushNotificationActionListener();
expect(mockAddListener).toHaveBeenCalledTimes(2);
expect(mockRequestPermissions).not.toHaveBeenCalled();
expect(mockRegister).not.toHaveBeenCalled();
});
it("retries the tap listener without repeating FCM registration", async () => {
mockAddListener.mockRejectedValueOnce(new Error("bridge down"));
await initializeNativePushAndFirebaseMessaging();
expect(mockRegister).toHaveBeenCalledTimes(1);
await initializeNativePushAndFirebaseMessaging();
const actionRegistrations = mockAddListener.mock.calls.filter(
(call) => call[0] === "pushNotificationActionPerformed",
);
expect(actionRegistrations).toHaveLength(2);
expect(mockRequestPermissions).toHaveBeenCalledTimes(1);
expect(mockRegister).toHaveBeenCalledTimes(1);
});
it("navigates once when Android delivers the same cold-start tap twice", async () => {
await ensurePushNotificationActionListener();
const listener = listeners.get("pushNotificationActionPerformed");
const tap = alertSearchAction();
listener?.(tap);
listener?.(tap);
await waitForReplace();
await new Promise((resolve) => setImmediate(resolve));
expect(mockReplace).toHaveBeenCalledTimes(1);
});
});
@@ -1,9 +1,10 @@
/**
* Firebase Cloud Messaging (JS SDK) + Capacitor Push Notifications (native bridge).
*
* Initializes the Firebase web app when VITE_FIREBASE_* env vars are set, wires
* Capacitor push listeners, requests permission before registration/token flow,
* and attaches Firebase messaging when the browser/WebView reports support.
* Initializes the Firebase web app when VITE_FIREBASE_* env vars are set.
* The notification-tap listener is registered on its own
* (`ensurePushNotificationActionListener`). Permission, FCM token registration,
* and Firebase messaging stay on `initializeNativePushAndFirebaseMessaging`.
*/
import { Capacitor } from "@capacitor/core";
@@ -23,6 +24,7 @@ import {
import { logger } from "@/utils/logger";
import { NotificationInspector } from "@/plugins/NotificationInspectorPlugin";
import { openAlertSearchFromNotificationTap } from "./alertSearchNotificationTap";
import { readFirebaseWebEnv } from "./firebaseWebEnv";
import { handleCapacitorPushNotificationReceived } from "./NativeNotificationService";
import { getNotificationApiHeaders } from "./notificationApiAuth";
import { deferFcmRegistration } from "./notificationAuthLifecycle";
@@ -37,6 +39,11 @@ const LOG = "[FirebaseMessaging]";
let firebaseAppSingleton: FirebaseApp | null = null;
let nativeInitPromise: Promise<void> | null = null;
/**
* Separate from `nativeInitPromise`. Permission denial and token-registration
* failure must not block attaching the tap listener, or a later retry of it.
*/
let actionListenerPromise: Promise<void> | null = null;
/** Avoid duplicate POSTs when the same token is delivered more than once. */
let lastRegisteredFcmToken: string | null = null;
/** Last token received from Capacitor/Firebase (may match registered). */
@@ -127,9 +134,7 @@ export async function reregisterFcmTokenNow(): Promise<string> {
const app = ensureFirebaseApp();
if (app && (await isSupported())) {
const messaging = getMessaging(app);
const vapidKey = import.meta.env.VITE_FIREBASE_VAPID_KEY as
| string
| undefined;
const vapidKey = readFirebaseWebEnv().VITE_FIREBASE_VAPID_KEY;
const token = await getToken(
messaging,
vapidKey ? { vapidKey } : undefined,
@@ -173,7 +178,7 @@ export async function reregisterFcmTokenNow(): Promise<string> {
}
function readFirebaseOptions(): FirebaseOptions | null {
const env = import.meta.env;
const env = readFirebaseWebEnv();
const apiKey = env.VITE_FIREBASE_API_KEY as string | undefined;
const projectId = env.VITE_FIREBASE_PROJECT_ID as string | undefined;
const appId = env.VITE_FIREBASE_APP_ID as string | undefined;
@@ -240,9 +245,7 @@ async function attachFirebaseMessagingIfSupported(
}
const messaging = getMessaging(app);
const vapidKey = import.meta.env.VITE_FIREBASE_VAPID_KEY as
| string
| undefined;
const vapidKey = readFirebaseWebEnv().VITE_FIREBASE_VAPID_KEY;
try {
const token = await getToken(
@@ -266,8 +269,9 @@ async function attachFirebaseMessagingIfSupported(
}
/**
* Native: register Capacitor push listeners, request permissions, register for push,
* then initialize Firebase Messaging when env config and platform support allow.
* Native: register token and foreground-delivery listeners, request permission,
* register for push, then initialize Firebase Messaging when env config and
* platform support allow. The tap listener is attached separately.
*/
/**
@@ -281,6 +285,55 @@ async function openNewActivityDeepLink(url: string): Promise<void> {
await new DeepLinkHandler(router).handleDeepLink(url);
}
/**
* One `pushNotificationActionPerformed` listener for the process.
*
* Capacitor retains that event until the first listener exists, including a
* cold-start tap. This does not request permission or register an FCM token.
* A failed `addListener` clears the promise so the next call can retry.
* A second call while registration is in flight shares that attempt.
*/
async function registerPushNotificationActionListener(): Promise<void> {
await PushNotifications.addListener(
"pushNotificationActionPerformed",
(action) => {
logger.debug(`${LOG} pushNotificationActionPerformed`, action);
logPushNotificationActionPerformed(action);
void openAlertSearchFromNotificationTap(
action,
openNewActivityDeepLink,
).catch((err: unknown) => {
logger.warn(`${LOG} Could not open New Activity`, err);
});
},
);
}
export function ensurePushNotificationActionListener(): Promise<void> {
if (!Capacitor.isNativePlatform()) {
return Promise.resolve();
}
if (!actionListenerPromise) {
actionListenerPromise = registerPushNotificationActionListener().catch(
(error: unknown) => {
actionListenerPromise = null;
logger.error(
`${LOG} pushNotificationActionPerformed listener failed`,
error,
);
throw error;
},
);
}
return actionListenerPromise;
}
/** Drops listener and FCM-init promises. Tests use this between cases. */
export function resetNativePushMessagingStateForTests(): void {
actionListenerPromise = null;
nativeInitPromise = null;
}
async function initializeNativePushAndFirebaseMessagingImpl(): Promise<void> {
if (!Capacitor.isNativePlatform()) {
return;
@@ -324,24 +377,6 @@ async function initializeNativePushAndFirebaseMessagingImpl(): Promise<void> {
},
);
// Tap only. pushNotificationReceived (above) stays a log. Cold start is this
// same event: native code forwards the launch tap, and Capacitor retains it
// until this listener exists. openAlertSearchFromNotificationTap ignores a
// second delivery of that tap.
await PushNotifications.addListener(
"pushNotificationActionPerformed",
(action) => {
logger.debug(`${LOG} pushNotificationActionPerformed`, action);
logPushNotificationActionPerformed(action);
void openAlertSearchFromNotificationTap(
action,
openNewActivityDeepLink,
).catch((err) => {
logger.warn(`${LOG} Could not open New Activity`, err);
});
},
);
const perm = await PushNotifications.requestPermissions();
if (perm.receive !== "granted") {
logger.warn(`${LOG} Push permission not granted`, perm);
@@ -366,14 +401,27 @@ async function initializeNativePushAndFirebaseMessagingImpl(): Promise<void> {
}
/**
* Idempotent startup hook for Capacitor iOS/Android.
* Idempotent hook for permission and FCM token registration.
*
* The promise is kept for the process, including when this returns early
* because notification permission was denied or this Android build has no
* Firebase config. A later call does not retry `PushNotifications.register()`.
* Tap handling does not use this promise; see
* `ensurePushNotificationActionListener`.
*/
export function initializeNativePushAndFirebaseMessaging(): Promise<void> {
if (!Capacitor.isNativePlatform()) {
return Promise.resolve();
}
// Outside nativeInitPromise so a cached permission/token attempt cannot
// block a retry of the tap listener, and a listener failure cannot skip
// token registration.
const actionListener = ensurePushNotificationActionListener().catch(() => {
// ensurePushNotificationActionListener logged this and cleared its promise.
});
if (!nativeInitPromise) {
nativeInitPromise = initializeNativePushAndFirebaseMessagingImpl();
}
return nativeInitPromise;
const registration = nativeInitPromise;
return Promise.all([actionListener, registration]).then(() => undefined);
}
@@ -0,0 +1,38 @@
/**
* Vite's Firebase web config. Kept in this module so the messaging client can
* be loaded by Jest, which cannot parse `import.meta`.
*/
export interface FirebaseWebEnv {
VITE_FIREBASE_API_KEY?: string;
VITE_FIREBASE_AUTH_DOMAIN?: string;
VITE_FIREBASE_PROJECT_ID?: string;
VITE_FIREBASE_STORAGE_BUCKET?: string;
VITE_FIREBASE_MESSAGING_SENDER_ID?: string;
VITE_FIREBASE_APP_ID?: string;
VITE_FIREBASE_MEASUREMENT_ID?: string;
VITE_FIREBASE_VAPID_KEY?: string;
}
export function readFirebaseWebEnv(): FirebaseWebEnv {
const env = import.meta.env;
return {
VITE_FIREBASE_API_KEY: env.VITE_FIREBASE_API_KEY as string | undefined,
VITE_FIREBASE_AUTH_DOMAIN: env.VITE_FIREBASE_AUTH_DOMAIN as
| string
| undefined,
VITE_FIREBASE_PROJECT_ID: env.VITE_FIREBASE_PROJECT_ID as
| string
| undefined,
VITE_FIREBASE_STORAGE_BUCKET: env.VITE_FIREBASE_STORAGE_BUCKET as
| string
| undefined,
VITE_FIREBASE_MESSAGING_SENDER_ID: env.VITE_FIREBASE_MESSAGING_SENDER_ID as
| string
| undefined,
VITE_FIREBASE_APP_ID: env.VITE_FIREBASE_APP_ID as string | undefined,
VITE_FIREBASE_MEASUREMENT_ID: env.VITE_FIREBASE_MEASUREMENT_ID as
| string
| undefined,
VITE_FIREBASE_VAPID_KEY: env.VITE_FIREBASE_VAPID_KEY as string | undefined,
};
}
+1
View File
@@ -60,6 +60,7 @@ export {
} from "./notificationAuthLifecycle";
export {
ensureFirebaseApp,
ensurePushNotificationActionListener,
initializeNativePushAndFirebaseMessaging,
} from "./firebaseMessagingClient";
export { syncStarredPlansToNativePlugin } from "./syncStarredPlansToNativePlugin";