create-expo-boilerplate 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +38 -0
  2. package/dist/add.js +218 -0
  3. package/dist/generate.js +3 -1
  4. package/dist/index.js +35 -5
  5. package/dist/manifest.js +51 -0
  6. package/dist/modules/index.js +7 -0
  7. package/dist/modules/notifications.js +241 -0
  8. package/dist/modules/shared.js +67 -0
  9. package/dist/modules/subscriptions.js +223 -0
  10. package/dist/modules/types.js +57 -0
  11. package/dist/steps/format.js +11 -2
  12. package/dist/steps/javascript.js +14 -7
  13. package/dist/steps/readme.js +1 -0
  14. package/dist/steps/styling.js +1 -0
  15. package/dist/template.js +2 -0
  16. package/dist/versions.js +8 -0
  17. package/modules/notifications/files/plugins/withAndroidDefaultNotificationChannel.js +64 -0
  18. package/modules/notifications/files/src/notifications/NotificationProvider.tsx +309 -0
  19. package/modules/notifications/files/src/notifications/NotificationRoot.tsx +21 -0
  20. package/modules/notifications/files/src/notifications/README.md +763 -0
  21. package/modules/notifications/files/src/notifications/__tests__/NotificationProvider.test.tsx +358 -0
  22. package/modules/notifications/files/src/notifications/__tests__/pendingPress.test.ts +61 -0
  23. package/modules/notifications/files/src/notifications/__tests__/permissionState.test.ts +92 -0
  24. package/modules/notifications/files/src/notifications/__tests__/routing.test.ts +109 -0
  25. package/modules/notifications/files/src/notifications/__tests__/service.test.ts +189 -0
  26. package/modules/notifications/files/src/notifications/backgroundHandler.ts +158 -0
  27. package/modules/notifications/files/src/notifications/channels.ts +70 -0
  28. package/modules/notifications/files/src/notifications/components/NotificationPermissionBanner.tsx +134 -0
  29. package/modules/notifications/files/src/notifications/config.ts +179 -0
  30. package/modules/notifications/files/src/notifications/index.ts +90 -0
  31. package/modules/notifications/files/src/notifications/log.ts +57 -0
  32. package/modules/notifications/files/src/notifications/navigation.ts +11 -0
  33. package/modules/notifications/files/src/notifications/pendingPress.ts +86 -0
  34. package/modules/notifications/files/src/notifications/permissionState.ts +75 -0
  35. package/modules/notifications/files/src/notifications/routing.ts +99 -0
  36. package/modules/notifications/files/src/notifications/service.ts +476 -0
  37. package/modules/notifications/files/src/notifications/setup.ts +18 -0
  38. package/modules/notifications/files/src/notifications/types.ts +74 -0
  39. package/modules/notifications/files/src/notifications/useNotificationPermission.ts +80 -0
  40. package/modules/notifications/files/src/notifications/useNotificationSync.ts +71 -0
  41. package/modules/notifications/files/src/notifications/useNotifications.ts +13 -0
  42. package/modules/notifications/overlays/react-navigation/src/navigation/navigationRef.ts +6 -0
  43. package/modules/notifications/overlays/react-navigation/src/notifications/navigation.ts +38 -0
  44. package/modules/notifications/overlays/styling/stylesheet/src/notifications/components/NotificationPermissionBanner.tsx +134 -0
  45. package/modules/notifications/overlays/styling/tailwind/src/notifications/components/NotificationPermissionBanner.tsx +108 -0
  46. package/modules/notifications/translations/ar.json +12 -0
  47. package/modules/notifications/translations/en.json +12 -0
  48. package/modules/notifications/translations/es.json +12 -0
  49. package/modules/subscriptions/files/src/app/subscription.tsx +1 -0
  50. package/modules/subscriptions/files/src/subscription/README.md +215 -0
  51. package/modules/subscriptions/files/src/subscription/SubscriptionProvider.tsx +562 -0
  52. package/modules/subscriptions/files/src/subscription/SubscriptionRoot.tsx +30 -0
  53. package/modules/subscriptions/files/src/subscription/__tests__/SubscriptionProvider.test.tsx +931 -0
  54. package/modules/subscriptions/files/src/subscription/__tests__/UnlockModal.test.tsx +79 -0
  55. package/modules/subscriptions/files/src/subscription/__tests__/config.test.ts +23 -0
  56. package/modules/subscriptions/files/src/subscription/__tests__/introOffer.test.ts +93 -0
  57. package/modules/subscriptions/files/src/subscription/__tests__/offeringContent.test.ts +215 -0
  58. package/modules/subscriptions/files/src/subscription/__tests__/planChange.test.ts +356 -0
  59. package/modules/subscriptions/files/src/subscription/__tests__/purchaseErrors.test.ts +111 -0
  60. package/modules/subscriptions/files/src/subscription/__tests__/service.test.ts +369 -0
  61. package/modules/subscriptions/files/src/subscription/__tests__/statusNotice.test.ts +259 -0
  62. package/modules/subscriptions/files/src/subscription/__tests__/subscriptionState.test.ts +690 -0
  63. package/modules/subscriptions/files/src/subscription/components/CrossPlatformNotice.tsx +94 -0
  64. package/modules/subscriptions/files/src/subscription/components/PremiumGate.tsx +74 -0
  65. package/modules/subscriptions/files/src/subscription/components/SubscriptionStatusNotice.tsx +153 -0
  66. package/modules/subscriptions/files/src/subscription/components/UnlockModal.tsx +223 -0
  67. package/modules/subscriptions/files/src/subscription/config.ts +54 -0
  68. package/modules/subscriptions/files/src/subscription/index.ts +95 -0
  69. package/modules/subscriptions/files/src/subscription/introOffer.ts +61 -0
  70. package/modules/subscriptions/files/src/subscription/management.ts +30 -0
  71. package/modules/subscriptions/files/src/subscription/navigation.ts +15 -0
  72. package/modules/subscriptions/files/src/subscription/offeringContent.ts +259 -0
  73. package/modules/subscriptions/files/src/subscription/planChange.ts +219 -0
  74. package/modules/subscriptions/files/src/subscription/purchaseErrors.ts +140 -0
  75. package/modules/subscriptions/files/src/subscription/screens/PaywallScreen.tsx +466 -0
  76. package/modules/subscriptions/files/src/subscription/service.ts +270 -0
  77. package/modules/subscriptions/files/src/subscription/statusNotice.ts +189 -0
  78. package/modules/subscriptions/files/src/subscription/subscriptionState.ts +485 -0
  79. package/modules/subscriptions/files/src/subscription/types.ts +164 -0
  80. package/modules/subscriptions/files/src/subscription/useSubscriptionUser.ts +29 -0
  81. package/modules/subscriptions/overlays/react-navigation/src/navigation/navigationRef.ts +6 -0
  82. package/modules/subscriptions/overlays/react-navigation/src/subscription/navigation.ts +14 -0
  83. package/modules/subscriptions/overlays/styling/stylesheet/src/subscription/components/CrossPlatformNotice.tsx +94 -0
  84. package/modules/subscriptions/overlays/styling/stylesheet/src/subscription/components/SubscriptionStatusNotice.tsx +153 -0
  85. package/modules/subscriptions/overlays/styling/stylesheet/src/subscription/components/UnlockModal.tsx +227 -0
  86. package/modules/subscriptions/overlays/styling/stylesheet/src/subscription/screens/PaywallScreen.tsx +467 -0
  87. package/modules/subscriptions/overlays/styling/tailwind/src/subscription/components/CrossPlatformNotice.tsx +74 -0
  88. package/modules/subscriptions/overlays/styling/tailwind/src/subscription/components/SubscriptionStatusNotice.tsx +136 -0
  89. package/modules/subscriptions/overlays/styling/tailwind/src/subscription/components/UnlockModal.tsx +181 -0
  90. package/modules/subscriptions/overlays/styling/tailwind/src/subscription/screens/PaywallScreen.tsx +364 -0
  91. package/modules/subscriptions/translations/ar.json +128 -0
  92. package/modules/subscriptions/translations/en.json +112 -0
  93. package/modules/subscriptions/translations/es.json +112 -0
  94. package/package.json +3 -2
  95. package/template/jest.config.js +3 -1
  96. package/template/jest.setup.ts +36 -10
  97. package/template/src/localization/__tests__/i18n.test.ts +25 -0
  98. package/template/src/services/client.ts +14 -5
  99. package/template/src/shared/components/__tests__/Button.test.tsx +24 -0
@@ -0,0 +1,179 @@
1
+ import { AndroidImportance } from 'react-native-notify-kit';
2
+
3
+ /**
4
+ * ─────────────────────────────────────────────────────────────────────────────
5
+ * EVERY project-specific value in this module lives here.
6
+ *
7
+ * Porting to another app means editing this file and `useNotificationSync.ts`,
8
+ * and nothing else. See README.md § Porting.
9
+ *
10
+ * Nothing outside this file names a channel, a payload type, or a route. If
11
+ * you find yourself writing `CHANNEL_IDS.something` in another file, that is
12
+ * the coupling this layout exists to prevent — add a constant here instead.
13
+ * ─────────────────────────────────────────────────────────────────────────────
14
+ */
15
+
16
+ // ── Vocabulary ───────────────────────────────────────────────────────────────
17
+
18
+ /**
19
+ * The payload discriminators this app understands.
20
+ *
21
+ * Declared here rather than in `types.ts` because it is a per-project list, and
22
+ * `NotificationType` is derived from it so adding a type is one edit. Anything
23
+ * off this list degrades to `general` at the parse edge — see `routing.ts`.
24
+ */
25
+ export const NOTIFICATION_TYPES = ['general', 'account'] as const;
26
+
27
+ export type NotificationType = (typeof NOTIFICATION_TYPES)[number];
28
+
29
+ /** The shape of an Android channel declaration. */
30
+ export interface NotificationChannelConfig {
31
+ id: string;
32
+ name: string;
33
+ description?: string;
34
+ importance?: AndroidImportance;
35
+ vibration?: boolean;
36
+ sound?: string;
37
+ }
38
+
39
+ // ── Channels ─────────────────────────────────────────────────────────────────
40
+
41
+ /**
42
+ * Android channel ids carry a VERSION SUFFIX, and it is not decoration.
43
+ *
44
+ * Once a channel exists on a device, Android freezes everything about it except
45
+ * the name and description — importance, sound, and vibration cannot be changed
46
+ * for as long as the app stays installed. Shipping the wrong importance in v1
47
+ * would otherwise strand every existing user on it forever.
48
+ *
49
+ * To change any frozen property: bump the suffix, add the old id to
50
+ * `DEPRECATED_CHANNEL_IDS` so it gets deleted, and update the backend's
51
+ * `channel_id` to match. Be aware this resets any per-channel preference the
52
+ * user had set, so do it deliberately rather than routinely.
53
+ */
54
+ export const CHANNEL_IDS = {
55
+ general: 'general.v1',
56
+ } as const;
57
+
58
+ /** Channels retired by a version bump. Deleted at startup. */
59
+ export const DEPRECATED_CHANNEL_IDS: readonly string[] = [];
60
+
61
+ /**
62
+ * The channel FCM falls back to when a payload carries no `channel_id`.
63
+ *
64
+ * The backend is not required to send one, so this has to match the
65
+ * `com.google.firebase.messaging.default_notification_channel_id` value written
66
+ * into the manifest by `plugins/withAndroidDefaultNotificationChannel`. If the
67
+ * two drift apart, Android silently invents a low-importance "Miscellaneous"
68
+ * channel and every remote notification stops appearing as heads-up.
69
+ */
70
+ export const DEFAULT_CHANNEL_ID: string = CHANNEL_IDS.general;
71
+
72
+ /**
73
+ * The channel whose mute state the permission UI cares about.
74
+ *
75
+ * Android lets a user grant app-level permission and then silence one channel.
76
+ * Every permission API still reports success while that channel's
77
+ * notifications are dropped — the `channel-blocked` state. Checking it needs a
78
+ * specific channel, so this names the one that matters most to this app.
79
+ *
80
+ * It is also where `openSettings` deep-links, so the user lands on the muted
81
+ * channel rather than the app's notification root.
82
+ *
83
+ * With a single channel that is the default one. When you add a channel for a
84
+ * feature whose whole value is arriving on time (reminders, alerts), point this
85
+ * at it instead.
86
+ */
87
+ export const PRIMARY_CHANNEL_ID: string = CHANNEL_IDS.general;
88
+
89
+ /**
90
+ * Heads-up requires importance HIGH or above on the channel AND
91
+ * `priority: "high"` on the FCM message. Both halves are necessary; neither is
92
+ * sufficient. See README.md § Heads-up.
93
+ */
94
+ export const CHANNELS: readonly NotificationChannelConfig[] = [
95
+ {
96
+ id: CHANNEL_IDS.general,
97
+ name: 'General',
98
+ description: 'Announcements and updates.',
99
+ importance: AndroidImportance.HIGH,
100
+ vibration: true,
101
+ },
102
+ ];
103
+
104
+ // ── Delivery ─────────────────────────────────────────────────────────────────
105
+
106
+ /**
107
+ * How Android draws REMOTE notifications.
108
+ *
109
+ * `fcm-draws` (the default): the backend sends a `notification` block, so FCM
110
+ * renders the tray notification itself in background and killed states, and the
111
+ * app draws only in the foreground. Works with any standard FCM sender.
112
+ *
113
+ * The trap this constant exists to prevent: under `fcm-draws` the background
114
+ * message handler must NEVER call `displayNotification` or `handleFcmMessage` —
115
+ * FCM has already drawn that notification and doing so draws a second one. The
116
+ * flag is read by `backgroundHandler.ts` so the rule is enforced rather than
117
+ * remembered.
118
+ *
119
+ * `app-draws` is NotifyKit's FCM Mode: data-only payloads drawn by the app in
120
+ * every state, identical styling throughout. Switching needs a backend payload
121
+ * change and an iOS Notification Service Extension — see README.md.
122
+ */
123
+ export const ANDROID_DISPLAY_STRATEGY: 'fcm-draws' | 'app-draws' = 'fcm-draws';
124
+
125
+ // ── Badge ────────────────────────────────────────────────────────────────────
126
+
127
+ /**
128
+ * Clear the app icon badge whenever the app is opened or brought back to the
129
+ * front — "opening the app means you've seen it", which is right for most apps.
130
+ *
131
+ * Turn it off when the badge is a real count the app keeps in sync itself
132
+ * (unread messages, pending tasks): call `setBadgeCount(n)` from wherever that
133
+ * number changes, and have the backend send the same number as `aps.badge`.
134
+ */
135
+ export const CLEAR_BADGE_ON_OPEN: boolean = true;
136
+
137
+ // ── Routing ──────────────────────────────────────────────────────────────────
138
+
139
+ /**
140
+ * Payload `type` → in-app route.
141
+ *
142
+ * The client owns this map rather than following a server-supplied URL. A push
143
+ * payload is attacker-reachable if the backend is ever compromised or a message
144
+ * is malformed, and an allowlist means the worst case is a notification that
145
+ * does nothing rather than one that deep-links anywhere it likes.
146
+ *
147
+ * `null` means "just open the app" — a valid outcome, not a missing entry.
148
+ */
149
+ export const ROUTE_BY_TYPE: Record<NotificationType, string | null> = {
150
+ general: null,
151
+ // Example: an account alert (new sign-in, profile change) opens Settings.
152
+ account: '/settings',
153
+ };
154
+
155
+ /**
156
+ * Types whose payload `id` is appended to the route as `?id=…` (URI-encoded).
157
+ * Add a type here when its screen takes an id, e.g. `order` → `/orders?id=42`.
158
+ */
159
+ export const TYPES_WITH_ID: readonly NotificationType[] = [];
160
+
161
+ /**
162
+ * Backend payload value → internal `NotificationType`.
163
+ *
164
+ * The wire format is the backend's, not ours — e.g. SCREAMING_SNAKE
165
+ * (`ACCOUNT_ALERT`) under a `notification_type` key. Translating at the edge
166
+ * means the rest of the module keeps its own vocabulary, and a backend rename
167
+ * is one line here instead of a find-and-replace through routing, config and
168
+ * tests.
169
+ *
170
+ * Keys are matched case-insensitively after trimming — see `parsePayload`.
171
+ */
172
+ export const TYPE_BY_PAYLOAD_VALUE: Record<string, NotificationType> = {
173
+ GENERAL: 'general',
174
+ ACCOUNT: 'account',
175
+ ACCOUNT_ALERT: 'account',
176
+ };
177
+
178
+ /** Routes that require a signed-in user. Dropped when logged out. */
179
+ export const AUTHENTICATED_ROUTES: readonly string[] = ['/settings'];
@@ -0,0 +1,90 @@
1
+ /**
2
+ * notifications/index.ts ← The public API of this module
3
+ *
4
+ * The ONLY import path app code should use:
5
+ * import { useNotifications, NotificationPermissionBanner } from '@/notifications';
6
+ *
7
+ * ─────────────────────────────────────────────────────────────────────────────
8
+ * Wiring (done for you by `create-expo-boilerplate add notifications`):
9
+ *
10
+ * 1. index.ts (entry) — before the app renders anything:
11
+ * import '@/notifications/setup'; // background handlers + channels
12
+ *
13
+ * 2. src/providers/AppProviders.tsx — inside APIProvider, around the navigator:
14
+ * <NotificationRoot>{children}</NotificationRoot>
15
+ *
16
+ * Then mount <NotificationPermissionBanner /> on whichever screen is allowed to
17
+ * ask for permission (Settings, by default). `useNotificationPermission` is
18
+ * what grants a screen that ability, and the banner only prompts on an explicit
19
+ * tap — nothing prompts on mount.
20
+ *
21
+ * ─────────────────────────────────────────────────────────────────────────────
22
+ * Scope: this module is the notification TRANSPORT — permission, channels, the
23
+ * FCM token, remote message handling, routing, and local trigger scheduling. It
24
+ * has no features in it. Anything that decides WHAT to notify about or WHEN
25
+ * lives in its own feature folder and calls in.
26
+ *
27
+ * ─────────────────────────────────────────────────────────────────────────────
28
+ * Note on the barrel: barrel exports have a bundle-size cost in Metro. This one
29
+ * is intentional because it is the module's external API boundary. Files INSIDE
30
+ * src/notifications/ import from each other directly, never through here, to
31
+ * avoid circular references.
32
+ * ─────────────────────────────────────────────────────────────────────────────
33
+ */
34
+
35
+ // ── Provider & context ────────────────────────────────────────────────────────
36
+ export { NotificationProvider, useNotificationContext } from './NotificationProvider';
37
+ export { NotificationRoot } from './NotificationRoot';
38
+
39
+ // ── Hooks ─────────────────────────────────────────────────────────────────────
40
+ export type { UseNotificationPermissionReturn } from './useNotificationPermission';
41
+ export { useNotificationPermission } from './useNotificationPermission';
42
+ export { useNotifications } from './useNotifications';
43
+
44
+ // ── Host adapter (adapt per project) ──────────────────────────────────────────
45
+ export { navigateFromNotification } from './navigation';
46
+ export { useNotificationSync, useRegisterPushToken } from './useNotificationSync';
47
+
48
+ // ── Components ────────────────────────────────────────────────────────────────
49
+ export { default as NotificationPermissionBanner } from './components/NotificationPermissionBanner';
50
+
51
+ // ── Service layer ─────────────────────────────────────────────────────────────
52
+ export type { ScheduleLocalOptions } from './service';
53
+ export {
54
+ cancelLocalNotifications,
55
+ clearBadge,
56
+ configureNotifications,
57
+ getBadgeCount,
58
+ getFcmToken,
59
+ getPermissionState,
60
+ openNotificationSettings,
61
+ scheduleLocalNotifications,
62
+ setBadgeCount,
63
+ } from './service';
64
+
65
+ // ── Dev tracing ───────────────────────────────────────────────────────────────
66
+ export { describeRemoteMessage, logNotification } from './log';
67
+
68
+ // ── Pure helpers (exported for tests and advanced consumers) ──────────────────
69
+ export { canPrompt, derivePermissionState, isDelivering } from './permissionState';
70
+ export { canOpenRoute, parsePayload, resolveRoute } from './routing';
71
+
72
+ // ── Config ────────────────────────────────────────────────────────────────────
73
+ export type { NotificationChannelConfig, NotificationType } from './config';
74
+ export {
75
+ ANDROID_DISPLAY_STRATEGY,
76
+ CHANNEL_IDS,
77
+ CLEAR_BADGE_ON_OPEN,
78
+ DEFAULT_CHANNEL_ID,
79
+ NOTIFICATION_TYPES,
80
+ PRIMARY_CHANNEL_ID,
81
+ ROUTE_BY_TYPE,
82
+ } from './config';
83
+
84
+ // ── Types ─────────────────────────────────────────────────────────────────────
85
+ export type {
86
+ LocalTrigger,
87
+ NotificationContextValue,
88
+ NotificationPayload,
89
+ NotificationPermissionState,
90
+ } from './types';
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Dev-only notification tracing.
3
+ *
4
+ * One helper rather than scattered `console.log`s so every entry point prints
5
+ * the same shape — which is what makes the Metro output readable when a single
6
+ * push produces several lines (received → displayed → pressed → routed).
7
+ *
8
+ * Stripped from release builds by the `__DEV__` guard: notification payloads
9
+ * routinely carry user-scoped ids, and a release build should not be writing
10
+ * those to the device log where any other app with log access can read them.
11
+ *
12
+ * The background handler runs in a headless JS runtime with no component tree —
13
+ * `console.log` still reaches Metro from there, which is the only visibility
14
+ * you get into a notification that arrived while the app was killed.
15
+ */
16
+ export function logNotification(event: string, detail?: unknown): void {
17
+ if (!__DEV__) return;
18
+
19
+ if (detail === undefined) {
20
+ console.log(`🔔 [notifications] ${event}`);
21
+ return;
22
+ }
23
+
24
+ console.log(`🔔 [notifications] ${event}`, detail);
25
+ }
26
+
27
+ /**
28
+ * The bits of an FCM message worth seeing, flattened.
29
+ *
30
+ * Logging the raw `RemoteMessage` buries the two things you actually check —
31
+ * the display block and the data block — under transport metadata, and on
32
+ * Android it carries native objects that stringify to `[object Object]`.
33
+ *
34
+ * `notification` being `undefined` here is the single most useful signal in the
35
+ * whole module: it means the payload was data-only, which is silently dropped
36
+ * on a killed Android app. If a push works in the foreground and vanishes when
37
+ * the app is closed, this line is where you find out why.
38
+ */
39
+ export function describeRemoteMessage(message: {
40
+ messageId?: string;
41
+ from?: string;
42
+ sentTime?: number;
43
+ notification?: { title?: string; body?: string };
44
+ data?: Record<string, unknown>;
45
+ }) {
46
+ return {
47
+ messageId: message.messageId,
48
+ from: message.from,
49
+ sentAt: message.sentTime ? new Date(message.sentTime).toLocaleTimeString() : undefined,
50
+ // Present = the OS will draw this itself in background/killed states.
51
+ // Absent = data-only, and Android drops it when the app is not running.
52
+ notification: message.notification
53
+ ? { title: message.notification.title, body: message.notification.body }
54
+ : '⚠ NONE — data-only, dropped on killed Android',
55
+ data: message.data ?? {},
56
+ };
57
+ }
@@ -0,0 +1,11 @@
1
+ import { type Href, router } from 'expo-router';
2
+
3
+ /**
4
+ * Opens a route resolved from a notification.
5
+ *
6
+ * Routes come from the allowlist in `config.ts`, never from the payload, so the
7
+ * cast only reconciles plain strings with Expo Router's typed hrefs.
8
+ */
9
+ export function navigateFromNotification(route: string): void {
10
+ router.push(route as Href);
11
+ }
@@ -0,0 +1,86 @@
1
+ import { logNotification } from './log';
2
+ import type { NotificationPayload } from './types';
3
+
4
+ /**
5
+ * A hand-off for notification presses that reach JS before anything can
6
+ * navigate.
7
+ *
8
+ * ── Why this exists ──────────────────────────────────────────────────────────
9
+ * `backgroundHandler.ts` runs at module scope, in a runtime with no component
10
+ * tree and no navigator, so it cannot route. Its original assumption was that a
11
+ * background press always relaunches the app and `getInitialPayload()` would
12
+ * pick the notification up on the next launch — true on Android, false on iOS
13
+ * in two separate ways:
14
+ *
15
+ * 1. NotifyKit routes a press to the BACKGROUND channel whenever the app is
16
+ * not `UIApplicationStateActive` at the moment iOS delivers it — which is
17
+ * exactly the state during the tap that brings a BACKGROUNDED app forward.
18
+ * There is no relaunch, so nothing ever re-reads the initial payload
19
+ * (`hasHandledColdStartRef` has already fired) and the tap is lost.
20
+ *
21
+ * 2. When NotifyKit claims a remote notification on iOS (see
22
+ * `backgroundHandler.ts` § remote hand-back) its own
23
+ * `getInitialNotification()` still returns `null` for it — the native store
24
+ * is only released when the payload carried a NotifyKit-authored id — so a
25
+ * COLD start from that tap has nothing to read either.
26
+ *
27
+ * Both cases end with the same fact: the press is in JS, on the background
28
+ * channel, and the only thing missing is somewhere to put it until the provider
29
+ * is alive. That is this module.
30
+ *
31
+ * Module-scope state rather than storage: the background event and the app it
32
+ * hands off to share one JS runtime in every case that reaches here — an iOS
33
+ * background press, an iOS cold start, and an Android headless press that
34
+ * launches the activity into the same process.
35
+ */
36
+
37
+ let pending: NotificationPayload | null = null;
38
+ let deliver: ((payload: NotificationPayload) => void) | null = null;
39
+
40
+ /**
41
+ * Records a press that had nowhere to go, or forwards it straight through if
42
+ * the provider is already listening.
43
+ *
44
+ * Only the most recent press is held. Two taps queued at once would both have
45
+ * to resolve to a route, and the second is the one the user actually chose.
46
+ */
47
+ export function enqueuePress(payload: NotificationPayload): void {
48
+ if (deliver) {
49
+ logNotification('PRESS handed to the live listener', payload);
50
+ deliver(payload);
51
+ return;
52
+ }
53
+
54
+ logNotification('PRESS parked until the app can navigate', payload);
55
+ pending = payload;
56
+ }
57
+
58
+ /**
59
+ * Subscribes the app to presses arriving through the background channel, and
60
+ * immediately drains anything parked before it mounted.
61
+ *
62
+ * The parked payload is cleared as it is delivered, so a remount cannot
63
+ * re-navigate to a notification the user already followed.
64
+ */
65
+ export function subscribeToPendingPress(
66
+ handler: (payload: NotificationPayload) => void,
67
+ ): () => void {
68
+ deliver = handler;
69
+
70
+ if (pending) {
71
+ const queued = pending;
72
+ pending = null;
73
+ logNotification('PRESS drained from the background queue', queued);
74
+ handler(queued);
75
+ }
76
+
77
+ return () => {
78
+ if (deliver === handler) deliver = null;
79
+ };
80
+ }
81
+
82
+ /** Test seam. Not part of the module's public API — see `index.ts`. */
83
+ export function __resetPendingPress(): void {
84
+ pending = null;
85
+ deliver = null;
86
+ }
@@ -0,0 +1,75 @@
1
+ import { AuthorizationStatus } from 'react-native-notify-kit';
2
+
3
+ import type { NotificationPermissionState } from './types';
4
+
5
+ /**
6
+ * Everything this function needs, named separately so tests can build one
7
+ * without constructing a whole `NotificationSettings`.
8
+ */
9
+ export interface PermissionInput {
10
+ authorizationStatus: AuthorizationStatus;
11
+ /** Android only: has the user muted `PRIMARY_CHANNEL_ID`? */
12
+ isChannelBlocked?: boolean;
13
+ /**
14
+ * Whether the OS will still show a prompt.
15
+ *
16
+ * iOS: false after the first denial, always. Android: false after the second.
17
+ * There is no API that reports this directly, so the caller tracks it — see
18
+ * `hasRequested` in `useNotificationPermission`.
19
+ */
20
+ canAskAgain?: boolean;
21
+ }
22
+
23
+ /**
24
+ * Raw OS status → the state the banner renders from.
25
+ *
26
+ * Pure, and the only place the five-way distinction is decided. Two orderings
27
+ * here are load-bearing:
28
+ *
29
+ * 1. `channel-blocked` is checked FIRST, before authorization. It only occurs
30
+ * while app-level permission is granted, so checking it after would be
31
+ * unreachable — the function would have already returned `granted` and the
32
+ * user would sit in front of a screen that claims notifications are on
33
+ * while Android silently drops every one.
34
+ *
35
+ * 2. `DENIED` splits on `canAskAgain`. Collapsing the two gives the banner a
36
+ * button that calls `requestPermission()` into the void on iOS, which is
37
+ * worse than no button: it looks like the app is broken rather than like the
38
+ * user has a decision to reverse in Settings.
39
+ *
40
+ * `PROVISIONAL` counts as granted. iOS delivers those quietly to the
41
+ * notification centre without a prompt, which is a real authorization — just a
42
+ * less prominent one — and nothing in this app requests it today.
43
+ */
44
+ export function derivePermissionState({
45
+ authorizationStatus,
46
+ isChannelBlocked = false,
47
+ canAskAgain = true,
48
+ }: PermissionInput): NotificationPermissionState {
49
+ const isAuthorized =
50
+ authorizationStatus === AuthorizationStatus.AUTHORIZED ||
51
+ authorizationStatus === AuthorizationStatus.PROVISIONAL;
52
+
53
+ if (isAuthorized) {
54
+ return isChannelBlocked ? 'channel-blocked' : 'granted';
55
+ }
56
+
57
+ if (authorizationStatus === AuthorizationStatus.DENIED) {
58
+ return canAskAgain ? 'denied' : 'blocked';
59
+ }
60
+
61
+ return 'undetermined';
62
+ }
63
+
64
+ /** Whether notifications will actually be delivered in this state. */
65
+ export function isDelivering(state: NotificationPermissionState): boolean {
66
+ return state === 'granted';
67
+ }
68
+
69
+ /**
70
+ * Whether the OS prompt is still reachable. `blocked` and `channel-blocked`
71
+ * both need a trip to Settings instead, so the banner has to swap its CTA.
72
+ */
73
+ export function canPrompt(state: NotificationPermissionState): boolean {
74
+ return state === 'undetermined' || state === 'denied';
75
+ }
@@ -0,0 +1,99 @@
1
+ import type { NotificationType } from './config';
2
+ import {
3
+ AUTHENTICATED_ROUTES,
4
+ ROUTE_BY_TYPE,
5
+ TYPE_BY_PAYLOAD_VALUE,
6
+ TYPES_WITH_ID,
7
+ } from './config';
8
+ import type { NotificationPayload } from './types';
9
+
10
+ /**
11
+ * Where the discriminator lives, in priority order.
12
+ *
13
+ * `notification_type` is a common backend convention; `type` is the
14
+ * conventional FCM field and is kept as a fallback so a payload from any other
15
+ * sender — a Firebase console test message, a future service — still routes.
16
+ */
17
+ const TYPE_KEYS = ['notification_type', 'type'] as const;
18
+
19
+ /**
20
+ * A raw FCM `data` block → a typed payload.
21
+ *
22
+ * Every value on the wire is a string, and the block is entirely
23
+ * backend-controlled, so nothing here trusts its input: an unknown or missing
24
+ * `type` degrades to `general` rather than throwing. A malformed payload should
25
+ * open the app, not crash the notification handler on a background thread where
26
+ * the error is invisible.
27
+ */
28
+ /**
29
+ * Reads the discriminator, whichever key and casing it arrived under.
30
+ *
31
+ * Normalised to upper case before lookup because the backend sends
32
+ * `ACCOUNT_ALERT` while nothing stops a future sender using `account_alert`.
33
+ * An unrecognised value degrades to `general` — which opens the app and
34
+ * navigates nowhere — rather than throwing on a background thread where the
35
+ * error would be invisible.
36
+ */
37
+ function readType(data: Record<string, unknown> | undefined | null): NotificationType {
38
+ for (const key of TYPE_KEYS) {
39
+ const raw = data?.[key];
40
+ if (typeof raw !== 'string') continue;
41
+
42
+ const mapped = TYPE_BY_PAYLOAD_VALUE[raw.trim().toUpperCase()];
43
+ if (mapped) return mapped;
44
+ }
45
+
46
+ return 'general';
47
+ }
48
+
49
+ export function parsePayload(
50
+ data: Record<string, unknown> | undefined | null,
51
+ ): NotificationPayload {
52
+ const payload: NotificationPayload = { type: readType(data) };
53
+
54
+ // Every other string field is carried through untouched — `notification_type`
55
+ // and `sender_id` included. They are not used for routing, but they are what
56
+ // makes a `[notifications]` log line enough to diagnose a bad payload without
57
+ // reaching for the backend.
58
+ for (const [key, value] of Object.entries(data ?? {})) {
59
+ if (key !== 'type' && typeof value === 'string') payload[key] = value;
60
+ }
61
+
62
+ return payload;
63
+ }
64
+
65
+ /**
66
+ * A payload → the route to open, or null for "just bring the app to the front".
67
+ *
68
+ * The route comes from the client's own `ROUTE_BY_TYPE` allowlist, never from a
69
+ * URL in the payload. A server-supplied destination would make every push a
70
+ * potential deep link into any screen in the app, which is a bad trade for
71
+ * saving one map entry — so a `route` field in `data` is deliberately ignored.
72
+ *
73
+ * `id` is appended as a query param only for types listed in `TYPES_WITH_ID`,
74
+ * and only after being URI-encoded.
75
+ */
76
+ export function resolveRoute(payload: NotificationPayload): string | null {
77
+ const base = ROUTE_BY_TYPE[payload.type];
78
+ if (!base) return null;
79
+
80
+ if (payload.id && TYPES_WITH_ID.includes(payload.type)) {
81
+ return `${base}?id=${encodeURIComponent(payload.id)}`;
82
+ }
83
+
84
+ return base;
85
+ }
86
+
87
+ /**
88
+ * Whether a route can be opened right now.
89
+ *
90
+ * A cold start from a notification resolves long before auth does, and pushing
91
+ * a gated route while logged out lands the user on a screen `Stack.Protected`
92
+ * immediately bounces them off. Dropping it is better than that flash.
93
+ */
94
+ export function canOpenRoute(route: string, isLoggedIn: boolean): boolean {
95
+ if (isLoggedIn) return true;
96
+
97
+ const path = route.split('?')[0];
98
+ return !AUTHENTICATED_ROUTES.includes(path);
99
+ }