@knocklabs/client 0.13.1 → 0.14.1

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.14.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 4c41841: feat: accept options in the fetchNextPage method
8
+
9
+ ## 0.14.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 711948c: feat: add guide client, hooks, provider, and components
14
+
3
15
  ## 0.13.1
4
16
 
5
17
  ### Patch Changes
@@ -1,2 +1,2 @@
1
- "use strict";var p=Object.defineProperty;var k=(c,e,t)=>e in c?p(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var d=(c,e,t)=>k(c,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const g=require("eventemitter2"),m=require("../../networkStatus.js"),_=require("./store.js"),f=require("./utils.js"),S=c=>c&&typeof c=="object"&&"default"in c?c:{default:c},v=S(g),y={archived:"exclude"},b=2e3;class w{constructor(e,t,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=e,this.feedId=t,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=_.default(),this.broadcaster=new v.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...y,...f.mergeDateRangeParams(s)},this.knock.log(`[Feed] Initialized a feed on channel ${t}`),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 e=this.knock.client().socket;e&&!e.isConnected()&&e.connect(),this.channel&&["closed","errored"].includes(this.channel.state)&&this.channel.join()}on(e,t){this.broadcaster.on(e,t)}off(e,t){this.broadcaster.off(e,t)}getState(){return this.store.getState()}async markAsSeen(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"seen",{seen_at:t},"unseen_count"),this.makeStatusUpdate(e,"seen")}async markAllAsSeen(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unseen")s.resetStore({...e,total_count:0,unseen_count:0});else{s.setMetadata({...e,unseen_count:0});const i={seen_at:new Date().toISOString()},o=t.map(r=>r.id);s.setItemAttrs(o,i)}const n=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),n}async markAsUnseen(e){return this.optimisticallyPerformStatusUpdate(e,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(e,"unseen")}async markAsRead(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"read",{read_at:t},"unread_count"),this.makeStatusUpdate(e,"read")}async markAllAsRead(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...e,total_count:0,unread_count:0});else{s.setMetadata({...e,unread_count:0});const i={read_at:new Date().toISOString()},o=t.map(r=>r.id);s.setItemAttrs(o,i)}const n=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),n}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e,t){const s=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:s,interacted_at:s},"unread_count"),this.makeStatusUpdate(e,"interacted",t)}async markAsArchived(e){const t=this.store.getState(),s=this.defaultOptions.archived==="exclude",a=Array.isArray(e)?e:[e],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={...t.metadata,total_count:Math.max(0,t.metadata.total_count-a.length),unseen_count:Math.max(0,t.metadata.unseen_count-i),unread_count:Math.max(0,t.metadata.unread_count-o)},l=t.items.filter(u=>!n.includes(u.id));t.setResult({entries:l,meta:r,page_info:t.pageInfo})}else t.setItemAttrs(n,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{items:e,...t}=this.store.getState();if(this.defaultOptions.archived==="exclude")t.resetStore();else{const n=e.map(i=>i.id);t.setItemAttrs(n,{archived_at:new Date().toISOString()})}const a=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),a}async markAllReadAsArchived(){const{items:e,...t}=this.store.getState(),a=e.filter(o=>o.read_at===null).map(o=>o.id);if(t.setItemAttrs(a,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const o=e.filter(l=>!a.includes(l.id)),r={...t.metadata,total_count:o.length,unread_count:0};t.setResult({entries:o,meta:r,page_info:t.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{networkStatus:t,...s}=this.store.getState();if(!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping fetch");return}if(m.isRequestInFlight(t)){this.knock.log("[Feed] Request is in flight, skipping fetch");return}s.setNetworkStatus(e.__loadingType??m.NetworkStatus.loading);const a={...this.defaultOptions,...f.mergeDateRangeParams(e),__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(e.before){const l={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,l)}else if(e.after){const l={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,l)}else s.setResult(i);this.broadcast("messages.new",i);const o=e.__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:e}=this.store.getState();e.after&&this.fetch({after:e.after,__loadingType:m.NetworkStatus.fetchMore})}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({metadata:e}){this.knock.log("[Feed] Received new real-time message");const{items:t,...s}=this.store.getState(),a=t[0];s.setMetadata(e),this.fetch({before:a==null?void 0:a.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,a){const n=this.store.getState(),i=Array.isArray(e)?e:[e],o=i.map(r=>r.id);if(a){const{metadata:r}=n,l=i.filter(h=>{switch(t){case"seen":return h.seen_at===null;case"unseen":return h.seen_at!==null;case"read":case"interacted":return h.read_at===null;case"unread":return h.read_at!==null;default:return!0}}),u=t.startsWith("un")?l.length:-l.length;n.setMetadata({...r,[a]:Math.max(0,r[a]+u)})}n.setItemAttrs(o,s)}async makeStatusUpdate(e,t,s){const a=Array.isArray(e)?e:[e],n=a.map(o=>o.id),i=await this.knock.messages.batchUpdateStatuses(n,t,{metadata:s});return this.emitEvent(t,a),i}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=e=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:s})}catch(s){console.warn(`Could not broadcast ${e}, got error: ${s}`)}}initializeRealtimeConnection(){const{socket:e}=this.knock.client();e&&(this.channel=e.channel(`feeds:${this.userFeedId}`,this.defaultOptions),this.channel.on("new-message",t=>this.onNewMessageReceived(t)),this.defaultOptions.auto_manage_socket_connection&&this.setupAutoSocketManager(),this.hasSubscribedToRealTimeUpdates&&this.knock.isAuthenticated()&&(e.isConnected()||e.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(e,t){this.broadcaster.emit(`items.${e}`,{items:t}),this.broadcaster.emit(`items:${e}`,{items:t}),this.broadcastOverChannel(`items:${e}`,{items:t})}handleVisibilityChange(){var s;const e=this.defaultOptions.auto_manage_socket_connection_delay??b,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var a;(a=t.socket)==null||a.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=t.socket)!=null&&s.isConnected()||this.initializeRealtimeConnection())}}exports.default=w;
1
+ "use strict";var p=Object.defineProperty;var k=(c,e,t)=>e in c?p(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var d=(c,e,t)=>k(c,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const g=require("eventemitter2"),m=require("../../networkStatus.js"),_=require("./store.js"),f=require("./utils.js"),S=c=>c&&typeof c=="object"&&"default"in c?c:{default:c},v=S(g),y={archived:"exclude"},b=2e3;class w{constructor(e,t,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=e,this.feedId=t,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=_.default(),this.broadcaster=new v.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...y,...f.mergeDateRangeParams(s)},this.knock.log(`[Feed] Initialized a feed on channel ${t}`),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 e=this.knock.client().socket;e&&!e.isConnected()&&e.connect(),this.channel&&["closed","errored"].includes(this.channel.state)&&this.channel.join()}on(e,t){this.broadcaster.on(e,t)}off(e,t){this.broadcaster.off(e,t)}getState(){return this.store.getState()}async markAsSeen(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"seen",{seen_at:t},"unseen_count"),this.makeStatusUpdate(e,"seen")}async markAllAsSeen(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unseen")s.resetStore({...e,total_count:0,unseen_count:0});else{s.setMetadata({...e,unseen_count:0});const i={seen_at:new Date().toISOString()},o=t.map(r=>r.id);s.setItemAttrs(o,i)}const n=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),n}async markAsUnseen(e){return this.optimisticallyPerformStatusUpdate(e,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(e,"unseen")}async markAsRead(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"read",{read_at:t},"unread_count"),this.makeStatusUpdate(e,"read")}async markAllAsRead(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...e,total_count:0,unread_count:0});else{s.setMetadata({...e,unread_count:0});const i={read_at:new Date().toISOString()},o=t.map(r=>r.id);s.setItemAttrs(o,i)}const n=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),n}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e,t){const s=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:s,interacted_at:s},"unread_count"),this.makeStatusUpdate(e,"interacted",t)}async markAsArchived(e){const t=this.store.getState(),s=this.defaultOptions.archived==="exclude",a=Array.isArray(e)?e:[e],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={...t.metadata,total_count:Math.max(0,t.metadata.total_count-a.length),unseen_count:Math.max(0,t.metadata.unseen_count-i),unread_count:Math.max(0,t.metadata.unread_count-o)},l=t.items.filter(u=>!n.includes(u.id));t.setResult({entries:l,meta:r,page_info:t.pageInfo})}else t.setItemAttrs(n,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{items:e,...t}=this.store.getState();if(this.defaultOptions.archived==="exclude")t.resetStore();else{const n=e.map(i=>i.id);t.setItemAttrs(n,{archived_at:new Date().toISOString()})}const a=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),a}async markAllReadAsArchived(){const{items:e,...t}=this.store.getState(),a=e.filter(o=>o.read_at===null).map(o=>o.id);if(t.setItemAttrs(a,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const o=e.filter(l=>!a.includes(l.id)),r={...t.metadata,total_count:o.length,unread_count:0};t.setResult({entries:o,meta:r,page_info:t.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{networkStatus:t,...s}=this.store.getState();if(!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping fetch");return}if(m.isRequestInFlight(t)){this.knock.log("[Feed] Request is in flight, skipping fetch");return}s.setNetworkStatus(e.__loadingType??m.NetworkStatus.loading);const a={...this.defaultOptions,...f.mergeDateRangeParams(e),__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(e.before){const l={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,l)}else if(e.after){const l={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,l)}else s.setResult(i);this.broadcast("messages.new",i);const o=e.__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(e={}){const{pageInfo:t}=this.store.getState();t.after&&this.fetch({...e,after:t.after,__loadingType:m.NetworkStatus.fetchMore})}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({metadata:e}){this.knock.log("[Feed] Received new real-time message");const{items:t,...s}=this.store.getState(),a=t[0];s.setMetadata(e),this.fetch({before:a==null?void 0:a.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,a){const n=this.store.getState(),i=Array.isArray(e)?e:[e],o=i.map(r=>r.id);if(a){const{metadata:r}=n,l=i.filter(h=>{switch(t){case"seen":return h.seen_at===null;case"unseen":return h.seen_at!==null;case"read":case"interacted":return h.read_at===null;case"unread":return h.read_at!==null;default:return!0}}),u=t.startsWith("un")?l.length:-l.length;n.setMetadata({...r,[a]:Math.max(0,r[a]+u)})}n.setItemAttrs(o,s)}async makeStatusUpdate(e,t,s){const a=Array.isArray(e)?e:[e],n=a.map(o=>o.id),i=await this.knock.messages.batchUpdateStatuses(n,t,{metadata:s});return this.emitEvent(t,a),i}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=e=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:s})}catch(s){console.warn(`Could not broadcast ${e}, got error: ${s}`)}}initializeRealtimeConnection(){const{socket:e}=this.knock.client();e&&(this.channel=e.channel(`feeds:${this.userFeedId}`,this.defaultOptions),this.channel.on("new-message",t=>this.onNewMessageReceived(t)),this.defaultOptions.auto_manage_socket_connection&&this.setupAutoSocketManager(),this.hasSubscribedToRealTimeUpdates&&this.knock.isAuthenticated()&&(e.isConnected()||e.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(e,t){this.broadcaster.emit(`items.${e}`,{items:t}),this.broadcaster.emit(`items:${e}`,{items:t}),this.broadcastOverChannel(`items:${e}`,{items:t})}handleVisibilityChange(){var s;const e=this.defaultOptions.auto_manage_socket_connection_delay??b,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var a;(a=t.socket)==null||a.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=t.socket)!=null&&s.isConnected()||this.initializeRealtimeConnection())}}exports.default=w;
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\";\nimport { mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\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 = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize() {\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 ...mergeDateRangeParams(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 // 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","mergeDateRangeParams","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","payload","stringifiedPayload","e","resp","disconnectDelay","client","_a"],"mappings":"ocAiCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAEjC,MAAMC,CAAK,CAcT,YACWC,EACAC,EACTC,EACA,CAjBMC,EA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K,YAAY,KAAK,SAASwB,CAAI,GAAI,CAAE,MAAAxB,EAAO,EAEhD,KAAK,qBAAqB,SAASwB,CAAI,GAAI,CAAE,MAAAxB,EAAO,CAAA,CAG9C,wBAAyB,OACzB,MAAAkC,EACJ,KAAK,eAAe,qCACpBjD,EAEIkD,EAAS,KAAK,MAAM,OAAO,EAE7B,SAAS,kBAAoB,SAE1B,KAAA,gBAAkB,WAAW,IAAM,QACtCC,EAAAD,EAAO,SAAP,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
+ {"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\";\nimport { mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\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 = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize() {\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 ...mergeDateRangeParams(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(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n 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","mergeDateRangeParams","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","payload","stringifiedPayload","e","resp","disconnectDelay","client","_a"],"mappings":"ocAiCMA,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,CACpB,GAAGR,EACH,GAAGS,uBAAqBJ,CAAO,CACjC,EACA,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,KAAA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AEK,KAAA,QAAQ,GAAG,cAAgBuC,GAAS,KAAK,qBAAqBA,CAAI,CAAC,EAEpE,KAAK,eAAe,+BACtB,KAAK,uBAAuB,EAK1B,KAAK,gCAAkC,KAAK,MAAM,oBAC/CvC,EAAY,iBAA2B,QAAQ,EACpD,KAAK,QAAQ,KAAK,GACpB,CAOM,wBAAyB,CAE7B,OAAO,SAAa,KACpB,KAAK,oCAKP,KAAK,wBAA0B,KAAK,uBAAuB,KAAK,IAAI,EACpE,KAAK,kCAAoC,GAChC,SAAA,iBAAiB,mBAAoB,KAAK,uBAAuB,EAAA,CAGpE,2BAA4B,CAC9B,OAAO,SAAa,MAEf,SAAA,oBACP,mBACA,KAAK,uBACP,EACA,KAAK,kCAAoC,GAAA,CAGnC,UACN8B,EAQAxB,EACA,CAEA,KAAK,YAAY,KAAK,SAASwB,CAAI,GAAI,CAAE,MAAAxB,EAAO,EAChD,KAAK,YAAY,KAAK,SAASwB,CAAI,GAAI,CAAE,MAAAxB,EAAO,EAEhD,KAAK,qBAAqB,SAASwB,CAAI,GAAI,CAAE,MAAAxB,EAAO,CAAA,CAG9C,wBAAyB,OACzB,MAAAkC,EACJ,KAAK,eAAe,qCACpBjD,EAEIkD,EAAS,KAAK,MAAM,OAAO,EAE7B,SAAS,kBAAoB,SAE1B,KAAA,gBAAkB,WAAW,IAAM,QACtCC,EAAAD,EAAO,SAAP,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"}
@@ -0,0 +1,2 @@
1
+ "use strict";var l=Object.defineProperty;var m=(o,e,t)=>e in o?l(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var u=(o,e,t)=>m(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@tanstack/store"),h=o=>[...o].sort((e,t)=>t.priority-e.priority||new Date(t.inserted_at).getTime()-new Date(e.inserted_at).getTime()),k=o=>`/v1/users/${o}/guides`;class y{constructor(e,t,s={}){u(this,"store");u(this,"socket");u(this,"socketChannel");u(this,"socketChannelTopic");u(this,"socketEventTypes",["guide.added","guide.updated","guide.removed"]);this.knock=e,this.channelId=t,this.targetParams=s,this.store=new g.Store({guides:[],queries:{}});const{socket:r}=this.knock.client();this.socket=r,this.socketChannelTopic=`guides:${t}`,this.knock.log("[Guide] Initialized a guide client")}async fetch(e){this.knock.failIfNotAuthenticated(),this.knock.log("[Guide] Loading all eligible guides");const t=this.buildQueryParams(e==null?void 0:e.filters),s=this.formatQueryKey(t),r=this.store.state.queries[s];if(r)return r;this.store.setState(i=>({...i,queries:{...i.queries,[s]:{status:"loading"}}}));let n;try{const i=await this.knock.user.getGuides(this.channelId,t);n={status:"ok"},this.store.setState(a=>({...a,guides:i.entries.map(d=>this.localCopy(d)),queries:{...a.queries,[s]:n}}))}catch(i){n={status:"error",error:i},this.store.setState(a=>({...a,queries:{...a.queries,[s]:n}}))}return n}subscribe(){if(!this.socket)return;this.knock.failIfNotAuthenticated(),this.knock.log("[Guide] Subscribing to real time updates"),this.socket.isConnected()||this.socket.connect(),this.socketChannel&&this.unsubscribe();const e={...this.targetParams,user_id:this.knock.userId},t=this.socket.channel(this.socketChannelTopic,e);for(const s of this.socketEventTypes)t.on(s,r=>this.handleSocketEvent(r));["closed","errored"].includes(t.state)&&t.join(),this.socketChannel=t}unsubscribe(){if(this.socketChannel){this.knock.log("[Guide] Unsubscribing from real time updates");for(const e of this.socketEventTypes)this.socketChannel.off(e);this.socketChannel.leave(),this.socketChannel=void 0}}handleSocketEvent(e){const{event:t,data:s}=e;switch(t){case"guide.added":return this.addGuide(e);case"guide.updated":return s.eligible?this.replaceOrAddGuide(e):this.removeGuide(e);case"guide.removed":return this.removeGuide(e);default:return}}select(e,t={}){return e.guides.filter(s=>!(t.type&&t.type!==s.type||t.key&&t.key!==s.key))}async markAsSeen(e,t){this.knock.log(`[Guide] Marking as seen (Guide key: ${e.key}, Step ref:${t.ref})`);const s=this.setStepMessageAttrs(e.key,t.ref,{seen_at:new Date().toISOString()});if(!s)return;const r={...this.buildEngagementEventBaseParams(e,s),content:s.content,data:this.targetParams.data,tenant:this.targetParams.tenant};return this.knock.user.markGuideStepAs("seen",r),s}async markAsInteracted(e,t,s){this.knock.log(`[Guide] Marking as interacted (Guide key: ${e.key}, Step ref:${t.ref})`);const r=new Date().toISOString(),n=this.setStepMessageAttrs(e.key,t.ref,{read_at:r,interacted_at:r});if(!n)return;const i={...this.buildEngagementEventBaseParams(e,n),metadata:s};return this.knock.user.markGuideStepAs("interacted",i),n}async markAsArchived(e,t){this.knock.log(`[Guide] Marking as archived (Guide key: ${e.key}, Step ref:${t.ref})`);const s=this.setStepMessageAttrs(e.key,t.ref,{archived_at:new Date().toISOString()});if(!s)return;const r=this.buildEngagementEventBaseParams(e,s);return this.knock.user.markGuideStepAs("archived",r),s}localCopy(e){const t=this,s={...e};return s.steps=e.steps.map(({message:r,...n})=>{const i={...n,message:{...r},markAsSeen(){if(!this.message.seen_at)return t.markAsSeen(s,this)},markAsInteracted({metadata:a}={}){return t.markAsInteracted(s,this,a)},markAsArchived(){if(!this.message.archived_at)return t.markAsArchived(s,this)}};return i.markAsSeen=i.markAsSeen.bind(i),i.markAsInteracted=i.markAsInteracted.bind(i),i.markAsArchived=i.markAsArchived.bind(i),i}),s}buildQueryParams(e={}){const t={...this.targetParams,...e};let s=Object.fromEntries(Object.entries(t).filter(([r,n])=>n!=null));return s=s.data?{...s,data:JSON.stringify(s.data)}:s,s}formatQueryKey(e){const s=Object.keys(e).sort().map(n=>`${encodeURIComponent(n)}=${encodeURIComponent(e[n])}`).join("&"),r=k(this.knock.userId);return s?`${r}?${s}`:r}setStepMessageAttrs(e,t,s){let r;return this.store.setState(n=>{const i=n.guides.map(a=>{if(a.key!==e)return a;const d=a.steps.map(c=>(c.ref!==t||(c.message={...c.message,...s},r=c),c));return{...a,steps:d}});return{...n,guides:i}}),r}buildEngagementEventBaseParams(e,t){return{message_id:t.message.id,channel_id:e.channel_id,guide_key:e.key,guide_id:e.id,guide_step_ref:t.ref}}addGuide({data:e}){const t=this.localCopy(e.guide);this.store.setState(s=>({...s,guides:h([...s.guides,t])}))}replaceOrAddGuide({data:e}){const t=this.localCopy(e.guide);this.store.setState(s=>{let r=!1;const n=s.guides.map(i=>i.key!==t.key?i:(r=!0,t));return{...s,guides:h(r?n:[...n,t])}})}removeGuide({data:e}){this.store.setState(t=>{const s=t.guides.filter(r=>r.key!==e.guide.key);return{...t,guides:s}})}}exports.KnockGuideClient=y;exports.guidesApiRootPath=k;
2
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sources":["../../../../src/clients/guide/client.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport { Store } from \"@tanstack/store\";\nimport { Channel, Socket } from \"phoenix\";\n\nimport Knock from \"../../knock\";\n\nconst sortGuides = (guides: KnockGuide[]) => {\n return [...guides].sort(\n (a, b) =>\n b.priority - a.priority ||\n new Date(b.inserted_at).getTime() - new Date(a.inserted_at).getTime(),\n );\n};\n\n//\n// Guides API (via User client)\n//\n\nexport const guidesApiRootPath = (userId: string | undefined | null) =>\n `/v1/users/${userId}/guides`;\n\ninterface StepMessageState {\n id: string;\n seen_at: string | null;\n read_at: string | null;\n interacted_at: string | null;\n archived_at: string | null;\n link_clicked_at: string | null;\n}\n\ninterface GuideStepData {\n ref: string;\n schema_key: string;\n schema_semver: string;\n schema_variant_key: string;\n message: StepMessageState;\n // eslint-disable-next-line\n content: any;\n}\n\ninterface GuideData {\n __typename: \"Guide\";\n channel_id: string;\n id: string;\n key: string;\n priority: number;\n type: string;\n semver: string;\n steps: GuideStepData[];\n inserted_at: string;\n updated_at: string;\n}\n\nexport interface KnockGuideStep extends GuideStepData {\n markAsSeen: () => void;\n markAsInteracted: (params?: { metadata?: GenericData }) => void;\n markAsArchived: () => void;\n}\n\nexport interface KnockGuide extends GuideData {\n steps: KnockGuideStep[];\n}\n\ntype GetGuidesQueryParams = {\n data?: string;\n tenant?: string;\n type?: string;\n};\n\ntype GetGuidesResponse = {\n entries: GuideData[];\n};\n\nexport type GuideEngagementEventBaseParams = {\n // Base params required for all engagement update events\n message_id: string;\n channel_id: string;\n guide_key: string;\n guide_id: string;\n guide_step_ref: string;\n};\n\ntype MarkAsSeenParams = GuideEngagementEventBaseParams & {\n // Rendered step content seen by the recipient\n content: GenericData;\n // Target params\n data?: GenericData;\n tenant?: string;\n};\ntype MarkAsInteractedParams = GuideEngagementEventBaseParams;\ntype MarkAsArchivedParams = GuideEngagementEventBaseParams;\n\ntype MarkGuideAsResponse = {\n status: \"ok\";\n};\n\ntype SocketEventType = \"guide.added\" | \"guide.updated\" | \"guide.removed\";\n\ntype SocketEventPayload<E extends SocketEventType, D> = {\n topic: string;\n event: E;\n data: D;\n};\n\ntype GuideAddedEvent = SocketEventPayload<\n \"guide.added\",\n { guide: GuideData; eligible: true }\n>;\n\ntype GuideUpdatedEvent = SocketEventPayload<\n \"guide.updated\",\n { guide: GuideData; eligible: boolean }\n>;\n\ntype GuideRemovedEvent = SocketEventPayload<\n \"guide.removed\",\n { guide: Pick<GuideData, \"key\"> }\n>;\n\ntype GuideSocketEvent = GuideAddedEvent | GuideUpdatedEvent | GuideRemovedEvent;\n\n//\n// Guides client\n//\n\ntype QueryKey = string;\n\ntype QueryStatus = {\n status: \"loading\" | \"ok\" | \"error\";\n error?: Error;\n};\n\ntype StoreState = {\n guides: KnockGuide[];\n queries: Record<QueryKey, QueryStatus>;\n};\n\ntype QueryFilterParams = Pick<GetGuidesQueryParams, \"type\">;\n\nexport type SelectFilterParams = {\n key?: string;\n type?: string;\n};\n\nexport type TargetParams = {\n data?: GenericData | undefined;\n tenant?: string | undefined;\n};\n\nexport class KnockGuideClient {\n public store: Store<StoreState, (state: StoreState) => StoreState>;\n\n // Phoenix channels for real time guide updates over websocket\n private socket: Socket | undefined;\n private socketChannel: Channel | undefined;\n private socketChannelTopic: string;\n private socketEventTypes = [\"guide.added\", \"guide.updated\", \"guide.removed\"];\n\n constructor(\n readonly knock: Knock,\n readonly channelId: string,\n readonly targetParams: TargetParams = {},\n ) {\n this.store = new Store<StoreState>({\n guides: [],\n queries: {},\n });\n\n // In server environments we might not have a socket connection.\n const { socket: maybeSocket } = this.knock.client();\n this.socket = maybeSocket;\n this.socketChannelTopic = `guides:${channelId}`;\n\n this.knock.log(\"[Guide] Initialized a guide client\");\n }\n\n async fetch(opts?: { filters?: QueryFilterParams }) {\n this.knock.failIfNotAuthenticated();\n this.knock.log(\"[Guide] Loading all eligible guides\");\n\n const queryParams = this.buildQueryParams(opts?.filters);\n const queryKey = this.formatQueryKey(queryParams);\n\n // If already fetched before, then noop.\n const maybeQueryStatus = this.store.state.queries[queryKey];\n if (maybeQueryStatus) {\n return maybeQueryStatus;\n }\n\n // Mark this query status as loading.\n this.store.setState((state) => ({\n ...state,\n queries: { ...state.queries, [queryKey]: { status: \"loading\" } },\n }));\n\n let queryStatus: QueryStatus;\n try {\n const data = await this.knock.user.getGuides<\n GetGuidesQueryParams,\n GetGuidesResponse\n >(this.channelId, queryParams);\n queryStatus = { status: \"ok\" };\n\n this.store.setState((state) => ({\n ...state,\n // For now assume a single fetch to get all eligible guides. When/if\n // we implement incremental loads, then this will need to be a merge\n // and sort operation.\n guides: data.entries.map((g) => this.localCopy(g)),\n queries: { ...state.queries, [queryKey]: queryStatus },\n }));\n } catch (e) {\n queryStatus = { status: \"error\", error: e as Error };\n\n this.store.setState((state) => ({\n ...state,\n queries: { ...state.queries, [queryKey]: queryStatus },\n }));\n }\n\n return queryStatus;\n }\n\n subscribe() {\n if (!this.socket) return;\n this.knock.failIfNotAuthenticated();\n this.knock.log(\"[Guide] Subscribing to real time updates\");\n\n // Ensure a live socket connection if not yet connected.\n if (!this.socket.isConnected()) {\n this.socket.connect();\n }\n\n // If there's an existing connected channel, then disconnect.\n if (this.socketChannel) {\n this.unsubscribe();\n }\n\n // Join the channel topic and subscribe to supported events.\n const params = { ...this.targetParams, user_id: this.knock.userId };\n const newChannel = this.socket.channel(this.socketChannelTopic, params);\n\n for (const eventType of this.socketEventTypes) {\n newChannel.on(eventType, (payload) => this.handleSocketEvent(payload));\n }\n\n if ([\"closed\", \"errored\"].includes(newChannel.state)) {\n newChannel.join();\n }\n\n // Track the joined channel.\n this.socketChannel = newChannel;\n }\n\n unsubscribe() {\n if (!this.socketChannel) return;\n this.knock.log(\"[Guide] Unsubscribing from real time updates\");\n\n // Unsubscribe from the socket events and leave the channel.\n for (const eventType of this.socketEventTypes) {\n this.socketChannel.off(eventType);\n }\n this.socketChannel.leave();\n\n // Unset the channel.\n this.socketChannel = undefined;\n }\n\n private handleSocketEvent(payload: GuideSocketEvent) {\n const { event, data } = payload;\n\n switch (event) {\n case \"guide.added\":\n return this.addGuide(payload);\n\n case \"guide.updated\":\n return data.eligible\n ? this.replaceOrAddGuide(payload)\n : this.removeGuide(payload);\n\n case \"guide.removed\":\n return this.removeGuide(payload);\n\n default:\n return;\n }\n }\n\n //\n // Store selector\n //\n\n select(state: StoreState, filters: SelectFilterParams = {}) {\n // TODO(KNO-7790): Need to evaluate activation rules also.\n\n return state.guides.filter((guide) => {\n if (filters.type && filters.type !== guide.type) {\n return false;\n }\n\n if (filters.key && filters.key !== guide.key) {\n return false;\n }\n\n return true;\n });\n }\n\n //\n // Engagement event handlers\n //\n // Make an optimistic update on the client side first, then send an engagement\n // event to the backend.\n //\n\n async markAsSeen(guide: GuideData, step: GuideStepData) {\n this.knock.log(\n `[Guide] Marking as seen (Guide key: ${guide.key}, Step ref:${step.ref})`,\n );\n\n const updatedStep = this.setStepMessageAttrs(guide.key, step.ref, {\n seen_at: new Date().toISOString(),\n });\n if (!updatedStep) return;\n\n const params = {\n ...this.buildEngagementEventBaseParams(guide, updatedStep),\n content: updatedStep.content,\n data: this.targetParams.data,\n tenant: this.targetParams.tenant,\n };\n\n this.knock.user.markGuideStepAs<MarkAsSeenParams, MarkGuideAsResponse>(\n \"seen\",\n params,\n );\n\n return updatedStep;\n }\n\n async markAsInteracted(\n guide: GuideData,\n step: GuideStepData,\n metadata?: GenericData,\n ) {\n this.knock.log(\n `[Guide] Marking as interacted (Guide key: ${guide.key}, Step ref:${step.ref})`,\n );\n\n const ts = new Date().toISOString();\n const updatedStep = this.setStepMessageAttrs(guide.key, step.ref, {\n read_at: ts,\n interacted_at: ts,\n });\n if (!updatedStep) return;\n\n const params = {\n ...this.buildEngagementEventBaseParams(guide, updatedStep),\n metadata,\n };\n\n this.knock.user.markGuideStepAs<\n MarkAsInteractedParams,\n MarkGuideAsResponse\n >(\"interacted\", params);\n\n return updatedStep;\n }\n\n async markAsArchived(guide: GuideData, step: GuideStepData) {\n this.knock.log(\n `[Guide] Marking as archived (Guide key: ${guide.key}, Step ref:${step.ref})`,\n );\n\n const updatedStep = this.setStepMessageAttrs(guide.key, step.ref, {\n archived_at: new Date().toISOString(),\n });\n if (!updatedStep) return;\n\n const params = this.buildEngagementEventBaseParams(guide, updatedStep);\n\n this.knock.user.markGuideStepAs<MarkAsArchivedParams, MarkGuideAsResponse>(\n \"archived\",\n params,\n );\n\n return updatedStep;\n }\n\n //\n // Helpers\n //\n\n private localCopy(remoteGuide: GuideData) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n\n // Build a local copy with helper methods added.\n const localGuide = { ...remoteGuide };\n\n localGuide.steps = remoteGuide.steps.map(({ message, ...rest }) => {\n const localStep = {\n ...rest,\n message: { ...message },\n markAsSeen() {\n // Send a seen event if it has not been previously seen.\n if (this.message.seen_at) return;\n return self.markAsSeen(localGuide, this);\n },\n markAsInteracted({ metadata }: { metadata?: GenericData } = {}) {\n // Always send an interaction event through.\n return self.markAsInteracted(localGuide, this, metadata);\n },\n markAsArchived() {\n // Send an archived event if it has not been previously archived.\n if (this.message.archived_at) return;\n return self.markAsArchived(localGuide, this);\n },\n };\n\n // Bind all engagement action handler methods to the local step object so\n // they can operate on itself.\n localStep.markAsSeen = localStep.markAsSeen.bind(localStep);\n localStep.markAsInteracted = localStep.markAsInteracted.bind(localStep);\n localStep.markAsArchived = localStep.markAsArchived.bind(localStep);\n\n return localStep;\n });\n\n return localGuide as KnockGuide;\n }\n\n private buildQueryParams(filterParams: QueryFilterParams = {}) {\n // Combine the target params with the given filter params.\n const combinedParams = { ...this.targetParams, ...filterParams };\n\n // Prune out any keys that have an undefined or null value.\n let params = Object.fromEntries(\n Object.entries(combinedParams).filter(\n ([_k, v]) => v !== undefined && v !== null,\n ),\n );\n\n // Encode target data as a JSON string, if provided.\n params = params.data\n ? { ...params, data: JSON.stringify(params.data) }\n : params;\n\n return params as GetGuidesQueryParams;\n }\n\n private formatQueryKey(queryParams: GenericData) {\n const sortedKeys = Object.keys(queryParams).sort();\n\n const queryStr = sortedKeys\n .map(\n (key) =>\n `${encodeURIComponent(key)}=${encodeURIComponent(queryParams[key])}`,\n )\n .join(\"&\");\n\n const basePath = guidesApiRootPath(this.knock.userId);\n return queryStr ? `${basePath}?${queryStr}` : basePath;\n }\n\n private setStepMessageAttrs(\n guideKey: string,\n stepRef: string,\n attrs: Partial<StepMessageState>,\n ) {\n let updatedStep: KnockGuideStep | undefined;\n\n this.store.setState((state) => {\n const guides = state.guides.map((guide) => {\n if (guide.key !== guideKey) return guide;\n\n const steps = guide.steps.map((step) => {\n if (step.ref !== stepRef) return step;\n\n // Mutate in place and maintain the same obj ref so to make it easier\n // to use in hook deps.\n step.message = { ...step.message, ...attrs };\n updatedStep = step;\n\n return step;\n });\n return { ...guide, steps };\n });\n return { ...state, guides };\n });\n\n return updatedStep;\n }\n\n private buildEngagementEventBaseParams(\n guide: GuideData,\n step: GuideStepData,\n ) {\n return {\n message_id: step.message.id,\n channel_id: guide.channel_id,\n guide_key: guide.key,\n guide_id: guide.id,\n guide_step_ref: step.ref,\n };\n }\n\n private addGuide({ data }: GuideAddedEvent) {\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n return { ...state, guides: sortGuides([...state.guides, guide]) };\n });\n }\n\n private replaceOrAddGuide({ data }: GuideUpdatedEvent) {\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n let replaced = false;\n\n const guides = state.guides.map((g) => {\n if (g.key !== guide.key) return g;\n replaced = true;\n return guide;\n });\n\n return {\n ...state,\n guides: replaced ? sortGuides(guides) : sortGuides([...guides, guide]),\n };\n });\n }\n\n private removeGuide({ data }: GuideUpdatedEvent | GuideRemovedEvent) {\n this.store.setState((state) => {\n const guides = state.guides.filter((g) => g.key !== data.guide.key);\n return { ...state, guides };\n });\n }\n}\n"],"names":["sortGuides","guides","a","b","guidesApiRootPath","userId","KnockGuideClient","knock","channelId","targetParams","__publicField","Store","maybeSocket","opts","queryParams","queryKey","maybeQueryStatus","state","queryStatus","data","g","e","params","newChannel","eventType","payload","event","filters","guide","step","updatedStep","metadata","ts","remoteGuide","self","localGuide","message","rest","localStep","filterParams","combinedParams","_k","v","queryStr","key","basePath","guideKey","stepRef","attrs","steps","replaced"],"mappings":"uRAMMA,EAAcC,GACX,CAAC,GAAGA,CAAM,EAAE,KACjB,CAACC,EAAGC,IACFA,EAAE,SAAWD,EAAE,UACf,IAAI,KAAKC,EAAE,WAAW,EAAE,UAAY,IAAI,KAAKD,EAAE,WAAW,EAAE,QAAQ,CACxE,EAOWE,EAAqBC,GAChC,aAAaA,CAAM,UAkId,MAAMC,CAAiB,CAS5B,YACWC,EACAC,EACAC,EAA6B,CAAA,EACtC,CAZKC,EAAA,cAGCA,EAAA,eACAA,EAAA,sBACAA,EAAA,2BACAA,EAAA,wBAAmB,CAAC,cAAe,gBAAiB,eAAe,GAGhE,KAAA,MAAAH,EACA,KAAA,UAAAC,EACA,KAAA,aAAAC,EAEJ,KAAA,MAAQ,IAAIE,QAAkB,CACjC,OAAQ,CAAC,EACT,QAAS,CAAA,C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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;
1
+ "use strict";var u=Object.defineProperty;var h=(n,e,t)=>e in n?u(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var a=(n,e,t)=>h(n,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("../guide/client.js"),r="default";class l{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||r,s=await this.instance.client().makeRequest({method:"GET",url:`/v1/users/${this.instance.userId}/preferences/${t}`,params:{tenant:e.tenant}});return this.handleResponse(s)}async setPreferences(e,t={}){this.instance.failIfNotAuthenticated();const s=t.preferenceSet||r,c=await this.instance.client().makeRequest({method:"PUT",url:`/v1/users/${this.instance.userId}/preferences/${s}`,data:e});return this.handleResponse(c)}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 s=await this.instance.client().makeRequest({method:"PUT",url:`/v1/users/${this.instance.userId}/channel_data/${e}`,data:{data:t}});return this.handleResponse(s)}async getGuides(e,t){const s=await this.instance.client().makeRequest({method:"GET",url:`${i.guidesApiRootPath(this.instance.userId)}/${e}`,params:t});return this.handleResponse(s)}async markGuideStepAs(e,t){const s=await this.instance.client().makeRequest({method:"PUT",url:`${i.guidesApiRootPath(this.instance.userId)}/messages/${t.message_id}/${e}`,data:t});return this.handleResponse(s)}handleResponse(e){if(e.statusCode==="error")throw new Error(e.error||e.body);return e.body}}exports.default=l;
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 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,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,EAAA,CACvC,EAEM,OAAA,KAAK,eAAqBA,CAAM,CAAA,CAGzC,MAAM,SAASC,EAAqB,GAAI,CACtC,KAAK,SAAS,uBAAuB,EAErC,MAAMD,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,GACtC,OAAQC,CAAA,CACT,EAEM,OAAA,KAAK,eAAqBD,CAAM,CAAA,CAGzC,MAAM,mBAAoB,CACxB,KAAK,SAAS,uBAAuB,EAErC,MAAMA,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,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1B,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,EAGjD,OAAOA,EAAS,IAAA,CAEpB"}
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 GuideEngagementEventBaseParams,\n guidesApiRootPath,\n} from \"../guide/client\";\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 async getGuides<P, R>(channelId: string, params: P) {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `${guidesApiRootPath(this.instance.userId)}/${channelId}`,\n params,\n });\n\n return this.handleResponse<R>(result);\n }\n\n async markGuideStepAs<P extends GuideEngagementEventBaseParams, R>(\n status: \"seen\" | \"interacted\" | \"archived\",\n params: P,\n ) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `${guidesApiRootPath(this.instance.userId)}/messages/${params.message_id}/${status}`,\n data: params,\n });\n\n return this.handleResponse<R>(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","guidesApiRootPath","status","response"],"mappings":"sTAkBMA,EAA4B,UAElC,MAAMC,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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;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const t=require("./clients/feed/index.js"),u=require("./knock.js"),i=require("./clients/guide/client.js"),n=require("./clients/objects/constants.js"),e=require("./networkStatus.js"),r=require("./clients/feed/feed.js");exports.FeedClient=t.default;exports.default=u.default;exports.KnockGuideClient=i.KnockGuideClient;exports.TENANT_OBJECT_COLLECTION=n.TENANT_OBJECT_COLLECTION;exports.NetworkStatus=e.NetworkStatus;exports.isRequestInFlight=e.isRequestInFlight;exports.Feed=r.default;
2
2
  //# sourceMappingURL=index.js.map
@@ -262,10 +262,11 @@ class I {
262
262
  };
263
263
  return this.broadcast(r.event, r), { data: i, status: n.statusCode };
264
264
  }
265
- async fetchNextPage() {
266
- const { pageInfo: e } = this.store.getState();
267
- e.after && this.fetch({
268
- after: e.after,
265
+ async fetchNextPage(e = {}) {
266
+ const { pageInfo: t } = this.store.getState();
267
+ t.after && this.fetch({
268
+ ...e,
269
+ after: t.after,
269
270
  __loadingType: m.fetchMore
270
271
  });
271
272
  }