@sagepilot-ai/react-native-push-addon 0.4.1 → 0.4.2

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.
package/README.md CHANGED
@@ -2,10 +2,10 @@
2
2
 
3
3
  Optional Android/iOS package. Base SDK **0.4.0+** supplies identity/session, installation registration, preferences and authenticated HTTP transport. This add-on owns **analytics capture, native storage, replay, retry and upload**. It has no second customer-token store. Chat-only apps do not install it; older base SDK integrations remain compatible.
4
4
 
5
- This push add-on release is **0.4.1**, matching the base SDK and camera add-on:
5
+ This push add-on release is **0.4.2**, matching the base SDK and camera add-on:
6
6
 
7
7
  ```sh
8
- npm install @sagepilot-ai/react-native-sdk@0.4.1 @sagepilot-ai/react-native-push-addon@0.4.1
8
+ npm install @sagepilot-ai/react-native-sdk@0.4.2 @sagepilot-ai/react-native-push-addon@0.4.2
9
9
  ```
10
10
 
11
11
  Integration host: RN 0.81.5, React 19.1, Expo 54, RNFirebase 26.4. Native minimums: Android 24, iOS 15.1. Other peer-compatible versions are not tested. Expo Go cannot load this module.
@@ -69,8 +69,20 @@ Server fields: `title`, `body`, `image_url`, `deep_link`. Android SDK mode puts
69
69
 
70
70
  Installation capabilities advertise modes/media and `preferred_display_mode`. The channel can follow the installation preference or force provider/SDK mode. SDK mode is capability-gated to Android; old clients keep provider payloads. A mistaken Android background alert still belongs to FCM to avoid double display. Foreign/unconfigured envelopes are ignored. Native display requires the registered endpoint owner; successful revocation clears it. Queued opens cannot navigate for a different customer. Provider/OS alerts already in flight cannot be recalled by the add-on.
71
71
 
72
+ Android creates the `sagepilot` notification channel with high importance for sound and heads-up banners. The notification worker uses this channel for SDK-registered Android devices in Firebase mode unless the template specifies another `android.notification.channel_id`; native foreground/SDK display uses the same channel. This requires the matching worker update. Android retains an existing channel's importance across app updates: for an installation that already has a silent/default channel, open the app's Android notification settings, select **Notifications** (or your `channelName`), and enable sound/pop-up and lock-screen notifications. Do not delete/recreate channels to override user choices. DND, lock-screen privacy and manufacturer settings can still suppress presentation. High FCM transport priority alone does not enable banners. See [Android notification channels](https://developer.android.com/develop/ui/views/notifications/channels).
73
+
72
74
  Static JPEG/PNG: public HTTPS, no URL credentials/redirects, <=5 MiB, <=16 megapixels. Android connect/read timeouts 1.5 seconds each, read deadline 3 seconds. iOS resource timeout 5 seconds plus extension expiry fallback. DNS/platform scheduling can extend wall time. Image errors retain text. Provider-managed Android image download follows FCM's own behavior. No video/carousel renderer.
73
75
 
76
+ ## Notification display setup (unreleased)
77
+
78
+ Release 0.4.2 includes SDK-owned guidance for pop-ups and lock-screen notifications. No brand-built dialog is required: `createSagepilotNativePushAdapter` shows **Pop-ups and lock-screen notifications** once after notification access is granted and a signed-in app is active. **Open Settings** opens the Android `sagepilot` category (or app settings as a fallback) or iOS notification settings; **Not now** and Android back/outside dismissal are remembered in the existing host push storage. Registration and analytics do not wait for the user's answer. Background receipt never prompts.
79
+
80
+ Set `notificationSettingsPrompt: false` in the adapter options if your app already provides this education. The base SDK passes its existing `push.storage` to the add-on; older bases without that context continue working but do not automatically show the new guidance. The add-on checks settings again when the app becomes active, without repeating a dismissed prompt.
81
+
82
+ `getSagepilotPushNotificationSettings()` returns `{ notificationsEnabled, alertsEnabled, lockScreenEnabled }`. `null` means unknown: Android does not reliably expose manufacturer/global lock-screen visibility or Cards/Icons layout. Android alert eligibility comes from channel importance; iOS reports its alert and lock-screen settings. These fields do not guarantee presentation under DND, Focus, or OS delivery restrictions.
83
+
84
+ `openSagepilotPushNotificationSettings()` opens settings following a user action; it does not grant permission or change user preferences. New JavaScript paired with an older native binary falls back to the existing permission query and app settings, with presentation settings reported as unknown. Only the existing `getSagepilotPushPermission(true)` / `push.requestPermission()` invokes the OS notification permission prompt. Lock-screen content privacy and the phone-wide Cards/Icons choice remain user-controlled.
85
+
74
86
  ## Analytics
75
87
 
76
88
  **Firebase/provider rendering supports Sagepilot push analytics.** Connect Firebase through `createFirebasePushAdapter(...)`, wrap it with `createSagepilotNativePushAdapter(..., { displayMode: 'provider', onError })`, and configure the Firebase callbacks and native forwarding above. Firebase/OS displays background alerts while the add-on captures and uploads available `received` and `opened` events for Sagepilot-sent notifications. Forward `onMessage`, `onNotificationOpenedApp`, `getInitialNotification` and background/native callbacks; token registration alone does not report engagement.
@@ -1,7 +1,14 @@
1
1
  package ai.sagepilot.push;
2
2
  import android.app.Activity;
3
+ import android.app.Notification;
4
+ import android.app.NotificationChannel;
5
+ import android.app.NotificationManager;
6
+ import android.content.ActivityNotFoundException;
7
+ import android.content.Intent;
3
8
  import android.content.pm.PackageManager;
9
+ import android.net.Uri;
4
10
  import android.os.Build;
11
+ import android.provider.Settings;
5
12
  import androidx.core.app.NotificationManagerCompat;
6
13
  import com.facebook.react.bridge.*;
7
14
  import com.facebook.react.modules.core.*;
@@ -46,4 +53,33 @@ public final class SagepilotPushModule extends ReactContextBaseJavaModule {
46
53
  if(!(activity instanceof PermissionAwareActivity)){promise.reject("push_permission","An active Activity is required");return;}
47
54
  activity.runOnUiThread(()->((PermissionAwareActivity)activity).requestPermissions(new String[]{"android.permission.POST_NOTIFICATIONS"},48123,(code,permissions,grants)->{if(code!=48123)return false;promise.resolve(grants.length>0&&grants[0]==PackageManager.PERMISSION_GRANTED?"authorized":"denied");return true;}));
48
55
  }
56
+ /** Reads this channel's settings; global/OEM lock-screen visibility remains unknown. */
57
+ @ReactMethod public void notificationSettings(Promise promise){
58
+ try {
59
+ boolean enabled=NotificationManagerCompat.from(getReactApplicationContext()).areNotificationsEnabled();
60
+ NotificationChannel channel=Build.VERSION.SDK_INT>=26?getReactApplicationContext().getSystemService(NotificationManager.class).getNotificationChannel("sagepilot"):null;
61
+ WritableMap result=Arguments.createMap();result.putBoolean("notificationsEnabled",enabled);
62
+ if(!enabled)result.putBoolean("alertsEnabled",false);
63
+ else if(channel==null)result.putNull("alertsEnabled");
64
+ else result.putBoolean("alertsEnabled",channel.getImportance()>=NotificationManager.IMPORTANCE_HIGH);
65
+ if(!enabled||(channel!=null&&(channel.getImportance()==NotificationManager.IMPORTANCE_NONE||channel.getLockscreenVisibility()==Notification.VISIBILITY_SECRET)))result.putBoolean("lockScreenEnabled",false);
66
+ else result.putNull("lockScreenEnabled");
67
+ promise.resolve(result);
68
+ }catch(Exception e){promise.reject("push_settings","Could not read notification settings",e);}
69
+ }
70
+ /** Opens the channel's OS controls, falling back to app settings on unsupported devices. */
71
+ @ReactMethod public void openNotificationSettings(Promise promise){
72
+ try {
73
+ Intent fallback=new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,Uri.parse("package:"+getReactApplicationContext().getPackageName())).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
74
+ Intent intent=fallback;
75
+ if(Build.VERSION.SDK_INT>=26){
76
+ boolean exists=getReactApplicationContext().getSystemService(NotificationManager.class).getNotificationChannel("sagepilot")!=null;
77
+ intent=new Intent(exists?Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS:Settings.ACTION_APP_NOTIFICATION_SETTINGS)
78
+ .putExtra(Settings.EXTRA_APP_PACKAGE,getReactApplicationContext().getPackageName()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
79
+ if(exists)intent.putExtra(Settings.EXTRA_CHANNEL_ID,"sagepilot");
80
+ }
81
+ try{getReactApplicationContext().startActivity(intent);}catch(ActivityNotFoundException e){getReactApplicationContext().startActivity(fallback);}
82
+ promise.resolve(null);
83
+ }catch(Exception e){promise.reject("push_settings","Could not open notification settings",e);}
84
+ }
49
85
  }
@@ -33,7 +33,7 @@ public final class SagepilotPushRuntime {
33
33
  static synchronized void configure(Context c, JSONObject config) throws Exception {
34
34
  save(c, "config", config);
35
35
  if (android.os.Build.VERSION.SDK_INT >= 26) c.getSystemService(NotificationManager.class).createNotificationChannel(
36
- new NotificationChannel("sagepilot", config.optString("channelName", "Notifications"), NotificationManager.IMPORTANCE_DEFAULT));
36
+ new NotificationChannel("sagepilot", config.optString("channelName", "Notifications"), NotificationManager.IMPORTANCE_HIGH));
37
37
  }
38
38
  /** Recognizes only the configured brand's complete signed tracking envelope. */
39
39
  static boolean owns(Context c, JSONObject message) throws Exception {
@@ -143,6 +143,7 @@ public final class SagepilotPushRuntime {
143
143
  Intent dismiss=new Intent(c,SagepilotPushDismissReceiver.class).setData(launch.getData()).putExtra("sagepilot_message",m.toString());
144
144
  int flags=PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE;
145
145
  return new NotificationCompat.Builder(c,"sagepilot").setSmallIcon(R.drawable.sagepilot_push_notification)
146
+ .setPriority(NotificationCompat.PRIORITY_HIGH).setDefaults(NotificationCompat.DEFAULT_SOUND)
146
147
  .setContentTitle(n==null?d.optString("title"):n.optString("title",d.optString("title")))
147
148
  .setContentText(n==null?d.optString("body"):n.optString("body",d.optString("body")))
148
149
  .setAutoCancel(true).setOnlyAlertOnce(true).setContentIntent(PendingIntent.getActivity(c,delivery.hashCode(),launch,flags))
package/dist/index.d.mts CHANGED
@@ -1,5 +1,13 @@
1
1
  import { SagepilotPushAdapter, SagepilotPushObservation, SagepilotPushMessage } from '@sagepilot-ai/react-native-sdk';
2
2
 
3
+ /** OS-reported settings, not a guarantee of delivery or a device's lock-screen layout. */
4
+ type SagepilotPushNotificationSettings = {
5
+ notificationsEnabled: boolean;
6
+ /** Android channel importance / iOS alert setting; null when unavailable. */
7
+ alertsEnabled: boolean | null;
8
+ /** Android can report an explicit block, but cannot confirm global/OEM visibility. */
9
+ lockScreenEnabled: boolean | null;
10
+ };
3
11
  type NativePush = {
4
12
  configure(options: Record<string, unknown>): Promise<void>;
5
13
  pending(): Promise<SagepilotPushObservation[]>;
@@ -9,6 +17,8 @@ type NativePush = {
9
17
  receive(message: SagepilotPushMessage, foreground: boolean): Promise<boolean>;
10
18
  opened(message: SagepilotPushMessage): Promise<boolean>;
11
19
  permission(request: boolean): Promise<'authorized' | 'provisional' | 'denied' | 'not_determined'>;
20
+ notificationSettings?(): Promise<SagepilotPushNotificationSettings>;
21
+ openNotificationSettings?(): Promise<void>;
12
22
  addListener(event: string): void;
13
23
  removeListeners(count: number): void;
14
24
  };
@@ -16,11 +26,17 @@ type NativePush = {
16
26
  declare function createSagepilotNativePushAdapter(transport: SagepilotPushAdapter, options: {
17
27
  displayMode?: 'provider' | 'sdk';
18
28
  channelName?: string;
29
+ /** Defaults to true. Set false when the host owns notification-settings education. */
30
+ notificationSettingsPrompt?: boolean;
19
31
  onError: (error: unknown) => void;
20
32
  }): SagepilotPushAdapter;
21
33
  /** Explicitly forwards a host callback; storage and upload remain owned by the add-on. */
22
34
  declare function handleSagepilotBackgroundPush(message: SagepilotPushMessage): Promise<boolean>;
23
35
  /** Allows a host diagnostics screen to inspect/request permission without another SDK instance. */
24
36
  declare function getSagepilotPushPermission(request?: boolean): ReturnType<NativePush['permission']>;
37
+ /** Read available settings; an older native binary reports unknown presentation settings. */
38
+ declare function getSagepilotPushNotificationSettings(): Promise<SagepilotPushNotificationSettings>;
39
+ /** Open OS settings from a user action without granting or changing any permission. */
40
+ declare function openSagepilotPushNotificationSettings(): Promise<void>;
25
41
 
26
- export { createSagepilotNativePushAdapter, getSagepilotPushPermission, handleSagepilotBackgroundPush };
42
+ export { type SagepilotPushNotificationSettings, createSagepilotNativePushAdapter, getSagepilotPushNotificationSettings, getSagepilotPushPermission, handleSagepilotBackgroundPush, openSagepilotPushNotificationSettings };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,13 @@
1
1
  import { SagepilotPushAdapter, SagepilotPushObservation, SagepilotPushMessage } from '@sagepilot-ai/react-native-sdk';
2
2
 
3
+ /** OS-reported settings, not a guarantee of delivery or a device's lock-screen layout. */
4
+ type SagepilotPushNotificationSettings = {
5
+ notificationsEnabled: boolean;
6
+ /** Android channel importance / iOS alert setting; null when unavailable. */
7
+ alertsEnabled: boolean | null;
8
+ /** Android can report an explicit block, but cannot confirm global/OEM visibility. */
9
+ lockScreenEnabled: boolean | null;
10
+ };
3
11
  type NativePush = {
4
12
  configure(options: Record<string, unknown>): Promise<void>;
5
13
  pending(): Promise<SagepilotPushObservation[]>;
@@ -9,6 +17,8 @@ type NativePush = {
9
17
  receive(message: SagepilotPushMessage, foreground: boolean): Promise<boolean>;
10
18
  opened(message: SagepilotPushMessage): Promise<boolean>;
11
19
  permission(request: boolean): Promise<'authorized' | 'provisional' | 'denied' | 'not_determined'>;
20
+ notificationSettings?(): Promise<SagepilotPushNotificationSettings>;
21
+ openNotificationSettings?(): Promise<void>;
12
22
  addListener(event: string): void;
13
23
  removeListeners(count: number): void;
14
24
  };
@@ -16,11 +26,17 @@ type NativePush = {
16
26
  declare function createSagepilotNativePushAdapter(transport: SagepilotPushAdapter, options: {
17
27
  displayMode?: 'provider' | 'sdk';
18
28
  channelName?: string;
29
+ /** Defaults to true. Set false when the host owns notification-settings education. */
30
+ notificationSettingsPrompt?: boolean;
19
31
  onError: (error: unknown) => void;
20
32
  }): SagepilotPushAdapter;
21
33
  /** Explicitly forwards a host callback; storage and upload remain owned by the add-on. */
22
34
  declare function handleSagepilotBackgroundPush(message: SagepilotPushMessage): Promise<boolean>;
23
35
  /** Allows a host diagnostics screen to inspect/request permission without another SDK instance. */
24
36
  declare function getSagepilotPushPermission(request?: boolean): ReturnType<NativePush['permission']>;
37
+ /** Read available settings; an older native binary reports unknown presentation settings. */
38
+ declare function getSagepilotPushNotificationSettings(): Promise<SagepilotPushNotificationSettings>;
39
+ /** Open OS settings from a user action without granting or changing any permission. */
40
+ declare function openSagepilotPushNotificationSettings(): Promise<void>;
25
41
 
26
- export { createSagepilotNativePushAdapter, getSagepilotPushPermission, handleSagepilotBackgroundPush };
42
+ export { type SagepilotPushNotificationSettings, createSagepilotNativePushAdapter, getSagepilotPushNotificationSettings, getSagepilotPushPermission, handleSagepilotBackgroundPush, openSagepilotPushNotificationSettings };
package/dist/index.js CHANGED
@@ -21,15 +21,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  createSagepilotNativePushAdapter: () => createSagepilotNativePushAdapter,
24
+ getSagepilotPushNotificationSettings: () => getSagepilotPushNotificationSettings,
24
25
  getSagepilotPushPermission: () => getSagepilotPushPermission,
25
- handleSagepilotBackgroundPush: () => handleSagepilotBackgroundPush
26
+ handleSagepilotBackgroundPush: () => handleSagepilotBackgroundPush,
27
+ openSagepilotPushNotificationSettings: () => openSagepilotPushNotificationSettings
26
28
  });
27
29
  module.exports = __toCommonJS(index_exports);
28
30
  var import_react_native = require("react-native");
29
31
  var import_react_native_sdk = require("@sagepilot-ai/react-native-sdk");
30
32
 
31
33
  // package.json
32
- var version = "0.4.1";
34
+ var version = "0.4.2";
33
35
 
34
36
  // src/index.ts
35
37
  function native() {
@@ -37,16 +39,60 @@ function native() {
37
39
  if (!module2) throw new Error("Install the Sagepilot push add-on and rebuild the native app. Expo Go is not supported.");
38
40
  return module2;
39
41
  }
42
+ var SETTINGS_PROMPT_KEY = "sagepilot_push_notification_settings_prompt:v1";
43
+ var settingsPromptVisible = false;
44
+ async function promptNotificationSettings(storage, isCurrent, onError) {
45
+ if (settingsPromptVisible || import_react_native.AppState.currentState !== "active" || !isCurrent()) return;
46
+ settingsPromptVisible = true;
47
+ let displayed = false;
48
+ try {
49
+ const settings = await getSagepilotPushNotificationSettings();
50
+ if (!settings.notificationsEnabled || settings.alertsEnabled === true && settings.lockScreenEnabled === true || await storage.getItem(SETTINGS_PROMPT_KEY)) return;
51
+ if (import_react_native.AppState.currentState !== "active" || !isCurrent()) return;
52
+ let answered = false;
53
+ async function finish(open) {
54
+ if (answered) return;
55
+ answered = true;
56
+ try {
57
+ await storage.setItem(SETTINGS_PROMPT_KEY, "shown");
58
+ } catch (error) {
59
+ onError(error);
60
+ } finally {
61
+ settingsPromptVisible = false;
62
+ }
63
+ if (open) await openSagepilotPushNotificationSettings().catch(onError);
64
+ }
65
+ import_react_native.Alert.alert("Pop-ups and lock-screen notifications", import_react_native.Platform.OS === "android" ? "Check that Show as pop-up and lock-screen notifications are enabled in notification settings. For full lock-screen cards, choose Cards instead of Icons in your phone settings. You control whether message content is visible." : "Check that Banners and Lock Screen are enabled in notification settings. You control when message previews are visible.", [
66
+ { text: "Not now", style: "cancel", onPress: () => {
67
+ void finish(false);
68
+ } },
69
+ { text: "Open Settings", onPress: () => {
70
+ void finish(true);
71
+ } }
72
+ ], { cancelable: true, onDismiss: () => {
73
+ void finish(false);
74
+ } });
75
+ displayed = true;
76
+ } finally {
77
+ if (!displayed) settingsPromptVisible = false;
78
+ }
79
+ }
40
80
  function createSagepilotNativePushAdapter(transport, options) {
41
81
  let flush = async () => {
42
82
  };
83
+ let guide = async () => {
84
+ };
43
85
  let setOwner = async () => {
44
86
  };
45
87
  return {
46
88
  ...transport,
47
89
  capabilities: { version: 1, display_modes: import_react_native.Platform.OS === "android" ? ["provider", "sdk"] : ["provider"], media: ["image"], addon_version: version, preferred_display_mode: import_react_native.Platform.OS === "android" ? options.displayMode ?? "provider" : "provider" },
48
90
  getPermission: () => native().permission(false),
49
- requestPermission: () => native().permission(true),
91
+ requestPermission: async () => {
92
+ const permission = await native().permission(true);
93
+ void guide().catch(options.onError);
94
+ return permission;
95
+ },
50
96
  onMessage: () => transport.onMessage((message) => {
51
97
  void native().receive(message, true).catch(options.onError);
52
98
  }),
@@ -68,6 +114,11 @@ function createSagepilotNativePushAdapter(transport, options) {
68
114
  start: async (context) => {
69
115
  const module2 = native();
70
116
  let stopped = false, draining = null;
117
+ guide = async () => {
118
+ if (options.notificationSettingsPrompt !== false && context.storage) {
119
+ await promptNotificationSettings(context.storage, () => !stopped && Boolean(context.customerId()), options.onError);
120
+ }
121
+ };
71
122
  async function drain() {
72
123
  if (draining) return draining;
73
124
  draining = (async () => {
@@ -107,13 +158,16 @@ function createSagepilotNativePushAdapter(transport, options) {
107
158
  return draining;
108
159
  }
109
160
  flush = drain;
110
- setOwner = (owner) => module2.configure({
111
- workspaceId: context.workspaceId,
112
- channelId: context.channelId,
113
- sdkVersion: context.sdkVersion,
114
- channelName: options.channelName ?? "Notifications",
115
- owner
116
- });
161
+ setOwner = async (owner) => {
162
+ await module2.configure({
163
+ workspaceId: context.workspaceId,
164
+ channelId: context.channelId,
165
+ sdkVersion: context.sdkVersion,
166
+ channelName: options.channelName ?? "Notifications",
167
+ owner
168
+ });
169
+ if (owner) void guide().catch(options.onError);
170
+ };
117
171
  const subscription = new import_react_native.NativeEventEmitter(module2).addListener("SagepilotPushPending", () => {
118
172
  void drain().catch(options.onError);
119
173
  });
@@ -123,6 +177,10 @@ function createSagepilotNativePushAdapter(transport, options) {
123
177
  subscription.remove();
124
178
  throw error;
125
179
  }
180
+ const appState = import_react_native.AppState.addEventListener("change", (state) => {
181
+ if (state === "active") void guide().catch(options.onError);
182
+ });
183
+ void guide().catch(options.onError);
126
184
  void drain().catch(options.onError);
127
185
  const retry = setInterval(() => {
128
186
  void drain().catch(options.onError);
@@ -131,8 +189,11 @@ function createSagepilotNativePushAdapter(transport, options) {
131
189
  stopped = true;
132
190
  clearInterval(retry);
133
191
  subscription.remove();
192
+ appState.remove();
134
193
  flush = async () => {
135
194
  };
195
+ guide = async () => {
196
+ };
136
197
  setOwner = async () => {
137
198
  };
138
199
  };
@@ -145,9 +206,22 @@ function handleSagepilotBackgroundPush(message) {
145
206
  function getSagepilotPushPermission(request = false) {
146
207
  return native().permission(request);
147
208
  }
209
+ async function getSagepilotPushNotificationSettings() {
210
+ const module2 = native();
211
+ if (module2.notificationSettings) return module2.notificationSettings();
212
+ const permission = await module2.permission(false);
213
+ return { notificationsEnabled: permission === "authorized" || permission === "provisional", alertsEnabled: null, lockScreenEnabled: null };
214
+ }
215
+ async function openSagepilotPushNotificationSettings() {
216
+ const module2 = native();
217
+ if (module2.openNotificationSettings) await module2.openNotificationSettings();
218
+ else await import_react_native.Linking.openSettings();
219
+ }
148
220
  // Annotate the CommonJS export names for ESM import in node:
149
221
  0 && (module.exports = {
150
222
  createSagepilotNativePushAdapter,
223
+ getSagepilotPushNotificationSettings,
151
224
  getSagepilotPushPermission,
152
- handleSagepilotBackgroundPush
225
+ handleSagepilotBackgroundPush,
226
+ openSagepilotPushNotificationSettings
153
227
  });
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  // src/index.ts
2
- import { NativeEventEmitter, NativeModules, Platform } from "react-native";
2
+ import { Alert, AppState, Linking, NativeEventEmitter, NativeModules, Platform } from "react-native";
3
3
  import { SagepilotChatError } from "@sagepilot-ai/react-native-sdk";
4
4
 
5
5
  // package.json
6
- var version = "0.4.1";
6
+ var version = "0.4.2";
7
7
 
8
8
  // src/index.ts
9
9
  function native() {
@@ -11,16 +11,60 @@ function native() {
11
11
  if (!module) throw new Error("Install the Sagepilot push add-on and rebuild the native app. Expo Go is not supported.");
12
12
  return module;
13
13
  }
14
+ var SETTINGS_PROMPT_KEY = "sagepilot_push_notification_settings_prompt:v1";
15
+ var settingsPromptVisible = false;
16
+ async function promptNotificationSettings(storage, isCurrent, onError) {
17
+ if (settingsPromptVisible || AppState.currentState !== "active" || !isCurrent()) return;
18
+ settingsPromptVisible = true;
19
+ let displayed = false;
20
+ try {
21
+ const settings = await getSagepilotPushNotificationSettings();
22
+ if (!settings.notificationsEnabled || settings.alertsEnabled === true && settings.lockScreenEnabled === true || await storage.getItem(SETTINGS_PROMPT_KEY)) return;
23
+ if (AppState.currentState !== "active" || !isCurrent()) return;
24
+ let answered = false;
25
+ async function finish(open) {
26
+ if (answered) return;
27
+ answered = true;
28
+ try {
29
+ await storage.setItem(SETTINGS_PROMPT_KEY, "shown");
30
+ } catch (error) {
31
+ onError(error);
32
+ } finally {
33
+ settingsPromptVisible = false;
34
+ }
35
+ if (open) await openSagepilotPushNotificationSettings().catch(onError);
36
+ }
37
+ Alert.alert("Pop-ups and lock-screen notifications", Platform.OS === "android" ? "Check that Show as pop-up and lock-screen notifications are enabled in notification settings. For full lock-screen cards, choose Cards instead of Icons in your phone settings. You control whether message content is visible." : "Check that Banners and Lock Screen are enabled in notification settings. You control when message previews are visible.", [
38
+ { text: "Not now", style: "cancel", onPress: () => {
39
+ void finish(false);
40
+ } },
41
+ { text: "Open Settings", onPress: () => {
42
+ void finish(true);
43
+ } }
44
+ ], { cancelable: true, onDismiss: () => {
45
+ void finish(false);
46
+ } });
47
+ displayed = true;
48
+ } finally {
49
+ if (!displayed) settingsPromptVisible = false;
50
+ }
51
+ }
14
52
  function createSagepilotNativePushAdapter(transport, options) {
15
53
  let flush = async () => {
16
54
  };
55
+ let guide = async () => {
56
+ };
17
57
  let setOwner = async () => {
18
58
  };
19
59
  return {
20
60
  ...transport,
21
61
  capabilities: { version: 1, display_modes: Platform.OS === "android" ? ["provider", "sdk"] : ["provider"], media: ["image"], addon_version: version, preferred_display_mode: Platform.OS === "android" ? options.displayMode ?? "provider" : "provider" },
22
62
  getPermission: () => native().permission(false),
23
- requestPermission: () => native().permission(true),
63
+ requestPermission: async () => {
64
+ const permission = await native().permission(true);
65
+ void guide().catch(options.onError);
66
+ return permission;
67
+ },
24
68
  onMessage: () => transport.onMessage((message) => {
25
69
  void native().receive(message, true).catch(options.onError);
26
70
  }),
@@ -42,6 +86,11 @@ function createSagepilotNativePushAdapter(transport, options) {
42
86
  start: async (context) => {
43
87
  const module = native();
44
88
  let stopped = false, draining = null;
89
+ guide = async () => {
90
+ if (options.notificationSettingsPrompt !== false && context.storage) {
91
+ await promptNotificationSettings(context.storage, () => !stopped && Boolean(context.customerId()), options.onError);
92
+ }
93
+ };
45
94
  async function drain() {
46
95
  if (draining) return draining;
47
96
  draining = (async () => {
@@ -81,13 +130,16 @@ function createSagepilotNativePushAdapter(transport, options) {
81
130
  return draining;
82
131
  }
83
132
  flush = drain;
84
- setOwner = (owner) => module.configure({
85
- workspaceId: context.workspaceId,
86
- channelId: context.channelId,
87
- sdkVersion: context.sdkVersion,
88
- channelName: options.channelName ?? "Notifications",
89
- owner
90
- });
133
+ setOwner = async (owner) => {
134
+ await module.configure({
135
+ workspaceId: context.workspaceId,
136
+ channelId: context.channelId,
137
+ sdkVersion: context.sdkVersion,
138
+ channelName: options.channelName ?? "Notifications",
139
+ owner
140
+ });
141
+ if (owner) void guide().catch(options.onError);
142
+ };
91
143
  const subscription = new NativeEventEmitter(module).addListener("SagepilotPushPending", () => {
92
144
  void drain().catch(options.onError);
93
145
  });
@@ -97,6 +149,10 @@ function createSagepilotNativePushAdapter(transport, options) {
97
149
  subscription.remove();
98
150
  throw error;
99
151
  }
152
+ const appState = AppState.addEventListener("change", (state) => {
153
+ if (state === "active") void guide().catch(options.onError);
154
+ });
155
+ void guide().catch(options.onError);
100
156
  void drain().catch(options.onError);
101
157
  const retry = setInterval(() => {
102
158
  void drain().catch(options.onError);
@@ -105,8 +161,11 @@ function createSagepilotNativePushAdapter(transport, options) {
105
161
  stopped = true;
106
162
  clearInterval(retry);
107
163
  subscription.remove();
164
+ appState.remove();
108
165
  flush = async () => {
109
166
  };
167
+ guide = async () => {
168
+ };
110
169
  setOwner = async () => {
111
170
  };
112
171
  };
@@ -119,8 +178,21 @@ function handleSagepilotBackgroundPush(message) {
119
178
  function getSagepilotPushPermission(request = false) {
120
179
  return native().permission(request);
121
180
  }
181
+ async function getSagepilotPushNotificationSettings() {
182
+ const module = native();
183
+ if (module.notificationSettings) return module.notificationSettings();
184
+ const permission = await module.permission(false);
185
+ return { notificationsEnabled: permission === "authorized" || permission === "provisional", alertsEnabled: null, lockScreenEnabled: null };
186
+ }
187
+ async function openSagepilotPushNotificationSettings() {
188
+ const module = native();
189
+ if (module.openNotificationSettings) await module.openNotificationSettings();
190
+ else await Linking.openSettings();
191
+ }
122
192
  export {
123
193
  createSagepilotNativePushAdapter,
194
+ getSagepilotPushNotificationSettings,
124
195
  getSagepilotPushPermission,
125
- handleSagepilotBackgroundPush
196
+ handleSagepilotBackgroundPush,
197
+ openSagepilotPushNotificationSettings
126
198
  };
@@ -5,6 +5,25 @@
5
5
  @end
6
6
  @implementation SagepilotPushAddon
7
7
  RCT_EXPORT_MODULE();
8
+ /** Reads notification controls without requesting permission or changing privacy preferences. */
9
+ RCT_REMAP_METHOD(notificationSettings, notificationSettings:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
10
+ [UNUserNotificationCenter.currentNotificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings){
11
+ BOOL enabled=settings.authorizationStatus==UNAuthorizationStatusAuthorized||settings.authorizationStatus==UNAuthorizationStatusProvisional||settings.authorizationStatus==UNAuthorizationStatusEphemeral;
12
+ resolve(@{@"notificationsEnabled":@(enabled),
13
+ @"alertsEnabled":!enabled?@NO:settings.alertSetting==UNNotificationSettingNotSupported?NSNull.null:@(settings.alertSetting==UNNotificationSettingEnabled),
14
+ @"lockScreenEnabled":!enabled?@NO:settings.lockScreenSetting==UNNotificationSettingNotSupported?NSNull.null:@(settings.lockScreenSetting==UNNotificationSettingEnabled)});
15
+ }];
16
+ }
17
+ /** Opens the system notification settings following a host's explicit user action. */
18
+ RCT_REMAP_METHOD(openNotificationSettings, openNotificationSettings:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
19
+ dispatch_async(dispatch_get_main_queue(), ^{
20
+ NSString *destination=UIApplicationOpenSettingsURLString;
21
+ if(@available(iOS 15.4,*))destination=UIApplicationOpenNotificationSettingsURLString;
22
+ [UIApplication.sharedApplication openURL:[NSURL URLWithString:destination] options:@{} completionHandler:^(BOOL opened){
23
+ if(opened)resolve(nil);else reject(@"push_settings",@"Could not open notification settings",nil);
24
+ }];
25
+ });
26
+ }
8
27
  /** Native notification APIs are initialized on the main queue. */
9
28
  + (BOOL)requiresMainQueueSetup { return YES; }
10
29
  /** Delivers pending-buffer signals rather than individual ephemeral events. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagepilot-ai/react-native-push-addon",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "Optional Android/iOS push presentation and durable observations for Sagepilot",
5
5
  "keywords": [
6
6
  "sagepilot",