@knocklabs/client 0.13.0-rc.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2 -2
- package/dist/cjs/clients/feed/feed.js +1 -1
- package/dist/cjs/clients/feed/feed.js.map +1 -1
- package/dist/cjs/clients/users/index.js +1 -1
- package/dist/cjs/clients/users/index.js.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/esm/clients/feed/feed.mjs +82 -67
- package/dist/esm/clients/feed/feed.mjs.map +1 -1
- package/dist/esm/clients/users/index.mjs +13 -30
- package/dist/esm/clients/users/index.mjs.map +1 -1
- package/dist/esm/index.mjs +7 -9
- package/dist/esm/index.mjs.map +1 -1
- package/dist/types/clients/feed/feed.d.ts.map +1 -1
- package/dist/types/clients/feed/interfaces.d.ts +5 -0
- package/dist/types/clients/feed/interfaces.d.ts.map +1 -1
- package/dist/types/clients/users/index.d.ts +0 -3
- package/dist/types/clients/users/index.d.ts.map +1 -1
- package/dist/types/index.d.ts +0 -1
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +1 -2
- package/src/clients/feed/feed.ts +32 -2
- package/src/clients/feed/interfaces.ts +9 -0
- package/src/clients/users/index.ts +0 -27
- package/src/index.ts +0 -1
- package/dist/cjs/clients/guide/client.js +0 -2
- package/dist/cjs/clients/guide/client.js.map +0 -1
- package/dist/esm/clients/guide/client.mjs +0 -225
- package/dist/esm/clients/guide/client.mjs.map +0 -1
- package/dist/types/clients/guide/client.d.ts +0 -102
- package/dist/types/clients/guide/client.d.ts.map +0 -1
- package/dist/types/clients/guide/index.d.ts +0 -3
- package/dist/types/clients/guide/index.d.ts.map +0 -1
- package/src/clients/guide/client.ts +0 -541
- package/src/clients/guide/index.ts +0 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var f=Object.defineProperty;var p=(c,t,e)=>t in c?f(c,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[t]=e;var d=(c,t,e)=>p(c,typeof t!="symbol"?t+"":t,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),m=require("../../networkStatus.js"),g=require("./store.js"),_=c=>c&&typeof c=="object"&&"default"in c?c:{default:c},S=_(k),v={archived:"exclude"},y=2e3;class b{constructor(t,e,s){d(this,"userFeedId");d(this,"channel");d(this,"broadcaster");d(this,"defaultOptions");d(this,"broadcastChannel");d(this,"disconnectTimer",null);d(this,"hasSubscribedToRealTimeUpdates",!1);d(this,"visibilityChangeHandler",()=>{});d(this,"visibilityChangeListenerConnected",!1);d(this,"store");this.knock=t,this.feedId=e,this.feedId=e,this.userFeedId=this.buildUserFeedId(),this.store=g.default(),this.broadcaster=new S.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...v,...s},this.knock.log(`[Feed] Initialized a feed on channel ${e}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(){this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){this.knock.log("[Feed] Tearing down feed instance"),this.channel&&(this.channel.leave(),this.channel.off("new-message")),this.teardownAutoSocketManager(),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(){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}const t=this.knock.client().socket;t&&!t.isConnected()&&t.connect(),this.channel&&["closed","errored"].includes(this.channel.state)&&this.channel.join()}on(t,e){this.broadcaster.on(t,e)}off(t,e){this.broadcaster.off(t,e)}getState(){return this.store.getState()}async markAsSeen(t){const e=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(t,"seen",{seen_at:e},"unseen_count"),this.makeStatusUpdate(t,"seen")}async markAllAsSeen(){const{metadata:t,items:e,...s}=this.store.getState();if(this.defaultOptions.status==="unseen")s.resetStore({...t,total_count:0,unseen_count:0});else{s.setMetadata({...t,unseen_count:0});const i={seen_at:new Date().toISOString()},o=e.map(r=>r.id);s.setItemAttrs(o,i)}const n=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",e),n}async markAsUnseen(t){return this.optimisticallyPerformStatusUpdate(t,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(t,"unseen")}async markAsRead(t){const e=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(t,"read",{read_at:e},"unread_count"),this.makeStatusUpdate(t,"read")}async markAllAsRead(){const{metadata:t,items:e,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...t,total_count:0,unread_count:0});else{s.setMetadata({...t,unread_count:0});const i={read_at:new Date().toISOString()},o=e.map(r=>r.id);s.setItemAttrs(o,i)}const n=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",e),n}async markAsUnread(t){return this.optimisticallyPerformStatusUpdate(t,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(t,"unread")}async markAsInteracted(t,e){const s=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(t,"interacted",{read_at:s,interacted_at:s},"unread_count"),this.makeStatusUpdate(t,"interacted",e)}async markAsArchived(t){const e=this.store.getState(),s=this.defaultOptions.archived==="exclude",a=Array.isArray(t)?t:[t],n=a.map(i=>i.id);if(s){const i=a.filter(u=>!u.seen_at).length,o=a.filter(u=>!u.read_at).length,r={...e.metadata,total_count:Math.max(0,e.metadata.total_count-a.length),unseen_count:Math.max(0,e.metadata.unseen_count-i),unread_count:Math.max(0,e.metadata.unread_count-o)},l=e.items.filter(u=>!n.includes(u.id));e.setResult({entries:l,meta:r,page_info:e.pageInfo})}else e.setItemAttrs(n,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(t,"archived")}async markAllAsArchived(){const{items:t,...e}=this.store.getState();if(this.defaultOptions.archived==="exclude")e.resetStore();else{const n=t.map(i=>i.id);e.setItemAttrs(n,{archived_at:new Date().toISOString()})}const a=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",t),a}async markAllReadAsArchived(){const{items:t,...e}=this.store.getState(),a=t.filter(o=>o.read_at===null).map(o=>o.id);if(e.setItemAttrs(a,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const o=t.filter(l=>!a.includes(l.id)),r={...e.metadata,total_count:o.length,unread_count:0};e.setResult({entries:o,meta:r,page_info:e.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(t){return this.optimisticallyPerformStatusUpdate(t,"unarchived",{archived_at:null}),this.makeStatusUpdate(t,"unarchived")}async fetch(t={}){const{networkStatus:e,...s}=this.store.getState();if(!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping fetch");return}if(m.isRequestInFlight(e)){this.knock.log("[Feed] Request is in flight, skipping fetch");return}s.setNetworkStatus(t.__loadingType??m.NetworkStatus.loading);const a={...this.defaultOptions,...t,__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:a});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(t.before){const l={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,l)}else if(t.after){const l={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,l)}else s.setResult(i);this.broadcast("messages.new",i);const o=t.__fetchSource==="socket"?"items.received.realtime":"items.received.page",r={items:i.entries,metadata:i.meta,event:o};return this.broadcast(r.event,r),{data:i,status:n.statusCode}}async fetchNextPage(){const{pageInfo:t}=this.store.getState();t.after&&this.fetch({after:t.after,__loadingType:m.NetworkStatus.fetchMore})}broadcast(t,e){this.broadcaster.emit(t,e)}async onNewMessageReceived({metadata:t}){this.knock.log("[Feed] Received new real-time message");const{items:e,...s}=this.store.getState(),a=e[0];s.setMetadata(t),this.fetch({before:a==null?void 0:a.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(t,e,s,a){const n=this.store.getState(),i=Array.isArray(t)?t:[t],o=i.map(r=>r.id);if(a){const{metadata:r}=n,l=i.filter(h=>{switch(e){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=e.startsWith("un")?l.length:-l.length;n.setMetadata({...r,[a]:Math.max(0,r[a]+u)})}n.setItemAttrs(o,s)}async makeStatusUpdate(t,e,s){const a=Array.isArray(t)?t:[t],n=a.map(o=>o.id),i=await this.knock.messages.batchUpdateStatuses(n,e,{metadata:s});return this.emitEvent(e,a),i}async makeBulkStatusUpdate(t){const e={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:t,options:e})}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=t=>{switch(t.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(t,e){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(e));this.broadcastChannel.postMessage({type:t,payload:s})}catch(s){console.warn(`Could not broadcast ${t}, got error: ${s}`)}}initializeRealtimeConnection(){const{socket:t}=this.knock.client();t&&(this.channel=t.channel(`feeds:${this.userFeedId}`,this.defaultOptions),this.channel.on("new-message",e=>this.onNewMessageReceived(e)),this.defaultOptions.auto_manage_socket_connection&&this.setupAutoSocketManager(),this.hasSubscribedToRealTimeUpdates&&this.knock.isAuthenticated()&&(t.isConnected()||t.connect(),this.channel.join()))}setupAutoSocketManager(){typeof document>"u"||this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}teardownAutoSocketManager(){typeof document>"u"||(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeListenerConnected=!1)}emitEvent(t,e){this.broadcaster.emit(`items.${t}`,{items:e}),this.broadcaster.emit(`items:${t}`,{items:e}),this.broadcastOverChannel(`items:${t}`,{items:e})}handleVisibilityChange(){var s;const t=this.defaultOptions.auto_manage_socket_connection_delay??y,e=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var a;(a=e.socket)==null||a.disconnect(),this.disconnectTimer=null},t):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=e.socket)!=null&&s.isConnected()||this.initializeRealtimeConnection())}}exports.default=b;
|
|
1
|
+
"use strict";var k=Object.defineProperty;var g=(d,t,e)=>t in d?k(d,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):d[t]=e;var l=(d,t,e)=>g(d,typeof t!="symbol"?t+"":t,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const _=require("eventemitter2"),m=require("../../networkStatus.js"),S=require("./store.js"),v=d=>d&&typeof d=="object"&&"default"in d?d:{default:d},y=v(_),b={archived:"exclude"},w=2e3;class C{constructor(t,e,s){l(this,"userFeedId");l(this,"channel");l(this,"broadcaster");l(this,"defaultOptions");l(this,"broadcastChannel");l(this,"disconnectTimer",null);l(this,"hasSubscribedToRealTimeUpdates",!1);l(this,"visibilityChangeHandler",()=>{});l(this,"visibilityChangeListenerConnected",!1);l(this,"store");this.knock=t,this.feedId=e,this.feedId=e,this.userFeedId=this.buildUserFeedId(),this.store=S.default(),this.broadcaster=new y.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...b,...s},this.knock.log(`[Feed] Initialized a feed on channel ${e}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(){this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){this.knock.log("[Feed] Tearing down feed instance"),this.channel&&(this.channel.leave(),this.channel.off("new-message")),this.teardownAutoSocketManager(),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(){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}const t=this.knock.client().socket;t&&!t.isConnected()&&t.connect(),this.channel&&["closed","errored"].includes(this.channel.state)&&this.channel.join()}on(t,e){this.broadcaster.on(t,e)}off(t,e){this.broadcaster.off(t,e)}getState(){return this.store.getState()}async markAsSeen(t){const e=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(t,"seen",{seen_at:e},"unseen_count"),this.makeStatusUpdate(t,"seen")}async markAllAsSeen(){const{metadata:t,items:e,...s}=this.store.getState();if(this.defaultOptions.status==="unseen")s.resetStore({...t,total_count:0,unseen_count:0});else{s.setMetadata({...t,unseen_count:0});const r={seen_at:new Date().toISOString()},n=e.map(o=>o.id);s.setItemAttrs(n,r)}const i=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",e),i}async markAsUnseen(t){return this.optimisticallyPerformStatusUpdate(t,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(t,"unseen")}async markAsRead(t){const e=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(t,"read",{read_at:e},"unread_count"),this.makeStatusUpdate(t,"read")}async markAllAsRead(){const{metadata:t,items:e,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...t,total_count:0,unread_count:0});else{s.setMetadata({...t,unread_count:0});const r={read_at:new Date().toISOString()},n=e.map(o=>o.id);s.setItemAttrs(n,r)}const i=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",e),i}async markAsUnread(t){return this.optimisticallyPerformStatusUpdate(t,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(t,"unread")}async markAsInteracted(t,e){const s=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(t,"interacted",{read_at:s,interacted_at:s},"unread_count"),this.makeStatusUpdate(t,"interacted",e)}async markAsArchived(t){const e=this.store.getState(),s=this.defaultOptions.archived==="exclude",a=Array.isArray(t)?t:[t],i=a.map(r=>r.id);if(s){const r=a.filter(u=>!u.seen_at).length,n=a.filter(u=>!u.read_at).length,o={...e.metadata,total_count:Math.max(0,e.metadata.total_count-a.length),unseen_count:Math.max(0,e.metadata.unseen_count-r),unread_count:Math.max(0,e.metadata.unread_count-n)},h=e.items.filter(u=>!i.includes(u.id));e.setResult({entries:h,meta:o,page_info:e.pageInfo})}else e.setItemAttrs(i,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(t,"archived")}async markAllAsArchived(){const{items:t,...e}=this.store.getState();if(this.defaultOptions.archived==="exclude")e.resetStore();else{const i=t.map(r=>r.id);e.setItemAttrs(i,{archived_at:new Date().toISOString()})}const a=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",t),a}async markAllReadAsArchived(){const{items:t,...e}=this.store.getState(),a=t.filter(n=>n.read_at===null).map(n=>n.id);if(e.setItemAttrs(a,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const n=t.filter(h=>!a.includes(h.id)),o={...e.metadata,total_count:n.length,unread_count:0};e.setResult({entries:n,meta:o,page_info:e.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(t){return this.optimisticallyPerformStatusUpdate(t,"unarchived",{archived_at:null}),this.makeStatusUpdate(t,"unarchived")}async fetch(t={}){const{networkStatus:e,...s}=this.store.getState();if(!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping fetch");return}if(m.isRequestInFlight(e)){this.knock.log("[Feed] Request is in flight, skipping fetch");return}s.setNetworkStatus(t.__loadingType??m.NetworkStatus.loading);const a={...this.defaultOptions,...t,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0,inserted_at_date_range:void 0},i=t.inserted_at_date_range;let r={...a};if(i){const c={},p=i.inclusive??!1;if(i.start){const f=p?"inserted_at.gte":"inserted_at.gt";c[f]=i.start}if(i.end){const f=p?"inserted_at.lte":"inserted_at.lt";c[f]=i.end}r={...a,...c}}const 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 o={entries:n.body.entries,meta:n.body.meta,page_info:n.body.page_info};if(t.before){const c={shouldSetPage:!1,shouldAppend:!0};s.setResult(o,c)}else if(t.after){const c={shouldSetPage:!0,shouldAppend:!0};s.setResult(o,c)}else s.setResult(o);this.broadcast("messages.new",o);const h=t.__fetchSource==="socket"?"items.received.realtime":"items.received.page",u={items:o.entries,metadata:o.meta,event:h};return this.broadcast(u.event,u),{data:o,status:n.statusCode}}async fetchNextPage(){const{pageInfo:t}=this.store.getState();t.after&&this.fetch({after:t.after,__loadingType:m.NetworkStatus.fetchMore})}broadcast(t,e){this.broadcaster.emit(t,e)}async onNewMessageReceived({metadata:t}){this.knock.log("[Feed] Received new real-time message");const{items:e,...s}=this.store.getState(),a=e[0];s.setMetadata(t),this.fetch({before:a==null?void 0:a.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(t,e,s,a){const i=this.store.getState(),r=Array.isArray(t)?t:[t],n=r.map(o=>o.id);if(a){const{metadata:o}=i,h=r.filter(c=>{switch(e){case"seen":return c.seen_at===null;case"unseen":return c.seen_at!==null;case"read":case"interacted":return c.read_at===null;case"unread":return c.read_at!==null;default:return!0}}),u=e.startsWith("un")?h.length:-h.length;i.setMetadata({...o,[a]:Math.max(0,o[a]+u)})}i.setItemAttrs(n,s)}async makeStatusUpdate(t,e,s){const a=Array.isArray(t)?t:[t],i=a.map(n=>n.id),r=await this.knock.messages.batchUpdateStatuses(i,e,{metadata:s});return this.emitEvent(e,a),r}async makeBulkStatusUpdate(t){const e={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:t,options:e})}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=t=>{switch(t.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(t,e){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(e));this.broadcastChannel.postMessage({type:t,payload:s})}catch(s){console.warn(`Could not broadcast ${t}, got error: ${s}`)}}initializeRealtimeConnection(){const{socket:t}=this.knock.client();t&&(this.channel=t.channel(`feeds:${this.userFeedId}`,this.defaultOptions),this.channel.on("new-message",e=>this.onNewMessageReceived(e)),this.defaultOptions.auto_manage_socket_connection&&this.setupAutoSocketManager(),this.hasSubscribedToRealTimeUpdates&&this.knock.isAuthenticated()&&(t.isConnected()||t.connect(),this.channel.join()))}setupAutoSocketManager(){typeof document>"u"||this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}teardownAutoSocketManager(){typeof document>"u"||(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeListenerConnected=!1)}emitEvent(t,e){this.broadcaster.emit(`items.${t}`,{items:e}),this.broadcaster.emit(`items:${t}`,{items:e}),this.broadcastOverChannel(`items:${t}`,{items:e})}handleVisibilityChange(){var s;const t=this.defaultOptions.auto_manage_socket_connection_delay??w,e=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var a;(a=e.socket)==null||a.disconnect(),this.disconnectTimer=null},t):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=e.socket)!=null&&s.isConnected()||this.initializeRealtimeConnection())}}exports.default=C;
|
|
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 { Channel } from \"phoenix\";\nimport type { StoreApi } from \"zustand\";\n\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} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nclass Feed {\n private userFeedId: string;\n private channel?: Channel;\n private broadcaster: EventEmitter;\n private defaultOptions: FeedClientOptions;\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: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n ) {\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = { ...feedClientDefaults, ...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() {\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 if (this.channel) {\n this.channel.leave();\n this.channel.off(\"new-message\");\n }\n\n this.teardownAutoSocketManager();\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 const maybeSocket = this.knock.client().socket;\n\n // Connect the socket only if we don't already have a connection\n if (maybeSocket && !maybeSocket.isConnected()) {\n maybeSocket.connect();\n }\n\n // Only join the channel if we're not already in a joining state\n if (this.channel && [\"closed\", \"errored\"].includes(this.channel.state)) {\n this.channel.join();\n }\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 // Always include the default params, if they have been set\n const queryParams = {\n ...this.defaultOptions,\n ...options,\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() {\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 after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\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({\n metadata,\n }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n // Optimistically set the badge counts\n state.setMetadata(metadata);\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 // Tnis 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 const { socket: maybeSocket } = this.knock.client();\n\n // In server environments we might not have a socket connection\n if (!maybeSocket) return;\n\n // Reinitialize channel connections incase the socket changed\n this.channel = maybeSocket.channel(\n `feeds:${this.userFeedId}`,\n this.defaultOptions,\n );\n\n this.channel.on(\"new-message\", (resp) => this.onNewMessageReceived(resp));\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setupAutoSocketManager();\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 if (!maybeSocket.isConnected()) maybeSocket.connect();\n this.channel.join();\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 setupAutoSocketManager() {\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 teardownAutoSocketManager() {\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 this.initializeRealtimeConnection();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","Feed","knock","feedId","options","__publicField","createStore","EventEmitter","maybeSocket","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","e","payload","stringifiedPayload","resp","disconnectDelay","client","_a"],"mappings":"4aAgCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAEjC,MAAMC,CAAK,CAcT,YACWC,EACAC,EACTC,EACA,CAjBMC,EAAA,mBACAA,EAAA,gBACAA,EAAA,oBACAA,EAAA,uBACAA,EAAA,yBACAA,EAAA,uBAAwD,MACxDA,EAAA,sCAA0C,IAC1CA,EAAA,+BAAsC,IAAM,CAAC,GAC7CA,EAAA,yCAA6C,IAG9CA,EAAA,cAGI,KAAA,MAAAH,EACA,KAAA,OAAAC,EAGT,KAAK,OAASA,EACT,KAAA,WAAa,KAAK,gBAAgB,EACvC,KAAK,MAAQG,UAAY,EACpB,KAAA,YAAc,IAAIC,UAAa,CAAE,SAAU,GAAM,UAAW,IAAK,EACtE,KAAK,eAAiB,CAAE,GAAGR,EAAoB,GAAGK,CAAQ,EAE1D,KAAK,MAAM,IAAI,wCA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,6BAA6B,EAEtC,CAEJ"}
|
|
1
|
+
{"version":3,"file":"feed.js","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { Channel } from \"phoenix\";\nimport type { StoreApi } from \"zustand\";\n\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} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nclass Feed {\n private userFeedId: string;\n private channel?: Channel;\n private broadcaster: EventEmitter;\n private defaultOptions: FeedClientOptions;\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: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n ) {\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = { ...feedClientDefaults, ...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() {\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 if (this.channel) {\n this.channel.leave();\n this.channel.off(\"new-message\");\n }\n\n this.teardownAutoSocketManager();\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 const maybeSocket = this.knock.client().socket;\n\n // Connect the socket only if we don't already have a connection\n if (maybeSocket && !maybeSocket.isConnected()) {\n maybeSocket.connect();\n }\n\n // Only join the channel if we're not already in a joining state\n if (this.channel && [\"closed\", \"errored\"].includes(this.channel.state)) {\n this.channel.join();\n }\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 // Always include the default params, if they have been set\n const queryParams = {\n ...this.defaultOptions,\n ...options,\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 inserted_at_date_range: undefined,\n };\n\n // If the user has set a date range, transform it to the backend's expected format\n const dateRange = options.inserted_at_date_range;\n let finalQueryParams = { ...queryParams };\n\n if (dateRange) {\n // Create a properly typed object for our date filter parameters\n const dateRangeParams: Record<string, string> = {};\n\n // Determine which operators to use based on the inclusive flag\n const isInclusive = dateRange.inclusive ?? false;\n\n // For start date: use gte if inclusive, gt if not\n if (dateRange.start) {\n const startOperator = isInclusive\n ? \"inserted_at.gte\"\n : \"inserted_at.gt\";\n dateRangeParams[startOperator] = dateRange.start;\n }\n\n // For end date: use lte if inclusive, lt if not\n if (dateRange.end) {\n const endOperator = isInclusive ? \"inserted_at.lte\" : \"inserted_at.lt\";\n dateRangeParams[endOperator] = dateRange.end;\n }\n\n // Create a new object combining queryParams and dateRangeParams\n finalQueryParams = { ...queryParams, ...dateRangeParams };\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: finalQueryParams,\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() {\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 after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\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({\n metadata,\n }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n // Optimistically set the badge counts\n state.setMetadata(metadata);\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 const { socket: maybeSocket } = this.knock.client();\n\n // In server environments we might not have a socket connection\n if (!maybeSocket) return;\n\n // Reinitialize channel connections incase the socket changed\n this.channel = maybeSocket.channel(\n `feeds:${this.userFeedId}`,\n this.defaultOptions,\n );\n\n this.channel.on(\"new-message\", (resp) => this.onNewMessageReceived(resp));\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setupAutoSocketManager();\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 if (!maybeSocket.isConnected()) maybeSocket.connect();\n this.channel.join();\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 setupAutoSocketManager() {\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 teardownAutoSocketManager() {\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 this.initializeRealtimeConnection();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","Feed","knock","feedId","options","__publicField","createStore","EventEmitter","maybeSocket","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","queryParams","dateRange","finalQueryParams","dateRangeParams","isInclusive","startOperator","endOperator","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","e","payload","stringifiedPayload","resp","disconnectDelay","client","_a"],"mappings":"4aAgCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAEjC,MAAMC,CAAK,CAcT,YACWC,EACAC,EACTC,EACA,CAjBMC,EAAA,mBACAA,EAAA,gBACAA,EAAA,oBACAA,EAAA,uBACAA,EAAA,yBACAA,EAAA,uBAAwD,MACxDA,EAAA,sCAA0C,IAC1CA,EAAA,+BAAsC,IAAM,CAAC,GAC7CA,EAAA,yCAA6C,IAG9CA,EAAA,cAGI,KAAA,MAAAH,EACA,KAAA,OAAAC,EAGT,KAAK,OAASA,EACT,KAAA,WAAa,KAAK,gBAAgB,EACvC,KAAK,MAAQG,UAAY,EACpB,KAAA,YAAc,IAAIC,UAAa,CAAE,SAAU,GAAM,UAAW,IAAK,EACtE,KAAK,eAAiB,CAAE,GAAGR,EAAoB,GAAGK,CAAQ,EAE1D,KAAK,MAAM,IAAI,wCAAwCD,CAAM,EAAE,EAG/D,KAAK,6BAA6B,EAElC,KAAK,sBAAsB,CAAA,CAM7B,cAAe,CAER,KAAA,WAAa,KAAK,gBAAgB,EAGvC,KAAK,6BAA6B,EAGlC,KAAK,sBAAsB,CAAA,CAO7B,UAAW,CACJ,KAAA,MAAM,IAAI,mCAAmC,EAE9C,KAAK,UACP,KAAK,QAAQ,MAAM,EACd,KAA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AP,MAAAC,EAAe,aACf,KAAK,gBAAkB,MACtBF,CAAe,EACT,SAAS,kBAAoB,YAGlC,KAAK,kBACP,aAAa,KAAK,eAAe,EACjC,KAAK,gBAAkB,OAIpBE,EAAAD,EAAO,SAAP,MAAAC,EAAe,eAClB,KAAK,6BAA6B,EAEtC,CAEJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var c=Object.defineProperty;var u=(s,e,t)=>e in s?c(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var a=(s,e,t)=>u(s,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i="default";class h{constructor(e){a(this,"instance");this.instance=e}async get(){this.instance.failIfNotAuthenticated();const e=await this.instance.client().makeRequest({method:"GET",url:`/v1/users/${this.instance.userId}`});return this.handleResponse(e)}async identify(e={}){this.instance.failIfNotAuthenticated();const t=await this.instance.client().makeRequest({method:"PUT",url:`/v1/users/${this.instance.userId}`,params:e});return this.handleResponse(t)}async getAllPreferences(){this.instance.failIfNotAuthenticated();const e=await this.instance.client().makeRequest({method:"GET",url:`/v1/users/${this.instance.userId}/preferences`});return this.handleResponse(e)}async getPreferences(e={}){this.instance.failIfNotAuthenticated();const t=e.preferenceSet||i,n=await this.instance.client().makeRequest({method:"GET",url:`/v1/users/${this.instance.userId}/preferences/${t}`,params:{tenant:e.tenant}});return this.handleResponse(n)}async setPreferences(e,t={}){this.instance.failIfNotAuthenticated();const n=t.preferenceSet||i,r=await this.instance.client().makeRequest({method:"PUT",url:`/v1/users/${this.instance.userId}/preferences/${n}`,data:e});return this.handleResponse(r)}async getChannelData(e){this.instance.failIfNotAuthenticated();const t=await this.instance.client().makeRequest({method:"GET",url:`/v1/users/${this.instance.userId}/channel_data/${e.channelId}`});return this.handleResponse(t)}async setChannelData({channelId:e,channelData:t}){this.instance.failIfNotAuthenticated();const n=await this.instance.client().makeRequest({method:"PUT",url:`/v1/users/${this.instance.userId}/channel_data/${e}`,data:{data:t}});return this.handleResponse(n)}handleResponse(e){if(e.statusCode==="error")throw new Error(e.error||e.body);return e.body}}exports.default=h;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/clients/users/index.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\n\nimport { ApiResponse } from \"../../api\";\nimport { ChannelData, User } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport {\n
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/clients/users/index.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\n\nimport { ApiResponse } from \"../../api\";\nimport { ChannelData, User } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport {\n GetPreferencesOptions,\n PreferenceOptions,\n PreferenceSet,\n SetPreferencesProperties,\n} from \"../preferences/interfaces\";\n\nimport { GetChannelDataInput, SetChannelDataInput } from \"./interfaces\";\n\nconst DEFAULT_PREFERENCE_SET_ID = \"default\";\n\nclass UserClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n async get() {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}`,\n });\n\n return this.handleResponse<User>(result);\n }\n\n async identify(props: GenericData = {}) {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}`,\n params: props,\n });\n\n return this.handleResponse<User>(result);\n }\n\n async getAllPreferences() {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences`,\n });\n\n return this.handleResponse<PreferenceSet[]>(result);\n }\n\n async getPreferences(\n options: GetPreferencesOptions = {},\n ): Promise<PreferenceSet> {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n params: { tenant: options.tenant },\n });\n\n return this.handleResponse<PreferenceSet>(result);\n }\n\n async setPreferences(\n preferenceSet: SetPreferencesProperties,\n options: PreferenceOptions = {},\n ): Promise<PreferenceSet> {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n data: preferenceSet,\n });\n\n return this.handleResponse<PreferenceSet>(result);\n }\n\n async getChannelData<T = GenericData>(params: GetChannelDataInput) {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/channel_data/${params.channelId}`,\n });\n\n return this.handleResponse<ChannelData<T>>(result);\n }\n\n async setChannelData<T = GenericData>({\n channelId,\n channelData,\n }: SetChannelDataInput) {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/channel_data/${channelId}`,\n data: { data: channelData },\n });\n\n return this.handleResponse<ChannelData<T>>(result);\n }\n\n private handleResponse<T>(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n throw new Error(response.error || response.body);\n }\n\n return response.body as T;\n }\n}\n\nexport default UserClient;\n"],"names":["DEFAULT_PREFERENCE_SET_ID","UserClient","instance","__publicField","result","props","options","preferenceSetId","preferenceSet","params","channelId","channelData","response"],"mappings":"gRAcA,MAAMA,EAA4B,UAElC,MAAMC,CAAW,CAGf,YAAYC,EAAiB,CAFrBC,EAAA,iBAGN,KAAK,SAAWD,CAAA,CAGlB,MAAM,KAAM,CACV,KAAK,SAAS,uBAAuB,EAErC,MAAME,EAAS,MAAM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AA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,iBAAiBK,EAAO,SAAS,EAAA,CACxE,EAEM,OAAA,KAAK,eAA+BL,CAAM,CAAA,CAGnD,MAAM,eAAgC,CACpC,UAAAM,EACA,YAAAC,CAAA,EACsB,CACtB,KAAK,SAAS,uBAAuB,EAErC,MAAMP,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,iBAAiBM,CAAS,GAChE,KAAM,CAAE,KAAMC,CAAY,CAAA,CAC3B,EAEM,OAAA,KAAK,eAA+BP,CAAM,CAAA,CAG3C,eAAkBQ,EAAuB,CAC3C,GAAAA,EAAS,aAAe,QAC1B,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,EAGjD,OAAOA,EAAS,IAAA,CAEpB"}
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const t=require("./clients/feed/index.js"),u=require("./knock.js"),
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const t=require("./clients/feed/index.js"),u=require("./knock.js"),r=require("./clients/objects/constants.js"),e=require("./networkStatus.js"),s=require("./clients/feed/feed.js");exports.FeedClient=t.default;exports.default=u.default;exports.TENANT_OBJECT_COLLECTION=r.TENANT_OBJECT_COLLECTION;exports.NetworkStatus=e.NetworkStatus;exports.isRequestInFlight=e.isRequestInFlight;exports.Feed=s.default;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var c = (
|
|
4
|
-
import
|
|
5
|
-
import { isRequestInFlight as
|
|
6
|
-
import
|
|
7
|
-
const
|
|
1
|
+
var g = Object.defineProperty;
|
|
2
|
+
var k = (h, e, t) => e in h ? g(h, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : h[e] = t;
|
|
3
|
+
var c = (h, e, t) => k(h, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
import _ from "eventemitter2";
|
|
5
|
+
import { isRequestInFlight as S, NetworkStatus as f } from "../../networkStatus.mjs";
|
|
6
|
+
import v from "./store.mjs";
|
|
7
|
+
const y = {
|
|
8
8
|
archived: "exclude"
|
|
9
|
-
},
|
|
10
|
-
class
|
|
9
|
+
}, b = 2e3;
|
|
10
|
+
class A {
|
|
11
11
|
constructor(e, t, s) {
|
|
12
12
|
c(this, "userFeedId");
|
|
13
13
|
c(this, "channel");
|
|
@@ -21,7 +21,7 @@ class U {
|
|
|
21
21
|
c(this, "visibilityChangeListenerConnected", !1);
|
|
22
22
|
// The raw store instance, used for binding in React and other environments
|
|
23
23
|
c(this, "store");
|
|
24
|
-
this.knock = e, this.feedId = t, this.feedId = t, this.userFeedId = this.buildUserFeedId(), this.store =
|
|
24
|
+
this.knock = e, this.feedId = t, this.feedId = t, this.userFeedId = this.buildUserFeedId(), this.store = v(), this.broadcaster = new _({ wildcard: !0, delimiter: "." }), this.defaultOptions = { ...y, ...s }, this.knock.log(`[Feed] Initialized a feed on channel ${t}`), this.initializeRealtimeConnection(), this.setupBroadcastChannel();
|
|
25
25
|
}
|
|
26
26
|
/**
|
|
27
27
|
* Used to reinitialize a current feed instance, which is useful when reauthenticating users
|
|
@@ -83,11 +83,11 @@ class U {
|
|
|
83
83
|
});
|
|
84
84
|
else {
|
|
85
85
|
s.setMetadata({ ...e, unseen_count: 0 });
|
|
86
|
-
const
|
|
87
|
-
s.setItemAttrs(
|
|
86
|
+
const r = { seen_at: (/* @__PURE__ */ new Date()).toISOString() }, n = t.map((o) => o.id);
|
|
87
|
+
s.setItemAttrs(n, r);
|
|
88
88
|
}
|
|
89
|
-
const
|
|
90
|
-
return this.emitEvent("all_seen", t),
|
|
89
|
+
const i = await this.makeBulkStatusUpdate("seen");
|
|
90
|
+
return this.emitEvent("all_seen", t), i;
|
|
91
91
|
}
|
|
92
92
|
async markAsUnseen(e) {
|
|
93
93
|
return this.optimisticallyPerformStatusUpdate(
|
|
@@ -116,11 +116,11 @@ class U {
|
|
|
116
116
|
});
|
|
117
117
|
else {
|
|
118
118
|
s.setMetadata({ ...e, unread_count: 0 });
|
|
119
|
-
const
|
|
120
|
-
s.setItemAttrs(
|
|
119
|
+
const r = { read_at: (/* @__PURE__ */ new Date()).toISOString() }, n = t.map((o) => o.id);
|
|
120
|
+
s.setItemAttrs(n, r);
|
|
121
121
|
}
|
|
122
|
-
const
|
|
123
|
-
return this.emitEvent("all_read", t),
|
|
122
|
+
const i = await this.makeBulkStatusUpdate("read");
|
|
123
|
+
return this.emitEvent("all_read", t), i;
|
|
124
124
|
}
|
|
125
125
|
async markAsUnread(e) {
|
|
126
126
|
return this.optimisticallyPerformStatusUpdate(
|
|
@@ -151,25 +151,25 @@ class U {
|
|
|
151
151
|
TODO: how do we handle rollbacks?
|
|
152
152
|
*/
|
|
153
153
|
async markAsArchived(e) {
|
|
154
|
-
const t = this.store.getState(), s = this.defaultOptions.archived === "exclude", a = Array.isArray(e) ? e : [e],
|
|
154
|
+
const t = this.store.getState(), s = this.defaultOptions.archived === "exclude", a = Array.isArray(e) ? e : [e], i = a.map((r) => r.id);
|
|
155
155
|
if (s) {
|
|
156
|
-
const
|
|
156
|
+
const r = a.filter((l) => !l.seen_at).length, n = a.filter((l) => !l.read_at).length, o = {
|
|
157
157
|
...t.metadata,
|
|
158
158
|
// Ensure that the counts don't ever go below 0 on archiving where the client state
|
|
159
159
|
// gets out of sync with the server state
|
|
160
160
|
total_count: Math.max(0, t.metadata.total_count - a.length),
|
|
161
|
-
unseen_count: Math.max(0, t.metadata.unseen_count -
|
|
162
|
-
unread_count: Math.max(0, t.metadata.unread_count -
|
|
163
|
-
},
|
|
164
|
-
(l) => !
|
|
161
|
+
unseen_count: Math.max(0, t.metadata.unseen_count - r),
|
|
162
|
+
unread_count: Math.max(0, t.metadata.unread_count - n)
|
|
163
|
+
}, u = t.items.filter(
|
|
164
|
+
(l) => !i.includes(l.id)
|
|
165
165
|
);
|
|
166
166
|
t.setResult({
|
|
167
|
-
entries:
|
|
168
|
-
meta:
|
|
167
|
+
entries: u,
|
|
168
|
+
meta: o,
|
|
169
169
|
page_info: t.pageInfo
|
|
170
170
|
});
|
|
171
171
|
} else
|
|
172
|
-
t.setItemAttrs(
|
|
172
|
+
t.setItemAttrs(i, { archived_at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
173
173
|
return this.makeStatusUpdate(e, "archived");
|
|
174
174
|
}
|
|
175
175
|
async markAllAsArchived() {
|
|
@@ -177,25 +177,25 @@ class U {
|
|
|
177
177
|
if (this.defaultOptions.archived === "exclude")
|
|
178
178
|
t.resetStore();
|
|
179
179
|
else {
|
|
180
|
-
const
|
|
181
|
-
t.setItemAttrs(
|
|
180
|
+
const i = e.map((r) => r.id);
|
|
181
|
+
t.setItemAttrs(i, { archived_at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
182
182
|
}
|
|
183
183
|
const a = await this.makeBulkStatusUpdate("archive");
|
|
184
184
|
return this.emitEvent("all_archived", e), a;
|
|
185
185
|
}
|
|
186
186
|
async markAllReadAsArchived() {
|
|
187
|
-
const { items: e, ...t } = this.store.getState(), a = e.filter((
|
|
187
|
+
const { items: e, ...t } = this.store.getState(), a = e.filter((n) => n.read_at === null).map((n) => n.id);
|
|
188
188
|
if (t.setItemAttrs(a, {
|
|
189
189
|
archived_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
190
190
|
}), this.defaultOptions.archived === "exclude") {
|
|
191
|
-
const
|
|
191
|
+
const n = e.filter((u) => !a.includes(u.id)), o = {
|
|
192
192
|
...t.metadata,
|
|
193
|
-
total_count:
|
|
193
|
+
total_count: n.length,
|
|
194
194
|
unread_count: 0
|
|
195
195
|
};
|
|
196
196
|
t.setResult({
|
|
197
|
-
entries:
|
|
198
|
-
meta:
|
|
197
|
+
entries: n,
|
|
198
|
+
meta: o,
|
|
199
199
|
page_info: t.pageInfo
|
|
200
200
|
});
|
|
201
201
|
}
|
|
@@ -213,11 +213,11 @@ class U {
|
|
|
213
213
|
this.knock.log("[Feed] User is not authenticated, skipping fetch");
|
|
214
214
|
return;
|
|
215
215
|
}
|
|
216
|
-
if (
|
|
216
|
+
if (S(t)) {
|
|
217
217
|
this.knock.log("[Feed] Request is in flight, skipping fetch");
|
|
218
218
|
return;
|
|
219
219
|
}
|
|
220
|
-
s.setNetworkStatus(e.__loadingType ??
|
|
220
|
+
s.setNetworkStatus(e.__loadingType ?? f.loading);
|
|
221
221
|
const a = {
|
|
222
222
|
...this.defaultOptions,
|
|
223
223
|
...e,
|
|
@@ -226,43 +226,58 @@ class U {
|
|
|
226
226
|
__fetchSource: void 0,
|
|
227
227
|
__experimentalCrossBrowserUpdates: void 0,
|
|
228
228
|
auto_manage_socket_connection: void 0,
|
|
229
|
-
auto_manage_socket_connection_delay: void 0
|
|
230
|
-
|
|
229
|
+
auto_manage_socket_connection_delay: void 0,
|
|
230
|
+
inserted_at_date_range: void 0
|
|
231
|
+
}, i = e.inserted_at_date_range;
|
|
232
|
+
let r = { ...a };
|
|
233
|
+
if (i) {
|
|
234
|
+
const d = {}, p = i.inclusive ?? !1;
|
|
235
|
+
if (i.start) {
|
|
236
|
+
const m = p ? "inserted_at.gte" : "inserted_at.gt";
|
|
237
|
+
d[m] = i.start;
|
|
238
|
+
}
|
|
239
|
+
if (i.end) {
|
|
240
|
+
const m = p ? "inserted_at.lte" : "inserted_at.lt";
|
|
241
|
+
d[m] = i.end;
|
|
242
|
+
}
|
|
243
|
+
r = { ...a, ...d };
|
|
244
|
+
}
|
|
245
|
+
const n = await this.knock.client().makeRequest({
|
|
231
246
|
method: "GET",
|
|
232
247
|
url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,
|
|
233
|
-
params:
|
|
248
|
+
params: r
|
|
234
249
|
});
|
|
235
250
|
if (n.statusCode === "error" || !n.body)
|
|
236
|
-
return s.setNetworkStatus(
|
|
251
|
+
return s.setNetworkStatus(f.error), {
|
|
237
252
|
status: n.statusCode,
|
|
238
253
|
data: n.error || n.body
|
|
239
254
|
};
|
|
240
|
-
const
|
|
255
|
+
const o = {
|
|
241
256
|
entries: n.body.entries,
|
|
242
257
|
meta: n.body.meta,
|
|
243
258
|
page_info: n.body.page_info
|
|
244
259
|
};
|
|
245
260
|
if (e.before) {
|
|
246
261
|
const d = { shouldSetPage: !1, shouldAppend: !0 };
|
|
247
|
-
s.setResult(
|
|
262
|
+
s.setResult(o, d);
|
|
248
263
|
} else if (e.after) {
|
|
249
264
|
const d = { shouldSetPage: !0, shouldAppend: !0 };
|
|
250
|
-
s.setResult(
|
|
265
|
+
s.setResult(o, d);
|
|
251
266
|
} else
|
|
252
|
-
s.setResult(
|
|
253
|
-
this.broadcast("messages.new",
|
|
254
|
-
const
|
|
255
|
-
items:
|
|
256
|
-
metadata:
|
|
257
|
-
event:
|
|
267
|
+
s.setResult(o);
|
|
268
|
+
this.broadcast("messages.new", o);
|
|
269
|
+
const u = e.__fetchSource === "socket" ? "items.received.realtime" : "items.received.page", l = {
|
|
270
|
+
items: o.entries,
|
|
271
|
+
metadata: o.meta,
|
|
272
|
+
event: u
|
|
258
273
|
};
|
|
259
|
-
return this.broadcast(
|
|
274
|
+
return this.broadcast(l.event, l), { data: o, status: n.statusCode };
|
|
260
275
|
}
|
|
261
276
|
async fetchNextPage() {
|
|
262
277
|
const { pageInfo: e } = this.store.getState();
|
|
263
278
|
e.after && this.fetch({
|
|
264
279
|
after: e.after,
|
|
265
|
-
__loadingType:
|
|
280
|
+
__loadingType: f.fetchMore
|
|
266
281
|
});
|
|
267
282
|
}
|
|
268
283
|
broadcast(e, t) {
|
|
@@ -280,37 +295,37 @@ class U {
|
|
|
280
295
|
return `${this.feedId}:${this.knock.userId}`;
|
|
281
296
|
}
|
|
282
297
|
optimisticallyPerformStatusUpdate(e, t, s, a) {
|
|
283
|
-
const
|
|
298
|
+
const i = this.store.getState(), r = Array.isArray(e) ? e : [e], n = r.map((o) => o.id);
|
|
284
299
|
if (a) {
|
|
285
|
-
const { metadata:
|
|
300
|
+
const { metadata: o } = i, u = r.filter((d) => {
|
|
286
301
|
switch (t) {
|
|
287
302
|
case "seen":
|
|
288
|
-
return
|
|
303
|
+
return d.seen_at === null;
|
|
289
304
|
case "unseen":
|
|
290
|
-
return
|
|
305
|
+
return d.seen_at !== null;
|
|
291
306
|
case "read":
|
|
292
307
|
case "interacted":
|
|
293
|
-
return
|
|
308
|
+
return d.read_at === null;
|
|
294
309
|
case "unread":
|
|
295
|
-
return
|
|
310
|
+
return d.read_at !== null;
|
|
296
311
|
default:
|
|
297
312
|
return !0;
|
|
298
313
|
}
|
|
299
|
-
}), l = t.startsWith("un") ?
|
|
300
|
-
|
|
301
|
-
...
|
|
302
|
-
[a]: Math.max(0,
|
|
314
|
+
}), l = t.startsWith("un") ? u.length : -u.length;
|
|
315
|
+
i.setMetadata({
|
|
316
|
+
...o,
|
|
317
|
+
[a]: Math.max(0, o[a] + l)
|
|
303
318
|
});
|
|
304
319
|
}
|
|
305
|
-
|
|
320
|
+
i.setItemAttrs(n, s);
|
|
306
321
|
}
|
|
307
322
|
async makeStatusUpdate(e, t, s) {
|
|
308
|
-
const a = Array.isArray(e) ? e : [e],
|
|
309
|
-
|
|
323
|
+
const a = Array.isArray(e) ? e : [e], i = a.map((n) => n.id), r = await this.knock.messages.batchUpdateStatuses(
|
|
324
|
+
i,
|
|
310
325
|
t,
|
|
311
326
|
{ metadata: s }
|
|
312
327
|
);
|
|
313
|
-
return this.emitEvent(t, a),
|
|
328
|
+
return this.emitEvent(t, a), r;
|
|
314
329
|
}
|
|
315
330
|
async makeBulkStatusUpdate(e) {
|
|
316
331
|
const t = {
|
|
@@ -381,7 +396,7 @@ class U {
|
|
|
381
396
|
}
|
|
382
397
|
handleVisibilityChange() {
|
|
383
398
|
var s;
|
|
384
|
-
const e = this.defaultOptions.auto_manage_socket_connection_delay ??
|
|
399
|
+
const e = this.defaultOptions.auto_manage_socket_connection_delay ?? b, t = this.knock.client();
|
|
385
400
|
document.visibilityState === "hidden" ? this.disconnectTimer = setTimeout(() => {
|
|
386
401
|
var a;
|
|
387
402
|
(a = t.socket) == null || a.disconnect(), this.disconnectTimer = null;
|
|
@@ -389,6 +404,6 @@ class U {
|
|
|
389
404
|
}
|
|
390
405
|
}
|
|
391
406
|
export {
|
|
392
|
-
|
|
407
|
+
A as default
|
|
393
408
|
};
|
|
394
409
|
//# sourceMappingURL=feed.mjs.map
|