@sagepilot-ai/react-native-push-addon 0.4.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.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sagepilot AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,97 @@
1
+ # Sagepilot React Native push add-on
2
+
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
+
5
+ The first push add-on release is **0.4.0**, matching the base SDK and camera add-on:
6
+
7
+ ```sh
8
+ npm install @sagepilot-ai/react-native-sdk@0.4.0 @sagepilot-ai/react-native-push-addon@0.4.0
9
+ ```
10
+
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.
12
+
13
+ ## Shared session
14
+
15
+ ```ts
16
+ const adapter = createSagepilotNativePushAdapter(firebaseAdapter, {
17
+ displayMode: 'provider', // or 'sdk'
18
+ onError: reportError,
19
+ });
20
+ await SagepilotChat.configure({ ...existingChatConfig,
21
+ push: { channelId: brandPushChannelId, storage: AsyncStorage, adapter,
22
+ onOpen: navigateToAllowedDestination },
23
+ });
24
+ await SagepilotChat.identify(existingCustomerIdentity);
25
+ await SagepilotChat.authorizePush(await yourAuthenticatedServer.getBrandIdentityProof());
26
+ await SagepilotChat.push.requestPermission(); // explicit user action
27
+ ```
28
+
29
+ Import `createSagepilotNativePushAdapter` from this package; import `SagepilotChat` and `createFirebasePushAdapter` from the base SDK. `firebaseAdapter` is the existing transport forwarding getToken, token refresh, onMessage, onNotificationOpenedApp and getInitialNotification from host Firebase. This add-on overrides permissions natively; `getSagepilotPushPermission(request=false)` is also exported for diagnostics.
30
+
31
+ The short-lived host-server proof follows Step 1: HS256, `aud: sagepilot-brand-push`, channel UUID and either existing `customer_id` or stable `client_customer_id`, `iat`, `exp`, maximum five minutes. Optional email/phone must be host-verified. Never put signing secrets or Firebase server credentials in the app. `authorizePush` adds a server-owned brand grant to the **existing** encrypted session; workspace/customer must match. Chat channel, session and conversation survive. One stored credential serves chat and push. Renew proof after 24 hours for registration/preferences. Revocation and signed historical events remain available after freshness expiry. Identify clears the previous brand grant: authorize again afterwards. Push-only hosts may use `SagepilotBrandPush`; do not create it alongside chat for this integration.
32
+
33
+ ## Native forwarding
34
+
35
+ The package does not install a competing Firebase service. Firebase/APNs configuration remains host-owned. For Expo + RNFirebase:
36
+
37
+ ```js
38
+ plugins: [['@sagepilot-ai/react-native-push-addon', { firebaseForwarding: true }]]
39
+ ```
40
+
41
+ Run `npx expo prebuild --no-install` and rebuild. This explicit plugin wraps the Android RNFirebase receiver, forwards Activity cold/warm taps, and installs an iOS forwarding delegate after startup. Existing RNFirebase handling and unrelated notifications remain forwarded. Repeated callbacks use persisted delivery/event IDs. Unsupported custom Activity/AppDelegate structures require manual forwarding; later delegate replacement must preserve it.
42
+
43
+ Manual Android: existing receiver/service calls `SagepilotPushRuntime.receive(context, extras, foreground)` off the UI thread. Activity onCreate/onNewIntent calls `SagepilotPushRuntime.opened(context, intent)`. JS background handlers can call `handleSagepilotBackgroundPush(message)` without bootstrapping chat; native forwarding is required for capture before JS.
44
+
45
+ Manual iOS: forward to `SagepilotPushRuntime.willPresent(...completion:)` and `didRespond(...)`, running your existing handler when false. Or explicitly call `SagepilotPushRuntime.installDelegate()` after setting the host delegate. Forward actual background callbacks to `receive:foreground:`. Only configured signed brand envelopes are claimed.
46
+
47
+ ## iOS images
48
+
49
+ Add a Notification Service Extension using the reusable source and installed CocoaPods tooling:
50
+
51
+ ```sh
52
+ ruby node_modules/@sagepilot-ai/react-native-push-addon/plugin/install-ios-extension.rb ios/YourApp.xcodeproj
53
+ pod install --project-directory=ios
54
+ ```
55
+
56
+ The idempotent script adds/embeds `SagepilotPushImages`, copies source and carries host version/team settings. Run again after clean prebuild/package upgrades. Sign both targets, enable host Push Notifications, and configure the correct Firebase Apple app/APNs key. No App Group is needed: the extension modifies images only. If you already have an extension, reuse the source there instead of adding a second one.
57
+
58
+ ## Display and payloads
59
+
60
+ | State/payload | Display owner |
61
+ |---|---|
62
+ | Android background alert + data | FCM/OS |
63
+ | Android background data-only | Native add-on |
64
+ | Android foreground | Native add-on, once per delivery |
65
+ | iOS background alert, either mode | APNs/OS with image extension |
66
+ | iOS foreground, either mode | Add-on requests OS presentation |
67
+
68
+ Server fields: `title`, `body`, `image_url`, `deep_link`. Android SDK mode puts content in `data` and omits FCM `notification` and Android notification overrides. Preserve signed `sp_workspace_id`, `sp_channel_id`, `sp_message_id`, `sp_endpoint_id`, `sp_event_token`. iOS images require alert + `aps.mutable-content=1` + `image_url` or Firebase `fcm_options.image`. Use `aps.category=sagepilot` for supported iOS dismissals.
69
+
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
+
72
+ 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
+
74
+ ## Analytics
75
+
76
+ App-private native storage holds **200 observations for seven days**, stable IDs and capture-time SDK version compiled from the installed base package. Rebuild native targets when changing the base SDK version; retained events keep their original version. At capacity it retains existing events, increments a local overflow counter and returns false for new captures; notification display continues. Expiry/overflow means incomplete analytics. No session credential is stored here. Server canonical deduplication supplements bounded local deduplication.
77
+
78
+ The add-on uploads through the shared transport immediately/on callbacks and every 30 seconds while JS runs. Network/service/auth failures retain events; server acceptance or terminal payload errors acknowledge them. Killed-process observations upload on next JS startup. There is no second auth flow or native networking worker. Old base SDK outbox entries retain their legacy drain for upgrade compatibility; all new add-on events live here.
79
+
80
+ Allowlist destinations and confirm navigation only when the intended screen loads:
81
+
82
+ ```ts
83
+ await SagepilotChat.push.track('destination_opened', message);
84
+ await SagepilotChat.push.track('destination_failed', message, { reason: 'unsupported_destination' });
85
+ ```
86
+
87
+ A tap does not prove destination success or reading. Navigation is claimed once locally; process death between claim and host routing can leave destination outcome unknown. iOS background alerts may not invoke app receipt callbacks. Android force-stop/OEM restrictions and iOS delivery policy still apply.
88
+
89
+ References: [FCM Android](https://firebase.google.com/docs/cloud-messaging/android/receive-messages), [Apple extensions](https://developer.apple.com/documentation/usernotifications/modifying-content-in-newly-delivered-notifications), [RNFirebase](https://rnfirebase.io/messaging/usage).
90
+
91
+ ## Anonymous customers and webhook parity
92
+
93
+ Enable `anonymous_push_enabled` in the channel before issuing a guest proof. Reuse the same external ID as webhook `client_customer_id`; `customers.external_id` is the canonical selector, with a compatible existing endpoint external identity as the legacy bridge. The SDK adopts a matching FCM endpoint without changing its ID. Tokens are delivery addresses, never authentication proof. Conflicting owners fail closed.
94
+
95
+ For shared chat, first identify with that same external ID and then authorize push; the proof must resolve to the current chat customer. Push-only apps use `SagepilotBrandPush.start()` and `identify(proof)`. Do not run both clients on one installation. Marketing consent remains opt-in.
96
+
97
+ Channel settings also control `display_mode` (`installation`, `provider`, `sdk`) and `media_enabled`. Missing settings preserve legacy delivery; anonymous SDK registration requires explicit opt-in. An explicit anonymous block applies to future webhook and SDK sends. Prefer images under 1 MB for provider compatibility; the native helper retains its own bounded download/decoding limits.
@@ -0,0 +1,18 @@
1
+ require 'json'
2
+ package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
3
+ sdk_version = JSON.parse(File.read(File.join(__dir__, '../react-native-sdk/package.json')))['version']
4
+ Pod::Spec.new do |s|
5
+ s.name = 'SagepilotPushAddon'
6
+ s.version = package['version']
7
+ s.summary = package['description']
8
+ s.homepage = 'https://github.com/sage-pilot/sage-sdk'
9
+ s.license = 'MIT'
10
+ s.author = 'Sagepilot'
11
+ s.source = { :git => 'https://github.com/sage-pilot/sage-sdk.git', :tag => s.version.to_s }
12
+ s.platform = :ios, '15.1'
13
+ s.source_files = 'ios/SagepilotPush*.{h,m}'
14
+ s.exclude_files = 'ios/SagepilotPushImageService.*'
15
+ s.frameworks = 'UserNotifications', 'UIKit', 'ImageIO'
16
+ s.dependency 'React-Core'
17
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'GCC_PREPROCESSOR_DEFINITIONS' => "$(inherited) SAGEPILOT_CAPTURE_SDK_VERSION=\\\"#{sdk_version}\\\"" }
18
+ end
@@ -0,0 +1,16 @@
1
+ apply plugin: 'com.android.library'
2
+ def captureSdkVersion = new groovy.json.JsonSlurper().parse(new File(projectDir, '../../react-native-sdk/package.json')).version
3
+ android {
4
+ namespace 'ai.sagepilot.push'
5
+ compileSdkVersion rootProject.ext.has('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 35
6
+ defaultConfig {
7
+ minSdkVersion 24
8
+ buildConfigField 'String', 'SAGEPILOT_SDK_VERSION', '"' + captureSdkVersion + '"'
9
+ }
10
+ buildFeatures { buildConfig true }
11
+ compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
12
+ }
13
+ dependencies {
14
+ implementation 'com.facebook.react:react-android'
15
+ implementation 'androidx.core:core:1.13.1'
16
+ }
@@ -0,0 +1,6 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
3
+ <application>
4
+ <receiver android:name="ai.sagepilot.push.SagepilotPushDismissReceiver" android:exported="false" />
5
+ </application>
6
+ </manifest>
@@ -0,0 +1,10 @@
1
+ package ai.sagepilot.push;
2
+ import android.content.*;
3
+ /** Receives only the private PendingIntent created by SDK presentation. */
4
+ public final class SagepilotPushDismissReceiver extends BroadcastReceiver {
5
+ /** Durably records a real dismissal callback. */
6
+ @Override public void onReceive(Context context, Intent intent) {
7
+ try { SagepilotPushRuntime.consumed(context,SagepilotPushRuntime.message(intent.getExtras()),"dismissed"); }
8
+ catch(Exception e) { android.util.Log.w("SagepilotPush","Native dismissal capture failed"); }
9
+ }
10
+ }
@@ -0,0 +1,49 @@
1
+ package ai.sagepilot.push;
2
+ import android.app.Activity;
3
+ import android.content.pm.PackageManager;
4
+ import android.os.Build;
5
+ import androidx.core.app.NotificationManagerCompat;
6
+ import com.facebook.react.bridge.*;
7
+ import com.facebook.react.modules.core.*;
8
+ import org.json.*;
9
+ import java.util.concurrent.*;
10
+ import java.util.*;
11
+ /** Exposes native buffering and presentation without an API client or customer credential. */
12
+ public final class SagepilotPushModule extends ReactContextBaseJavaModule {
13
+ private final ExecutorService executor=Executors.newSingleThreadExecutor();
14
+ /** Registers a lightweight pending-events signal; storage is the source of truth. */
15
+ public SagepilotPushModule(ReactApplicationContext c){super(c);SagepilotPushRuntime.changed=()->{if(c.hasActiveReactInstance())c.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("SagepilotPushPending",null);};}
16
+ /** Returns the autolinked module name. */
17
+ @Override public String getName(){return "SagepilotPushAddon";}
18
+ /** Releases callback references when the React bridge is destroyed. */
19
+ @Override public void invalidate(){SagepilotPushRuntime.changed=null;executor.shutdown();super.invalidate();}
20
+ /** NativeEventEmitter compatibility. */
21
+ @ReactMethod public void addListener(String event){}
22
+ /** NativeEventEmitter compatibility. */
23
+ @ReactMethod public void removeListeners(double count){}
24
+ /** Persists brand ownership before callbacks may be claimed. */
25
+ @ReactMethod public void configure(ReadableMap config,Promise promise){try{SagepilotPushRuntime.configure(getReactApplicationContext(),new JSONObject(config.toHashMap()));promise.resolve(null);}catch(Exception e){promise.reject("push_storage","Push setup failed",e);}}
26
+ /** Returns bounded observations without deleting them. */
27
+ @ReactMethod public void pending(Promise promise){try{JSONArray events=SagepilotPushRuntime.pending(getReactApplicationContext());WritableArray result=Arguments.createArray();for(int i=0;i<events.length();i++)result.pushMap(Arguments.makeNativeMap(map(events.getJSONObject(i))));promise.resolve(result);}catch(Exception e){promise.reject("push_storage","Push buffer read failed",e);}}
28
+ /** Converts the JSON message/event objects to React bridge values. */
29
+ private Map<String,Object> map(JSONObject object)throws Exception{Map<String,Object> result=new HashMap<>();Iterator<String> keys=object.keys();while(keys.hasNext()){String key=keys.next();result.put(key,value(object.get(key)));}return result;}
30
+ /** Converts nested metadata arrays as well as objects for React Native. */
31
+ private Object value(Object value)throws Exception{if(value==JSONObject.NULL)return null;if(value instanceof JSONObject)return map((JSONObject)value);if(value instanceof JSONArray){List<Object> list=new ArrayList<>();JSONArray array=(JSONArray)value;for(int i=0;i<array.length();i++)list.add(value(array.get(i)));return list;}return value;}
32
+ /** Commits acknowledgment only after JS confirms durable handoff. */
33
+ @ReactMethod public void acknowledge(String id,Promise promise){try{SagepilotPushRuntime.acknowledge(getReactApplicationContext(),id);promise.resolve(null);}catch(Exception e){promise.reject("push_storage","Push acknowledgment failed",e);}}
34
+ /** Persists navigation ownership independently of network upload. */
35
+ @ReactMethod public void claimOpen(String id,Promise promise){try{promise.resolve(SagepilotPushRuntime.claimOpen(getReactApplicationContext(),id));}catch(Exception e){promise.reject("push_storage","Push routing claim failed",e);}}
36
+ /** Captures host-confirmed analytics through the same native durable store. */
37
+ @ReactMethod public void capture(String type,ReadableMap message,ReadableMap metadata,Promise promise){try{promise.resolve(SagepilotPushRuntime.record(getReactApplicationContext(),type,new JSONObject(message.toHashMap()),true,new JSONObject(metadata.toHashMap())));}catch(Exception e){promise.reject("push_storage","Push capture failed",e);}}
38
+ /** Runs image downloads away from the JS and UI threads. */
39
+ @ReactMethod public void receive(ReadableMap message,boolean foreground,Promise promise){JSONObject json=new JSONObject(message.toHashMap());executor.execute(()->{try{promise.resolve(SagepilotPushRuntime.receive(getReactApplicationContext(),json,foreground));}catch(Exception e){promise.reject("push_receive","Push receive failed",e);}});}
40
+ /** Accepts explicit provider tap forwarding without duplicate display. */
41
+ @ReactMethod public void opened(ReadableMap message,Promise promise){try{promise.resolve(SagepilotPushRuntime.consumed(getReactApplicationContext(),new JSONObject(message.toHashMap()),"opened"));}catch(Exception e){promise.reject("push_open","Push open failed",e);}}
42
+ /** Checks the system permission and requests it only on explicit user action. */
43
+ @ReactMethod public void permission(boolean request,Promise promise){
44
+ if(Build.VERSION.SDK_INT<33||getReactApplicationContext().checkSelfPermission("android.permission.POST_NOTIFICATIONS")==PackageManager.PERMISSION_GRANTED){promise.resolve(NotificationManagerCompat.from(getReactApplicationContext()).areNotificationsEnabled()?"authorized":"denied");return;}
45
+ Activity activity=getCurrentActivity();if(!request){promise.resolve("denied");return;}
46
+ if(!(activity instanceof PermissionAwareActivity)){promise.reject("push_permission","An active Activity is required");return;}
47
+ 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
+ }
49
+ }
@@ -0,0 +1,12 @@
1
+ package ai.sagepilot.push;
2
+ import com.facebook.react.*;
3
+ import com.facebook.react.bridge.*;
4
+ import com.facebook.react.uimanager.ViewManager;
5
+ import java.util.*;
6
+ /** Autolinks only the optional push native module. */
7
+ public final class SagepilotPushPackage implements ReactPackage {
8
+ /** Creates the native bridge. */
9
+ @Override public List<NativeModule> createNativeModules(ReactApplicationContext c){return Collections.singletonList(new SagepilotPushModule(c));}
10
+ /** Push uses system notifications rather than React views. */
11
+ @Override public List<ViewManager> createViewManagers(ReactApplicationContext c){return Collections.emptyList();}
12
+ }
@@ -0,0 +1,174 @@
1
+ package ai.sagepilot.push;
2
+
3
+ import android.app.*;
4
+ import android.content.*;
5
+ import android.graphics.*;
6
+ import android.net.Uri;
7
+ import android.os.Bundle;
8
+ import androidx.core.app.NotificationCompat;
9
+ import androidx.core.app.NotificationManagerCompat;
10
+ import org.json.*;
11
+ import java.io.*;
12
+ import java.net.*;
13
+ import java.nio.charset.StandardCharsets;
14
+ import java.text.SimpleDateFormat;
15
+ import java.util.*;
16
+
17
+ /** Native presentation and bounded durable observations; never stores customer session credentials. */
18
+ public final class SagepilotPushRuntime {
19
+ static Runnable changed;
20
+ private static final String STORE = "sagepilot_push_native";
21
+ private static final long AGE = 7L * 86400000;
22
+ private static final int LIMIT = 200;
23
+
24
+ /** Opens app-private state shared by the receiver and React bridge. */
25
+ static android.content.SharedPreferences prefs(Context c) { return c.getSharedPreferences(STORE, Context.MODE_PRIVATE); }
26
+ /** Reads a persisted JSON object, failing visibly instead of discarding events. */
27
+ static JSONObject read(Context c, String key) throws JSONException { return new JSONObject(prefs(c).getString(key, "{}")); }
28
+ /** Commits storage before acknowledging a callback. */
29
+ static void save(Context c, String key, JSONObject data) {
30
+ if (!prefs(c).edit().putString(key, data.toString()).commit()) throw new IllegalStateException("Push storage failed");
31
+ }
32
+ /** Configures explicit ownership without touching another notification handler. */
33
+ static synchronized void configure(Context c, JSONObject config) throws Exception {
34
+ save(c, "config", config);
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));
37
+ }
38
+ /** Recognizes only the configured brand's complete signed tracking envelope. */
39
+ static boolean owns(Context c, JSONObject message) throws Exception {
40
+ JSONObject data = message.optJSONObject("data"), cfg = read(c, "config");
41
+ JSONObject owner = cfg.optJSONObject("owner");
42
+ return data != null && owner != null && !owner.optString("customerId").isEmpty() && owner.optString("endpointId").equals(data.optString("sp_endpoint_id"))
43
+ && !cfg.optString("workspaceId").isEmpty() && cfg.optString("workspaceId").equals(data.optString("sp_workspace_id"))
44
+ && cfg.optString("channelId").equals(data.optString("sp_channel_id")) && !data.optString("sp_event_token").isEmpty()
45
+ && !data.optString("sp_message_id").isEmpty() && !data.optString("sp_endpoint_id").isEmpty();
46
+ }
47
+ /** Canonicalizes a delivery identity without trusting an arbitrary URI from the payload. */
48
+ static String key(JSONObject message) throws Exception {
49
+ JSONObject d = message.getJSONObject("data");
50
+ return d.optString("sp_workspace_id")+":"+d.optString("sp_channel_id")+":"+d.optString("sp_message_id")+":"+d.optString("sp_endpoint_id");
51
+ }
52
+ /** Prunes expired entries and bounds retained callback identities. */
53
+ static void prune(JSONObject values, int limit) throws Exception {
54
+ List<String> keys = new ArrayList<>(); values.keys().forEachRemaining(keys::add);
55
+ keys.sort(Comparator.comparingLong(k -> values.optJSONObject(k) == null ? values.optLong(k) : values.optJSONObject(k).optLong("stored_at")));
56
+ for (String k : keys) {
57
+ long at = values.optJSONObject(k) == null ? values.optLong(k) : values.optJSONObject(k).optLong("stored_at");
58
+ if (at < System.currentTimeMillis()-AGE || values.length()>limit) values.remove(k);
59
+ }
60
+ }
61
+ /** Persists capture-time facts with stable IDs before JavaScript exists. */
62
+ static synchronized boolean record(Context c, String type, JSONObject message, boolean foreground) throws Exception {
63
+ return record(c,type,message,foreground,new JSONObject());
64
+ }
65
+ /** Adds host-confirmed outcomes while preserving native capture identity. */
66
+ static synchronized boolean record(Context c, String type, JSONObject message, boolean foreground, JSONObject details) throws Exception {
67
+ if (!owns(c,message)) return false;
68
+ JSONObject events=read(c,"events"), recent=read(c,"recent"); prune(events,LIMIT); prune(recent,LIMIT);
69
+ String action=(type.equals("action")||type.equals("conversion"))?details.optString("action_id"):"";
70
+ String id=UUID.nameUUIDFromBytes((key(message)+":"+type+":"+action).getBytes(StandardCharsets.UTF_8)).toString();
71
+ if (events.has(id)||recent.has(id)) return true;
72
+ if(events.length()>=LIMIT) { prefs(c).edit().putInt("overflow",prefs(c).getInt("overflow",0)+1).commit(); return false; }
73
+ SimpleDateFormat date=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.US); date.setTimeZone(TimeZone.getTimeZone("UTC"));
74
+ JSONObject metadata=new JSONObject().put("platform","android").put("app_id",c.getPackageName()).put("app_state",foreground?"active":"background")
75
+ .put("app_version",c.getPackageManager().getPackageInfo(c.getPackageName(),0).versionName);
76
+ Iterator<String> fields=details.keys();while(fields.hasNext()){String field=fields.next();metadata.put(field,details.get(field));}
77
+ metadata.put("owner_customer_id",read(c,"config").getJSONObject("owner").getString("customerId"));
78
+ JSONObject event=new JSONObject().put("event_id",id).put("occurred_at",date.format(new Date())).put("sdk_version",BuildConfig.SAGEPILOT_SDK_VERSION)
79
+ .put("event_type",type).put("message",message).put("metadata",metadata).put("stored_at",System.currentTimeMillis());
80
+ if(event.toString().getBytes(StandardCharsets.UTF_8).length>32768)throw new IllegalArgumentException("Push observation exceeds 32 KiB");
81
+ events.put(id,event); save(c,"events",events); if(changed!=null) changed.run(); return true;
82
+ }
83
+ /** Returns snapshots for durable base-SDK handoff. */
84
+ static synchronized JSONArray pending(Context c) throws Exception {
85
+ JSONObject events=read(c,"events"); prune(events,LIMIT); save(c,"events",events);
86
+ JSONArray result=new JSONArray(); Iterator<String> keys=events.keys(); while(keys.hasNext()) result.put(events.getJSONObject(keys.next())); return result;
87
+ }
88
+ /** Removes only an event that the base SDK has acknowledged. */
89
+ static synchronized void acknowledge(Context c,String id) throws Exception {
90
+ JSONObject events=read(c,"events"), recent=read(c,"recent");
91
+ if(events.has(id)){recent.put(id,System.currentTimeMillis());prune(recent,LIMIT);save(c,"recent",recent);events.remove(id);save(c,"events",events);}
92
+ }
93
+ /** Claims navigation once while retaining the event until its analytics upload succeeds. */
94
+ static synchronized boolean claimOpen(Context c,String id)throws Exception{
95
+ JSONObject events=read(c,"events"),event=events.optJSONObject(id);if(event==null||event.optBoolean("routed"))return false;
96
+ event.put("routed",true);save(c,"events",events);return true;
97
+ }
98
+ /** Converts FCM extras without importing Firebase or installing another transport service. */
99
+ static JSONObject message(Bundle extras) throws Exception {
100
+ if(extras==null) return new JSONObject();
101
+ String wrapped=extras.getString("sagepilot_message"); if(wrapped!=null)return new JSONObject(wrapped);
102
+ JSONObject data=new JSONObject(),notification=new JSONObject();
103
+ for(String k:extras.keySet()) { Object v=extras.get(k); if(v instanceof String)data.put(k,v); }
104
+ for(String name:new String[]{"title","body","image"}) {
105
+ String value=extras.getString("gcm.n."+name); if(value==null)value=extras.getString("gcm.notification."+name);
106
+ if(value!=null)notification.put(name.equals("image")?"imageUrl":name,value);
107
+ }
108
+ return new JSONObject().put("data",data).put("notification",notification);
109
+ }
110
+ /** Receives an explicitly forwarded native callback; only signed brand envelopes are claimed. */
111
+ public static boolean receive(Context c, Bundle extras, boolean foreground) {
112
+ try{return receive(c,message(extras),foreground);}catch(Exception e){android.util.Log.w("SagepilotPush","Native receipt failed");return false;}
113
+ }
114
+ /** Records receipt and uses a single display owner for the current payload/app state. */
115
+ static boolean receive(Context c, JSONObject m, boolean foreground) throws Exception {
116
+ if(!owns(c,m))return false;
117
+ record(c,"received",m,foreground);
118
+ JSONObject n=m.optJSONObject("notification"),d=m.getJSONObject("data");
119
+ boolean providerAlert=(n!=null&&n.length()>0)||"1".equals(d.optString("gcm.n.e"))||"1".equals(d.optString("gcm.notification.e"));
120
+ if(!foreground&&providerAlert)return true; // FCM alone displays background alert payloads.
121
+ String delivery=key(m), tag=d.optString("sp_delivery_id",key(m));
122
+ synchronized(SagepilotPushRuntime.class){JSONObject displayed=read(c,"displayed");prune(displayed,LIMIT);if(displayed.has(delivery))return true;
123
+ displayed.put(delivery,System.currentTimeMillis());save(c,"displayed",displayed);}
124
+ try {
125
+ if(foreground)record(c,"presentation_requested",m,true);
126
+ if(!NotificationManagerCompat.from(c).areNotificationsEnabled())throw new IllegalStateException("Permission denied");
127
+ NotificationCompat.Builder builder=builder(c,m);
128
+ NotificationManagerCompat.from(c).notify(tag,0,builder.build());
129
+ String image=n==null?"":n.optString("imageUrl");if(image.isEmpty())image=d.optString("image_url");
130
+ if(!image.isEmpty()){
131
+ Bitmap bitmap=download(image);
132
+ if(bitmap!=null&&!read(c,"consumed").has(delivery))NotificationManagerCompat.from(c).notify(tag,0,builder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap)).build());
133
+ }
134
+ }catch(Exception e){record(c,"presentation_failed",m,foreground);}
135
+ return true;
136
+ }
137
+ /** Builds an app-launch PendingIntent, avoiding notification trampolines and arbitrary destinations. */
138
+ private static NotificationCompat.Builder builder(Context c,JSONObject m)throws Exception{
139
+ JSONObject d=m.getJSONObject("data"),n=m.optJSONObject("notification");String delivery=key(m);
140
+ Intent launch=c.getPackageManager().getLaunchIntentForPackage(c.getPackageName());if(launch==null)throw new IllegalStateException("No launcher");
141
+ launch.setData(Uri.parse("sagepilot-push://open/"+UUID.nameUUIDFromBytes(delivery.getBytes(StandardCharsets.UTF_8))));launch.putExtra("sagepilot_message",m.toString());
142
+ launch.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
143
+ Intent dismiss=new Intent(c,SagepilotPushDismissReceiver.class).setData(launch.getData()).putExtra("sagepilot_message",m.toString());
144
+ int flags=PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE;
145
+ return new NotificationCompat.Builder(c,"sagepilot").setSmallIcon(R.drawable.sagepilot_push_notification)
146
+ .setContentTitle(n==null?d.optString("title"):n.optString("title",d.optString("title")))
147
+ .setContentText(n==null?d.optString("body"):n.optString("body",d.optString("body")))
148
+ .setAutoCancel(true).setOnlyAlertOnce(true).setContentIntent(PendingIntent.getActivity(c,delivery.hashCode(),launch,flags))
149
+ .setDeleteIntent(PendingIntent.getBroadcast(c,delivery.hashCode(),dismiss,flags));
150
+ }
151
+ /** Downloads only public HTTPS images with a three-second/5-MiB/16-megapixel ceiling and no redirects. */
152
+ static Bitmap download(String value){
153
+ try{
154
+ URL url=new URL(value);if(!url.getProtocol().equals("https")||url.getUserInfo()!=null)return null;
155
+ for(InetAddress address:InetAddress.getAllByName(url.getHost()))if(address.isAnyLocalAddress()||address.isLoopbackAddress()||address.isLinkLocalAddress()||address.isSiteLocalAddress()||((address.getAddress()[0]&0xfe)==0xfc))return null;
156
+ HttpURLConnection connection=(HttpURLConnection)url.openConnection();connection.setInstanceFollowRedirects(false);connection.setConnectTimeout(1500);connection.setReadTimeout(1500);
157
+ try{if(connection.getResponseCode()!=200||connection.getContentLengthLong()>5*1024*1024)return null;
158
+ String type=connection.getContentType();if(type==null||!(type.startsWith("image/jpeg")||type.startsWith("image/png")))return null;
159
+ ByteArrayOutputStream bytes=new ByteArrayOutputStream();byte[] buffer=new byte[8192];long deadline=System.currentTimeMillis()+3000;
160
+ try(InputStream input=connection.getInputStream()){int n;while((n=input.read(buffer))!=-1){if(bytes.size()+n>5*1024*1024||System.currentTimeMillis()>deadline)return null;bytes.write(buffer,0,n);}}
161
+ byte[] data=bytes.toByteArray();BitmapFactory.Options bounds=new BitmapFactory.Options();bounds.inJustDecodeBounds=true;BitmapFactory.decodeByteArray(data,0,data.length,bounds);
162
+ if(bounds.outWidth<=0||bounds.outHeight<=0||(long)bounds.outWidth*bounds.outHeight>16000000)return null;
163
+ return BitmapFactory.decodeByteArray(data,0,data.length);
164
+ }finally{connection.disconnect();}
165
+ }catch(Exception e){return null;}
166
+ }
167
+ /** Records actual taps/dismissals and prevents a late image update from resurrecting the notification. */
168
+ static synchronized boolean consumed(Context c,JSONObject m,String type)throws Exception{
169
+ if(!owns(c,m))return false;JSONObject consumed=read(c,"consumed");consumed.put(key(m),System.currentTimeMillis());prune(consumed,LIMIT);save(c,"consumed",consumed);
170
+ return record(c,type,m,type.equals("opened"));
171
+ }
172
+ /** Host Activity forwards both cold-start and onNewIntent payloads here. */
173
+ public static void opened(Context c,Intent intent){try{if(intent!=null)consumed(c,message(intent.getExtras()),"opened");}catch(Exception e){android.util.Log.w("SagepilotPush","Native open capture failed");}}
174
+ }
@@ -0,0 +1,3 @@
1
+ <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
2
+ <path android:fillColor="#FFFFFFFF" android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.9,2 2,2zM18,16v-5c0,-3.1 -1.6,-5.6 -4.5,-6.3V4c0,-0.8 -0.7,-1.5 -1.5,-1.5S10.5,3.2 10.5,4v0.7C7.6,5.4 6,7.9 6,11v5l-2,2v1h16v-1z" />
3
+ </vector>
package/app.plugin.js ADDED
@@ -0,0 +1,55 @@
1
+ const { withAndroidManifest, withMainActivity, withDangerousMod, withAppDelegate, createRunOncePlugin } = require('expo/config-plugins');
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ /** Explicit RNFirebase integration; fail on unsupported host code instead of silently dropping callbacks. */
5
+ function withSagepilotPush(config, { firebaseForwarding = false } = {}) {
6
+ if (!firebaseForwarding) return config;
7
+ config = withAndroidManifest(config, mod => {
8
+ const manifest=mod.modResults.manifest;
9
+ manifest.$['xmlns:tools']='http://schemas.android.com/tools';
10
+ const app=manifest.application[0];
11
+ app.receiver=(app.receiver||[]).filter(r=>!['io.invertase.firebase.messaging.ReactNativeFirebaseMessagingReceiver','ai.sagepilot.hostpush.SagepilotMessagingReceiver'].includes(r.$['android:name']));
12
+ app.receiver.push({$:{'android:name':'io.invertase.firebase.messaging.ReactNativeFirebaseMessagingReceiver','tools:node':'remove'}},
13
+ {$:{'android:name':'ai.sagepilot.hostpush.SagepilotMessagingReceiver','android:exported':'true','android:permission':'com.google.android.c2dm.permission.SEND'},
14
+ 'intent-filter':[{'action':[{$:{'android:name':'com.google.android.c2dm.intent.RECEIVE'}}]}]});
15
+ return mod;
16
+ });
17
+ config = withDangerousMod(config,['android', async mod => {
18
+ const target=path.join(mod.modRequest.platformProjectRoot,'app/src/main/java/ai/sagepilot/hostpush');
19
+ fs.mkdirSync(target,{recursive:true});fs.copyFileSync(path.join(__dirname,'plugin/SagepilotMessagingReceiver.java'),path.join(target,'SagepilotMessagingReceiver.java'));return mod;
20
+ }]);
21
+ config = withMainActivity(config, mod => {
22
+ if(mod.modResults.language!=='kt')throw new Error('Sagepilot push: forward MainActivity callbacks manually for Java hosts.');
23
+ let text=mod.modResults.contents;
24
+ if(!text.includes('SagepilotPushRuntime.opened(this, intent)')) {
25
+ if(!text.includes('super.onCreate(null)'))throw new Error('Sagepilot push: forward onCreate manually for this Activity.');
26
+ text=text.replace('super.onCreate(null)','super.onCreate(null)\n ai.sagepilot.push.SagepilotPushRuntime.opened(this, intent)');
27
+ }
28
+ const warmHandler=text.match(/override fun onNewIntent\([^]*?\n \}/)?.[0];
29
+ if(warmHandler && !warmHandler.includes('SagepilotPushRuntime.opened(this, intent)'))
30
+ throw new Error('Sagepilot push: add forwarding to the existing onNewIntent manually.');
31
+ if(!warmHandler) {
32
+ const activity='class MainActivity : ReactActivity() {';
33
+ if(!text.includes(activity))throw new Error('Sagepilot push: forward onNewIntent manually for this Activity.');
34
+ text=text.replace(activity,`class MainActivity : ReactActivity() {
35
+ /** Captures real warm-start taps before JavaScript routing. */
36
+ override fun onNewIntent(intent: android.content.Intent) {
37
+ super.onNewIntent(intent)
38
+ ai.sagepilot.push.SagepilotPushRuntime.opened(this, intent)
39
+ }`);
40
+ }
41
+ mod.modResults.contents=text;return mod;
42
+ });
43
+ return withAppDelegate(config, mod => {
44
+ let text=mod.modResults.contents;
45
+ if(mod.modResults.language!=='swift')throw new Error('Sagepilot push: install the iOS delegate manually for Objective-C hosts.');
46
+ if(!text.includes('SagepilotPushRuntime.installDelegate()')) {
47
+ const anchor='return super.application(application, didFinishLaunchingWithOptions: launchOptions)';
48
+ if(!text.includes(anchor))throw new Error('Sagepilot push: install the delegate after host startup manually.');
49
+ text='import SagepilotPushAddon\n'+text;
50
+ text=text.replace(anchor,'let launched = super.application(application, didFinishLaunchingWithOptions: launchOptions)\n SagepilotPushRuntime.installDelegate()\n return launched');
51
+ }
52
+ mod.modResults.contents=text;return mod;
53
+ });
54
+ }
55
+ module.exports=createRunOncePlugin(withSagepilotPush,'@sagepilot-ai/react-native-push-addon','0.1.0');
@@ -0,0 +1,26 @@
1
+ import { SagepilotPushAdapter, SagepilotPushObservation, SagepilotPushMessage } from '@sagepilot-ai/react-native-sdk';
2
+
3
+ type NativePush = {
4
+ configure(options: Record<string, unknown>): Promise<void>;
5
+ pending(): Promise<SagepilotPushObservation[]>;
6
+ acknowledge(id: string): Promise<void>;
7
+ claimOpen(id: string): Promise<boolean>;
8
+ capture(type: string, message: SagepilotPushMessage, metadata: Record<string, unknown>): Promise<boolean>;
9
+ receive(message: SagepilotPushMessage, foreground: boolean): Promise<boolean>;
10
+ opened(message: SagepilotPushMessage): Promise<boolean>;
11
+ permission(request: boolean): Promise<'authorized' | 'provisional' | 'denied' | 'not_determined'>;
12
+ addListener(event: string): void;
13
+ removeListeners(count: number): void;
14
+ };
15
+ /** Owns native capture, durable buffering and analytics upload through the base SDK's scoped session transport. */
16
+ declare function createSagepilotNativePushAdapter(transport: SagepilotPushAdapter, options: {
17
+ displayMode?: 'provider' | 'sdk';
18
+ channelName?: string;
19
+ onError: (error: unknown) => void;
20
+ }): SagepilotPushAdapter;
21
+ /** Explicitly forwards a host callback; storage and upload remain owned by the add-on. */
22
+ declare function handleSagepilotBackgroundPush(message: SagepilotPushMessage): Promise<boolean>;
23
+ /** Allows a host diagnostics screen to inspect/request permission without another SDK instance. */
24
+ declare function getSagepilotPushPermission(request?: boolean): ReturnType<NativePush['permission']>;
25
+
26
+ export { createSagepilotNativePushAdapter, getSagepilotPushPermission, handleSagepilotBackgroundPush };
@@ -0,0 +1,26 @@
1
+ import { SagepilotPushAdapter, SagepilotPushObservation, SagepilotPushMessage } from '@sagepilot-ai/react-native-sdk';
2
+
3
+ type NativePush = {
4
+ configure(options: Record<string, unknown>): Promise<void>;
5
+ pending(): Promise<SagepilotPushObservation[]>;
6
+ acknowledge(id: string): Promise<void>;
7
+ claimOpen(id: string): Promise<boolean>;
8
+ capture(type: string, message: SagepilotPushMessage, metadata: Record<string, unknown>): Promise<boolean>;
9
+ receive(message: SagepilotPushMessage, foreground: boolean): Promise<boolean>;
10
+ opened(message: SagepilotPushMessage): Promise<boolean>;
11
+ permission(request: boolean): Promise<'authorized' | 'provisional' | 'denied' | 'not_determined'>;
12
+ addListener(event: string): void;
13
+ removeListeners(count: number): void;
14
+ };
15
+ /** Owns native capture, durable buffering and analytics upload through the base SDK's scoped session transport. */
16
+ declare function createSagepilotNativePushAdapter(transport: SagepilotPushAdapter, options: {
17
+ displayMode?: 'provider' | 'sdk';
18
+ channelName?: string;
19
+ onError: (error: unknown) => void;
20
+ }): SagepilotPushAdapter;
21
+ /** Explicitly forwards a host callback; storage and upload remain owned by the add-on. */
22
+ declare function handleSagepilotBackgroundPush(message: SagepilotPushMessage): Promise<boolean>;
23
+ /** Allows a host diagnostics screen to inspect/request permission without another SDK instance. */
24
+ declare function getSagepilotPushPermission(request?: boolean): ReturnType<NativePush['permission']>;
25
+
26
+ export { createSagepilotNativePushAdapter, getSagepilotPushPermission, handleSagepilotBackgroundPush };
package/dist/index.js ADDED
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createSagepilotNativePushAdapter: () => createSagepilotNativePushAdapter,
24
+ getSagepilotPushPermission: () => getSagepilotPushPermission,
25
+ handleSagepilotBackgroundPush: () => handleSagepilotBackgroundPush
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+ var import_react_native = require("react-native");
29
+ var import_react_native_sdk = require("@sagepilot-ai/react-native-sdk");
30
+
31
+ // package.json
32
+ var version = "0.4.0";
33
+
34
+ // src/index.ts
35
+ function native() {
36
+ const module2 = import_react_native.NativeModules.SagepilotPushAddon;
37
+ if (!module2) throw new Error("Install the Sagepilot push add-on and rebuild the native app. Expo Go is not supported.");
38
+ return module2;
39
+ }
40
+ function createSagepilotNativePushAdapter(transport, options) {
41
+ let flush = async () => {
42
+ };
43
+ let setOwner = async () => {
44
+ };
45
+ return {
46
+ ...transport,
47
+ 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
+ getPermission: () => native().permission(false),
49
+ requestPermission: () => native().permission(true),
50
+ onMessage: () => transport.onMessage((message) => {
51
+ void native().receive(message, true).catch(options.onError);
52
+ }),
53
+ onOpened: () => transport.onOpened((message) => {
54
+ void native().opened(message).catch(options.onError);
55
+ }),
56
+ getInitialNotification: async () => {
57
+ const message = await transport.getInitialNotification();
58
+ if (message) await native().opened(message);
59
+ return null;
60
+ },
61
+ track: async (type, message, metadata = {}, actionId) => {
62
+ const accepted = await native().capture(type, message, { ...metadata, ...actionId ? { action_id: actionId } : {} });
63
+ void flush().catch(options.onError);
64
+ return accepted;
65
+ },
66
+ flush: () => flush(),
67
+ setOwner: (owner) => setOwner(owner),
68
+ start: async (context) => {
69
+ const module2 = native();
70
+ let stopped = false, draining = null;
71
+ async function drain() {
72
+ if (draining) return draining;
73
+ draining = (async () => {
74
+ for (const event of await module2.pending()) {
75
+ if (stopped) break;
76
+ const data = event.message.data;
77
+ if (!data || data.sp_workspace_id !== context.workspaceId || data.sp_channel_id !== context.channelId) continue;
78
+ if (event.event_type === "opened" && event.metadata?.owner_customer_id === context.customerId() && context.customerId() && await module2.claimOpen(event.event_id)) {
79
+ try {
80
+ context.onOpen(event.message);
81
+ } catch (error) {
82
+ options.onError(error);
83
+ }
84
+ }
85
+ try {
86
+ await context.upload({
87
+ event_id: event.event_id,
88
+ occurred_at: event.occurred_at,
89
+ sdk_version: event.sdk_version,
90
+ event_type: event.event_type,
91
+ message_id: data.sp_message_id,
92
+ endpoint_id: data.sp_endpoint_id,
93
+ event_token: data.sp_event_token,
94
+ metadata: { ...event.metadata, sdk: "@sagepilot-ai/react-native-sdk", addon_version: version },
95
+ ...typeof event.metadata?.action_id === "string" ? { action_id: event.metadata.action_id } : {}
96
+ });
97
+ } catch (error) {
98
+ const terminal = error instanceof import_react_native_sdk.SagepilotChatError && ([400, 410, 422].includes(error.status ?? 0) || error.status === 401 && error.details?.terminal === true);
99
+ if (!terminal) throw error;
100
+ options.onError(error);
101
+ }
102
+ await module2.acknowledge(event.event_id);
103
+ }
104
+ })().finally(() => {
105
+ draining = null;
106
+ });
107
+ return draining;
108
+ }
109
+ 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
+ });
117
+ const subscription = new import_react_native.NativeEventEmitter(module2).addListener("SagepilotPushPending", () => {
118
+ void drain().catch(options.onError);
119
+ });
120
+ try {
121
+ await setOwner(context.owner);
122
+ } catch (error) {
123
+ subscription.remove();
124
+ throw error;
125
+ }
126
+ void drain().catch(options.onError);
127
+ const retry = setInterval(() => {
128
+ void drain().catch(options.onError);
129
+ }, 3e4);
130
+ return () => {
131
+ stopped = true;
132
+ clearInterval(retry);
133
+ subscription.remove();
134
+ flush = async () => {
135
+ };
136
+ setOwner = async () => {
137
+ };
138
+ };
139
+ }
140
+ };
141
+ }
142
+ function handleSagepilotBackgroundPush(message) {
143
+ return native().receive(message, false);
144
+ }
145
+ function getSagepilotPushPermission(request = false) {
146
+ return native().permission(request);
147
+ }
148
+ // Annotate the CommonJS export names for ESM import in node:
149
+ 0 && (module.exports = {
150
+ createSagepilotNativePushAdapter,
151
+ getSagepilotPushPermission,
152
+ handleSagepilotBackgroundPush
153
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,126 @@
1
+ // src/index.ts
2
+ import { NativeEventEmitter, NativeModules, Platform } from "react-native";
3
+ import { SagepilotChatError } from "@sagepilot-ai/react-native-sdk";
4
+
5
+ // package.json
6
+ var version = "0.4.0";
7
+
8
+ // src/index.ts
9
+ function native() {
10
+ const module = NativeModules.SagepilotPushAddon;
11
+ if (!module) throw new Error("Install the Sagepilot push add-on and rebuild the native app. Expo Go is not supported.");
12
+ return module;
13
+ }
14
+ function createSagepilotNativePushAdapter(transport, options) {
15
+ let flush = async () => {
16
+ };
17
+ let setOwner = async () => {
18
+ };
19
+ return {
20
+ ...transport,
21
+ 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
+ getPermission: () => native().permission(false),
23
+ requestPermission: () => native().permission(true),
24
+ onMessage: () => transport.onMessage((message) => {
25
+ void native().receive(message, true).catch(options.onError);
26
+ }),
27
+ onOpened: () => transport.onOpened((message) => {
28
+ void native().opened(message).catch(options.onError);
29
+ }),
30
+ getInitialNotification: async () => {
31
+ const message = await transport.getInitialNotification();
32
+ if (message) await native().opened(message);
33
+ return null;
34
+ },
35
+ track: async (type, message, metadata = {}, actionId) => {
36
+ const accepted = await native().capture(type, message, { ...metadata, ...actionId ? { action_id: actionId } : {} });
37
+ void flush().catch(options.onError);
38
+ return accepted;
39
+ },
40
+ flush: () => flush(),
41
+ setOwner: (owner) => setOwner(owner),
42
+ start: async (context) => {
43
+ const module = native();
44
+ let stopped = false, draining = null;
45
+ async function drain() {
46
+ if (draining) return draining;
47
+ draining = (async () => {
48
+ for (const event of await module.pending()) {
49
+ if (stopped) break;
50
+ const data = event.message.data;
51
+ if (!data || data.sp_workspace_id !== context.workspaceId || data.sp_channel_id !== context.channelId) continue;
52
+ if (event.event_type === "opened" && event.metadata?.owner_customer_id === context.customerId() && context.customerId() && await module.claimOpen(event.event_id)) {
53
+ try {
54
+ context.onOpen(event.message);
55
+ } catch (error) {
56
+ options.onError(error);
57
+ }
58
+ }
59
+ try {
60
+ await context.upload({
61
+ event_id: event.event_id,
62
+ occurred_at: event.occurred_at,
63
+ sdk_version: event.sdk_version,
64
+ event_type: event.event_type,
65
+ message_id: data.sp_message_id,
66
+ endpoint_id: data.sp_endpoint_id,
67
+ event_token: data.sp_event_token,
68
+ metadata: { ...event.metadata, sdk: "@sagepilot-ai/react-native-sdk", addon_version: version },
69
+ ...typeof event.metadata?.action_id === "string" ? { action_id: event.metadata.action_id } : {}
70
+ });
71
+ } catch (error) {
72
+ const terminal = error instanceof SagepilotChatError && ([400, 410, 422].includes(error.status ?? 0) || error.status === 401 && error.details?.terminal === true);
73
+ if (!terminal) throw error;
74
+ options.onError(error);
75
+ }
76
+ await module.acknowledge(event.event_id);
77
+ }
78
+ })().finally(() => {
79
+ draining = null;
80
+ });
81
+ return draining;
82
+ }
83
+ 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
+ });
91
+ const subscription = new NativeEventEmitter(module).addListener("SagepilotPushPending", () => {
92
+ void drain().catch(options.onError);
93
+ });
94
+ try {
95
+ await setOwner(context.owner);
96
+ } catch (error) {
97
+ subscription.remove();
98
+ throw error;
99
+ }
100
+ void drain().catch(options.onError);
101
+ const retry = setInterval(() => {
102
+ void drain().catch(options.onError);
103
+ }, 3e4);
104
+ return () => {
105
+ stopped = true;
106
+ clearInterval(retry);
107
+ subscription.remove();
108
+ flush = async () => {
109
+ };
110
+ setOwner = async () => {
111
+ };
112
+ };
113
+ }
114
+ };
115
+ }
116
+ function handleSagepilotBackgroundPush(message) {
117
+ return native().receive(message, false);
118
+ }
119
+ function getSagepilotPushPermission(request = false) {
120
+ return native().permission(request);
121
+ }
122
+ export {
123
+ createSagepilotNativePushAdapter,
124
+ getSagepilotPushPermission,
125
+ handleSagepilotBackgroundPush
126
+ };
@@ -0,0 +1,30 @@
1
+ #import "SagepilotPushRuntime.h"
2
+ @interface SagepilotPushDelegate : NSObject <UNUserNotificationCenterDelegate>
3
+ @property(nonatomic,weak) id<UNUserNotificationCenterDelegate> previous;
4
+ @end
5
+ @implementation SagepilotPushDelegate
6
+ /** Handles owned foreground alerts and preserves the host delegate for everything else. */
7
+ - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completion {
8
+ @try{if([SagepilotPushRuntime willPresent:notification completion:completion])return;}@catch(NSException *e){}
9
+ if([self.previous respondsToSelector:_cmd])[self.previous userNotificationCenter:center willPresentNotification:notification withCompletionHandler:completion];else completion(UNNotificationPresentationOptionNone);
10
+ }
11
+ /** Captures a tap before JS startup and forwards unrelated notifications unchanged. */
12
+ - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completion {
13
+ @try{if([SagepilotPushRuntime didRespond:response]){completion();return;}}@catch(NSException *e){}
14
+ if([self.previous respondsToSelector:_cmd])[self.previous userNotificationCenter:center didReceiveNotificationResponse:response withCompletionHandler:completion];else completion();
15
+ }
16
+ /** Preserves optional host delegate callbacks that this adapter does not implement. */
17
+ - (BOOL)respondsToSelector:(SEL)selector { return [super respondsToSelector:selector]||[self.previous respondsToSelector:selector]; }
18
+ /** Forwards optional callbacks instead of taking ownership of other host integrations. */
19
+ - (id)forwardingTargetForSelector:(SEL)selector { return [self.previous respondsToSelector:selector]?self.previous:[super forwardingTargetForSelector:selector]; }
20
+ @end
21
+ @implementation SagepilotPushRuntime (Delegate)
22
+ /** Explicit host opt-in; install once after Firebase startup and preserve the existing delegate. */
23
+ + (void)installDelegate {
24
+ static SagepilotPushDelegate *delegate;UNUserNotificationCenter *center=UNUserNotificationCenter.currentNotificationCenter;
25
+ if(center.delegate==delegate && delegate)return;
26
+ if(!delegate)delegate=[SagepilotPushDelegate new];delegate.previous=center.delegate;center.delegate=delegate;
27
+ [center getNotificationCategoriesWithCompletionHandler:^(NSSet<UNNotificationCategory *> *categories){NSMutableSet *all=[categories mutableCopy];
28
+ [all addObject:[UNNotificationCategory categoryWithIdentifier:@"sagepilot" actions:@[] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction]];[center setNotificationCategories:all];}];
29
+ }
30
+ @end
@@ -0,0 +1,4 @@
1
+ #import <UserNotifications/UserNotifications.h>
2
+ /** Subclass from the host Notification Service Extension target; no React/Firebase dependency. */
3
+ @interface SagepilotPushImageService : UNNotificationServiceExtension
4
+ @end
@@ -0,0 +1,66 @@
1
+ #import "SagepilotPushImageService.h"
2
+ #import <ImageIO/ImageIO.h>
3
+ #import <netdb.h>
4
+ #import <arpa/inet.h>
5
+ @interface SagepilotPushImageService () <NSURLSessionDownloadDelegate>
6
+ @property(nonatomic,copy) void (^handler)(UNNotificationContent *);
7
+ @property(nonatomic,strong) UNMutableNotificationContent *content;
8
+ @property(nonatomic,strong) NSURLSession *session;
9
+ @end
10
+ @implementation SagepilotPushImageService
11
+ /** Delivers the text fallback once, including on extension time expiration. */
12
+ - (void)finish { @synchronized(self) { if(self.handler){void (^handler)(UNNotificationContent *)=self.handler;self.handler=nil;handler(self.content);}[self.session invalidateAndCancel];self.session=nil; } }
13
+ /** Rejects local addresses and requires HTTPS before downloading optional media. */
14
+ - (BOOL)publicURL:(NSURL *)url {
15
+ if(![url.scheme.lowercaseString isEqual:@"https"]||!url.host.length||url.user||url.password)return NO;
16
+ struct addrinfo hints={0},*addresses=NULL;hints.ai_socktype=SOCK_STREAM;
17
+ if(getaddrinfo(url.host.UTF8String,NULL,&hints,&addresses)!=0)return NO;
18
+ BOOL allowed=YES;
19
+ for(struct addrinfo *a=addresses;a;a=a->ai_next){
20
+ if(a->ai_family==AF_INET){uint32_t ip=ntohl(((struct sockaddr_in *)a->ai_addr)->sin_addr.s_addr);
21
+ if((ip>>24)==0||(ip>>24)==10||(ip>>24)==127||(ip>>16)==0xa9fe||(ip>>20)==0xac1||(ip>>16)==0xc0a8||(ip>>28)>=14)allowed=NO;
22
+ }else if(a->ai_family==AF_INET6){struct in6_addr ip=((struct sockaddr_in6 *)a->ai_addr)->sin6_addr;
23
+ if(IN6_IS_ADDR_UNSPECIFIED(&ip)||IN6_IS_ADDR_LOOPBACK(&ip)||IN6_IS_ADDR_LINKLOCAL(&ip)||IN6_IS_ADDR_V4MAPPED(&ip)||(ip.s6_addr[0]&0xfe)==0xfc||ip.s6_addr[0]==0xff)allowed=NO;
24
+ }else allowed=NO;
25
+ }freeaddrinfo(addresses);return allowed;
26
+ }
27
+ /** Limits optional image processing to five seconds and always retains the original text. */
28
+ - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *))handler {
29
+ self.handler=handler;self.content=[request.content mutableCopy];
30
+ NSDictionary *info=request.content.userInfo,*data=[info[@"data"] isKindOfClass:NSDictionary.class]?info[@"data"]:info;
31
+ NSDictionary *fcm=[info[@"fcm_options"] isKindOfClass:NSDictionary.class]?info[@"fcm_options"]:@{};
32
+ id value=data[@"image_url"] ?: fcm[@"image"];
33
+ if(![value isKindOfClass:NSString.class]||![data[@"sp_event_token"] isKindOfClass:NSString.class]){[self finish];return;}
34
+ NSURL *url=[NSURL URLWithString:value];
35
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY,0),^{
36
+ if(![self publicURL:url]){[self finish];return;}
37
+ @synchronized(self){if(!self.handler)return;
38
+ NSURLSessionConfiguration *config=NSURLSessionConfiguration.ephemeralSessionConfiguration;config.timeoutIntervalForRequest=3;config.timeoutIntervalForResource=5;
39
+ self.session=[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];[[self.session downloadTaskWithURL:url] resume];}
40
+ });
41
+ }
42
+ /** Rejects redirects so another URL cannot bypass the media validation. */
43
+ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completion { completion(nil); }
44
+ /** Cancels oversized transfers before they consume unbounded disk space. */
45
+ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)task didWriteData:(int64_t)bytes totalBytesWritten:(int64_t)total totalBytesExpectedToWrite:(int64_t)expected { if(total>5*1024*1024||expected>5*1024*1024){[task cancel];[self finish];} }
46
+ /** Attaches a validated static image; invalid media leaves a usable text notification. */
47
+ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)task didFinishDownloadingToURL:(NSURL *)location {
48
+ @synchronized(self){if(!self.handler)return;
49
+ NSHTTPURLResponse *response=(NSHTTPURLResponse *)task.response;
50
+ NSString *mime=response.MIMEType;
51
+ if(response.statusCode!=200||(![mime isEqual:@"image/jpeg"]&&![mime isEqual:@"image/png"]))return;
52
+ NSNumber *size=nil;[location getResourceValue:&size forKey:NSURLFileSizeKey error:nil];if(!size||size.longLongValue>5*1024*1024)return;
53
+ CGImageSourceRef source=CGImageSourceCreateWithURL((__bridge CFURLRef)location,NULL);if(!source)return;
54
+ NSDictionary *props=CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(source,0,NULL));CFRelease(source);
55
+ double w=[props[(__bridge NSString *)kCGImagePropertyPixelWidth] doubleValue],h=[props[(__bridge NSString *)kCGImagePropertyPixelHeight] doubleValue];if(w<=0||h<=0||w*h>16000000)return;
56
+ NSURL *target=[[NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",NSUUID.UUID.UUIDString,[mime isEqual:@"image/png"]?@"png":@"jpg"]];
57
+ if(![NSFileManager.defaultManager moveItemAtURL:location toURL:target error:nil])return;
58
+ UNNotificationAttachment *attachment=[UNNotificationAttachment attachmentWithIdentifier:@"sagepilot-image" URL:target options:nil error:nil];if(attachment)self.content.attachments=@[attachment];
59
+ // Keep the temporary attachment available until the OS consumes the completed content.
60
+ }
61
+ }
62
+ /** Finishes both successful and failed downloads through the same fallback path. */
63
+ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { [self finish]; }
64
+ /** Handles the operating system's final deadline without discarding text. */
65
+ - (void)serviceExtensionTimeWillExpire { [self finish]; }
66
+ @end
@@ -0,0 +1,38 @@
1
+ #import <React/RCTEventEmitter.h>
2
+ #import <React/RCTBridgeModule.h>
3
+ #import "SagepilotPushRuntime.h"
4
+ @interface SagepilotPushAddon : RCTEventEmitter <RCTBridgeModule>
5
+ @end
6
+ @implementation SagepilotPushAddon
7
+ RCT_EXPORT_MODULE();
8
+ /** Native notification APIs are initialized on the main queue. */
9
+ + (BOOL)requiresMainQueueSetup { return YES; }
10
+ /** Delivers pending-buffer signals rather than individual ephemeral events. */
11
+ - (NSArray<NSString *> *)supportedEvents { return @[@"SagepilotPushPending"]; }
12
+ /** Begins observing while the add-on has a JS subscriber. */
13
+ - (void)startObserving { [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(pendingChanged:) name:@"SagepilotPushPending" object:nil]; }
14
+ /** Stops retaining the module after subscriber removal. */
15
+ - (void)stopObserving { [NSNotificationCenter.defaultCenter removeObserver:self]; }
16
+ /** Signals JS to drain durable observations. */
17
+ - (void)pendingChanged:(NSNotification *)note { [self sendEventWithName:@"SagepilotPushPending" body:nil]; }
18
+ /** Configures only local brand ownership and SDK capture version. */
19
+ RCT_REMAP_METHOD(configure, configure:(NSDictionary *)options resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { @try{[SagepilotPushRuntime configure:options];resolve(nil);}@catch(NSException *e){reject(@"push_storage",@"Push setup failed",nil);} }
20
+ /** Reads bounded native analytics. */
21
+ RCT_REMAP_METHOD(pending, pending:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { @try{resolve([SagepilotPushRuntime pending]);}@catch(NSException *e){reject(@"push_storage",@"Push read failed",nil);} }
22
+ /** Removes only server-acknowledged events. */
23
+ RCT_REMAP_METHOD(acknowledge, acknowledge:(NSString *)eventId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { @try{[SagepilotPushRuntime acknowledge:eventId];resolve(nil);}@catch(NSException *e){reject(@"push_storage",@"Push acknowledgment failed",nil);} }
24
+ /** Claims routing once across retries. */
25
+ RCT_REMAP_METHOD(claimOpen, claimOpen:(NSString *)eventId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { @try{resolve(@([SagepilotPushRuntime claimOpen:eventId]));}@catch(NSException *e){reject(@"push_storage",@"Push routing failed",nil);} }
26
+ /** Accepts explicit host-confirmed destination and dismissal observations. */
27
+ RCT_REMAP_METHOD(capture, capture:(NSString *)type message:(NSDictionary *)message metadata:(NSDictionary *)metadata resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { @try{resolve(@([SagepilotPushRuntime capture:type message:message metadata:metadata]));}@catch(NSException *e){reject(@"push_storage",@"Push capture failed",nil);} }
28
+ /** Records an actual provider callback. */
29
+ RCT_REMAP_METHOD(receive, receive:(NSDictionary *)message foreground:(BOOL)foreground resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { @try{resolve(@([SagepilotPushRuntime receive:message foreground:foreground]));}@catch(NSException *e){reject(@"push_storage",@"Push receipt failed",nil);} }
30
+ /** Records an actual tap callback. */
31
+ RCT_REMAP_METHOD(opened, opened:(NSDictionary *)message resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { @try{resolve(@([SagepilotPushRuntime opened:message]));}@catch(NSException *e){reject(@"push_storage",@"Push open failed",nil);} }
32
+ /** Requests permission only following a host action; APNs registration remains host-owned. */
33
+ RCT_REMAP_METHOD(permission, permission:(BOOL)request resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
34
+ UNUserNotificationCenter *center=UNUserNotificationCenter.currentNotificationCenter;
35
+ void (^status)(void)=^{[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings){resolve(settings.authorizationStatus==UNAuthorizationStatusAuthorized?@"authorized":settings.authorizationStatus==UNAuthorizationStatusProvisional?@"provisional":settings.authorizationStatus==UNAuthorizationStatusDenied?@"denied":@"not_determined");}];};
36
+ if(request)[center requestAuthorizationWithOptions:UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge completionHandler:^(BOOL granted,NSError *error){if(error)reject(@"push_permission",@"Permission request failed",error);else status();}];else status();
37
+ }
38
+ @end
@@ -0,0 +1,20 @@
1
+ #import <Foundation/Foundation.h>
2
+ #import <UserNotifications/UserNotifications.h>
3
+ #import <UIKit/UIKit.h>
4
+ /** Explicit native forwarding API; never installs or replaces the host delegate automatically. */
5
+ @interface SagepilotPushRuntime : NSObject
6
+ + (void)configure:(NSDictionary *)config;
7
+ + (BOOL)owns:(NSDictionary *)message;
8
+ + (NSDictionary *)message:(NSDictionary *)userInfo;
9
+ + (BOOL)capture:(NSString *)type message:(NSDictionary *)message metadata:(NSDictionary *)metadata;
10
+ + (NSArray *)pending;
11
+ + (void)acknowledge:(NSString *)eventId;
12
+ + (BOOL)claimOpen:(NSString *)eventId;
13
+ + (BOOL)receive:(NSDictionary *)message foreground:(BOOL)foreground;
14
+ + (BOOL)opened:(NSDictionary *)message;
15
+ + (BOOL)willPresent:(UNNotification *)notification completion:(void (^)(UNNotificationPresentationOptions))completion;
16
+ + (BOOL)didRespond:(UNNotificationResponse *)response;
17
+ @end
18
+ @interface SagepilotPushRuntime (Delegate)
19
+ + (void)installDelegate;
20
+ @end
@@ -0,0 +1,82 @@
1
+ #import "SagepilotPushRuntime.h"
2
+ #import <CommonCrypto/CommonDigest.h>
3
+ #ifndef SAGEPILOT_CAPTURE_SDK_VERSION
4
+ #error "Build with the SagepilotPushAddon podspec to capture the installed base SDK version"
5
+ #endif
6
+
7
+ @implementation SagepilotPushRuntime
8
+ /** Returns an app-private defaults suite; no session token is stored here. */
9
+ + (NSUserDefaults *)store { return [[NSUserDefaults alloc] initWithSuiteName:@"ai.sagepilot.push"]; }
10
+ /** Loads mutable JSON-compatible state. */
11
+ + (NSMutableDictionary *)read:(NSString *)key {
12
+ id stored=[[self store] objectForKey:key];if(!stored)return [NSMutableDictionary new];
13
+ id value=[stored isKindOfClass:NSData.class]?[NSJSONSerialization JSONObjectWithData:stored options:NSJSONReadingMutableContainers error:nil]:stored;
14
+ if(![value isKindOfClass:NSDictionary.class])@throw [NSException exceptionWithName:@"PushStorage" reason:@"Invalid push state" userInfo:nil];
15
+ return [value mutableCopy];
16
+ }
17
+ /** Commits capture state before signaling the React bridge. */
18
+ + (void)save:(NSString *)key value:(NSDictionary *)value { NSData *json=[NSJSONSerialization dataWithJSONObject:value options:0 error:nil];if(!json)@throw [NSException exceptionWithName:@"PushStorage" reason:@"Invalid push JSON" userInfo:nil];NSUserDefaults *s=[self store];[s setObject:json forKey:key];if(![s synchronize])@throw [NSException exceptionWithName:@"PushStorage" reason:@"Push storage failed" userInfo:nil]; }
19
+ /** Configures ownership only through the explicit SDK opt-in. */
20
+ + (void)configure:(NSDictionary *)config { @synchronized(self) { [self save:@"config" value:config]; } }
21
+ /** Accepts nested APNs data and flattened FCM data without changing routing metadata. */
22
+ + (NSDictionary *)message:(NSDictionary *)info {
23
+ if([info[@"data"] isKindOfClass:NSDictionary.class] && [info[@"notification"] isKindOfClass:NSDictionary.class])return info;
24
+ NSDictionary *data=[info[@"data"] isKindOfClass:NSDictionary.class]?info[@"data"]:info;
25
+ NSDictionary *aps=[info[@"aps"] isKindOfClass:NSDictionary.class]?info[@"aps"]:@{};
26
+ id alert=aps[@"alert"];NSDictionary *notification=[alert isKindOfClass:NSDictionary.class]?alert:([alert isKindOfClass:NSString.class]?@{@"body":alert}:@{});
27
+ return @{@"data":data,@"notification":notification};
28
+ }
29
+ /** Claims only the configured workspace/channel's complete signed tracking envelope. */
30
+ + (BOOL)owns:(NSDictionary *)message { NSDictionary *d=message[@"data"],*cfg=[self read:@"config"],*owner=[cfg[@"owner"] isKindOfClass:NSDictionary.class]?cfg[@"owner"]:@{};
31
+ return [d isKindOfClass:NSDictionary.class] && [owner[@"customerId"] length] && [owner[@"endpointId"] isEqual:d[@"sp_endpoint_id"]]
32
+ && [cfg[@"workspaceId"] length] && [cfg[@"workspaceId"] isEqual:d[@"sp_workspace_id"]] && [cfg[@"channelId"] isEqual:d[@"sp_channel_id"]]
33
+ && [d[@"sp_message_id"] isKindOfClass:NSString.class] && [d[@"sp_endpoint_id"] isKindOfClass:NSString.class] && [d[@"sp_event_token"] isKindOfClass:NSString.class]; }
34
+ /** Derives stable event IDs for callbacks repeated across process launches. */
35
+ + (NSString *)eventId:(NSString *)type message:(NSDictionary *)message metadata:(NSDictionary *)metadata {
36
+ NSDictionary *d=message[@"data"];NSString *action=([type isEqual:@"action"]||[type isEqual:@"conversion"])?metadata[@"action_id"]?:@"":@"";
37
+ NSString *key=[NSString stringWithFormat:@"%@:%@:%@:%@:%@:%@",d[@"sp_workspace_id"],d[@"sp_channel_id"],d[@"sp_message_id"],d[@"sp_endpoint_id"],type,action];
38
+ NSData *bytes=[key dataUsingEncoding:NSUTF8StringEncoding];unsigned char hash[CC_SHA256_DIGEST_LENGTH];CC_SHA256(bytes.bytes,(CC_LONG)bytes.length,hash);
39
+ hash[6]=(hash[6]&15)|64;hash[8]=(hash[8]&63)|128;return [[[NSUUID alloc] initWithUUIDBytes:hash] UUIDString];
40
+ }
41
+ /** Removes expired observations and bounds recent deduplication state. */
42
+ + (void)prune:(NSMutableDictionary *)values limit:(NSUInteger)limit {
43
+ NSArray *keys=[values keysSortedByValueUsingComparator:^NSComparisonResult(id a,id b){return [a[@"stored_at"] compare:b[@"stored_at"]];}];
44
+ NSTimeInterval earliest=NSDate.date.timeIntervalSince1970-7*86400;
45
+ for(NSString *key in keys)if([values[key][@"stored_at"] doubleValue]<earliest || values.count>limit)[values removeObjectForKey:key];
46
+ }
47
+ /** Persists an observation and the capture SDK version before JS or networking starts. */
48
+ + (BOOL)capture:(NSString *)type message:(NSDictionary *)message metadata:(NSDictionary *)metadata {
49
+ @synchronized(self){if(![self owns:message])return NO;
50
+ NSMutableDictionary *events=[self read:@"events"],*recent=[self read:@"recent"];[self prune:events limit:200];[self prune:recent limit:200];
51
+ NSString *eventId=[self eventId:type message:message metadata:metadata];if(events[eventId]||recent[eventId])return YES;
52
+ if(events.count>=200){NSUserDefaults *s=[self store];[s setInteger:[s integerForKey:@"overflow"]+1 forKey:@"overflow"];return NO;}
53
+ NSMutableDictionary *details=[@{@"platform":@"ios",@"app_id":NSBundle.mainBundle.bundleIdentifier?:@"",@"app_version":[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]?:@"",@"app_state":@"unknown"} mutableCopy];[details addEntriesFromDictionary:metadata];
54
+ details[@"owner_customer_id"]=[self read:@"config"][@"owner"][@"customerId"];
55
+ NSISO8601DateFormatter *date=[NSISO8601DateFormatter new];
56
+ events[eventId]=@{@"event_id":eventId,@"event_type":type,@"occurred_at":[date stringFromDate:NSDate.date],@"sdk_version":@SAGEPILOT_CAPTURE_SDK_VERSION,@"message":message,@"metadata":details,@"stored_at":@(NSDate.date.timeIntervalSince1970)};
57
+ if([NSJSONSerialization dataWithJSONObject:events[eventId] options:0 error:nil].length>32768)@throw [NSException exceptionWithName:@"PushPayload" reason:@"Push observation exceeds 32 KiB" userInfo:nil];
58
+ [self save:@"events" value:events];[NSNotificationCenter.defaultCenter postNotificationName:@"SagepilotPushPending" object:nil];return YES;
59
+ }
60
+ }
61
+ /** Returns retained events without removing unacknowledged observations. */
62
+ + (NSArray *)pending { @synchronized(self){NSMutableDictionary *events=[self read:@"events"];[self prune:events limit:200];[self save:@"events" value:events];return events.allValues;} }
63
+ /** Records server acceptance while retaining a bounded replay identity. */
64
+ + (void)acknowledge:(NSString *)eventId { @synchronized(self){NSMutableDictionary *events=[self read:@"events"],*recent=[self read:@"recent"];if(events[eventId]){recent[eventId]=@{@"stored_at":@(NSDate.date.timeIntervalSince1970)};[self prune:recent limit:200];[self save:@"recent" value:recent];[events removeObjectForKey:eventId];[self save:@"events" value:events];}} }
65
+ /** Persists one navigation claim independently from analytics retries. */
66
+ + (BOOL)claimOpen:(NSString *)eventId { @synchronized(self){NSMutableDictionary *events=[self read:@"events"];NSMutableDictionary *event=[events[eventId] mutableCopy];if(!event||[event[@"routed"] boolValue])return NO;event[@"routed"]=@YES;events[eventId]=event;[self save:@"events" value:events];return YES;} }
67
+ /** Receives a JS/provider callback without synthesizing a second iOS background alert. */
68
+ + (BOOL)receive:(NSDictionary *)message foreground:(BOOL)foreground { return [self capture:@"received" message:message metadata:@{@"app_state":foreground?@"active":@"background"}]; }
69
+ /** Records a real notification tap before host routing. */
70
+ + (BOOL)opened:(NSDictionary *)message { return [self capture:@"opened" message:message metadata:@{@"app_state":@"active"}]; }
71
+ /** Host forwards foreground notifications here; the OS performs the requested presentation once. */
72
+ + (BOOL)willPresent:(UNNotification *)notification completion:(void (^)(UNNotificationPresentationOptions))completion {
73
+ NSDictionary *message=[self message:notification.request.content.userInfo];if(![self owns:message])return NO;
74
+ [self receive:message foreground:YES];[self capture:@"presentation_requested" message:message metadata:@{@"app_state":@"active"}];completion(UNNotificationPresentationOptionBanner|UNNotificationPresentationOptionList|UNNotificationPresentationOptionSound);return YES;
75
+ }
76
+ /** Host forwards supported response callbacks; dismissal is never inferred from missing taps. */
77
+ + (BOOL)didRespond:(UNNotificationResponse *)response {
78
+ NSDictionary *message=[self message:response.notification.request.content.userInfo];if(![self owns:message])return NO;
79
+ if([response.actionIdentifier isEqual:UNNotificationDismissActionIdentifier])return [self capture:@"dismissed" message:message metadata:@{}];
80
+ return [response.actionIdentifier isEqual:UNNotificationDefaultActionIdentifier] ? [self opened:message] : NO;
81
+ }
82
+ @end
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@sagepilot-ai/react-native-push-addon",
3
+ "version": "0.4.0",
4
+ "description": "Optional Android/iOS push presentation and durable observations for Sagepilot",
5
+ "keywords": [
6
+ "sagepilot",
7
+ "react-native",
8
+ "push",
9
+ "fcm",
10
+ "apns"
11
+ ],
12
+ "license": "MIT",
13
+ "main": "./dist/index.js",
14
+ "module": "./dist/index.mjs",
15
+ "react-native": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.mjs",
21
+ "require": "./dist/index.js"
22
+ },
23
+ "./app.plugin.js": "./app.plugin.js",
24
+ "./package.json": "./package.json"
25
+ },
26
+ "files": [
27
+ "android",
28
+ "ios",
29
+ "plugin",
30
+ "app.plugin.js",
31
+ "SagepilotPushAddon.podspec",
32
+ "react-native.config.js",
33
+ "dist",
34
+ "README.md",
35
+ "LICENSE.md"
36
+ ],
37
+ "sideEffects": false,
38
+ "scripts": {
39
+ "build": "tsup",
40
+ "typecheck": "tsc --noEmit",
41
+ "prepublishOnly": "npm run typecheck && npm run build"
42
+ },
43
+ "peerDependencies": {
44
+ "@sagepilot-ai/react-native-sdk": ">=0.4.0",
45
+ "react": ">=18",
46
+ "react-native": ">=0.81.5"
47
+ },
48
+ "devDependencies": {
49
+ "tsup": "^8.3.5",
50
+ "typescript": "^5.7.2"
51
+ }
52
+ }
@@ -0,0 +1,18 @@
1
+ package ai.sagepilot.hostpush;
2
+ import android.content.Context;
3
+ import android.content.Intent;
4
+ import io.invertase.firebase.messaging.ReactNativeFirebaseMessagingReceiver;
5
+ import io.invertase.firebase.common.SharedUtils;
6
+ import ai.sagepilot.push.SagepilotPushRuntime;
7
+ /** Explicit replacement for the host RNFirebase receiver; forwards unrelated traffic to it. */
8
+ public final class SagepilotMessagingReceiver extends ReactNativeFirebaseMessagingReceiver {
9
+ /** Persists brand callbacks before JS; RNFirebase retains its normal headless/token behavior. */
10
+ @Override public void onReceive(Context context, Intent intent) {
11
+ super.onReceive(context,intent);
12
+ if(intent.getExtras()==null || (intent.hasExtra("message_type") && !"gcm".equals(intent.getStringExtra("message_type"))))return;
13
+ boolean foreground=SharedUtils.isAppInForeground(context);
14
+ PendingResult pending=goAsync();
15
+ // ponytail: one short-lived worker per callback; bounded media transfer fits the broadcast deadline.
16
+ new Thread(()->{try{SagepilotPushRuntime.receive(context.getApplicationContext(),intent.getExtras(),foreground);}finally{pending.finish();}},"SagepilotPush").start();
17
+ }
18
+ }
@@ -0,0 +1,42 @@
1
+ # Adds an image extension to an existing CocoaPods/Xcode host. Run again after Expo clean prebuild.
2
+ require 'xcodeproj'
3
+ require 'fileutils'
4
+ # Reuses the installed CocoaPods xcodeproj library; does not touch host capabilities or signing profiles.
5
+ def install_extension(project_path)
6
+ project = Xcodeproj::Project.open(project_path)
7
+ host = project.targets.find { |t| t.product_type == 'com.apple.product-type.application' }
8
+ raise 'Expected an application target' unless host
9
+ name = 'SagepilotPushImages'
10
+ root = File.dirname(project_path)
11
+ folder = File.join(root, name)
12
+ FileUtils.mkdir_p(folder)
13
+ %w[SagepilotPushImageService.h SagepilotPushImageService.m].each do |file|
14
+ FileUtils.cp(File.expand_path("../ios/#{file}", __dir__), File.join(folder, file))
15
+ end
16
+ Xcodeproj::Plist.write_to_path({ 'CFBundleDisplayName' => 'Notification images', 'CFBundleExecutable' => '$(EXECUTABLE_NAME)',
17
+ 'CFBundleIdentifier' => '$(PRODUCT_BUNDLE_IDENTIFIER)', 'CFBundleInfoDictionaryVersion' => '6.0', 'CFBundleName' => '$(PRODUCT_NAME)',
18
+ 'CFBundlePackageType' => 'XPC!', 'CFBundleShortVersionString' => '$(MARKETING_VERSION)', 'CFBundleVersion' => '$(CURRENT_PROJECT_VERSION)',
19
+ 'NSExtension' => { 'NSExtensionPointIdentifier' => 'com.apple.usernotifications.service', 'NSExtensionPrincipalClass' => 'SagepilotPushImageService' }
20
+ }, File.join(folder, 'Info.plist'))
21
+ target = project.targets.find { |t| t.name == name } || project.new_target(:app_extension, name, :ios, '15.1')
22
+ group = project.main_group.find_subpath(name, true)
23
+ group.set_source_tree('<group>'); group.path = name
24
+ %w[SagepilotPushImageService.h SagepilotPushImageService.m Info.plist].each do |file|
25
+ ref = group.files.find { |f| f.path == file } || group.new_file(file)
26
+ target.source_build_phase.add_file_reference(ref, true) if file.end_with?('.m')
27
+ end
28
+ target.build_configurations.each do |config|
29
+ source = host.build_configurations.find { |c| c.name == config.name }.build_settings
30
+ config.build_settings.merge!({ 'INFOPLIST_FILE' => "#{name}/Info.plist", 'CLANG_ENABLE_OBJC_ARC' => 'YES',
31
+ 'PRODUCT_BUNDLE_IDENTIFIER' => "#{source['PRODUCT_BUNDLE_IDENTIFIER']}.push-images", 'PRODUCT_NAME' => '$(TARGET_NAME)',
32
+ 'APPLICATION_EXTENSION_API_ONLY' => 'YES', 'SKIP_INSTALL' => 'YES', 'TARGETED_DEVICE_FAMILY' => '1,2' })
33
+ %w[DEVELOPMENT_TEAM CODE_SIGN_STYLE CURRENT_PROJECT_VERSION MARKETING_VERSION].each { |key| config.build_settings[key] = source[key] if source[key] }
34
+ end
35
+ host.add_dependency(target) unless host.dependencies.any? { |d| d.target == target }
36
+ phase = host.copy_files_build_phases.find { |p| p.name == 'Embed App Extensions' } || host.new_copy_files_build_phase('Embed App Extensions')
37
+ phase.dst_subfolder_spec = '13'
38
+ phase.add_file_reference(target.product_reference, true).settings = { 'ATTRIBUTES' => ['RemoveHeadersOnCopy'] }
39
+ project.save
40
+ end
41
+ abort 'Usage: ruby install-ios-extension.rb path/to/App.xcodeproj' unless ARGV.length == 1
42
+ install_extension(File.expand_path(ARGV[0]))
@@ -0,0 +1,4 @@
1
+ module.exports = { dependency: { platforms: {
2
+ android: { sourceDir: './android', packageImportPath: 'import ai.sagepilot.push.SagepilotPushPackage;', packageInstance: 'new SagepilotPushPackage()' },
3
+ ios: { podspecPath: './SagepilotPushAddon.podspec' }
4
+ } } };