@knocklabs/client 0.18.1 → 0.18.3
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/CHANGELOG.md +14 -0
- package/dist/cjs/api.js +1 -1
- package/dist/cjs/clients/feed/feed.js +1 -1
- package/dist/cjs/clients/feed/feed.js.map +1 -1
- package/dist/esm/api.mjs +1 -1
- package/dist/esm/clients/feed/feed.mjs +196 -177
- package/dist/esm/clients/feed/feed.mjs.map +1 -1
- package/dist/types/clients/feed/feed.d.ts.map +1 -1
- package/dist/types/clients/messages/interfaces.d.ts +1 -0
- package/dist/types/clients/messages/interfaces.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/clients/feed/feed.ts +40 -3
- package/src/clients/messages/interfaces.ts +1 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.18.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 9f0d317: fix(KNO-9711) Add step_ref to NotificationSource
|
|
8
|
+
|
|
9
|
+
Add optional nullable field corresponding to API spec
|
|
10
|
+
|
|
11
|
+
## 0.18.2
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- 1fc802b: fix(feed): optimistically update when unarchiving an item
|
|
16
|
+
|
|
3
17
|
## 0.18.1
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
package/dist/cjs/api.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var a=Object.defineProperty;var n=(t,e,s)=>e in t?a(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var r=(t,e,s)=>n(t,typeof e!="symbol"?e+"":e,s);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("axios"),l=require("axios-retry"),c=require("phoenix"),i=t=>t&&typeof t=="object"&&"default"in t?t:{default:t},d=i(u),o=i(l);class h{constructor(e){r(this,"host");r(this,"apiKey");r(this,"userToken");r(this,"axiosClient");r(this,"socket");this.host=e.host,this.apiKey=e.apiKey,this.userToken=e.userToken||null,this.axiosClient=d.default.create({baseURL:this.host,headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-Knock-User-Token":this.userToken,"X-Knock-Client":this.getKnockClientHeader()}}),typeof window<"u"&&(this.socket=new c.Socket(`${this.host.replace("http","ws")}/ws/v1`,{params:{user_token:this.userToken,api_key:this.apiKey}})),o.default(this.axiosClient,{retries:3,retryCondition:this.canRetryRequest,retryDelay:o.default.exponentialDelay})}async makeRequest(e){try{const s=await this.axiosClient(e);return{statusCode:s.status<300?"ok":"error",body:s.data,error:void 0,status:s.status}}catch(s){return console.error(s),{statusCode:"error",status:500,body:void 0,error:s}}}canRetryRequest(e){return o.default.isNetworkError(e)?!0:e.response?e.response.status>=500&&e.response.status<=599||e.response.status===429:!1}getKnockClientHeader(){return"Knock/ClientJS 0.18.
|
|
1
|
+
"use strict";var a=Object.defineProperty;var n=(t,e,s)=>e in t?a(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var r=(t,e,s)=>n(t,typeof e!="symbol"?e+"":e,s);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("axios"),l=require("axios-retry"),c=require("phoenix"),i=t=>t&&typeof t=="object"&&"default"in t?t:{default:t},d=i(u),o=i(l);class h{constructor(e){r(this,"host");r(this,"apiKey");r(this,"userToken");r(this,"axiosClient");r(this,"socket");this.host=e.host,this.apiKey=e.apiKey,this.userToken=e.userToken||null,this.axiosClient=d.default.create({baseURL:this.host,headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-Knock-User-Token":this.userToken,"X-Knock-Client":this.getKnockClientHeader()}}),typeof window<"u"&&(this.socket=new c.Socket(`${this.host.replace("http","ws")}/ws/v1`,{params:{user_token:this.userToken,api_key:this.apiKey}})),o.default(this.axiosClient,{retries:3,retryCondition:this.canRetryRequest,retryDelay:o.default.exponentialDelay})}async makeRequest(e){try{const s=await this.axiosClient(e);return{statusCode:s.status<300?"ok":"error",body:s.data,error:void 0,status:s.status}}catch(s){return console.error(s),{statusCode:"error",status:500,body:void 0,error:s}}}canRetryRequest(e){return o.default.isNetworkError(e)?!0:e.response?e.response.status>=500&&e.response.status<=599||e.response.status===429:!1}getKnockClientHeader(){return"Knock/ClientJS 0.18.3"}}exports.default=h;
|
|
2
2
|
//# sourceMappingURL=api.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var g=Object.defineProperty;var p=(c,e,t)=>e in c?g(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var d=(c,e,t)=>p(c,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),_=require("nanoid"),v=require("../../helpers.js"),m=require("../../networkStatus.js"),S=require("./socket-manager.js"),y=require("./store.js"),f=require("./utils.js"),b=c=>c&&typeof c=="object"&&"default"in c?c:{default:c},w=b(k),I={archived:"exclude"},C=2e3,U="client_";class A{constructor(e,t,s,a){d(this,"defaultOptions");d(this,"referenceId");d(this,"unsubscribeFromSocketEvents");d(this,"socketManager");d(this,"userFeedId");d(this,"broadcaster");d(this,"broadcastChannel");d(this,"disconnectTimer",null);d(this,"hasSubscribedToRealTimeUpdates",!1);d(this,"visibilityChangeHandler",()=>{});d(this,"visibilityChangeListenerConnected",!1);d(this,"store");this.knock=e,this.feedId=t,(!t||!v.isValidUuid(t))&&this.knock.log("[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.",!0),this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.referenceId=U+_.nanoid(),this.socketManager=a,this.store=y.default(),this.broadcaster=new w.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...I,...f.mergeDateRangeParams(s)},this.knock.log(`[Feed] Initialized a feed on channel ${t}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(e){this.socketManager=e,this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){var e;this.knock.log("[Feed] Tearing down feed instance"),(e=this.socketManager)==null||e.leave(this),this.tearDownVisibilityListeners(),this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.broadcastChannel&&this.broadcastChannel.close()}dispose(){this.knock.log("[Feed] Disposing of feed instance"),this.teardown(),this.broadcaster.removeAllListeners(),this.knock.feeds.removeInstance(this)}listenForUpdates(){var e;if(this.knock.log("[Feed] Connecting to real-time service"),this.hasSubscribedToRealTimeUpdates=!0,!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping listening for updates");return}this.unsubscribeFromSocketEvents=(e=this.socketManager)==null?void 0:e.join(this)}on(e,t){this.broadcaster.on(e,t)}off(e,t){this.broadcaster.off(e,t)}getState(){return this.store.getState()}async markAsSeen(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"seen",{seen_at:t},"unseen_count"),this.makeStatusUpdate(e,"seen")}async markAllAsSeen(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unseen")s.resetStore({...e,total_count:0,unseen_count:0});else{s.setMetadata({...e,unseen_count:0});const n={seen_at:new Date().toISOString()},i=t.map(o=>o.id);s.setItemAttrs(i,n)}const r=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),r}async markAsUnseen(e){return this.optimisticallyPerformStatusUpdate(e,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(e,"unseen")}async markAsRead(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"read",{read_at:t},"unread_count"),this.makeStatusUpdate(e,"read")}async markAllAsRead(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...e,total_count:0,unread_count:0});else{s.setMetadata({...e,unread_count:0});const n={read_at:new Date().toISOString()},i=t.map(o=>o.id);s.setItemAttrs(i,n)}const r=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),r}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e,t){const s=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:s,interacted_at:s},"unread_count"),this.makeStatusUpdate(e,"interacted",t)}async markAsArchived(e){const t=this.store.getState(),s=this.defaultOptions.archived==="exclude",a=Array.isArray(e)?e:[e],r=a.map(n=>n.id);if(s){const n=a.filter(u=>!u.seen_at).length,i=a.filter(u=>!u.read_at).length,o={...t.metadata,total_count:Math.max(0,t.metadata.total_count-a.length),unseen_count:Math.max(0,t.metadata.unseen_count-n),unread_count:Math.max(0,t.metadata.unread_count-i)},l=t.items.filter(u=>!r.includes(u.id));t.setResult({entries:l,meta:o,page_info:t.pageInfo})}else t.setItemAttrs(r,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{items:e,...t}=this.store.getState();if(this.defaultOptions.archived==="exclude")t.resetStore();else{const r=e.map(n=>n.id);t.setItemAttrs(r,{archived_at:new Date().toISOString()})}const a=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),a}async markAllReadAsArchived(){const{items:e,...t}=this.store.getState(),a=e.filter(i=>i.read_at===null).map(i=>i.id);if(t.setItemAttrs(a,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const i=e.filter(l=>!a.includes(l.id)),o={...t.metadata,total_count:i.length,unread_count:0};t.setResult({entries:i,meta:o,page_info:t.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{networkStatus:t,...s}=this.store.getState();if(!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping fetch");return}if(m.isRequestInFlight(t)){this.knock.log("[Feed] Request is in flight, skipping fetch");return}s.setNetworkStatus(e.__loadingType??m.NetworkStatus.loading);const a=f.getFormattedTriggerData({...this.defaultOptions,...e}),r={...this.defaultOptions,...f.mergeDateRangeParams(e),trigger_data:a,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},n=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:r});if(n.statusCode==="error"||!n.body)return s.setNetworkStatus(m.NetworkStatus.error),{status:n.statusCode,data:n.error||n.body};const i={entries:n.body.entries,meta:n.body.meta,page_info:n.body.page_info};if(e.before){const u={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,u)}else if(e.after){const u={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,u)}else s.setResult(i);this.broadcast("messages.new",i);const o=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",l={items:i.entries,metadata:i.meta,event:o};return this.broadcast(l.event,l),{data:i,status:n.statusCode}}async fetchNextPage(e={}){const{pageInfo:t}=this.store.getState();t.after&&this.fetch({...e,after:t.after,__loadingType:m.NetworkStatus.fetchMore})}get socketChannelTopic(){return`feeds:${this.userFeedId}`}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({data:e}){var n;this.knock.log("[Feed] Received new real-time message");const{items:t,...s}=this.store.getState(),a=t[0],r=(n=e[this.referenceId])==null?void 0:n.metadata;r&&s.setMetadata(r),this.fetch({before:a==null?void 0:a.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,a){const r=this.store.getState(),n=Array.isArray(e)?e:[e],i=n.map(o=>o.id);if(a){const{metadata:o}=r,l=n.filter(h=>{switch(t){case"seen":return h.seen_at===null;case"unseen":return h.seen_at!==null;case"read":case"interacted":return h.read_at===null;case"unread":return h.read_at!==null;default:return!0}}),u=t.startsWith("un")?l.length:-l.length;r.setMetadata({...o,[a]:Math.max(0,o[a]+u)})}r.setItemAttrs(i,s)}async makeStatusUpdate(e,t,s){const a=Array.isArray(e)?e:[e],r=a.map(i=>i.id),n=await this.knock.messages.batchUpdateStatuses(r,t,{metadata:s});return this.emitEvent(t,a),n}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=e=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:s})}catch(s){console.warn(`Could not broadcast ${e}, got error: ${s}`)}}initializeRealtimeConnection(){var e;this.socketManager&&(this.defaultOptions.auto_manage_socket_connection&&this.setUpVisibilityListeners(),this.hasSubscribedToRealTimeUpdates&&this.knock.isAuthenticated()&&(this.unsubscribeFromSocketEvents=(e=this.socketManager)==null?void 0:e.join(this)))}async handleSocketEvent(e){switch(e.event){case S.SocketEventType.NewMessage:this.onNewMessageReceived(e);return;default:{e.event;return}}}setUpVisibilityListeners(){typeof document>"u"||this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}tearDownVisibilityListeners(){typeof document>"u"||(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeListenerConnected=!1)}emitEvent(e,t){this.broadcaster.emit(`items.${e}`,{items:t}),this.broadcaster.emit(`items:${e}`,{items:t}),this.broadcastOverChannel(`items:${e}`,{items:t})}handleVisibilityChange(){var s,a;const e=this.defaultOptions.auto_manage_socket_connection_delay??C,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var r;(r=t.socket)==null||r.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=t.socket)!=null&&s.isConnected()||(a=t.socket)==null||a.connect())}}exports.default=A;
|
|
1
|
+
"use strict";var g=Object.defineProperty;var p=(u,e,t)=>e in u?g(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var c=(u,e,t)=>p(u,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),_=require("nanoid"),v=require("../../helpers.js"),m=require("../../networkStatus.js"),S=require("./socket-manager.js"),y=require("./store.js"),f=require("./utils.js"),b=u=>u&&typeof u=="object"&&"default"in u?u:{default:u},I=b(k),w={archived:"exclude"},C=2e3,U="client_";class A{constructor(e,t,s,n){c(this,"defaultOptions");c(this,"referenceId");c(this,"unsubscribeFromSocketEvents");c(this,"socketManager");c(this,"userFeedId");c(this,"broadcaster");c(this,"broadcastChannel");c(this,"disconnectTimer",null);c(this,"hasSubscribedToRealTimeUpdates",!1);c(this,"visibilityChangeHandler",()=>{});c(this,"visibilityChangeListenerConnected",!1);c(this,"store");this.knock=e,this.feedId=t,(!t||!v.isValidUuid(t))&&this.knock.log("[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.",!0),this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.referenceId=U+_.nanoid(),this.socketManager=n,this.store=y.default(),this.broadcaster=new I.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...w,...f.mergeDateRangeParams(s)},this.knock.log(`[Feed] Initialized a feed on channel ${t}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(e){this.socketManager=e,this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){var e;this.knock.log("[Feed] Tearing down feed instance"),(e=this.socketManager)==null||e.leave(this),this.tearDownVisibilityListeners(),this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.broadcastChannel&&this.broadcastChannel.close()}dispose(){this.knock.log("[Feed] Disposing of feed instance"),this.teardown(),this.broadcaster.removeAllListeners(),this.knock.feeds.removeInstance(this)}listenForUpdates(){var e;if(this.knock.log("[Feed] Connecting to real-time service"),this.hasSubscribedToRealTimeUpdates=!0,!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping listening for updates");return}this.unsubscribeFromSocketEvents=(e=this.socketManager)==null?void 0:e.join(this)}on(e,t){this.broadcaster.on(e,t)}off(e,t){this.broadcaster.off(e,t)}getState(){return this.store.getState()}async markAsSeen(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"seen",{seen_at:t},"unseen_count"),this.makeStatusUpdate(e,"seen")}async markAllAsSeen(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unseen")s.resetStore({...e,total_count:0,unseen_count:0});else{s.setMetadata({...e,unseen_count:0});const a={seen_at:new Date().toISOString()},i=t.map(d=>d.id);s.setItemAttrs(i,a)}const r=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),r}async markAsUnseen(e){return this.optimisticallyPerformStatusUpdate(e,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(e,"unseen")}async markAsRead(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"read",{read_at:t},"unread_count"),this.makeStatusUpdate(e,"read")}async markAllAsRead(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...e,total_count:0,unread_count:0});else{s.setMetadata({...e,unread_count:0});const a={read_at:new Date().toISOString()},i=t.map(d=>d.id);s.setItemAttrs(i,a)}const r=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),r}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e,t){const s=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:s,interacted_at:s},"unread_count"),this.makeStatusUpdate(e,"interacted",t)}async markAsArchived(e){const t=this.store.getState(),s=this.defaultOptions.archived==="exclude",n=Array.isArray(e)?e:[e],r=n.map(a=>a.id);if(s){const a=n.filter(o=>!o.seen_at).length,i=n.filter(o=>!o.read_at).length,d={...t.metadata,total_count:Math.max(0,t.metadata.total_count-n.length),unseen_count:Math.max(0,t.metadata.unseen_count-a),unread_count:Math.max(0,t.metadata.unread_count-i)},l=t.items.filter(o=>!r.includes(o.id));t.setResult({entries:l,meta:d,page_info:t.pageInfo})}else t.setItemAttrs(r,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{items:e,...t}=this.store.getState();if(this.defaultOptions.archived==="exclude")t.resetStore();else{const r=e.map(a=>a.id);t.setItemAttrs(r,{archived_at:new Date().toISOString()})}const n=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),n}async markAllReadAsArchived(){const{items:e,...t}=this.store.getState(),n=e.filter(i=>i.read_at===null).map(i=>i.id);if(t.setItemAttrs(n,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const i=e.filter(l=>!n.includes(l.id)),d={...t.metadata,total_count:i.length,unread_count:0};t.setResult({entries:i,meta:d,page_info:t.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(e){const t=this.store.getState(),s=Array.isArray(e)?e:[e],n=s.map(a=>a.id);if(this.defaultOptions.archived==="only"){const a=s.filter(o=>!o.seen_at).length,i=s.filter(o=>!o.read_at).length,d={...t.metadata,total_count:Math.max(0,t.metadata.total_count-s.length),unseen_count:Math.max(0,t.metadata.unseen_count-a),unread_count:Math.max(0,t.metadata.unread_count-i)},l=t.items.filter(o=>!n.includes(o.id));t.setResult({entries:l,meta:d,page_info:t.pageInfo})}else this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null});return this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{networkStatus:t,...s}=this.store.getState();if(!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping fetch");return}if(m.isRequestInFlight(t)){this.knock.log("[Feed] Request is in flight, skipping fetch");return}s.setNetworkStatus(e.__loadingType??m.NetworkStatus.loading);const n=f.getFormattedTriggerData({...this.defaultOptions,...e}),r={...this.defaultOptions,...f.mergeDateRangeParams(e),trigger_data:n,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},a=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:r});if(a.statusCode==="error"||!a.body)return s.setNetworkStatus(m.NetworkStatus.error),{status:a.statusCode,data:a.error||a.body};const i={entries:a.body.entries,meta:a.body.meta,page_info:a.body.page_info};if(e.before){const o={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,o)}else if(e.after){const o={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,o)}else s.setResult(i);this.broadcast("messages.new",i);const d=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",l={items:i.entries,metadata:i.meta,event:d};return this.broadcast(l.event,l),{data:i,status:a.statusCode}}async fetchNextPage(e={}){const{pageInfo:t}=this.store.getState();t.after&&this.fetch({...e,after:t.after,__loadingType:m.NetworkStatus.fetchMore})}get socketChannelTopic(){return`feeds:${this.userFeedId}`}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({data:e}){var a;this.knock.log("[Feed] Received new real-time message");const{items:t,...s}=this.store.getState(),n=t[0],r=(a=e[this.referenceId])==null?void 0:a.metadata;r&&s.setMetadata(r),this.fetch({before:n==null?void 0:n.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,n){const r=this.store.getState(),a=Array.isArray(e)?e:[e],i=a.map(d=>d.id);if(n){const{metadata:d}=r,l=a.filter(h=>{switch(t){case"seen":return h.seen_at===null;case"unseen":return h.seen_at!==null;case"read":case"interacted":return h.read_at===null;case"unread":return h.read_at!==null;default:return!0}}),o=t.startsWith("un")?l.length:-l.length;r.setMetadata({...d,[n]:Math.max(0,d[n]+o)})}r.setItemAttrs(i,s)}async makeStatusUpdate(e,t,s){const n=Array.isArray(e)?e:[e],r=n.map(i=>i.id),a=await this.knock.messages.batchUpdateStatuses(r,t,{metadata:s});return this.emitEvent(t,n),a}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=e=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:s})}catch(s){console.warn(`Could not broadcast ${e}, got error: ${s}`)}}initializeRealtimeConnection(){var e;this.socketManager&&(this.defaultOptions.auto_manage_socket_connection&&this.setUpVisibilityListeners(),this.hasSubscribedToRealTimeUpdates&&this.knock.isAuthenticated()&&(this.unsubscribeFromSocketEvents=(e=this.socketManager)==null?void 0:e.join(this)))}async handleSocketEvent(e){switch(e.event){case S.SocketEventType.NewMessage:this.onNewMessageReceived(e);return;default:{e.event;return}}}setUpVisibilityListeners(){typeof document>"u"||this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}tearDownVisibilityListeners(){typeof document>"u"||(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeListenerConnected=!1)}emitEvent(e,t){this.broadcaster.emit(`items.${e}`,{items:t}),this.broadcaster.emit(`items:${e}`,{items:t}),this.broadcastOverChannel(`items:${e}`,{items:t})}handleVisibilityChange(){var s,n;const e=this.defaultOptions.auto_manage_socket_connection_delay??C,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var r;(r=t.socket)==null||r.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=t.socket)!=null&&s.isConnected()||(n=t.socket)==null||n.connect())}}exports.default=A;
|
|
2
2
|
//# sourceMappingURL=feed.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed.js","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { nanoid } from \"nanoid\";\n\nimport { isValidUuid } from \"../../helpers\";\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport {\n FeedSocketManager,\n SocketEventPayload,\n SocketEventType,\n} from \"./socket-manager\";\nimport createStore, { FeedStore } from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nconst CLIENT_REF_ID_PREFIX = \"client_\";\n\nclass Feed {\n public readonly defaultOptions: FeedClientOptions;\n public readonly referenceId: string;\n public unsubscribeFromSocketEvents: (() => void) | undefined = undefined;\n private socketManager: FeedSocketManager | undefined;\n private userFeedId: string;\n private broadcaster: EventEmitter;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: FeedStore;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n socketManager: FeedSocketManager | undefined,\n ) {\n if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.referenceId = CLIENT_REF_ID_PREFIX + nanoid();\n this.socketManager = socketManager;\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize(socketManager?: FeedSocketManager) {\n this.socketManager = socketManager;\n\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n this.socketManager?.leave(this);\n\n this.tearDownVisibilityListeners();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n get socketChannelTopic(): string {\n return `feeds:${this.userFeedId}`;\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({ data }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n\n // Optimistically set the badge counts\n const metadata = data[this.referenceId]?.metadata;\n if (metadata) {\n state.setMetadata(metadata);\n }\n\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // This is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n // In server environments we might not have a socket connection\n if (!this.socketManager) return;\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setUpVisibilityListeners();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n }\n\n async handleSocketEvent(payload: SocketEventPayload) {\n switch (payload.event) {\n case SocketEventType.NewMessage:\n this.onNewMessageReceived(payload);\n return;\n default: {\n const _exhaustiveCheck: never = payload.event;\n return;\n }\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setUpVisibilityListeners() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private tearDownVisibilityListeners() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n client.socket?.connect();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","CLIENT_REF_ID_PREFIX","Feed","knock","feedId","options","socketManager","__publicField","isValidUuid","nanoid","createStore","EventEmitter","mergeDateRangeParams","_a","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","SocketEventType","disconnectDelay","client","_b"],"mappings":"uhBAsCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAE3BC,EAAuB,UAE7B,MAAMC,CAAK,CAgBT,YACWC,EACAC,EACTC,EACAC,EACA,CApBcC,EAAA,uBACAA,EAAA,oBACTA,EAAA,oCACCA,EAAA,sBACAA,EAAA,mBACAA,EAAA,oBACAA,EAAA,yBACAA,EAAA,uBAAwD,MACxDA,EAAA,sCAA0C,IAC1CA,EAAA,+BAAsC,IAAM,CAAC,GAC7CA,EAAA,yCAA6C,IAG9CA,EAAA,cAGI,KAAA,MAAAJ,EACA,KAAA,OAAAC,GAIL,CAACA,GAAU,CAACI,EAAA,YAAYJ,CAAM,IAChC,KAAK,MAAM,IACT,8NACA,EACF,EAGF,KAAK,OAASA,EACT,KAAA,WAAa,KAAK,gBAAgB,EAClC,KAAA,YAAcH,EAAuBQ,SAAO,EACjD,KAAK,cAAgBH,EACrB,KAAK,MAAQI,UAAY,EACpB,KAAA,YAAc,IAAIC,UAAa,CAAE,SAAU,GAAM,UAAW,IAAK,EACtE,KAAK,eAAiB,CACpB,GAAGZ,EACH,GAAGa,uBAAqBP,CAAO,CACjC,EACA,KAAK,MAAM,IAAI,wCAAwCD,CAAM,EAAE,EAG/D,KAAK,6BAA6B,EAElC,KAAK,sBAAsB,CAAA,CAM7B,aAAaE,EAAmC,CAC9C,KAAK,cAAgBA,EAGhB,KAAA,WAAa,KAAK,gBAAgB,EAGvC,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AD,EAAO,SAAP,MAAAC,EAAe,UAEnB,CAEJ"}
|
|
1
|
+
{"version":3,"file":"feed.js","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { nanoid } from \"nanoid\";\n\nimport { isValidUuid } from \"../../helpers\";\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport {\n FeedSocketManager,\n SocketEventPayload,\n SocketEventType,\n} from \"./socket-manager\";\nimport createStore, { FeedStore } from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nconst CLIENT_REF_ID_PREFIX = \"client_\";\n\nclass Feed {\n public readonly defaultOptions: FeedClientOptions;\n public readonly referenceId: string;\n public unsubscribeFromSocketEvents: (() => void) | undefined = undefined;\n private socketManager: FeedSocketManager | undefined;\n private userFeedId: string;\n private broadcaster: EventEmitter;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: FeedStore;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n socketManager: FeedSocketManager | undefined,\n ) {\n if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.referenceId = CLIENT_REF_ID_PREFIX + nanoid();\n this.socketManager = socketManager;\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize(socketManager?: FeedSocketManager) {\n this.socketManager = socketManager;\n\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n this.socketManager?.leave(this);\n\n this.tearDownVisibilityListeners();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"only\";\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on unarchiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the unarchived entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n get socketChannelTopic(): string {\n return `feeds:${this.userFeedId}`;\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({ data }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n\n // Optimistically set the badge counts\n const metadata = data[this.referenceId]?.metadata;\n if (metadata) {\n state.setMetadata(metadata);\n }\n\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // This is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n // In server environments we might not have a socket connection\n if (!this.socketManager) return;\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setUpVisibilityListeners();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n }\n\n async handleSocketEvent(payload: SocketEventPayload) {\n switch (payload.event) {\n case SocketEventType.NewMessage:\n this.onNewMessageReceived(payload);\n return;\n default: {\n const _exhaustiveCheck: never = payload.event;\n return;\n }\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setUpVisibilityListeners() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private tearDownVisibilityListeners() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n client.socket?.connect();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","CLIENT_REF_ID_PREFIX","Feed","knock","feedId","options","socketManager","__publicField","isValidUuid","nanoid","createStore","EventEmitter","mergeDateRangeParams","_a","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","SocketEventType","disconnectDelay","client","_b"],"mappings":"uhBAsCMA,EAA0D,CAC9D,SAAU,SACZ,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pBvD,EAEIwD,EAAS,KAAK,MAAM,OAAO,EAE7B,SAAS,kBAAoB,SAE1B,KAAA,gBAAkB,WAAW,IAAM,QACtC3C,EAAA2C,EAAO,SAAP,MAAA3C,EAAe,aACf,KAAK,gBAAkB,MACtB0C,CAAe,EACT,SAAS,kBAAoB,YAGlC,KAAK,kBACP,aAAa,KAAK,eAAe,EACjC,KAAK,gBAAkB,OAIpB1C,EAAA2C,EAAO,SAAP,MAAA3C,EAAe,gBAClB4C,EAAAD,EAAO,SAAP,MAAAC,EAAe,UAEnB,CAEJ"}
|
package/dist/esm/api.mjs
CHANGED
|
@@ -53,7 +53,7 @@ class k {
|
|
|
53
53
|
return o.isNetworkError(e) ? !0 : e.response ? e.response.status >= 500 && e.response.status <= 599 || e.response.status === 429 : !1;
|
|
54
54
|
}
|
|
55
55
|
getKnockClientHeader() {
|
|
56
|
-
return "Knock/ClientJS 0.18.
|
|
56
|
+
return "Knock/ClientJS 0.18.3";
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
59
|
export {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
var p = Object.defineProperty;
|
|
2
|
-
var g = (u,
|
|
3
|
-
var
|
|
2
|
+
var g = (u, t, e) => t in u ? p(u, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : u[t] = e;
|
|
3
|
+
var c = (u, t, e) => g(u, typeof t != "symbol" ? t + "" : t, e);
|
|
4
4
|
import k from "eventemitter2";
|
|
5
5
|
import { nanoid as _ } from "nanoid";
|
|
6
6
|
import { isValidUuid as v } from "../../helpers.mjs";
|
|
@@ -8,46 +8,46 @@ import { isRequestInFlight as S, NetworkStatus as m } from "../../networkStatus.
|
|
|
8
8
|
import { SocketEventType as y } from "./socket-manager.mjs";
|
|
9
9
|
import b from "./store.mjs";
|
|
10
10
|
import { mergeDateRangeParams as f, getFormattedTriggerData as I } from "./utils.mjs";
|
|
11
|
-
const
|
|
11
|
+
const C = {
|
|
12
12
|
archived: "exclude"
|
|
13
|
-
},
|
|
13
|
+
}, U = 2e3, w = "client_";
|
|
14
14
|
class P {
|
|
15
|
-
constructor(
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
15
|
+
constructor(t, e, s, n) {
|
|
16
|
+
c(this, "defaultOptions");
|
|
17
|
+
c(this, "referenceId");
|
|
18
|
+
c(this, "unsubscribeFromSocketEvents");
|
|
19
|
+
c(this, "socketManager");
|
|
20
|
+
c(this, "userFeedId");
|
|
21
|
+
c(this, "broadcaster");
|
|
22
|
+
c(this, "broadcastChannel");
|
|
23
|
+
c(this, "disconnectTimer", null);
|
|
24
|
+
c(this, "hasSubscribedToRealTimeUpdates", !1);
|
|
25
|
+
c(this, "visibilityChangeHandler", () => {
|
|
26
26
|
});
|
|
27
|
-
|
|
27
|
+
c(this, "visibilityChangeListenerConnected", !1);
|
|
28
28
|
// The raw store instance, used for binding in React and other environments
|
|
29
|
-
|
|
30
|
-
this.knock =
|
|
29
|
+
c(this, "store");
|
|
30
|
+
this.knock = t, this.feedId = e, (!e || !v(e)) && this.knock.log(
|
|
31
31
|
"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.",
|
|
32
32
|
!0
|
|
33
|
-
), this.feedId =
|
|
34
|
-
...
|
|
33
|
+
), this.feedId = e, this.userFeedId = this.buildUserFeedId(), this.referenceId = w + _(), this.socketManager = n, this.store = b(), this.broadcaster = new k({ wildcard: !0, delimiter: "." }), this.defaultOptions = {
|
|
34
|
+
...C,
|
|
35
35
|
...f(s)
|
|
36
|
-
}, this.knock.log(`[Feed] Initialized a feed on channel ${
|
|
36
|
+
}, this.knock.log(`[Feed] Initialized a feed on channel ${e}`), this.initializeRealtimeConnection(), this.setupBroadcastChannel();
|
|
37
37
|
}
|
|
38
38
|
/**
|
|
39
39
|
* Used to reinitialize a current feed instance, which is useful when reauthenticating users
|
|
40
40
|
*/
|
|
41
|
-
reinitialize(
|
|
42
|
-
this.socketManager =
|
|
41
|
+
reinitialize(t) {
|
|
42
|
+
this.socketManager = t, this.userFeedId = this.buildUserFeedId(), this.initializeRealtimeConnection(), this.setupBroadcastChannel();
|
|
43
43
|
}
|
|
44
44
|
/**
|
|
45
45
|
* Cleans up a feed instance by destroying the store and disconnecting
|
|
46
46
|
* an open socket connection.
|
|
47
47
|
*/
|
|
48
48
|
teardown() {
|
|
49
|
-
var
|
|
50
|
-
this.knock.log("[Feed] Tearing down feed instance"), (
|
|
49
|
+
var t;
|
|
50
|
+
this.knock.log("[Feed] Tearing down feed instance"), (t = this.socketManager) == null || t.leave(this), this.tearDownVisibilityListeners(), this.disconnectTimer && (clearTimeout(this.disconnectTimer), this.disconnectTimer = null), this.broadcastChannel && this.broadcastChannel.close();
|
|
51
51
|
}
|
|
52
52
|
/** Tears down an instance and removes it entirely from the feed manager */
|
|
53
53
|
dispose() {
|
|
@@ -58,102 +58,102 @@ class P {
|
|
|
58
58
|
current ApiClient instance if the socket is not already connected.
|
|
59
59
|
*/
|
|
60
60
|
listenForUpdates() {
|
|
61
|
-
var
|
|
61
|
+
var t;
|
|
62
62
|
if (this.knock.log("[Feed] Connecting to real-time service"), this.hasSubscribedToRealTimeUpdates = !0, !this.knock.isAuthenticated()) {
|
|
63
63
|
this.knock.log(
|
|
64
64
|
"[Feed] User is not authenticated, skipping listening for updates"
|
|
65
65
|
);
|
|
66
66
|
return;
|
|
67
67
|
}
|
|
68
|
-
this.unsubscribeFromSocketEvents = (
|
|
68
|
+
this.unsubscribeFromSocketEvents = (t = this.socketManager) == null ? void 0 : t.join(this);
|
|
69
69
|
}
|
|
70
70
|
/* Binds a handler to be invoked when event occurs */
|
|
71
|
-
on(
|
|
72
|
-
this.broadcaster.on(
|
|
71
|
+
on(t, e) {
|
|
72
|
+
this.broadcaster.on(t, e);
|
|
73
73
|
}
|
|
74
|
-
off(
|
|
75
|
-
this.broadcaster.off(
|
|
74
|
+
off(t, e) {
|
|
75
|
+
this.broadcaster.off(t, e);
|
|
76
76
|
}
|
|
77
77
|
getState() {
|
|
78
78
|
return this.store.getState();
|
|
79
79
|
}
|
|
80
|
-
async markAsSeen(
|
|
81
|
-
const
|
|
80
|
+
async markAsSeen(t) {
|
|
81
|
+
const e = (/* @__PURE__ */ new Date()).toISOString();
|
|
82
82
|
return this.optimisticallyPerformStatusUpdate(
|
|
83
|
-
|
|
83
|
+
t,
|
|
84
84
|
"seen",
|
|
85
|
-
{ seen_at:
|
|
85
|
+
{ seen_at: e },
|
|
86
86
|
"unseen_count"
|
|
87
|
-
), this.makeStatusUpdate(
|
|
87
|
+
), this.makeStatusUpdate(t, "seen");
|
|
88
88
|
}
|
|
89
89
|
async markAllAsSeen() {
|
|
90
|
-
const { metadata:
|
|
90
|
+
const { metadata: t, items: e, ...s } = this.store.getState();
|
|
91
91
|
if (this.defaultOptions.status === "unseen")
|
|
92
92
|
s.resetStore({
|
|
93
|
-
...
|
|
93
|
+
...t,
|
|
94
94
|
total_count: 0,
|
|
95
95
|
unseen_count: 0
|
|
96
96
|
});
|
|
97
97
|
else {
|
|
98
|
-
s.setMetadata({ ...
|
|
99
|
-
const
|
|
100
|
-
s.setItemAttrs(
|
|
98
|
+
s.setMetadata({ ...t, unseen_count: 0 });
|
|
99
|
+
const a = { seen_at: (/* @__PURE__ */ new Date()).toISOString() }, i = e.map((d) => d.id);
|
|
100
|
+
s.setItemAttrs(i, a);
|
|
101
101
|
}
|
|
102
|
-
const
|
|
103
|
-
return this.emitEvent("all_seen",
|
|
102
|
+
const o = await this.makeBulkStatusUpdate("seen");
|
|
103
|
+
return this.emitEvent("all_seen", e), o;
|
|
104
104
|
}
|
|
105
|
-
async markAsUnseen(
|
|
105
|
+
async markAsUnseen(t) {
|
|
106
106
|
return this.optimisticallyPerformStatusUpdate(
|
|
107
|
-
|
|
107
|
+
t,
|
|
108
108
|
"unseen",
|
|
109
109
|
{ seen_at: null },
|
|
110
110
|
"unseen_count"
|
|
111
|
-
), this.makeStatusUpdate(
|
|
111
|
+
), this.makeStatusUpdate(t, "unseen");
|
|
112
112
|
}
|
|
113
|
-
async markAsRead(
|
|
114
|
-
const
|
|
113
|
+
async markAsRead(t) {
|
|
114
|
+
const e = (/* @__PURE__ */ new Date()).toISOString();
|
|
115
115
|
return this.optimisticallyPerformStatusUpdate(
|
|
116
|
-
|
|
116
|
+
t,
|
|
117
117
|
"read",
|
|
118
|
-
{ read_at:
|
|
118
|
+
{ read_at: e },
|
|
119
119
|
"unread_count"
|
|
120
|
-
), this.makeStatusUpdate(
|
|
120
|
+
), this.makeStatusUpdate(t, "read");
|
|
121
121
|
}
|
|
122
122
|
async markAllAsRead() {
|
|
123
|
-
const { metadata:
|
|
123
|
+
const { metadata: t, items: e, ...s } = this.store.getState();
|
|
124
124
|
if (this.defaultOptions.status === "unread")
|
|
125
125
|
s.resetStore({
|
|
126
|
-
...
|
|
126
|
+
...t,
|
|
127
127
|
total_count: 0,
|
|
128
128
|
unread_count: 0
|
|
129
129
|
});
|
|
130
130
|
else {
|
|
131
|
-
s.setMetadata({ ...
|
|
132
|
-
const
|
|
133
|
-
s.setItemAttrs(
|
|
131
|
+
s.setMetadata({ ...t, unread_count: 0 });
|
|
132
|
+
const a = { read_at: (/* @__PURE__ */ new Date()).toISOString() }, i = e.map((d) => d.id);
|
|
133
|
+
s.setItemAttrs(i, a);
|
|
134
134
|
}
|
|
135
|
-
const
|
|
136
|
-
return this.emitEvent("all_read",
|
|
135
|
+
const o = await this.makeBulkStatusUpdate("read");
|
|
136
|
+
return this.emitEvent("all_read", e), o;
|
|
137
137
|
}
|
|
138
|
-
async markAsUnread(
|
|
138
|
+
async markAsUnread(t) {
|
|
139
139
|
return this.optimisticallyPerformStatusUpdate(
|
|
140
|
-
|
|
140
|
+
t,
|
|
141
141
|
"unread",
|
|
142
142
|
{ read_at: null },
|
|
143
143
|
"unread_count"
|
|
144
|
-
), this.makeStatusUpdate(
|
|
144
|
+
), this.makeStatusUpdate(t, "unread");
|
|
145
145
|
}
|
|
146
|
-
async markAsInteracted(
|
|
146
|
+
async markAsInteracted(t, e) {
|
|
147
147
|
const s = (/* @__PURE__ */ new Date()).toISOString();
|
|
148
148
|
return this.optimisticallyPerformStatusUpdate(
|
|
149
|
-
|
|
149
|
+
t,
|
|
150
150
|
"interacted",
|
|
151
151
|
{
|
|
152
152
|
read_at: s,
|
|
153
153
|
interacted_at: s
|
|
154
154
|
},
|
|
155
155
|
"unread_count"
|
|
156
|
-
), this.makeStatusUpdate(
|
|
156
|
+
), this.makeStatusUpdate(t, "interacted", e);
|
|
157
157
|
}
|
|
158
158
|
/*
|
|
159
159
|
Marking one or more items as archived should:
|
|
@@ -163,147 +163,166 @@ class P {
|
|
|
163
163
|
|
|
164
164
|
TODO: how do we handle rollbacks?
|
|
165
165
|
*/
|
|
166
|
-
async markAsArchived(
|
|
167
|
-
const
|
|
166
|
+
async markAsArchived(t) {
|
|
167
|
+
const e = this.store.getState(), s = this.defaultOptions.archived === "exclude", n = Array.isArray(t) ? t : [t], o = n.map((a) => a.id);
|
|
168
168
|
if (s) {
|
|
169
|
-
const
|
|
170
|
-
...
|
|
169
|
+
const a = n.filter((r) => !r.seen_at).length, i = n.filter((r) => !r.read_at).length, d = {
|
|
170
|
+
...e.metadata,
|
|
171
171
|
// Ensure that the counts don't ever go below 0 on archiving where the client state
|
|
172
172
|
// gets out of sync with the server state
|
|
173
|
-
total_count: Math.max(0,
|
|
174
|
-
unseen_count: Math.max(0,
|
|
175
|
-
unread_count: Math.max(0,
|
|
176
|
-
}, l =
|
|
177
|
-
(
|
|
173
|
+
total_count: Math.max(0, e.metadata.total_count - n.length),
|
|
174
|
+
unseen_count: Math.max(0, e.metadata.unseen_count - a),
|
|
175
|
+
unread_count: Math.max(0, e.metadata.unread_count - i)
|
|
176
|
+
}, l = e.items.filter(
|
|
177
|
+
(r) => !o.includes(r.id)
|
|
178
178
|
);
|
|
179
|
-
|
|
179
|
+
e.setResult({
|
|
180
180
|
entries: l,
|
|
181
|
-
meta:
|
|
182
|
-
page_info:
|
|
181
|
+
meta: d,
|
|
182
|
+
page_info: e.pageInfo
|
|
183
183
|
});
|
|
184
184
|
} else
|
|
185
|
-
|
|
186
|
-
return this.makeStatusUpdate(
|
|
185
|
+
e.setItemAttrs(o, { archived_at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
186
|
+
return this.makeStatusUpdate(t, "archived");
|
|
187
187
|
}
|
|
188
188
|
async markAllAsArchived() {
|
|
189
|
-
const { items:
|
|
189
|
+
const { items: t, ...e } = this.store.getState();
|
|
190
190
|
if (this.defaultOptions.archived === "exclude")
|
|
191
|
-
|
|
191
|
+
e.resetStore();
|
|
192
192
|
else {
|
|
193
|
-
const
|
|
194
|
-
|
|
193
|
+
const o = t.map((a) => a.id);
|
|
194
|
+
e.setItemAttrs(o, { archived_at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
195
195
|
}
|
|
196
|
-
const
|
|
197
|
-
return this.emitEvent("all_archived",
|
|
196
|
+
const n = await this.makeBulkStatusUpdate("archive");
|
|
197
|
+
return this.emitEvent("all_archived", t), n;
|
|
198
198
|
}
|
|
199
199
|
async markAllReadAsArchived() {
|
|
200
|
-
const { items:
|
|
201
|
-
if (
|
|
200
|
+
const { items: t, ...e } = this.store.getState(), n = t.filter((i) => i.read_at === null).map((i) => i.id);
|
|
201
|
+
if (e.setItemAttrs(n, {
|
|
202
202
|
archived_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
203
203
|
}), this.defaultOptions.archived === "exclude") {
|
|
204
|
-
const
|
|
205
|
-
...
|
|
206
|
-
total_count:
|
|
204
|
+
const i = t.filter((l) => !n.includes(l.id)), d = {
|
|
205
|
+
...e.metadata,
|
|
206
|
+
total_count: i.length,
|
|
207
207
|
unread_count: 0
|
|
208
208
|
};
|
|
209
|
-
|
|
210
|
-
entries:
|
|
211
|
-
meta:
|
|
212
|
-
page_info:
|
|
209
|
+
e.setResult({
|
|
210
|
+
entries: i,
|
|
211
|
+
meta: d,
|
|
212
|
+
page_info: e.pageInfo
|
|
213
213
|
});
|
|
214
214
|
}
|
|
215
215
|
return await this.makeBulkStatusUpdate("archive");
|
|
216
216
|
}
|
|
217
|
-
async markAsUnarchived(
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
217
|
+
async markAsUnarchived(t) {
|
|
218
|
+
const e = this.store.getState(), s = Array.isArray(t) ? t : [t], n = s.map((a) => a.id);
|
|
219
|
+
if (this.defaultOptions.archived === "only") {
|
|
220
|
+
const a = s.filter((r) => !r.seen_at).length, i = s.filter((r) => !r.read_at).length, d = {
|
|
221
|
+
...e.metadata,
|
|
222
|
+
// Ensure that the counts don't ever go below 0 on unarchiving where the client state
|
|
223
|
+
// gets out of sync with the server state
|
|
224
|
+
total_count: Math.max(0, e.metadata.total_count - s.length),
|
|
225
|
+
unseen_count: Math.max(0, e.metadata.unseen_count - a),
|
|
226
|
+
unread_count: Math.max(0, e.metadata.unread_count - i)
|
|
227
|
+
}, l = e.items.filter(
|
|
228
|
+
(r) => !n.includes(r.id)
|
|
229
|
+
);
|
|
230
|
+
e.setResult({
|
|
231
|
+
entries: l,
|
|
232
|
+
meta: d,
|
|
233
|
+
page_info: e.pageInfo
|
|
234
|
+
});
|
|
235
|
+
} else
|
|
236
|
+
this.optimisticallyPerformStatusUpdate(t, "unarchived", {
|
|
237
|
+
archived_at: null
|
|
238
|
+
});
|
|
239
|
+
return this.makeStatusUpdate(t, "unarchived");
|
|
221
240
|
}
|
|
222
241
|
/* Fetches the feed content, appending it to the store */
|
|
223
|
-
async fetch(
|
|
224
|
-
const { networkStatus:
|
|
242
|
+
async fetch(t = {}) {
|
|
243
|
+
const { networkStatus: e, ...s } = this.store.getState();
|
|
225
244
|
if (!this.knock.isAuthenticated()) {
|
|
226
245
|
this.knock.log("[Feed] User is not authenticated, skipping fetch");
|
|
227
246
|
return;
|
|
228
247
|
}
|
|
229
|
-
if (S(
|
|
248
|
+
if (S(e)) {
|
|
230
249
|
this.knock.log("[Feed] Request is in flight, skipping fetch");
|
|
231
250
|
return;
|
|
232
251
|
}
|
|
233
|
-
s.setNetworkStatus(
|
|
234
|
-
const
|
|
252
|
+
s.setNetworkStatus(t.__loadingType ?? m.loading);
|
|
253
|
+
const n = I({
|
|
235
254
|
...this.defaultOptions,
|
|
236
|
-
...
|
|
237
|
-
}),
|
|
255
|
+
...t
|
|
256
|
+
}), o = {
|
|
238
257
|
...this.defaultOptions,
|
|
239
|
-
...f(
|
|
240
|
-
trigger_data:
|
|
258
|
+
...f(t),
|
|
259
|
+
trigger_data: n,
|
|
241
260
|
// Unset options that should not be sent to the API
|
|
242
261
|
__loadingType: void 0,
|
|
243
262
|
__fetchSource: void 0,
|
|
244
263
|
__experimentalCrossBrowserUpdates: void 0,
|
|
245
264
|
auto_manage_socket_connection: void 0,
|
|
246
265
|
auto_manage_socket_connection_delay: void 0
|
|
247
|
-
},
|
|
266
|
+
}, a = await this.knock.client().makeRequest({
|
|
248
267
|
method: "GET",
|
|
249
268
|
url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,
|
|
250
|
-
params:
|
|
269
|
+
params: o
|
|
251
270
|
});
|
|
252
|
-
if (
|
|
271
|
+
if (a.statusCode === "error" || !a.body)
|
|
253
272
|
return s.setNetworkStatus(m.error), {
|
|
254
|
-
status:
|
|
255
|
-
data:
|
|
273
|
+
status: a.statusCode,
|
|
274
|
+
data: a.error || a.body
|
|
256
275
|
};
|
|
257
|
-
const
|
|
258
|
-
entries:
|
|
259
|
-
meta:
|
|
260
|
-
page_info:
|
|
276
|
+
const i = {
|
|
277
|
+
entries: a.body.entries,
|
|
278
|
+
meta: a.body.meta,
|
|
279
|
+
page_info: a.body.page_info
|
|
261
280
|
};
|
|
262
|
-
if (
|
|
263
|
-
const
|
|
264
|
-
s.setResult(
|
|
265
|
-
} else if (
|
|
266
|
-
const
|
|
267
|
-
s.setResult(
|
|
281
|
+
if (t.before) {
|
|
282
|
+
const r = { shouldSetPage: !1, shouldAppend: !0 };
|
|
283
|
+
s.setResult(i, r);
|
|
284
|
+
} else if (t.after) {
|
|
285
|
+
const r = { shouldSetPage: !0, shouldAppend: !0 };
|
|
286
|
+
s.setResult(i, r);
|
|
268
287
|
} else
|
|
269
|
-
s.setResult(
|
|
270
|
-
this.broadcast("messages.new",
|
|
271
|
-
const
|
|
272
|
-
items:
|
|
273
|
-
metadata:
|
|
274
|
-
event:
|
|
288
|
+
s.setResult(i);
|
|
289
|
+
this.broadcast("messages.new", i);
|
|
290
|
+
const d = t.__fetchSource === "socket" ? "items.received.realtime" : "items.received.page", l = {
|
|
291
|
+
items: i.entries,
|
|
292
|
+
metadata: i.meta,
|
|
293
|
+
event: d
|
|
275
294
|
};
|
|
276
|
-
return this.broadcast(l.event, l), { data:
|
|
295
|
+
return this.broadcast(l.event, l), { data: i, status: a.statusCode };
|
|
277
296
|
}
|
|
278
|
-
async fetchNextPage(
|
|
279
|
-
const { pageInfo:
|
|
280
|
-
|
|
281
|
-
...
|
|
282
|
-
after:
|
|
297
|
+
async fetchNextPage(t = {}) {
|
|
298
|
+
const { pageInfo: e } = this.store.getState();
|
|
299
|
+
e.after && this.fetch({
|
|
300
|
+
...t,
|
|
301
|
+
after: e.after,
|
|
283
302
|
__loadingType: m.fetchMore
|
|
284
303
|
});
|
|
285
304
|
}
|
|
286
305
|
get socketChannelTopic() {
|
|
287
306
|
return `feeds:${this.userFeedId}`;
|
|
288
307
|
}
|
|
289
|
-
broadcast(
|
|
290
|
-
this.broadcaster.emit(
|
|
308
|
+
broadcast(t, e) {
|
|
309
|
+
this.broadcaster.emit(t, e);
|
|
291
310
|
}
|
|
292
311
|
// Invoked when a new real-time message comes in from the socket
|
|
293
|
-
async onNewMessageReceived({ data:
|
|
294
|
-
var
|
|
312
|
+
async onNewMessageReceived({ data: t }) {
|
|
313
|
+
var a;
|
|
295
314
|
this.knock.log("[Feed] Received new real-time message");
|
|
296
|
-
const { items:
|
|
297
|
-
|
|
315
|
+
const { items: e, ...s } = this.store.getState(), n = e[0], o = (a = t[this.referenceId]) == null ? void 0 : a.metadata;
|
|
316
|
+
o && s.setMetadata(o), this.fetch({ before: n == null ? void 0 : n.__cursor, __fetchSource: "socket" });
|
|
298
317
|
}
|
|
299
318
|
buildUserFeedId() {
|
|
300
319
|
return `${this.feedId}:${this.knock.userId}`;
|
|
301
320
|
}
|
|
302
|
-
optimisticallyPerformStatusUpdate(
|
|
303
|
-
const
|
|
304
|
-
if (
|
|
305
|
-
const { metadata:
|
|
306
|
-
switch (
|
|
321
|
+
optimisticallyPerformStatusUpdate(t, e, s, n) {
|
|
322
|
+
const o = this.store.getState(), a = Array.isArray(t) ? t : [t], i = a.map((d) => d.id);
|
|
323
|
+
if (n) {
|
|
324
|
+
const { metadata: d } = o, l = a.filter((h) => {
|
|
325
|
+
switch (e) {
|
|
307
326
|
case "seen":
|
|
308
327
|
return h.seen_at === null;
|
|
309
328
|
case "unseen":
|
|
@@ -316,24 +335,24 @@ class P {
|
|
|
316
335
|
default:
|
|
317
336
|
return !0;
|
|
318
337
|
}
|
|
319
|
-
}),
|
|
320
|
-
|
|
321
|
-
...
|
|
322
|
-
[
|
|
338
|
+
}), r = e.startsWith("un") ? l.length : -l.length;
|
|
339
|
+
o.setMetadata({
|
|
340
|
+
...d,
|
|
341
|
+
[n]: Math.max(0, d[n] + r)
|
|
323
342
|
});
|
|
324
343
|
}
|
|
325
|
-
|
|
344
|
+
o.setItemAttrs(i, s);
|
|
326
345
|
}
|
|
327
|
-
async makeStatusUpdate(
|
|
328
|
-
const
|
|
329
|
-
|
|
330
|
-
|
|
346
|
+
async makeStatusUpdate(t, e, s) {
|
|
347
|
+
const n = Array.isArray(t) ? t : [t], o = n.map((i) => i.id), a = await this.knock.messages.batchUpdateStatuses(
|
|
348
|
+
o,
|
|
349
|
+
e,
|
|
331
350
|
{ metadata: s }
|
|
332
351
|
);
|
|
333
|
-
return this.emitEvent(
|
|
352
|
+
return this.emitEvent(e, n), a;
|
|
334
353
|
}
|
|
335
|
-
async makeBulkStatusUpdate(
|
|
336
|
-
const
|
|
354
|
+
async makeBulkStatusUpdate(t) {
|
|
355
|
+
const e = {
|
|
337
356
|
user_ids: [this.knock.userId],
|
|
338
357
|
engagement_status: this.defaultOptions.status !== "all" ? this.defaultOptions.status : void 0,
|
|
339
358
|
archived: this.defaultOptions.archived,
|
|
@@ -342,13 +361,13 @@ class P {
|
|
|
342
361
|
};
|
|
343
362
|
return await this.knock.messages.bulkUpdateAllStatusesInChannel({
|
|
344
363
|
channelId: this.feedId,
|
|
345
|
-
status:
|
|
346
|
-
options:
|
|
364
|
+
status: t,
|
|
365
|
+
options: e
|
|
347
366
|
});
|
|
348
367
|
}
|
|
349
368
|
setupBroadcastChannel() {
|
|
350
|
-
this.broadcastChannel = typeof self < "u" && "BroadcastChannel" in self ? new BroadcastChannel(`knock:feed:${this.userFeedId}`) : null, this.broadcastChannel && this.defaultOptions.__experimentalCrossBrowserUpdates === !0 && (this.broadcastChannel.onmessage = (
|
|
351
|
-
switch (
|
|
369
|
+
this.broadcastChannel = typeof self < "u" && "BroadcastChannel" in self ? new BroadcastChannel(`knock:feed:${this.userFeedId}`) : null, this.broadcastChannel && this.defaultOptions.__experimentalCrossBrowserUpdates === !0 && (this.broadcastChannel.onmessage = (t) => {
|
|
370
|
+
switch (t.data.type) {
|
|
352
371
|
case "items:archived":
|
|
353
372
|
case "items:unarchived":
|
|
354
373
|
case "items:seen":
|
|
@@ -364,29 +383,29 @@ class P {
|
|
|
364
383
|
}
|
|
365
384
|
});
|
|
366
385
|
}
|
|
367
|
-
broadcastOverChannel(
|
|
386
|
+
broadcastOverChannel(t, e) {
|
|
368
387
|
if (this.broadcastChannel)
|
|
369
388
|
try {
|
|
370
|
-
const s = JSON.parse(JSON.stringify(
|
|
389
|
+
const s = JSON.parse(JSON.stringify(e));
|
|
371
390
|
this.broadcastChannel.postMessage({
|
|
372
|
-
type:
|
|
391
|
+
type: t,
|
|
373
392
|
payload: s
|
|
374
393
|
});
|
|
375
394
|
} catch (s) {
|
|
376
|
-
console.warn(`Could not broadcast ${
|
|
395
|
+
console.warn(`Could not broadcast ${t}, got error: ${s}`);
|
|
377
396
|
}
|
|
378
397
|
}
|
|
379
398
|
initializeRealtimeConnection() {
|
|
380
|
-
var
|
|
381
|
-
this.socketManager && (this.defaultOptions.auto_manage_socket_connection && this.setUpVisibilityListeners(), this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated() && (this.unsubscribeFromSocketEvents = (
|
|
399
|
+
var t;
|
|
400
|
+
this.socketManager && (this.defaultOptions.auto_manage_socket_connection && this.setUpVisibilityListeners(), this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated() && (this.unsubscribeFromSocketEvents = (t = this.socketManager) == null ? void 0 : t.join(this)));
|
|
382
401
|
}
|
|
383
|
-
async handleSocketEvent(
|
|
384
|
-
switch (
|
|
402
|
+
async handleSocketEvent(t) {
|
|
403
|
+
switch (t.event) {
|
|
385
404
|
case y.NewMessage:
|
|
386
|
-
this.onNewMessageReceived(
|
|
405
|
+
this.onNewMessageReceived(t);
|
|
387
406
|
return;
|
|
388
407
|
default: {
|
|
389
|
-
|
|
408
|
+
t.event;
|
|
390
409
|
return;
|
|
391
410
|
}
|
|
392
411
|
}
|
|
@@ -404,16 +423,16 @@ class P {
|
|
|
404
423
|
this.visibilityChangeHandler
|
|
405
424
|
), this.visibilityChangeListenerConnected = !1);
|
|
406
425
|
}
|
|
407
|
-
emitEvent(
|
|
408
|
-
this.broadcaster.emit(`items.${
|
|
426
|
+
emitEvent(t, e) {
|
|
427
|
+
this.broadcaster.emit(`items.${t}`, { items: e }), this.broadcaster.emit(`items:${t}`, { items: e }), this.broadcastOverChannel(`items:${t}`, { items: e });
|
|
409
428
|
}
|
|
410
429
|
handleVisibilityChange() {
|
|
411
|
-
var s,
|
|
412
|
-
const
|
|
430
|
+
var s, n;
|
|
431
|
+
const t = this.defaultOptions.auto_manage_socket_connection_delay ?? U, e = this.knock.client();
|
|
413
432
|
document.visibilityState === "hidden" ? this.disconnectTimer = setTimeout(() => {
|
|
414
|
-
var
|
|
415
|
-
(
|
|
416
|
-
},
|
|
433
|
+
var o;
|
|
434
|
+
(o = e.socket) == null || o.disconnect(), this.disconnectTimer = null;
|
|
435
|
+
}, t) : document.visibilityState === "visible" && (this.disconnectTimer && (clearTimeout(this.disconnectTimer), this.disconnectTimer = null), (s = e.socket) != null && s.isConnected() || (n = e.socket) == null || n.connect());
|
|
417
436
|
}
|
|
418
437
|
}
|
|
419
438
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed.mjs","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { nanoid } from \"nanoid\";\n\nimport { isValidUuid } from \"../../helpers\";\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport {\n FeedSocketManager,\n SocketEventPayload,\n SocketEventType,\n} from \"./socket-manager\";\nimport createStore, { FeedStore } from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nconst CLIENT_REF_ID_PREFIX = \"client_\";\n\nclass Feed {\n public readonly defaultOptions: FeedClientOptions;\n public readonly referenceId: string;\n public unsubscribeFromSocketEvents: (() => void) | undefined = undefined;\n private socketManager: FeedSocketManager | undefined;\n private userFeedId: string;\n private broadcaster: EventEmitter;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: FeedStore;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n socketManager: FeedSocketManager | undefined,\n ) {\n if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.referenceId = CLIENT_REF_ID_PREFIX + nanoid();\n this.socketManager = socketManager;\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize(socketManager?: FeedSocketManager) {\n this.socketManager = socketManager;\n\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n this.socketManager?.leave(this);\n\n this.tearDownVisibilityListeners();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n get socketChannelTopic(): string {\n return `feeds:${this.userFeedId}`;\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({ data }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n\n // Optimistically set the badge counts\n const metadata = data[this.referenceId]?.metadata;\n if (metadata) {\n state.setMetadata(metadata);\n }\n\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // This is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n // In server environments we might not have a socket connection\n if (!this.socketManager) return;\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setUpVisibilityListeners();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n }\n\n async handleSocketEvent(payload: SocketEventPayload) {\n switch (payload.event) {\n case SocketEventType.NewMessage:\n this.onNewMessageReceived(payload);\n return;\n default: {\n const _exhaustiveCheck: never = payload.event;\n return;\n }\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setUpVisibilityListeners() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private tearDownVisibilityListeners() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n client.socket?.connect();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","CLIENT_REF_ID_PREFIX","Feed","knock","feedId","options","socketManager","__publicField","isValidUuid","nanoid","createStore","EventEmitter","mergeDateRangeParams","_a","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","SocketEventType","disconnectDelay","client","_b"],"mappings":";;;;;;;;;;AAsCA,MAAMA,IAA0D;AAAA,EAC9D,UAAU;AACZ,GAEMC,IAA2B,KAE3BC,IAAuB;AAE7B,MAAMC,EAAK;AAAA,EAgBT,YACWC,GACAC,GACTC,GACAC,GACA;AApBc,IAAAC,EAAA;AACA,IAAAA,EAAA;AACT,IAAAA,EAAA;AACC,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA,yBAAwD;AACxD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AAAC,EAAe;AAAA,EAEnB;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"feed.mjs","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { nanoid } from \"nanoid\";\n\nimport { isValidUuid } from \"../../helpers\";\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport {\n FeedSocketManager,\n SocketEventPayload,\n SocketEventType,\n} from \"./socket-manager\";\nimport createStore, { FeedStore } from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nconst CLIENT_REF_ID_PREFIX = \"client_\";\n\nclass Feed {\n public readonly defaultOptions: FeedClientOptions;\n public readonly referenceId: string;\n public unsubscribeFromSocketEvents: (() => void) | undefined = undefined;\n private socketManager: FeedSocketManager | undefined;\n private userFeedId: string;\n private broadcaster: EventEmitter;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: FeedStore;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n socketManager: FeedSocketManager | undefined,\n ) {\n if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.referenceId = CLIENT_REF_ID_PREFIX + nanoid();\n this.socketManager = socketManager;\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize(socketManager?: FeedSocketManager) {\n this.socketManager = socketManager;\n\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n this.socketManager?.leave(this);\n\n this.tearDownVisibilityListeners();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"only\";\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on unarchiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the unarchived entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n get socketChannelTopic(): string {\n return `feeds:${this.userFeedId}`;\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({ data }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n\n // Optimistically set the badge counts\n const metadata = data[this.referenceId]?.metadata;\n if (metadata) {\n state.setMetadata(metadata);\n }\n\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // This is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n // In server environments we might not have a socket connection\n if (!this.socketManager) return;\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setUpVisibilityListeners();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n }\n\n async handleSocketEvent(payload: SocketEventPayload) {\n switch (payload.event) {\n case SocketEventType.NewMessage:\n this.onNewMessageReceived(payload);\n return;\n default: {\n const _exhaustiveCheck: never = payload.event;\n return;\n }\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setUpVisibilityListeners() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private tearDownVisibilityListeners() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n client.socket?.connect();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","CLIENT_REF_ID_PREFIX","Feed","knock","feedId","options","socketManager","__publicField","isValidUuid","nanoid","createStore","EventEmitter","mergeDateRangeParams","_a","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","e","payload","stringifiedPayload","SocketEventType","disconnectDelay","client","_b"],"mappings":";;;;;;;;;;AAsCA,MAAMA,IAA0D;AAAA,EAC9D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,iCAAiC;YAiD3B,gBAAgB;YAsBhB,oBAAoB;IA2BlC,OAAO,CAAC,qBAAqB;IAoC7B,OAAO,CAAC,oBAAoB;IAoB5B,OAAO,CAAC,4BAA4B;IAe9B,iBAAiB,CAAC,OAAO,EAAE,kBAAkB;IAYnD;;;OAGG;IACH,OAAO,CAAC,wBAAwB;IAahC,OAAO,CAAC,2BAA2B;IAUnC,OAAO,CAAC,SAAS;IAkBjB,OAAO,CAAC,sBAAsB;CA2B/B;AAED,eAAe,IAAI,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../../../../src/clients/messages/interfaces.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAErC,MAAM,MAAM,qBAAqB,GAC7B,QAAQ,GACR,MAAM,GACN,WAAW,GACX,oBAAoB,GACpB,aAAa,GACb,UAAU,CAAC;AAEf,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../../../../src/clients/messages/interfaces.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAErC,MAAM,MAAM,qBAAqB,GAC7B,QAAQ,GACR,MAAM,GACN,WAAW,GACX,oBAAoB,GACpB,aAAa,GACb,UAAU,CAAC;AAEf,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAA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C;QACrB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;KACpB,CAAC;CACH,CAAC;AAEF,MAAM,MAAM,0BAA0B,GAAG;IACvC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACnC,CAAC"}
|
package/package.json
CHANGED
package/src/clients/feed/feed.ts
CHANGED
|
@@ -472,9 +472,46 @@ class Feed {
|
|
|
472
472
|
}
|
|
473
473
|
|
|
474
474
|
async markAsUnarchived(itemOrItems: FeedItemOrItems) {
|
|
475
|
-
this.
|
|
476
|
-
|
|
477
|
-
|
|
475
|
+
const state = this.store.getState();
|
|
476
|
+
|
|
477
|
+
const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];
|
|
478
|
+
|
|
479
|
+
const itemIds: string[] = items.map((item) => item.id);
|
|
480
|
+
|
|
481
|
+
const shouldOptimisticallyRemoveItems =
|
|
482
|
+
this.defaultOptions.archived === "only";
|
|
483
|
+
|
|
484
|
+
if (shouldOptimisticallyRemoveItems) {
|
|
485
|
+
// If any of the items are unseen or unread, then capture as we'll want to decrement
|
|
486
|
+
// the counts for these in the metadata we have
|
|
487
|
+
const unseenCount = items.filter((i) => !i.seen_at).length;
|
|
488
|
+
const unreadCount = items.filter((i) => !i.read_at).length;
|
|
489
|
+
|
|
490
|
+
// Build the new metadata
|
|
491
|
+
const updatedMetadata = {
|
|
492
|
+
...state.metadata,
|
|
493
|
+
// Ensure that the counts don't ever go below 0 on unarchiving where the client state
|
|
494
|
+
// gets out of sync with the server state
|
|
495
|
+
total_count: Math.max(0, state.metadata.total_count - items.length),
|
|
496
|
+
unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),
|
|
497
|
+
unread_count: Math.max(0, state.metadata.unread_count - unreadCount),
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
// Remove the unarchived entries
|
|
501
|
+
const entriesToSet = state.items.filter(
|
|
502
|
+
(item) => !itemIds.includes(item.id),
|
|
503
|
+
);
|
|
504
|
+
|
|
505
|
+
state.setResult({
|
|
506
|
+
entries: entriesToSet,
|
|
507
|
+
meta: updatedMetadata,
|
|
508
|
+
page_info: state.pageInfo,
|
|
509
|
+
});
|
|
510
|
+
} else {
|
|
511
|
+
this.optimisticallyPerformStatusUpdate(itemOrItems, "unarchived", {
|
|
512
|
+
archived_at: null,
|
|
513
|
+
});
|
|
514
|
+
}
|
|
478
515
|
|
|
479
516
|
return this.makeStatusUpdate(itemOrItems, "unarchived");
|
|
480
517
|
}
|