@webority/mobile-core 0.182.0 → 0.184.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/README.md
CHANGED
|
@@ -103,6 +103,8 @@ tapped notification's data as strings, including the tap that launched the app.
|
|
|
103
103
|
settings switch its `status` and `enabled`. The library does not remember the switch: an app that
|
|
104
104
|
keeps push on calls `enablePush` at each start. `setBadgeCount(count)` sets the app icon badge. `dismissAllNotifications()` clears every notification from the notification tray; it never throws, and logs a failure at warn.
|
|
105
105
|
|
|
106
|
+
`showInForeground` and `playSoundInForeground` receive the notification's data, so an app can hide a push for a screen already open: `showInForeground: (data) => !(data.targetKind === 'chat' && data.targetId === openChatId())`. On Android, an app that draws data-only pushes in its own native messaging service makes the same decision in that service, because those pushes never reach this handler.
|
|
107
|
+
|
|
106
108
|
- `enablePush({ prompt: false })` never shows the permission prompt: a phone already granted
|
|
107
109
|
registers silently, and any other resolves with its status (`undetermined` when the person has not
|
|
108
110
|
been asked yet, `denied` when refused and the prompt can still show, `blocked` when only
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.usePush=exports.toPushReceived=exports.toPushAction=exports.toNotificationActions=exports.setPushImplementation=exports.setCategories=exports.setBadgeCount=exports.routeTaskPayload=exports.resolveModules=exports.resetPush=exports.readDevicePushToken=exports.onReceive=exports.onAction=exports.notifyLocal=exports.initPush=exports.enablePush=exports.dismissAllNotifications=exports.disablePush=void 0;var _react=require("react"),_reactNative=require("react-native"),_index=require("../logger/index.js"),_guards=require("../utils/guards.js");let resolved,override=null;const setPushImplementation=e=>{override=e};exports.setPushImplementation=setPushImplementation;const resolveModules=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{if(require("expo").isRunningInExpoGo())return resolved=null,resolved;const e=require("expo-notifications"),t=require("expo-application");resolved={notifications:e,applicationId:t.applicationId,getApnsEnvironment:()=>t.getIosPushNotificationServiceEnvironmentAsync()}}catch(e){_index.Logger.warn("[push] expo-notifications is not available; push is off",e),resolved=null}return resolved};exports.resolveModules=resolveModules;let state={status:"unknown",enabled:!1,registrationError:null};const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,channelsReady=Promise.resolve(),tokenSubscription=null,actionHandler=null;const receiveHandlers=new Set;let listening=!1,listeningForReceived=!1;const pendingResponses=[],routedAt=new Map,REPEAT_WINDOW_MS=1e4,requireConfig=()=>{if(!config)throw new Error("[@webority/mobile-core] call initPush before enablePush or disablePush.");return config},toPermissionStatus=e=>e.granted?"granted":"denied"===e.status?e.canAskAgain?"denied":"blocked":"undetermined",toStringData=e=>{const t={};for(const[n,i]of Object.entries(e??{}))null!=i&&(t[n]="object"==typeof i?JSON.stringify(i):String(i));return t},contentData=e=>{const t=e.request.content;if(t.data)return toStringData(t.data);if("string"==typeof t.dataString)try{const e=JSON.parse(t.dataString);if(!(0,_guards.isRecord)(e))throw new Error("the notification data is not a JSON object");return toStringData(e)}catch(e){_index.Logger.error("[push] notification data is not JSON",e)}return{}},triggerData=e=>{const t=e.request.trigger,n={...t?.remoteMessage?.data??{}};for(const[e,i]of Object.entries(t?.payload??{}))"aps"===e||"body"===e&&"object"==typeof i||(n[e]=i);return toStringData(n)},notificationData=e=>({...triggerData(e),...contentData(e)}),responseData=e=>notificationData(e.notification),toPushReceived=e=>({notificationId:e.request.identifier,title:e.request.content.title??null,body:e.request.content.body??null,data:notificationData(e)});exports.toPushReceived=toPushReceived;const toPushAction=e=>({actionId:e.actionIdentifier,...e.userText?{userText:e.userText}:{},data:responseData(e),notificationId:e.notification.request.identifier});exports.toPushAction=toPushAction;const toNotificationActions=e=>e.map(e=>({identifier:e.id,buttonTitle:e.title,...e.textInput?{textInput:{submitButtonTitle:e.textInput.submitTitle,placeholder:e.textInput.placeholder}}:{},options:{opensAppToForeground:e.opensApp??!0,isDestructive:e.destructive??!1,isAuthenticationRequired:e.authenticationRequired??!1}}));exports.toNotificationActions=toNotificationActions;const routeResponse=async(e,t)=>{const n=`${t.notification.request.identifier}:${t.actionIdentifier}`,i=routedAt.get(n);if(void 0!==i&&Date.now()-i<1e4)return;if(t.actionIdentifier!==e.DEFAULT_ACTION_IDENTIFIER&&actionHandler){routedAt.set(n,Date.now());try{await actionHandler(toPushAction(t))}catch(e){_index.Logger.error("[push] onAction threw",e)}}else if(config){routedAt.set(n,Date.now());try{config.onOpen(responseData(t))}catch(e){_index.Logger.error("[push] onOpen threw",e)}}else pendingResponses.push(t)},drainPending=async e=>{const t=pendingResponses.splice(0);for(const n of t)await routeResponse(e,n)},listenForResponses=e=>{listening||(listening=!0,e.addNotificationResponseReceivedListener(t=>{routeResponse(e,t)}),e.getLastNotificationResponseAsync().then(async t=>(t&&await routeResponse(e,t),e.clearLastNotificationResponseAsync?.())).catch(e=>_index.Logger.error("[push] reading the launch notification failed",e)))},isString=e=>"string"==typeof e,isStringOrNull=e=>null===e||"string"==typeof e,isRecordOrNull=e=>null===e||(0,_guards.isRecord)(e),optionalOf=(e,t)=>t(e)?e:void 0,remoteMessageOf=e=>(0,_guards.isRecord)(e)?{data:optionalOf(e.data,isRecordOrNull)}:void 0,toNotificationResponse=e=>{if(!(0,_guards.isRecord)(e))return null;const{actionIdentifier:t,userText:n,notification:i}=e;if(!isString(t)||!(0,_guards.isRecord)(i))return null;const{request:o}=i;if(!(0,_guards.isRecord)(o))return null;const{identifier:s,content:r,trigger:a}=o;return isString(s)&&(0,_guards.isRecord)(r)?{actionIdentifier:t,userText:optionalOf(n,isString),notification:{request:{identifier:s,content:{title:optionalOf(r.title,isStringOrNull),body:optionalOf(r.body,isStringOrNull),data:optionalOf(r.data,isRecordOrNull),dataString:optionalOf(r.dataString,isString)},trigger:(0,_guards.isRecord)(a)?{type:optionalOf(a.type,isString),payload:optionalOf(a.payload,isRecordOrNull),remoteMessage:remoteMessageOf(a.remoteMessage)}:void 0}}}:null},routeTaskPayload=async e=>{const t=resolveModules();if(!t)return;const n=toNotificationResponse(e);n&&await routeResponse(t.notifications,n)};exports.routeTaskPayload=routeTaskPayload;const createChannels=async(e,t)=>{for(const n of t)try{await e.setNotificationChannelAsync(n.id,{name:n.name,importance:"high"===n.importance?e.AndroidImportance.HIGH:e.AndroidImportance.DEFAULT})}catch(e){_index.Logger.error(`[push] creating channel ${n.id} failed`,e)}},APNS_ENVIRONMENTS={development:"Development",production:"Production"},readApnsEnvironment=async e=>{try{return APNS_ENVIRONMENTS[await e.getApnsEnvironment()??""]??null}catch(e){return _index.Logger.warn("[push] reading the APNs environment failed",e),null}},deviceTimeZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone||null,toDevice=async(e,t)=>{const n="android"===e.type?"Fcm":"ios"===e.type?"Apns":null;if(!n||"string"!=typeof e.data)return null;if(!t.applicationId)throw new Error("[@webority/mobile-core] push needs the app bundle id from expo-application.");return{installationId:await requireConfig().getInstallationId(),platform:n,token:e.data,appId:t.applicationId,apnsEnvironment:"Apns"===n?await readApnsEnvironment(t):null,timeZone:deviceTimeZone()}},initPush=e=>{const t=null===config;if(config=e,!t)return;const n=resolveModules();if(!n)return void setState({status:"unavailable"});const i=n.notifications;i.setNotificationHandler({handleNotification:async()=>{const e=config?.showInForeground?.()??!0;return{shouldShowBanner:e,shouldShowList:e,shouldPlaySound:e&&(config?.playSoundInForeground?.()??!0),shouldSetBadge:!0}}}),"android"===_reactNative.Platform.OS&&e.androidChannels?.length&&(channelsReady=createChannels(i,e.androidChannels)),listenForResponses(i),drainPending(i),i.getPermissionsAsync().then(e=>setState({status:toPermissionStatus(e)})).catch(e=>_index.Logger.error("[push] permission check failed",e))};exports.initPush=initPush;let registering=null,registeredKey=null,unregistering=null,tokenDrop=Promise.resolve();const registerOnce=e=>{const t=JSON.stringify(e);if(registering?.key===t)return registering.promise;const n=requireConfig().register(e).then(()=>{registeredKey=t,state.registrationError&&setState({registrationError:null})}).finally(()=>{registering?.promise===n&&(registering=null)});return registering={key:t,promise:n},n},enablePush=async({prompt:e=!0}={})=>{requireConfig();const t=resolveModules();if(!t)return setState({status:"unavailable"}),"unavailable";const n=t.notifications;await channelsReady,await tokenDrop;let i=await n.getPermissionsAsync();if(!i.granted&&e&&(i=await n.requestPermissionsAsync()),!i.granted){const e=toPermissionStatus(i);return setState({status:e}),e}const o=await toDevice(await n.getDevicePushTokenAsync(),t);return o?(await registerOnce(o),tokenSubscription?.remove(),tokenSubscription=n.addPushTokenListener(e=>{(unregistering??Promise.resolve()).then(()=>state.enabled?toDevice(e,t):null).then(e=>e&&JSON.stringify(e)!==registeredKey?registerOnce(e):void 0).catch(e=>{_index.Logger.error("[push] re-registering a new token failed",e),setState({registrationError:e instanceof Error?e:new Error(String(e))})})}),setState({status:"granted",enabled:!0}),"granted"):(setState({status:"unavailable"}),"unavailable")};exports.enablePush=enablePush;const readDevicePushToken=async()=>{const e=resolveModules();if(!e)return null;await tokenDrop;if(!(await e.notifications.getPermissionsAsync()).granted)return null;const t=await e.notifications.getDevicePushTokenAsync(),n="android"===t.type?"android":"ios"===t.type?"ios":null;return n&&"string"==typeof t.data?{platform:n,token:t.data}:null};exports.readDevicePushToken=readDevicePushToken;const stopFollowingToken=()=>{tokenSubscription?.remove(),tokenSubscription=null,registeredKey=null,setState({enabled:!1,registrationError:null})},disablePush=async()=>{const e=requireConfig(),t=await e.getInstallationId();await Promise.allSettled([registering?.promise]);let settle=()=>{};const n=new Promise(e=>{settle=e});unregistering=n;try{await e.unregister(t),stopFollowingToken()}finally{unregistering===n&&(unregistering=null),settle()}};exports.disablePush=disablePush;const resetPush=async()=>{stopFollowingToken();const e=resolveModules();if(!e)return;const t=e.notifications.unregisterForNotificationsAsync();tokenDrop=Promise.allSettled([t]),await t};exports.resetPush=resetPush;const setBadgeCount=async e=>{const t=resolveModules();t&&await t.notifications.setBadgeCountAsync(e)};exports.setBadgeCount=setBadgeCount;const dismissAllNotifications=async()=>{const e=resolveModules();if(e)try{await e.notifications.dismissAllNotificationsAsync()}catch(e){_index.Logger.warn("[push] dismissing the notifications failed",e)}};exports.dismissAllNotifications=dismissAllNotifications;const setCategories=async e=>{const t=resolveModules();if(t)for(const n of e)await t.notifications.setNotificationCategoryAsync(n.id,toNotificationActions(n.actions))};exports.setCategories=setCategories;const onAction=e=>{actionHandler=e;const t=resolveModules();return t&&(listenForResponses(t.notifications),drainPending(t.notifications)),()=>{actionHandler===e&&(actionHandler=null)}};exports.onAction=onAction;const onReceive=e=>{receiveHandlers.add(e);const t=resolveModules();return t&&!listeningForReceived&&(listeningForReceived=!0,t.notifications.addNotificationReceivedListener(e=>{const t=toPushReceived(e);for(const e of[...receiveHandlers])try{e(t)}catch(e){_index.Logger.error("[push] onReceive threw",e)}})),()=>{receiveHandlers.delete(e)}};exports.onReceive=onReceive;const notifyLocal=async({title:e,body:t,data:n})=>{const i=resolveModules();i&&await i.notifications.scheduleNotificationAsync({content:{title:e,body:t,data:n??{}},trigger:null})};exports.notifyLocal=notifyLocal;const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,enable=async()=>{await enablePush()},usePush=()=>({...(0,_react.useSyncExternalStore)(subscribe,getSnapshot,getSnapshot),enable:enable,disable:disablePush});exports.usePush=usePush;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.usePush=exports.toPushReceived=exports.toPushAction=exports.toNotificationActions=exports.setPushImplementation=exports.setCategories=exports.setBadgeCount=exports.routeTaskPayload=exports.resolveModules=exports.resetPush=exports.readDevicePushToken=exports.onReceive=exports.onAction=exports.notifyLocal=exports.initPush=exports.enablePush=exports.dismissAllNotifications=exports.disablePush=void 0;var _react=require("react"),_reactNative=require("react-native"),_index=require("../logger/index.js"),_guards=require("../utils/guards.js");let resolved,override=null;const setPushImplementation=e=>{override=e};exports.setPushImplementation=setPushImplementation;const resolveModules=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{if(require("expo").isRunningInExpoGo())return resolved=null,resolved;const e=require("expo-notifications"),t=require("expo-application");resolved={notifications:e,applicationId:t.applicationId,getApnsEnvironment:()=>t.getIosPushNotificationServiceEnvironmentAsync()}}catch(e){_index.Logger.warn("[push] expo-notifications is not available; push is off",e),resolved=null}return resolved};exports.resolveModules=resolveModules;let state={status:"unknown",enabled:!1,registrationError:null};const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,channelsReady=Promise.resolve(),tokenSubscription=null,actionHandler=null;const receiveHandlers=new Set;let listening=!1,listeningForReceived=!1;const pendingResponses=[],routedAt=new Map,REPEAT_WINDOW_MS=1e4,requireConfig=()=>{if(!config)throw new Error("[@webority/mobile-core] call initPush before enablePush or disablePush.");return config},toPermissionStatus=e=>e.granted?"granted":"denied"===e.status?e.canAskAgain?"denied":"blocked":"undetermined",toStringData=e=>{const t={};for(const[n,i]of Object.entries(e??{}))null!=i&&(t[n]="object"==typeof i?JSON.stringify(i):String(i));return t},contentData=e=>{const t=e.request.content;if(t.data)return toStringData(t.data);if("string"==typeof t.dataString)try{const e=JSON.parse(t.dataString);if(!(0,_guards.isRecord)(e))throw new Error("the notification data is not a JSON object");return toStringData(e)}catch(e){_index.Logger.error("[push] notification data is not JSON",e)}return{}},triggerData=e=>{const t=e.request.trigger,n={...t?.remoteMessage?.data??{}};for(const[e,i]of Object.entries(t?.payload??{}))"aps"===e||"body"===e&&"object"==typeof i||(n[e]=i);return toStringData(n)},notificationData=e=>({...triggerData(e),...contentData(e)}),responseData=e=>notificationData(e.notification),toPushReceived=e=>({notificationId:e.request.identifier,title:e.request.content.title??null,body:e.request.content.body??null,data:notificationData(e)});exports.toPushReceived=toPushReceived;const toPushAction=e=>({actionId:e.actionIdentifier,...e.userText?{userText:e.userText}:{},data:responseData(e),notificationId:e.notification.request.identifier});exports.toPushAction=toPushAction;const toNotificationActions=e=>e.map(e=>({identifier:e.id,buttonTitle:e.title,...e.textInput?{textInput:{submitButtonTitle:e.textInput.submitTitle,placeholder:e.textInput.placeholder}}:{},options:{opensAppToForeground:e.opensApp??!0,isDestructive:e.destructive??!1,isAuthenticationRequired:e.authenticationRequired??!1}}));exports.toNotificationActions=toNotificationActions;const routeResponse=async(e,t)=>{const n=`${t.notification.request.identifier}:${t.actionIdentifier}`,i=routedAt.get(n);if(void 0!==i&&Date.now()-i<1e4)return;if(t.actionIdentifier!==e.DEFAULT_ACTION_IDENTIFIER&&actionHandler){routedAt.set(n,Date.now());try{await actionHandler(toPushAction(t))}catch(e){_index.Logger.error("[push] onAction threw",e)}}else if(config){routedAt.set(n,Date.now());try{config.onOpen(responseData(t))}catch(e){_index.Logger.error("[push] onOpen threw",e)}}else pendingResponses.push(t)},drainPending=async e=>{const t=pendingResponses.splice(0);for(const n of t)await routeResponse(e,n)},listenForResponses=e=>{listening||(listening=!0,e.addNotificationResponseReceivedListener(t=>{routeResponse(e,t)}),e.getLastNotificationResponseAsync().then(async t=>(t&&await routeResponse(e,t),e.clearLastNotificationResponseAsync?.())).catch(e=>_index.Logger.error("[push] reading the launch notification failed",e)))},isString=e=>"string"==typeof e,isStringOrNull=e=>null===e||"string"==typeof e,isRecordOrNull=e=>null===e||(0,_guards.isRecord)(e),optionalOf=(e,t)=>t(e)?e:void 0,remoteMessageOf=e=>(0,_guards.isRecord)(e)?{data:optionalOf(e.data,isRecordOrNull)}:void 0,toNotificationResponse=e=>{if(!(0,_guards.isRecord)(e))return null;const{actionIdentifier:t,userText:n,notification:i}=e;if(!isString(t)||!(0,_guards.isRecord)(i))return null;const{request:o}=i;if(!(0,_guards.isRecord)(o))return null;const{identifier:s,content:r,trigger:a}=o;return isString(s)&&(0,_guards.isRecord)(r)?{actionIdentifier:t,userText:optionalOf(n,isString),notification:{request:{identifier:s,content:{title:optionalOf(r.title,isStringOrNull),body:optionalOf(r.body,isStringOrNull),data:optionalOf(r.data,isRecordOrNull),dataString:optionalOf(r.dataString,isString)},trigger:(0,_guards.isRecord)(a)?{type:optionalOf(a.type,isString),payload:optionalOf(a.payload,isRecordOrNull),remoteMessage:remoteMessageOf(a.remoteMessage)}:void 0}}}:null},routeTaskPayload=async e=>{const t=resolveModules();if(!t)return;const n=toNotificationResponse(e);n&&await routeResponse(t.notifications,n)};exports.routeTaskPayload=routeTaskPayload;const createChannels=async(e,t)=>{for(const n of t)try{await e.setNotificationChannelAsync(n.id,{name:n.name,importance:"high"===n.importance?e.AndroidImportance.HIGH:e.AndroidImportance.DEFAULT})}catch(e){_index.Logger.error(`[push] creating channel ${n.id} failed`,e)}},APNS_ENVIRONMENTS={development:"Development",production:"Production"},readApnsEnvironment=async e=>{try{return APNS_ENVIRONMENTS[await e.getApnsEnvironment()??""]??null}catch(e){return _index.Logger.warn("[push] reading the APNs environment failed",e),null}},deviceTimeZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone||null,toDevice=async(e,t)=>{const n="android"===e.type?"Fcm":"ios"===e.type?"Apns":null;if(!n||"string"!=typeof e.data)return null;if(!t.applicationId)throw new Error("[@webority/mobile-core] push needs the app bundle id from expo-application.");return{installationId:await requireConfig().getInstallationId(),platform:n,token:e.data,appId:t.applicationId,apnsEnvironment:"Apns"===n?await readApnsEnvironment(t):null,timeZone:deviceTimeZone()}},initPush=e=>{const t=null===config;if(config=e,!t)return;const n=resolveModules();if(!n)return void setState({status:"unavailable"});const i=n.notifications;i.setNotificationHandler({handleNotification:async e=>{const t=notificationData(e),n=config?.showInForeground?.(t)??!0;return{shouldShowBanner:n,shouldShowList:n,shouldPlaySound:n&&(config?.playSoundInForeground?.(t)??!0),shouldSetBadge:!0}}}),"android"===_reactNative.Platform.OS&&e.androidChannels?.length&&(channelsReady=createChannels(i,e.androidChannels)),listenForResponses(i),drainPending(i),i.getPermissionsAsync().then(e=>setState({status:toPermissionStatus(e)})).catch(e=>_index.Logger.error("[push] permission check failed",e))};exports.initPush=initPush;let registering=null,registeredKey=null,unregistering=null,tokenDrop=Promise.resolve();const registerOnce=e=>{const t=JSON.stringify(e);if(registering?.key===t)return registering.promise;const n=requireConfig().register(e).then(()=>{registeredKey=t,state.registrationError&&setState({registrationError:null})}).finally(()=>{registering?.promise===n&&(registering=null)});return registering={key:t,promise:n},n},enablePush=async({prompt:e=!0}={})=>{requireConfig();const t=resolveModules();if(!t)return setState({status:"unavailable"}),"unavailable";const n=t.notifications;await channelsReady,await tokenDrop;let i=await n.getPermissionsAsync();if(!i.granted&&e&&(i=await n.requestPermissionsAsync()),!i.granted){const e=toPermissionStatus(i);return setState({status:e}),e}const o=await toDevice(await n.getDevicePushTokenAsync(),t);return o?(await registerOnce(o),tokenSubscription?.remove(),tokenSubscription=n.addPushTokenListener(e=>{(unregistering??Promise.resolve()).then(()=>state.enabled?toDevice(e,t):null).then(e=>e&&JSON.stringify(e)!==registeredKey?registerOnce(e):void 0).catch(e=>{_index.Logger.error("[push] re-registering a new token failed",e),setState({registrationError:e instanceof Error?e:new Error(String(e))})})}),setState({status:"granted",enabled:!0}),"granted"):(setState({status:"unavailable"}),"unavailable")};exports.enablePush=enablePush;const readDevicePushToken=async()=>{const e=resolveModules();if(!e)return null;await tokenDrop;if(!(await e.notifications.getPermissionsAsync()).granted)return null;const t=await e.notifications.getDevicePushTokenAsync(),n="android"===t.type?"android":"ios"===t.type?"ios":null;return n&&"string"==typeof t.data?{platform:n,token:t.data}:null};exports.readDevicePushToken=readDevicePushToken;const stopFollowingToken=()=>{tokenSubscription?.remove(),tokenSubscription=null,registeredKey=null,setState({enabled:!1,registrationError:null})},disablePush=async()=>{const e=requireConfig(),t=await e.getInstallationId();await Promise.allSettled([registering?.promise]);let settle=()=>{};const n=new Promise(e=>{settle=e});unregistering=n;try{await e.unregister(t),stopFollowingToken()}finally{unregistering===n&&(unregistering=null),settle()}};exports.disablePush=disablePush;const resetPush=async()=>{stopFollowingToken();const e=resolveModules();if(!e)return;const t=e.notifications.unregisterForNotificationsAsync();tokenDrop=Promise.allSettled([t]),await t};exports.resetPush=resetPush;const setBadgeCount=async e=>{const t=resolveModules();t&&await t.notifications.setBadgeCountAsync(e)};exports.setBadgeCount=setBadgeCount;const dismissAllNotifications=async()=>{const e=resolveModules();if(e)try{await e.notifications.dismissAllNotificationsAsync()}catch(e){_index.Logger.warn("[push] dismissing the notifications failed",e)}};exports.dismissAllNotifications=dismissAllNotifications;const setCategories=async e=>{const t=resolveModules();if(t)for(const n of e)await t.notifications.setNotificationCategoryAsync(n.id,toNotificationActions(n.actions))};exports.setCategories=setCategories;const onAction=e=>{actionHandler=e;const t=resolveModules();return t&&(listenForResponses(t.notifications),drainPending(t.notifications)),()=>{actionHandler===e&&(actionHandler=null)}};exports.onAction=onAction;const onReceive=e=>{receiveHandlers.add(e);const t=resolveModules();return t&&!listeningForReceived&&(listeningForReceived=!0,t.notifications.addNotificationReceivedListener(e=>{const t=toPushReceived(e);for(const e of[...receiveHandlers])try{e(t)}catch(e){_index.Logger.error("[push] onReceive threw",e)}})),()=>{receiveHandlers.delete(e)}};exports.onReceive=onReceive;const notifyLocal=async({title:e,body:t,data:n})=>{const i=resolveModules();i&&await i.notifications.scheduleNotificationAsync({content:{title:e,body:t,data:n??{}},trigger:null})};exports.notifyLocal=notifyLocal;const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,enable=async()=>{await enablePush()},usePush=()=>({...(0,_react.useSyncExternalStore)(subscribe,getSnapshot,getSnapshot),enable:enable,disable:disablePush});exports.usePush=usePush;
|
package/lib/module/push/push.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{useSyncExternalStore}from"react";import{Platform}from"react-native";import{Logger}from"../logger/index.js";import{isRecord}from"../utils/guards.js";let resolved,override=null;export const setPushImplementation=e=>{override=e};export const resolveModules=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{if(require("expo").isRunningInExpoGo())return resolved=null,resolved;const e=require("expo-notifications"),t=require("expo-application");resolved={notifications:e,applicationId:t.applicationId,getApnsEnvironment:()=>t.getIosPushNotificationServiceEnvironmentAsync()}}catch(e){Logger.warn("[push] expo-notifications is not available; push is off",e),resolved=null}return resolved};let state={status:"unknown",enabled:!1,registrationError:null};const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,channelsReady=Promise.resolve(),tokenSubscription=null,actionHandler=null;const receiveHandlers=new Set;let listening=!1,listeningForReceived=!1;const pendingResponses=[],routedAt=new Map,REPEAT_WINDOW_MS=1e4,requireConfig=()=>{if(!config)throw new Error("[@webority/mobile-core] call initPush before enablePush or disablePush.");return config},toPermissionStatus=e=>e.granted?"granted":"denied"===e.status?e.canAskAgain?"denied":"blocked":"undetermined",toStringData=e=>{const t={};for(const[n,o]of Object.entries(e??{}))null!=o&&(t[n]="object"==typeof o?JSON.stringify(o):String(o));return t},contentData=e=>{const t=e.request.content;if(t.data)return toStringData(t.data);if("string"==typeof t.dataString)try{const e=JSON.parse(t.dataString);if(!isRecord(e))throw new Error("the notification data is not a JSON object");return toStringData(e)}catch(e){Logger.error("[push] notification data is not JSON",e)}return{}},triggerData=e=>{const t=e.request.trigger,n={...t?.remoteMessage?.data??{}};for(const[e,o]of Object.entries(t?.payload??{}))"aps"===e||"body"===e&&"object"==typeof o||(n[e]=o);return toStringData(n)},notificationData=e=>({...triggerData(e),...contentData(e)}),responseData=e=>notificationData(e.notification);export const toPushReceived=e=>({notificationId:e.request.identifier,title:e.request.content.title??null,body:e.request.content.body??null,data:notificationData(e)});export const toPushAction=e=>({actionId:e.actionIdentifier,...e.userText?{userText:e.userText}:{},data:responseData(e),notificationId:e.notification.request.identifier});export const toNotificationActions=e=>e.map(e=>({identifier:e.id,buttonTitle:e.title,...e.textInput?{textInput:{submitButtonTitle:e.textInput.submitTitle,placeholder:e.textInput.placeholder}}:{},options:{opensAppToForeground:e.opensApp??!0,isDestructive:e.destructive??!1,isAuthenticationRequired:e.authenticationRequired??!1}}));const routeResponse=async(e,t)=>{const n=`${t.notification.request.identifier}:${t.actionIdentifier}`,o=routedAt.get(n);if(void 0!==o&&Date.now()-o<1e4)return;if(t.actionIdentifier!==e.DEFAULT_ACTION_IDENTIFIER&&actionHandler){routedAt.set(n,Date.now());try{await actionHandler(toPushAction(t))}catch(e){Logger.error("[push] onAction threw",e)}}else if(config){routedAt.set(n,Date.now());try{config.onOpen(responseData(t))}catch(e){Logger.error("[push] onOpen threw",e)}}else pendingResponses.push(t)},drainPending=async e=>{const t=pendingResponses.splice(0);for(const n of t)await routeResponse(e,n)},listenForResponses=e=>{listening||(listening=!0,e.addNotificationResponseReceivedListener(t=>{routeResponse(e,t)}),e.getLastNotificationResponseAsync().then(async t=>(t&&await routeResponse(e,t),e.clearLastNotificationResponseAsync?.())).catch(e=>Logger.error("[push] reading the launch notification failed",e)))},isString=e=>"string"==typeof e,isStringOrNull=e=>null===e||"string"==typeof e,isRecordOrNull=e=>null===e||isRecord(e),optionalOf=(e,t)=>t(e)?e:void 0,remoteMessageOf=e=>isRecord(e)?{data:optionalOf(e.data,isRecordOrNull)}:void 0,toNotificationResponse=e=>{if(!isRecord(e))return null;const{actionIdentifier:t,userText:n,notification:o}=e;if(!isString(t)||!isRecord(o))return null;const{request:i}=o;if(!isRecord(i))return null;const{identifier:r,content:s,trigger:a}=i;return isString(r)&&isRecord(s)?{actionIdentifier:t,userText:optionalOf(n,isString),notification:{request:{identifier:r,content:{title:optionalOf(s.title,isStringOrNull),body:optionalOf(s.body,isStringOrNull),data:optionalOf(s.data,isRecordOrNull),dataString:optionalOf(s.dataString,isString)},trigger:isRecord(a)?{type:optionalOf(a.type,isString),payload:optionalOf(a.payload,isRecordOrNull),remoteMessage:remoteMessageOf(a.remoteMessage)}:void 0}}}:null};export const routeTaskPayload=async e=>{const t=resolveModules();if(!t)return;const n=toNotificationResponse(e);n&&await routeResponse(t.notifications,n)};const createChannels=async(e,t)=>{for(const n of t)try{await e.setNotificationChannelAsync(n.id,{name:n.name,importance:"high"===n.importance?e.AndroidImportance.HIGH:e.AndroidImportance.DEFAULT})}catch(e){Logger.error(`[push] creating channel ${n.id} failed`,e)}},APNS_ENVIRONMENTS={development:"Development",production:"Production"},readApnsEnvironment=async e=>{try{return APNS_ENVIRONMENTS[await e.getApnsEnvironment()??""]??null}catch(e){return Logger.warn("[push] reading the APNs environment failed",e),null}},deviceTimeZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone||null,toDevice=async(e,t)=>{const n="android"===e.type?"Fcm":"ios"===e.type?"Apns":null;if(!n||"string"!=typeof e.data)return null;if(!t.applicationId)throw new Error("[@webority/mobile-core] push needs the app bundle id from expo-application.");return{installationId:await requireConfig().getInstallationId(),platform:n,token:e.data,appId:t.applicationId,apnsEnvironment:"Apns"===n?await readApnsEnvironment(t):null,timeZone:deviceTimeZone()}};export const initPush=e=>{const t=null===config;if(config=e,!t)return;const n=resolveModules();if(!n)return void setState({status:"unavailable"});const o=n.notifications;o.setNotificationHandler({handleNotification:async()=>{const e=config?.showInForeground?.()??!0;return{shouldShowBanner:e,shouldShowList:e,shouldPlaySound:e&&(config?.playSoundInForeground?.()??!0),shouldSetBadge:!0}}}),"android"===Platform.OS&&e.androidChannels?.length&&(channelsReady=createChannels(o,e.androidChannels)),listenForResponses(o),drainPending(o),o.getPermissionsAsync().then(e=>setState({status:toPermissionStatus(e)})).catch(e=>Logger.error("[push] permission check failed",e))};let registering=null,registeredKey=null,unregistering=null,tokenDrop=Promise.resolve();const registerOnce=e=>{const t=JSON.stringify(e);if(registering?.key===t)return registering.promise;const n=requireConfig().register(e).then(()=>{registeredKey=t,state.registrationError&&setState({registrationError:null})}).finally(()=>{registering?.promise===n&&(registering=null)});return registering={key:t,promise:n},n};export const enablePush=async({prompt:e=!0}={})=>{requireConfig();const t=resolveModules();if(!t)return setState({status:"unavailable"}),"unavailable";const n=t.notifications;await channelsReady,await tokenDrop;let o=await n.getPermissionsAsync();if(!o.granted&&e&&(o=await n.requestPermissionsAsync()),!o.granted){const e=toPermissionStatus(o);return setState({status:e}),e}const i=await toDevice(await n.getDevicePushTokenAsync(),t);return i?(await registerOnce(i),tokenSubscription?.remove(),tokenSubscription=n.addPushTokenListener(e=>{(unregistering??Promise.resolve()).then(()=>state.enabled?toDevice(e,t):null).then(e=>e&&JSON.stringify(e)!==registeredKey?registerOnce(e):void 0).catch(e=>{Logger.error("[push] re-registering a new token failed",e),setState({registrationError:e instanceof Error?e:new Error(String(e))})})}),setState({status:"granted",enabled:!0}),"granted"):(setState({status:"unavailable"}),"unavailable")};export const readDevicePushToken=async()=>{const e=resolveModules();if(!e)return null;await tokenDrop;if(!(await e.notifications.getPermissionsAsync()).granted)return null;const t=await e.notifications.getDevicePushTokenAsync(),n="android"===t.type?"android":"ios"===t.type?"ios":null;return n&&"string"==typeof t.data?{platform:n,token:t.data}:null};const stopFollowingToken=()=>{tokenSubscription?.remove(),tokenSubscription=null,registeredKey=null,setState({enabled:!1,registrationError:null})};export const disablePush=async()=>{const e=requireConfig(),t=await e.getInstallationId();await Promise.allSettled([registering?.promise]);let settle=()=>{};const n=new Promise(e=>{settle=e});unregistering=n;try{await e.unregister(t),stopFollowingToken()}finally{unregistering===n&&(unregistering=null),settle()}};export const resetPush=async()=>{stopFollowingToken();const e=resolveModules();if(!e)return;const t=e.notifications.unregisterForNotificationsAsync();tokenDrop=Promise.allSettled([t]),await t};export const setBadgeCount=async e=>{const t=resolveModules();t&&await t.notifications.setBadgeCountAsync(e)};export const dismissAllNotifications=async()=>{const e=resolveModules();if(e)try{await e.notifications.dismissAllNotificationsAsync()}catch(e){Logger.warn("[push] dismissing the notifications failed",e)}};export const setCategories=async e=>{const t=resolveModules();if(t)for(const n of e)await t.notifications.setNotificationCategoryAsync(n.id,toNotificationActions(n.actions))};export const onAction=e=>{actionHandler=e;const t=resolveModules();return t&&(listenForResponses(t.notifications),drainPending(t.notifications)),()=>{actionHandler===e&&(actionHandler=null)}};export const onReceive=e=>{receiveHandlers.add(e);const t=resolveModules();return t&&!listeningForReceived&&(listeningForReceived=!0,t.notifications.addNotificationReceivedListener(e=>{const t=toPushReceived(e);for(const e of[...receiveHandlers])try{e(t)}catch(e){Logger.error("[push] onReceive threw",e)}})),()=>{receiveHandlers.delete(e)}};export const notifyLocal=async({title:e,body:t,data:n})=>{const o=resolveModules();o&&await o.notifications.scheduleNotificationAsync({content:{title:e,body:t,data:n??{}},trigger:null})};const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,enable=async()=>{await enablePush()};export const usePush=()=>({...useSyncExternalStore(subscribe,getSnapshot,getSnapshot),enable:enable,disable:disablePush});
|
|
1
|
+
"use strict";import{useSyncExternalStore}from"react";import{Platform}from"react-native";import{Logger}from"../logger/index.js";import{isRecord}from"../utils/guards.js";let resolved,override=null;export const setPushImplementation=e=>{override=e};export const resolveModules=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{if(require("expo").isRunningInExpoGo())return resolved=null,resolved;const e=require("expo-notifications"),t=require("expo-application");resolved={notifications:e,applicationId:t.applicationId,getApnsEnvironment:()=>t.getIosPushNotificationServiceEnvironmentAsync()}}catch(e){Logger.warn("[push] expo-notifications is not available; push is off",e),resolved=null}return resolved};let state={status:"unknown",enabled:!1,registrationError:null};const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,channelsReady=Promise.resolve(),tokenSubscription=null,actionHandler=null;const receiveHandlers=new Set;let listening=!1,listeningForReceived=!1;const pendingResponses=[],routedAt=new Map,REPEAT_WINDOW_MS=1e4,requireConfig=()=>{if(!config)throw new Error("[@webority/mobile-core] call initPush before enablePush or disablePush.");return config},toPermissionStatus=e=>e.granted?"granted":"denied"===e.status?e.canAskAgain?"denied":"blocked":"undetermined",toStringData=e=>{const t={};for(const[n,i]of Object.entries(e??{}))null!=i&&(t[n]="object"==typeof i?JSON.stringify(i):String(i));return t},contentData=e=>{const t=e.request.content;if(t.data)return toStringData(t.data);if("string"==typeof t.dataString)try{const e=JSON.parse(t.dataString);if(!isRecord(e))throw new Error("the notification data is not a JSON object");return toStringData(e)}catch(e){Logger.error("[push] notification data is not JSON",e)}return{}},triggerData=e=>{const t=e.request.trigger,n={...t?.remoteMessage?.data??{}};for(const[e,i]of Object.entries(t?.payload??{}))"aps"===e||"body"===e&&"object"==typeof i||(n[e]=i);return toStringData(n)},notificationData=e=>({...triggerData(e),...contentData(e)}),responseData=e=>notificationData(e.notification);export const toPushReceived=e=>({notificationId:e.request.identifier,title:e.request.content.title??null,body:e.request.content.body??null,data:notificationData(e)});export const toPushAction=e=>({actionId:e.actionIdentifier,...e.userText?{userText:e.userText}:{},data:responseData(e),notificationId:e.notification.request.identifier});export const toNotificationActions=e=>e.map(e=>({identifier:e.id,buttonTitle:e.title,...e.textInput?{textInput:{submitButtonTitle:e.textInput.submitTitle,placeholder:e.textInput.placeholder}}:{},options:{opensAppToForeground:e.opensApp??!0,isDestructive:e.destructive??!1,isAuthenticationRequired:e.authenticationRequired??!1}}));const routeResponse=async(e,t)=>{const n=`${t.notification.request.identifier}:${t.actionIdentifier}`,i=routedAt.get(n);if(void 0!==i&&Date.now()-i<1e4)return;if(t.actionIdentifier!==e.DEFAULT_ACTION_IDENTIFIER&&actionHandler){routedAt.set(n,Date.now());try{await actionHandler(toPushAction(t))}catch(e){Logger.error("[push] onAction threw",e)}}else if(config){routedAt.set(n,Date.now());try{config.onOpen(responseData(t))}catch(e){Logger.error("[push] onOpen threw",e)}}else pendingResponses.push(t)},drainPending=async e=>{const t=pendingResponses.splice(0);for(const n of t)await routeResponse(e,n)},listenForResponses=e=>{listening||(listening=!0,e.addNotificationResponseReceivedListener(t=>{routeResponse(e,t)}),e.getLastNotificationResponseAsync().then(async t=>(t&&await routeResponse(e,t),e.clearLastNotificationResponseAsync?.())).catch(e=>Logger.error("[push] reading the launch notification failed",e)))},isString=e=>"string"==typeof e,isStringOrNull=e=>null===e||"string"==typeof e,isRecordOrNull=e=>null===e||isRecord(e),optionalOf=(e,t)=>t(e)?e:void 0,remoteMessageOf=e=>isRecord(e)?{data:optionalOf(e.data,isRecordOrNull)}:void 0,toNotificationResponse=e=>{if(!isRecord(e))return null;const{actionIdentifier:t,userText:n,notification:i}=e;if(!isString(t)||!isRecord(i))return null;const{request:o}=i;if(!isRecord(o))return null;const{identifier:r,content:s,trigger:a}=o;return isString(r)&&isRecord(s)?{actionIdentifier:t,userText:optionalOf(n,isString),notification:{request:{identifier:r,content:{title:optionalOf(s.title,isStringOrNull),body:optionalOf(s.body,isStringOrNull),data:optionalOf(s.data,isRecordOrNull),dataString:optionalOf(s.dataString,isString)},trigger:isRecord(a)?{type:optionalOf(a.type,isString),payload:optionalOf(a.payload,isRecordOrNull),remoteMessage:remoteMessageOf(a.remoteMessage)}:void 0}}}:null};export const routeTaskPayload=async e=>{const t=resolveModules();if(!t)return;const n=toNotificationResponse(e);n&&await routeResponse(t.notifications,n)};const createChannels=async(e,t)=>{for(const n of t)try{await e.setNotificationChannelAsync(n.id,{name:n.name,importance:"high"===n.importance?e.AndroidImportance.HIGH:e.AndroidImportance.DEFAULT})}catch(e){Logger.error(`[push] creating channel ${n.id} failed`,e)}},APNS_ENVIRONMENTS={development:"Development",production:"Production"},readApnsEnvironment=async e=>{try{return APNS_ENVIRONMENTS[await e.getApnsEnvironment()??""]??null}catch(e){return Logger.warn("[push] reading the APNs environment failed",e),null}},deviceTimeZone=()=>Intl.DateTimeFormat().resolvedOptions().timeZone||null,toDevice=async(e,t)=>{const n="android"===e.type?"Fcm":"ios"===e.type?"Apns":null;if(!n||"string"!=typeof e.data)return null;if(!t.applicationId)throw new Error("[@webority/mobile-core] push needs the app bundle id from expo-application.");return{installationId:await requireConfig().getInstallationId(),platform:n,token:e.data,appId:t.applicationId,apnsEnvironment:"Apns"===n?await readApnsEnvironment(t):null,timeZone:deviceTimeZone()}};export const initPush=e=>{const t=null===config;if(config=e,!t)return;const n=resolveModules();if(!n)return void setState({status:"unavailable"});const i=n.notifications;i.setNotificationHandler({handleNotification:async e=>{const t=notificationData(e),n=config?.showInForeground?.(t)??!0;return{shouldShowBanner:n,shouldShowList:n,shouldPlaySound:n&&(config?.playSoundInForeground?.(t)??!0),shouldSetBadge:!0}}}),"android"===Platform.OS&&e.androidChannels?.length&&(channelsReady=createChannels(i,e.androidChannels)),listenForResponses(i),drainPending(i),i.getPermissionsAsync().then(e=>setState({status:toPermissionStatus(e)})).catch(e=>Logger.error("[push] permission check failed",e))};let registering=null,registeredKey=null,unregistering=null,tokenDrop=Promise.resolve();const registerOnce=e=>{const t=JSON.stringify(e);if(registering?.key===t)return registering.promise;const n=requireConfig().register(e).then(()=>{registeredKey=t,state.registrationError&&setState({registrationError:null})}).finally(()=>{registering?.promise===n&&(registering=null)});return registering={key:t,promise:n},n};export const enablePush=async({prompt:e=!0}={})=>{requireConfig();const t=resolveModules();if(!t)return setState({status:"unavailable"}),"unavailable";const n=t.notifications;await channelsReady,await tokenDrop;let i=await n.getPermissionsAsync();if(!i.granted&&e&&(i=await n.requestPermissionsAsync()),!i.granted){const e=toPermissionStatus(i);return setState({status:e}),e}const o=await toDevice(await n.getDevicePushTokenAsync(),t);return o?(await registerOnce(o),tokenSubscription?.remove(),tokenSubscription=n.addPushTokenListener(e=>{(unregistering??Promise.resolve()).then(()=>state.enabled?toDevice(e,t):null).then(e=>e&&JSON.stringify(e)!==registeredKey?registerOnce(e):void 0).catch(e=>{Logger.error("[push] re-registering a new token failed",e),setState({registrationError:e instanceof Error?e:new Error(String(e))})})}),setState({status:"granted",enabled:!0}),"granted"):(setState({status:"unavailable"}),"unavailable")};export const readDevicePushToken=async()=>{const e=resolveModules();if(!e)return null;await tokenDrop;if(!(await e.notifications.getPermissionsAsync()).granted)return null;const t=await e.notifications.getDevicePushTokenAsync(),n="android"===t.type?"android":"ios"===t.type?"ios":null;return n&&"string"==typeof t.data?{platform:n,token:t.data}:null};const stopFollowingToken=()=>{tokenSubscription?.remove(),tokenSubscription=null,registeredKey=null,setState({enabled:!1,registrationError:null})};export const disablePush=async()=>{const e=requireConfig(),t=await e.getInstallationId();await Promise.allSettled([registering?.promise]);let settle=()=>{};const n=new Promise(e=>{settle=e});unregistering=n;try{await e.unregister(t),stopFollowingToken()}finally{unregistering===n&&(unregistering=null),settle()}};export const resetPush=async()=>{stopFollowingToken();const e=resolveModules();if(!e)return;const t=e.notifications.unregisterForNotificationsAsync();tokenDrop=Promise.allSettled([t]),await t};export const setBadgeCount=async e=>{const t=resolveModules();t&&await t.notifications.setBadgeCountAsync(e)};export const dismissAllNotifications=async()=>{const e=resolveModules();if(e)try{await e.notifications.dismissAllNotificationsAsync()}catch(e){Logger.warn("[push] dismissing the notifications failed",e)}};export const setCategories=async e=>{const t=resolveModules();if(t)for(const n of e)await t.notifications.setNotificationCategoryAsync(n.id,toNotificationActions(n.actions))};export const onAction=e=>{actionHandler=e;const t=resolveModules();return t&&(listenForResponses(t.notifications),drainPending(t.notifications)),()=>{actionHandler===e&&(actionHandler=null)}};export const onReceive=e=>{receiveHandlers.add(e);const t=resolveModules();return t&&!listeningForReceived&&(listeningForReceived=!0,t.notifications.addNotificationReceivedListener(e=>{const t=toPushReceived(e);for(const e of[...receiveHandlers])try{e(t)}catch(e){Logger.error("[push] onReceive threw",e)}})),()=>{receiveHandlers.delete(e)}};export const notifyLocal=async({title:e,body:t,data:n})=>{const i=resolveModules();i&&await i.notifications.scheduleNotificationAsync({content:{title:e,body:t,data:n??{}},trigger:null})};const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,enable=async()=>{await enablePush()};export const usePush=()=>({...useSyncExternalStore(subscribe,getSnapshot,getSnapshot),enable:enable,disable:disablePush});
|
|
@@ -50,10 +50,10 @@ export interface PushConfig {
|
|
|
50
50
|
onOpen: (data: Record<string, string>) => void;
|
|
51
51
|
/** Only for channels the app does not create natively. */
|
|
52
52
|
androidChannels?: PushAndroidChannel[] | undefined;
|
|
53
|
-
/** Whether a notification arriving while the app is open is shown. Defaults to true. */
|
|
54
|
-
showInForeground?: (() => boolean) | undefined;
|
|
55
|
-
/** Whether a notification shown while the app is open plays its sound. Defaults to true. */
|
|
56
|
-
playSoundInForeground?: (() => boolean) | undefined;
|
|
53
|
+
/** Whether a notification arriving while the app is open is shown, given that notification's data. Defaults to true. */
|
|
54
|
+
showInForeground?: ((data: Record<string, string>) => boolean) | undefined;
|
|
55
|
+
/** Whether a notification shown while the app is open plays its sound, given that notification's data. Defaults to true. */
|
|
56
|
+
playSoundInForeground?: ((data: Record<string, string>) => boolean) | undefined;
|
|
57
57
|
}
|
|
58
58
|
/** A button on a notification category. */
|
|
59
59
|
export interface PushCategoryAction {
|
|
@@ -160,7 +160,7 @@ export interface PushNotificationsLike {
|
|
|
160
160
|
getLastNotificationResponseAsync: () => Promise<NotificationResponseLike | null>;
|
|
161
161
|
clearLastNotificationResponseAsync?: (() => Promise<void>) | undefined;
|
|
162
162
|
setNotificationHandler: (handler: {
|
|
163
|
-
handleNotification: () => Promise<{
|
|
163
|
+
handleNotification: (notification: NotificationLike) => Promise<{
|
|
164
164
|
shouldShowBanner: boolean;
|
|
165
165
|
shouldShowList: boolean;
|
|
166
166
|
shouldPlaySound: boolean;
|
|
@@ -50,10 +50,10 @@ export interface PushConfig {
|
|
|
50
50
|
onOpen: (data: Record<string, string>) => void;
|
|
51
51
|
/** Only for channels the app does not create natively. */
|
|
52
52
|
androidChannels?: PushAndroidChannel[] | undefined;
|
|
53
|
-
/** Whether a notification arriving while the app is open is shown. Defaults to true. */
|
|
54
|
-
showInForeground?: (() => boolean) | undefined;
|
|
55
|
-
/** Whether a notification shown while the app is open plays its sound. Defaults to true. */
|
|
56
|
-
playSoundInForeground?: (() => boolean) | undefined;
|
|
53
|
+
/** Whether a notification arriving while the app is open is shown, given that notification's data. Defaults to true. */
|
|
54
|
+
showInForeground?: ((data: Record<string, string>) => boolean) | undefined;
|
|
55
|
+
/** Whether a notification shown while the app is open plays its sound, given that notification's data. Defaults to true. */
|
|
56
|
+
playSoundInForeground?: ((data: Record<string, string>) => boolean) | undefined;
|
|
57
57
|
}
|
|
58
58
|
/** A button on a notification category. */
|
|
59
59
|
export interface PushCategoryAction {
|
|
@@ -160,7 +160,7 @@ export interface PushNotificationsLike {
|
|
|
160
160
|
getLastNotificationResponseAsync: () => Promise<NotificationResponseLike | null>;
|
|
161
161
|
clearLastNotificationResponseAsync?: (() => Promise<void>) | undefined;
|
|
162
162
|
setNotificationHandler: (handler: {
|
|
163
|
-
handleNotification: () => Promise<{
|
|
163
|
+
handleNotification: (notification: NotificationLike) => Promise<{
|
|
164
164
|
shouldShowBanner: boolean;
|
|
165
165
|
shouldShowList: boolean;
|
|
166
166
|
shouldPlaySound: boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/mobile-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.184.0",
|
|
4
4
|
"description": "Platform layer for Webority React Native apps: HTTP clients, auth/token storage, config, logging, formatters, validators, network status, permissions, storage, version checks and over-the-air updates. No UI.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react-native",
|
|
@@ -404,7 +404,7 @@
|
|
|
404
404
|
}
|
|
405
405
|
},
|
|
406
406
|
"dependencies": {
|
|
407
|
-
"@webority/api-contract": "0.
|
|
407
|
+
"@webority/api-contract": "0.184.0",
|
|
408
408
|
"axios": "^1.19.0",
|
|
409
409
|
"libphonenumber-js": "^1.12.41"
|
|
410
410
|
},
|