@knocklabs/client 0.14.4 → 0.14.6

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.
Files changed (33) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/cjs/clients/feed/feed.js +1 -1
  3. package/dist/cjs/clients/feed/feed.js.map +1 -1
  4. package/dist/cjs/clients/feed/index.js +1 -1
  5. package/dist/cjs/clients/feed/index.js.map +1 -1
  6. package/dist/cjs/clients/feed/socket-manager.js +2 -0
  7. package/dist/cjs/clients/feed/socket-manager.js.map +1 -0
  8. package/dist/cjs/clients/guide/client.js +1 -1
  9. package/dist/cjs/clients/guide/client.js.map +1 -1
  10. package/dist/esm/clients/feed/feed.mjs +117 -102
  11. package/dist/esm/clients/feed/feed.mjs.map +1 -1
  12. package/dist/esm/clients/feed/index.mjs +31 -15
  13. package/dist/esm/clients/feed/index.mjs.map +1 -1
  14. package/dist/esm/clients/feed/socket-manager.mjs +81 -0
  15. package/dist/esm/clients/feed/socket-manager.mjs.map +1 -0
  16. package/dist/esm/clients/guide/client.mjs +123 -65
  17. package/dist/esm/clients/guide/client.mjs.map +1 -1
  18. package/dist/types/clients/feed/feed.d.ts +11 -6
  19. package/dist/types/clients/feed/feed.d.ts.map +1 -1
  20. package/dist/types/clients/feed/index.d.ts +2 -0
  21. package/dist/types/clients/feed/index.d.ts.map +1 -1
  22. package/dist/types/clients/feed/socket-manager.d.ts +31 -0
  23. package/dist/types/clients/feed/socket-manager.d.ts.map +1 -0
  24. package/dist/types/clients/feed/types.d.ts +4 -3
  25. package/dist/types/clients/feed/types.d.ts.map +1 -1
  26. package/dist/types/clients/guide/client.d.ts +22 -1
  27. package/dist/types/clients/guide/client.d.ts.map +1 -1
  28. package/package.json +5 -3
  29. package/src/clients/feed/feed.ts +51 -41
  30. package/src/clients/feed/index.ts +27 -3
  31. package/src/clients/feed/socket-manager.ts +185 -0
  32. package/src/clients/feed/types.ts +5 -3
  33. package/src/clients/guide/client.ts +146 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.14.6
4
+
5
+ ### Patch Changes
6
+
7
+ - a5c615e: Allow multiple instances of `Feed` to listen for real-time updates to the same notification feed
8
+
9
+ Previously, using two or more instances of `Feed` with the same in-app feed channel would result in
10
+ only the most recently connected `Feed` receiving real-time updates. Now, all instances of `Feed`
11
+ configured with the same in-app channel will receive real-time updates.
12
+
13
+ ## 0.14.5
14
+
15
+ ### Patch Changes
16
+
17
+ - 8f00623: activation location rules support for guides
18
+
3
19
  ## 0.14.4
4
20
 
5
21
  ### Patch Changes
@@ -1,2 +1,2 @@
1
- "use strict";var p=Object.defineProperty;var g=(d,e,t)=>e in d?p(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t;var l=(d,e,t)=>g(d,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),_=require("../../helpers.js"),m=require("../../networkStatus.js"),S=require("./store.js"),f=require("./utils.js"),v=d=>d&&typeof d=="object"&&"default"in d?d:{default:d},y=v(k),b={archived:"exclude"},w=2e3;class C{constructor(e,t,s){l(this,"userFeedId");l(this,"channel");l(this,"broadcaster");l(this,"defaultOptions");l(this,"broadcastChannel");l(this,"disconnectTimer",null);l(this,"hasSubscribedToRealTimeUpdates",!1);l(this,"visibilityChangeHandler",()=>{});l(this,"visibilityChangeListenerConnected",!1);l(this,"store");this.knock=e,this.feedId=t,(!t||!_.isValidUuid(t))&&this.knock.log("[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.",!0),this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=S.default(),this.broadcaster=new y.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...b,...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 n={seen_at:new Date().toISOString()},i=t.map(r=>r.id);s.setItemAttrs(i,n)}const o=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),o}async markAsUnseen(e){return this.optimisticallyPerformStatusUpdate(e,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(e,"unseen")}async markAsRead(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"read",{read_at:t},"unread_count"),this.makeStatusUpdate(e,"read")}async markAllAsRead(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...e,total_count:0,unread_count:0});else{s.setMetadata({...e,unread_count:0});const n={read_at:new Date().toISOString()},i=t.map(r=>r.id);s.setItemAttrs(i,n)}const o=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),o}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],o=a.map(n=>n.id);if(s){const n=a.filter(c=>!c.seen_at).length,i=a.filter(c=>!c.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-n),unread_count:Math.max(0,t.metadata.unread_count-i)},u=t.items.filter(c=>!o.includes(c.id));t.setResult({entries:u,meta:r,page_info:t.pageInfo})}else t.setItemAttrs(o,{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 o=e.map(n=>n.id);t.setItemAttrs(o,{archived_at:new Date().toISOString()})}const a=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),a}async markAllReadAsArchived(){const{items:e,...t}=this.store.getState(),a=e.filter(i=>i.read_at===null).map(i=>i.id);if(t.setItemAttrs(a,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const i=e.filter(u=>!a.includes(u.id)),r={...t.metadata,total_count:i.length,unread_count:0};t.setResult({entries:i,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=f.getFormattedTriggerData({...this.defaultOptions,...e}),o={...this.defaultOptions,...f.mergeDateRangeParams(e),trigger_data:a,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},n=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:o});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 c={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,c)}else if(e.after){const c={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,c)}else s.setResult(i);this.broadcast("messages.new",i);const r=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",u={items:i.entries,metadata:i.meta,event:r};return this.broadcast(u.event,u),{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 o=this.store.getState(),n=Array.isArray(e)?e:[e],i=n.map(r=>r.id);if(a){const{metadata:r}=o,u=n.filter(h=>{switch(t){case"seen":return h.seen_at===null;case"unseen":return h.seen_at!==null;case"read":case"interacted":return h.read_at===null;case"unread":return h.read_at!==null;default:return!0}}),c=t.startsWith("un")?u.length:-u.length;o.setMetadata({...r,[a]:Math.max(0,r[a]+c)})}o.setItemAttrs(i,s)}async makeStatusUpdate(e,t,s){const a=Array.isArray(e)?e:[e],o=a.map(i=>i.id),n=await this.knock.messages.batchUpdateStatuses(o,t,{metadata:s});return this.emitEvent(t,a),n}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=e=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:s})}catch(s){console.warn(`Could not broadcast ${e}, got error: ${s}`)}}initializeRealtimeConnection(){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??w,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=C;
1
+ "use strict";var g=Object.defineProperty;var p=(c,e,t)=>e in c?g(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var d=(c,e,t)=>p(c,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),_=require("nanoid"),v=require("../../helpers.js"),m=require("../../networkStatus.js"),S=require("./socket-manager.js"),y=require("./store.js"),f=require("./utils.js"),b=c=>c&&typeof c=="object"&&"default"in c?c:{default:c},w=b(k),I={archived:"exclude"},C=2e3,U="client_";class A{constructor(e,t,s,a){d(this,"defaultOptions");d(this,"referenceId");d(this,"unsubscribeFromSocketEvents");d(this,"socketManager");d(this,"userFeedId");d(this,"broadcaster");d(this,"broadcastChannel");d(this,"disconnectTimer",null);d(this,"hasSubscribedToRealTimeUpdates",!1);d(this,"visibilityChangeHandler",()=>{});d(this,"visibilityChangeListenerConnected",!1);d(this,"store");this.knock=e,this.feedId=t,(!t||!v.isValidUuid(t))&&this.knock.log("[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.",!0),this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.referenceId=U+_.nanoid(),this.socketManager=a,this.store=y.default(),this.broadcaster=new w.default({wildcard:!0,delimiter:"."}),this.defaultOptions={...I,...f.mergeDateRangeParams(s)},this.knock.log(`[Feed] Initialized a feed on channel ${t}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(e){this.socketManager=e,this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){var e;this.knock.log("[Feed] Tearing down feed instance"),(e=this.socketManager)==null||e.leave(this),this.tearDownVisibilityListeners(),this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.broadcastChannel&&this.broadcastChannel.close()}dispose(){this.knock.log("[Feed] Disposing of feed instance"),this.teardown(),this.broadcaster.removeAllListeners(),this.knock.feeds.removeInstance(this)}listenForUpdates(){var e;if(this.knock.log("[Feed] Connecting to real-time service"),this.hasSubscribedToRealTimeUpdates=!0,!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping listening for updates");return}this.unsubscribeFromSocketEvents=(e=this.socketManager)==null?void 0:e.join(this)}on(e,t){this.broadcaster.on(e,t)}off(e,t){this.broadcaster.off(e,t)}getState(){return this.store.getState()}async markAsSeen(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"seen",{seen_at:t},"unseen_count"),this.makeStatusUpdate(e,"seen")}async markAllAsSeen(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unseen")s.resetStore({...e,total_count:0,unseen_count:0});else{s.setMetadata({...e,unseen_count:0});const n={seen_at:new Date().toISOString()},i=t.map(o=>o.id);s.setItemAttrs(i,n)}const r=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),r}async markAsUnseen(e){return this.optimisticallyPerformStatusUpdate(e,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(e,"unseen")}async markAsRead(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"read",{read_at:t},"unread_count"),this.makeStatusUpdate(e,"read")}async markAllAsRead(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...e,total_count:0,unread_count:0});else{s.setMetadata({...e,unread_count:0});const n={read_at:new Date().toISOString()},i=t.map(o=>o.id);s.setItemAttrs(i,n)}const r=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),r}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e,t){const s=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:s,interacted_at:s},"unread_count"),this.makeStatusUpdate(e,"interacted",t)}async markAsArchived(e){const t=this.store.getState(),s=this.defaultOptions.archived==="exclude",a=Array.isArray(e)?e:[e],r=a.map(n=>n.id);if(s){const n=a.filter(u=>!u.seen_at).length,i=a.filter(u=>!u.read_at).length,o={...t.metadata,total_count:Math.max(0,t.metadata.total_count-a.length),unseen_count:Math.max(0,t.metadata.unseen_count-n),unread_count:Math.max(0,t.metadata.unread_count-i)},l=t.items.filter(u=>!r.includes(u.id));t.setResult({entries:l,meta:o,page_info:t.pageInfo})}else t.setItemAttrs(r,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{items:e,...t}=this.store.getState();if(this.defaultOptions.archived==="exclude")t.resetStore();else{const r=e.map(n=>n.id);t.setItemAttrs(r,{archived_at:new Date().toISOString()})}const a=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),a}async markAllReadAsArchived(){const{items:e,...t}=this.store.getState(),a=e.filter(i=>i.read_at===null).map(i=>i.id);if(t.setItemAttrs(a,{archived_at:new Date().toISOString()}),this.defaultOptions.archived==="exclude"){const i=e.filter(l=>!a.includes(l.id)),o={...t.metadata,total_count:i.length,unread_count:0};t.setResult({entries:i,meta:o,page_info:t.pageInfo})}return await this.makeBulkStatusUpdate("archive")}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{networkStatus:t,...s}=this.store.getState();if(!this.knock.isAuthenticated()){this.knock.log("[Feed] User is not authenticated, skipping fetch");return}if(m.isRequestInFlight(t)){this.knock.log("[Feed] Request is in flight, skipping fetch");return}s.setNetworkStatus(e.__loadingType??m.NetworkStatus.loading);const a=f.getFormattedTriggerData({...this.defaultOptions,...e}),r={...this.defaultOptions,...f.mergeDateRangeParams(e),trigger_data:a,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},n=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:r});if(n.statusCode==="error"||!n.body)return s.setNetworkStatus(m.NetworkStatus.error),{status:n.statusCode,data:n.error||n.body};const i={entries:n.body.entries,meta:n.body.meta,page_info:n.body.page_info};if(e.before){const u={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,u)}else if(e.after){const u={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,u)}else s.setResult(i);this.broadcast("messages.new",i);const o=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",l={items:i.entries,metadata:i.meta,event:o};return this.broadcast(l.event,l),{data:i,status:n.statusCode}}async fetchNextPage(e={}){const{pageInfo:t}=this.store.getState();t.after&&this.fetch({...e,after:t.after,__loadingType:m.NetworkStatus.fetchMore})}get socketChannelTopic(){return`feeds:${this.userFeedId}`}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({data:e}){var n;this.knock.log("[Feed] Received new real-time message");const{items:t,...s}=this.store.getState(),a=t[0],r=(n=e[this.referenceId])==null?void 0:n.metadata;r&&s.setMetadata(r),this.fetch({before:a==null?void 0:a.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,a){const r=this.store.getState(),n=Array.isArray(e)?e:[e],i=n.map(o=>o.id);if(a){const{metadata:o}=r,l=n.filter(h=>{switch(t){case"seen":return h.seen_at===null;case"unseen":return h.seen_at!==null;case"read":case"interacted":return h.read_at===null;case"unread":return h.read_at!==null;default:return!0}}),u=t.startsWith("un")?l.length:-l.length;r.setMetadata({...o,[a]:Math.max(0,o[a]+u)})}r.setItemAttrs(i,s)}async makeStatusUpdate(e,t,s){const a=Array.isArray(e)?e:[e],r=a.map(i=>i.id),n=await this.knock.messages.batchUpdateStatuses(r,t,{metadata:s});return this.emitEvent(t,a),n}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=e=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:s})}catch(s){console.warn(`Could not broadcast ${e}, got error: ${s}`)}}initializeRealtimeConnection(){var e;this.socketManager&&(this.defaultOptions.auto_manage_socket_connection&&this.setUpVisibilityListeners(),this.hasSubscribedToRealTimeUpdates&&this.knock.isAuthenticated()&&(this.unsubscribeFromSocketEvents=(e=this.socketManager)==null?void 0:e.join(this)))}async handleSocketEvent(e){switch(e.event){case S.SocketEventType.NewMessage:this.onNewMessageReceived(e);return;default:{e.event;return}}}setUpVisibilityListeners(){typeof document>"u"||this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}tearDownVisibilityListeners(){typeof document>"u"||(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeListenerConnected=!1)}emitEvent(e,t){this.broadcaster.emit(`items.${e}`,{items:t}),this.broadcaster.emit(`items:${e}`,{items:t}),this.broadcastOverChannel(`items:${e}`,{items:t})}handleVisibilityChange(){var s,a;const e=this.defaultOptions.auto_manage_socket_connection_delay??C,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var r;(r=t.socket)==null||r.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=t.socket)!=null&&s.isConnected()||(a=t.socket)==null||a.connect())}}exports.default=A;
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 { isValidUuid } from \"../../helpers\";\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\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 if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.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 // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n 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","isValidUuid","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","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","resp","disconnectDelay","client","_a"],"mappings":"keAmCMA,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,M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ChD,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAEhD,KAAK,qBAAqB,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,CAAA,CAG9C,wBAAyB,OACzB,MAAAoC,EACJ,KAAK,eAAe,qCACpBpD,EAEIqD,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 { nanoid } from \"nanoid\";\nimport type { StoreApi } from \"zustand\";\n\nimport { isValidUuid } from \"../../helpers\";\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n FetchFeedOptionsForRequest,\n} from \"./interfaces\";\nimport {\n FeedSocketManager,\n SocketEventPayload,\n SocketEventType,\n} from \"./socket-manager\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\nimport { getFormattedTriggerData, mergeDateRangeParams } from \"./utils\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nconst CLIENT_REF_ID_PREFIX = \"client_\";\n\nclass Feed {\n public readonly defaultOptions: FeedClientOptions;\n public readonly referenceId: string;\n public unsubscribeFromSocketEvents: (() => void) | undefined = undefined;\n private socketManager: FeedSocketManager | undefined;\n private userFeedId: string;\n private broadcaster: EventEmitter;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n socketManager: FeedSocketManager | undefined,\n ) {\n if (!feedId || !isValidUuid(feedId)) {\n this.knock.log(\n \"[Feed] Invalid or missing feedId provided to the Feed constructor. The feed should be a UUID of an in-app feed channel (`in_app_feed`) found in the Knock dashboard. Please provide a valid feedId to the Feed constructor.\",\n true,\n );\n }\n\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.referenceId = CLIENT_REF_ID_PREFIX + nanoid();\n this.socketManager = socketManager;\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = {\n ...feedClientDefaults,\n ...mergeDateRangeParams(options),\n };\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize(socketManager?: FeedSocketManager) {\n this.socketManager = socketManager;\n\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n this.socketManager?.leave(this);\n\n this.tearDownVisibilityListeners();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // trigger_data should be a JSON string for the API\n // this function will format the trigger data if it's an object\n // https://docs.knock.app/reference#get-feed\n const formattedTriggerData = getFormattedTriggerData({\n ...this.defaultOptions,\n ...options,\n });\n\n // Always include the default params, if they have been set\n const queryParams: FetchFeedOptionsForRequest = {\n ...this.defaultOptions,\n ...mergeDateRangeParams(options),\n trigger_data: formattedTriggerData,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage(options: FetchFeedOptions = {}) {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n ...options,\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n get socketChannelTopic(): string {\n return `feeds:${this.userFeedId}`;\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({ data }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n\n // Optimistically set the badge counts\n const metadata = data[this.referenceId]?.metadata;\n if (metadata) {\n state.setMetadata(metadata);\n }\n\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // This is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n // In server environments we might not have a socket connection\n if (!this.socketManager) return;\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setUpVisibilityListeners();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n this.unsubscribeFromSocketEvents = this.socketManager?.join(this);\n }\n }\n\n async handleSocketEvent(payload: SocketEventPayload) {\n switch (payload.event) {\n case SocketEventType.NewMessage:\n this.onNewMessageReceived(payload);\n return;\n default: {\n const _exhaustiveCheck: never = payload.event;\n return;\n }\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setUpVisibilityListeners() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private tearDownVisibilityListeners() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n client.socket?.connect();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","CLIENT_REF_ID_PREFIX","Feed","knock","feedId","options","socketManager","__publicField","isValidUuid","nanoid","createStore","EventEmitter","mergeDateRangeParams","_a","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","formattedTriggerData","getFormattedTriggerData","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","payload","stringifiedPayload","e","SocketEventType","disconnectDelay","client","_b"],"mappings":"uhBAwCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAE3BC,EAAuB,UAE7B,MAAMC,CAAK,CAgBT,YACWC,EACAC,EACTC,EACAC,EACA,CApBcC,EAAA,uBACAA,EAAA,oBACTA,EAAA,oCACCA,EAAA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B,mBAAoB,KAAK,uBAAuB,EAAA,CAGpE,6BAA8B,CAChC,OAAO,SAAa,MAEf,SAAA,oBACP,mBACA,KAAK,uBACP,EACA,KAAK,kCAAoC,GAAA,CAGnC,UACNN,EAQA1B,EACA,CAEA,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAChD,KAAK,YAAY,KAAK,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,EAEhD,KAAK,qBAAqB,SAAS0B,CAAI,GAAI,CAAE,MAAA1B,EAAO,CAAA,CAG9C,wBAAyB,SACzB,MAAAoC,EACJ,KAAK,eAAe,qCACpBvD,EAEIwD,EAAS,KAAK,MAAM,OAAO,EAE7B,SAAS,kBAAoB,SAE1B,KAAA,gBAAkB,WAAW,IAAM,QACtC3C,EAAA2C,EAAO,SAAP,MAAA3C,EAAe,aACf,KAAK,gBAAkB,MACtB0C,CAAe,EACT,SAAS,kBAAoB,YAGlC,KAAK,kBACP,aAAa,KAAK,eAAe,EACjC,KAAK,gBAAkB,OAIpB1C,EAAA2C,EAAO,SAAP,MAAA3C,EAAe,gBAClB4C,EAAAD,EAAO,SAAP,MAAAC,EAAe,UAEnB,CAEJ"}
@@ -1,2 +1,2 @@
1
- "use strict";var c=Object.defineProperty;var d=(n,e,t)=>e in n?c(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var s=(n,e,t)=>d(n,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const a=require("./feed.js");class f{constructor(e){s(this,"instance");s(this,"feedInstances",[]);this.instance=e}initialize(e,t={}){const i=new a.default(this.instance,e,t);return this.feedInstances.push(i),i}removeInstance(e){this.feedInstances=this.feedInstances.filter(t=>t!==e)}teardownInstances(){for(const e of this.feedInstances)e.teardown()}reinitializeInstances(){for(const e of this.feedInstances)e.reinitialize()}}exports.Feed=a.default;exports.default=f;
1
+ "use strict";var c=Object.defineProperty;var o=(s,e,t)=>e in s?c(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var n=(s,e,t)=>o(s,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("./feed.js"),r=require("./socket-manager.js");class d{constructor(e){n(this,"instance");n(this,"feedInstances",[]);n(this,"socketManager");this.instance=e}initialize(e,t={}){this.initSocketManager();const a=new i.default(this.instance,e,t,this.socketManager);return this.feedInstances.push(a),a}removeInstance(e){this.feedInstances=this.feedInstances.filter(t=>t!==e)}teardownInstances(){for(const e of this.feedInstances)e.teardown()}reinitializeInstances(){var e;for(const t of this.feedInstances)(e=this.socketManager)==null||e.leave(t);this.socketManager=void 0,this.initSocketManager();for(const t of this.feedInstances)t.reinitialize(this.socketManager)}initSocketManager(){const e=this.instance.client().socket;e&&!this.socketManager&&(this.socketManager=new r.FeedSocketManager(e))}}exports.Feed=i.default;exports.default=d;
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/clients/feed/index.ts"],"sourcesContent":["import Knock from \"../../knock\";\n\nimport Feed from \"./feed\";\nimport { FeedClientOptions } from \"./interfaces\";\n\nclass FeedClient {\n private instance: Knock;\n private feedInstances: Feed[] = [];\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n initialize(feedChannelId: string, options: FeedClientOptions = {}) {\n const feedInstance = new Feed(this.instance, feedChannelId, options);\n this.feedInstances.push(feedInstance);\n\n return feedInstance;\n }\n\n removeInstance(feed: Feed) {\n this.feedInstances = this.feedInstances.filter((f) => f !== feed);\n }\n\n teardownInstances() {\n for (const feed of this.feedInstances) {\n feed.teardown();\n }\n }\n\n reinitializeInstances() {\n for (const feed of this.feedInstances) {\n feed.reinitialize();\n }\n }\n}\n\nexport { Feed };\nexport default FeedClient;\n"],"names":["FeedClient","instance","__publicField","feedChannelId","options","feedInstance","Feed","feed","f"],"mappings":"6SAKA,MAAMA,CAAW,CAIf,YAAYC,EAAiB,CAHrBC,EAAA,iBACAA,EAAA,qBAAwB,CAAC,GAG/B,KAAK,SAAWD,CAAA,CAGlB,WAAWE,EAAuBC,EAA6B,GAAI,CACjE,MAAMC,EAAe,IAAIC,EAAA,QAAK,KAAK,SAAUH,EAAeC,CAAO,EAC9D,YAAA,cAAc,KAAKC,CAAY,EAE7BA,CAAA,CAGT,eAAeE,EAAY,CACzB,KAAK,cAAgB,KAAK,cAAc,OAAQC,GAAMA,IAAMD,CAAI,CAAA,CAGlE,mBAAoB,CACP,UAAAA,KAAQ,KAAK,cACtBA,EAAK,SAAS,CAChB,CAGF,uBAAwB,CACX,UAAAA,KAAQ,KAAK,cACtBA,EAAK,aAAa,CACpB,CAEJ"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/clients/feed/index.ts"],"sourcesContent":["import Knock from \"../../knock\";\n\nimport Feed from \"./feed\";\nimport { FeedClientOptions } from \"./interfaces\";\nimport { FeedSocketManager } from \"./socket-manager\";\n\nclass FeedClient {\n private instance: Knock;\n private feedInstances: Feed[] = [];\n private socketManager: FeedSocketManager | undefined;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n initialize(feedChannelId: string, options: FeedClientOptions = {}) {\n this.initSocketManager();\n\n const feedInstance = new Feed(\n this.instance,\n feedChannelId,\n options,\n this.socketManager,\n );\n this.feedInstances.push(feedInstance);\n return feedInstance;\n }\n\n removeInstance(feed: Feed) {\n this.feedInstances = this.feedInstances.filter((f) => f !== feed);\n }\n\n teardownInstances() {\n for (const feed of this.feedInstances) {\n feed.teardown();\n }\n }\n\n reinitializeInstances() {\n for (const feed of this.feedInstances) {\n this.socketManager?.leave(feed);\n }\n\n // The API client has a new socket once it's reinitialized,\n // so we need to set up a new socket manager\n this.socketManager = undefined;\n this.initSocketManager();\n\n for (const feed of this.feedInstances) {\n feed.reinitialize(this.socketManager);\n }\n }\n\n private initSocketManager() {\n const socket = this.instance.client().socket;\n if (socket && !this.socketManager) {\n this.socketManager = new FeedSocketManager(socket);\n }\n }\n}\n\nexport { Feed };\nexport default FeedClient;\n"],"names":["FeedClient","instance","__publicField","feedChannelId","options","feedInstance","Feed","feed","f","_a","socket","FeedSocketManager"],"mappings":"8UAMA,MAAMA,CAAW,CAKf,YAAYC,EAAiB,CAJrBC,EAAA,iBACAA,EAAA,qBAAwB,CAAC,GACzBA,EAAA,sBAGN,KAAK,SAAWD,CAAA,CAGlB,WAAWE,EAAuBC,EAA6B,GAAI,CACjE,KAAK,kBAAkB,EAEvB,MAAMC,EAAe,IAAIC,EAAA,QACvB,KAAK,SACLH,EACAC,EACA,KAAK,aACP,EACK,YAAA,cAAc,KAAKC,CAAY,EAC7BA,CAAA,CAGT,eAAeE,EAAY,CACzB,KAAK,cAAgB,KAAK,cAAc,OAAQC,GAAMA,IAAMD,CAAI,CAAA,CAGlE,mBAAoB,CACP,UAAAA,KAAQ,KAAK,cACtBA,EAAK,SAAS,CAChB,CAGF,uBAAwB,OACX,UAAAA,KAAQ,KAAK,eACjBE,EAAA,KAAA,gBAAA,MAAAA,EAAe,MAAMF,GAK5B,KAAK,cAAgB,OACrB,KAAK,kBAAkB,EAEZ,UAAAA,KAAQ,KAAK,cACjBA,EAAA,aAAa,KAAK,aAAa,CACtC,CAGM,mBAAoB,CAC1B,MAAMG,EAAS,KAAK,SAAS,OAAS,EAAA,OAClCA,GAAU,CAAC,KAAK,gBACb,KAAA,cAAgB,IAAIC,EAAA,kBAAkBD,CAAM,EACnD,CAEJ"}
@@ -0,0 +1,2 @@
1
+ "use strict";var f=Object.defineProperty;var S=(c,e,s)=>e in c?f(c,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):c[e]=s;var h=(c,e,s)=>S(c,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("@tanstack/store"),u={NewMessage:"new-message"},m=[u.NewMessage];class d{constructor(e){h(this,"channels");h(this,"params");h(this,"inbox");this.socket=e,this.channels={},this.params={},this.inbox=new k.Store({})}join(e){const s=e.socketChannelTopic,t=e.referenceId,a=e.defaultOptions;this.socket.isConnected()||this.socket.connect(),this.params[s]||(this.params[s]={});const n=this.params[s][t],l=!n||JSON.stringify(n)!==JSON.stringify(a);if(l&&(this.params[s]={...this.params[s],[t]:a}),!this.channels[s]||l){const o=this.socket.channel(s,this.params[s]);for(const p of m)o.on(p,b=>this.setInbox(b));this.channels[s]=o}const r=this.channels[s];return["closed","errored"].includes(r.state)&&r.join(),this.inbox.subscribe(()=>{const o=this.inbox.state[t];o&&e.handleSocketEvent(o)})}leave(e){var o;(o=e.unsubscribeFromSocketEvents)==null||o.call(e);const s=e.socketChannelTopic,t=e.referenceId,a={...this.params},n=a[s]||{};n[t]&&delete n[t];const r={...this.channels},i=r[s];if(i&&Object.keys(n).length===0){for(const p of m)i.off(p);i.leave(),delete r[s]}this.params=a,this.channels=r}setInbox(e){const{attn:s,...t}=e;this.inbox.setState(()=>s.reduce((a,n)=>({...a,[n]:t}),{}))}}exports.FeedSocketManager=d;exports.SocketEventType=u;
2
+ //# sourceMappingURL=socket-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"socket-manager.js","sources":["../../../../src/clients/feed/socket-manager.ts"],"sourcesContent":["import { Store } from \"@tanstack/store\";\nimport { Channel, Socket } from \"phoenix\";\n\nimport Feed from \"./feed\";\nimport type { FeedClientOptions, FeedMetadata } from \"./interfaces\";\n\nexport const SocketEventType = {\n NewMessage: \"new-message\",\n} as const;\n\nconst SOCKET_EVENT_TYPES = [SocketEventType.NewMessage];\n\ntype ClientQueryParams = FeedClientOptions;\n\n// e.g. feeds:<channel_id>:<user_id>\ntype ChannelTopic = string;\n\n// Unique reference id of a feed client\ntype ClientReferenceId = string;\n\ntype NewMessageEventPayload = {\n event: typeof SocketEventType.NewMessage;\n /**\n * @deprecated Top-level feed metadata. Exists for legacy reasons.\n */\n metadata: FeedMetadata;\n /** Feed metadata, keyed by client reference id. */\n data: Record<ClientReferenceId, { metadata: FeedMetadata }>;\n};\n\nexport type SocketEventPayload = NewMessageEventPayload;\n\n// \"attn\" field contains a list of client reference ids that should be notified\n// of a socket event.\ntype WithAttn<P> = P & { attn: ClientReferenceId[] };\n\ntype FeedSocketInbox = Record<ClientReferenceId, SocketEventPayload>;\n\n/*\n * Manages socket subscriptions for feeds, allowing multiple feed clients\n * to listen for real time updates from the socket API via a single socket\n * connection.\n */\nexport class FeedSocketManager {\n // Mapping of live channels by topic. Note, there can be one or more feed\n // client(s) that can subscribe.\n private channels: Record<ChannelTopic, Channel>;\n\n // Mapping of query params for each feeds client, partitioned by reference id,\n // and grouped by channel topic. It's a double nested object that looks like:\n // {\n // \"feeds:<channel_1>:<user_1>\": {\n // \"ref-1\": {\n // \"tenant\": \"foo\",\n // },\n // \"ref-2\": {\n // \"tenant\": \"bar\",\n // },\n // },\n // \"feeds:<channel_2>:<user_1>\": {\n // \"ref-3\": {\n // \"tenant\": \"baz\",\n // },\n // }\n // }\n //\n // Each time a new feed client joins a channel, we send all cumulated\n // params such that the socket API can apply filtering rules and figure out\n // which feed clients should be notified based on reference ids in\n // \"attn\" field of the event payload when sending out an event.\n private params: Record<\n ChannelTopic,\n Record<ClientReferenceId, ClientQueryParams>\n >;\n\n // A reactive store that captures a new socket event, that notifies any feed\n // clients that have subscribed.\n private inbox: Store<\n FeedSocketInbox,\n (cb: FeedSocketInbox) => FeedSocketInbox\n >;\n\n constructor(readonly socket: Socket) {\n this.channels = {};\n this.params = {};\n this.inbox = new Store<FeedSocketInbox>({});\n }\n\n join(feed: Feed) {\n const topic = feed.socketChannelTopic;\n const referenceId = feed.referenceId;\n const params = feed.defaultOptions;\n\n // Ensure a live socket connection if not yet connected.\n if (!this.socket.isConnected()) {\n this.socket.connect();\n }\n\n // If a new feed client joins, or has updated query params, then\n // track the updated params and (re)join with the latest query params.\n // Note, each time we send combined params of all feed clients that\n // have subscribed for a given feed channel and user, grouped by\n // client's reference id.\n if (!this.params[topic]) {\n this.params[topic] = {};\n }\n\n const maybeParams = this.params[topic][referenceId];\n const hasNewOrUpdatedParams =\n !maybeParams || JSON.stringify(maybeParams) !== JSON.stringify(params);\n\n if (hasNewOrUpdatedParams) {\n // Tracks all subscribed clients' params by reference id and by topic.\n this.params[topic] = { ...this.params[topic], [referenceId]: params };\n }\n\n if (!this.channels[topic] || hasNewOrUpdatedParams) {\n const newChannel = this.socket.channel(topic, this.params[topic]);\n for (const eventType of SOCKET_EVENT_TYPES) {\n newChannel.on(eventType, (payload) => this.setInbox(payload));\n }\n // Tracks live channels by channel topic.\n this.channels[topic] = newChannel;\n }\n\n const channel = this.channels[topic];\n\n // Join the channel if not already joined or joining or leaving.\n if ([\"closed\", \"errored\"].includes(channel.state)) {\n channel.join();\n }\n\n // Let the feed client subscribe to the \"inbox\", so it can be notified\n // when there's a new socket event that is relevant to it\n const unsub = this.inbox.subscribe(() => {\n const payload = this.inbox.state[referenceId];\n if (!payload) return;\n\n feed.handleSocketEvent(payload);\n });\n\n return unsub;\n }\n\n leave(feed: Feed) {\n feed.unsubscribeFromSocketEvents?.();\n\n const topic = feed.socketChannelTopic;\n const referenceId = feed.referenceId;\n\n const partitionedParams = { ...this.params };\n const paramsForTopic = partitionedParams[topic] || {};\n const paramsForReferenceClient = paramsForTopic[referenceId];\n\n if (paramsForReferenceClient) {\n delete paramsForTopic[referenceId];\n }\n\n const channels = { ...this.channels };\n const channelForTopic = channels[topic];\n if (channelForTopic && Object.keys(paramsForTopic).length === 0) {\n for (const eventType of SOCKET_EVENT_TYPES) {\n channelForTopic.off(eventType);\n }\n channelForTopic.leave();\n delete channels[topic];\n }\n\n this.params = partitionedParams;\n this.channels = channels;\n }\n\n private setInbox(payload: WithAttn<SocketEventPayload>) {\n const { attn, ...rest } = payload;\n\n // Set the incoming socket event into the inbox, keyed by relevant client\n // reference ids provided by the server (via attn field), so we can notify\n // only the clients that need to be notified.\n this.inbox.setState(() =>\n attn.reduce((acc, referenceId) => {\n return { ...acc, [referenceId]: rest };\n }, {}),\n );\n }\n}\n"],"names":["SocketEventType","SOCKET_EVENT_TYPES","FeedSocketManager","socket","__publicField","Store","feed","topic","referenceId","params","maybeParams","hasNewOrUpdatedParams","newChannel","eventType","payload","channel","_a","partitionedParams","paramsForTopic","channels","channelForTopic","attn","rest","acc"],"mappings":"uRAMaA,EAAkB,CAC7B,WAAY,aACd,EAEMC,EAAqB,CAACD,EAAgB,UAAU,EAiC/C,MAAME,CAAkB,CAuC7B,YAAqBC,EAAgB,CApC7BC,EAAA,iBAwBAA,EAAA,eAOAA,EAAA,cAKa,KAAA,OAAAD,EACnB,KAAK,SAAW,CAAC,EACjB,KAAK,OAAS,CAAC,EACf,KAAK,MAAQ,IAAIE,EAAuB,MAAA,EAAE,CAAA,CAG5C,KAAKC,EAAY,CACf,MAAMC,EAAQD,EAAK,mBACbE,EAAcF,EAAK,YACnBG,EAASH,EAAK,eAGf,KAAK,OAAO,eACf,KAAK,OAAO,QAAQ,EAQjB,KAAK,OAAOC,CAAK,IACf,KAAA,OAAOA,CAAK,EAAI,CAAC,GAGxB,MAAMG,EAAc,KAAK,OAAOH,CAAK,EAAEC,CAAW,EAC5CG,EACJ,CAACD,GAAe,KAAK,UAAUA,CAAW,IAAM,KAAK,UAAUD,CAAM,EAOvE,GALIE,IAEF,KAAK,OAAOJ,CAAK,EAAI,CAAE,GAAG,KAAK,OAAOA,CAAK,EAAG,CAACC,CAAW,EAAGC,CAAO,GAGlE,CAAC,KAAK,SAASF,CAAK,GAAKI,EAAuB,CAC5C,MAAAC,EAAa,KAAK,OAAO,QAAQL,EAAO,KAAK,OAAOA,CAAK,CAAC,EAChE,UAAWM,KAAaZ,EACtBW,EAAW,GAAGC,EAAYC,GAAY,KAAK,SAASA,CAAO,CAAC,EAGzD,KAAA,SAASP,CAAK,EAAIK,CAAA,CAGnB,MAAAG,EAAU,KAAK,SAASR,CAAK,EAGnC,MAAI,CAAC,SAAU,SAAS,EAAE,SAASQ,EAAQ,KAAK,GAC9CA,EAAQ,KAAK,EAKD,KAAK,MAAM,UAAU,IAAM,CACvC,MAAMD,EAAU,KAAK,MAAM,MAAMN,CAAW,EACvCM,GAELR,EAAK,kBAAkBQ,CAAO,CAAA,CAC/B,CAEM,CAGT,MAAMR,EAAY,QAChBU,EAAAV,EAAK,8BAAL,MAAAU,EAAA,KAAAV,GAEA,MAAMC,EAAQD,EAAK,mBACbE,EAAcF,EAAK,YAEnBW,EAAoB,CAAE,GAAG,KAAK,MAAO,EACrCC,EAAiBD,EAAkBV,CAAK,GAAK,CAAC,EACnBW,EAAeV,CAAW,GAGzD,OAAOU,EAAeV,CAAW,EAGnC,MAAMW,EAAW,CAAE,GAAG,KAAK,QAAS,EAC9BC,EAAkBD,EAASZ,CAAK,EACtC,GAAIa,GAAmB,OAAO,KAAKF,CAAc,EAAE,SAAW,EAAG,CAC/D,UAAWL,KAAaZ,EACtBmB,EAAgB,IAAIP,CAAS,EAE/BO,EAAgB,MAAM,EACtB,OAAOD,EAASZ,CAAK,CAAA,CAGvB,KAAK,OAASU,EACd,KAAK,SAAWE,CAAA,CAGV,SAASL,EAAuC,CACtD,KAAM,CAAE,KAAAO,EAAM,GAAGC,CAAA,EAASR,EAK1B,KAAK,MAAM,SAAS,IAClBO,EAAK,OAAO,CAACE,EAAKf,KACT,CAAE,GAAGe,EAAK,CAACf,CAAW,EAAGc,CAAK,GACpC,CAAE,CAAA,CACP,CAAA,CAEJ"}
@@ -1,2 +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;
1
+ "use strict";var k=Object.defineProperty;var m=(o,e,t)=>e in o?k(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var c=(o,e,t)=>m(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@tanstack/store"),g=require("urlpattern-polyfill"),u=o=>[...o].sort((e,t)=>t.priority-e.priority||new Date(t.inserted_at).getTime()-new Date(e.inserted_at).getTime()),l=o=>`/v1/users/${o}/guides`;class f{constructor(e,t,s={},n={}){c(this,"store");c(this,"socket");c(this,"socketChannel");c(this,"socketChannelTopic");c(this,"socketEventTypes",["guide.added","guide.updated","guide.removed"]);c(this,"pushStateFn");c(this,"replaceStateFn");this.knock=e,this.channelId=t,this.targetParams=s,this.options=n;const{trackLocationFromWindow:i=!0}=n,r=i?window==null?void 0:window.location.href:void 0;this.store=new p.Store({guides:[],queries:{},location:r});const{socket:a}=this.knock.client();this.socket=a,this.socketChannelTopic=`guides:${t}`,i&&this.listenForLocationChangesFromWindow(),this.knock.log("[Guide] Initialized a guide client")}cleanup(){this.unsubscribe(),this.removeEventListeners()}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),n=this.store.state.queries[s];if(n)return n;this.store.setState(r=>({...r,queries:{...r.queries,[s]:{status:"loading"}}}));let i;try{const r=await this.knock.user.getGuides(this.channelId,t);i={status:"ok"},this.store.setState(a=>({...a,guides:r.entries.map(h=>this.localCopy(h)),queries:{...a.queries,[s]:i}}))}catch(r){i={status:"error",error:r},this.store.setState(a=>({...a,queries:{...a.queries,[s]:i}}))}return i}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,n=>this.handleSocketEvent(n));["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=>{if(t.type&&t.type!==s.type||t.key&&t.key!==s.key)return!1;const n=s.activation_location_rules||[];return!(n.length>0&&e.location&&!n.reduce((r,a)=>{if(r===!1)return!1;switch(a.directive){case"allow":return r===!0||a.pattern.test(e.location)?!0:void 0;case"block":return a.pattern.test(e.location)?!1:r}},void 0))})}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 n={...this.buildEngagementEventBaseParams(e,s),content:s.content,data:this.targetParams.data,tenant:this.targetParams.tenant};return this.knock.user.markGuideStepAs("seen",n),s}async markAsInteracted(e,t,s){this.knock.log(`[Guide] Marking as interacted (Guide key: ${e.key}, Step ref:${t.ref})`);const n=new Date().toISOString(),i=this.setStepMessageAttrs(e.key,t.ref,{read_at:n,interacted_at:n});if(!i)return;const r={...this.buildEngagementEventBaseParams(e,i),metadata:s};return this.knock.user.markGuideStepAs("interacted",r),i}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 n=this.buildEngagementEventBaseParams(e,s);return this.knock.user.markGuideStepAs("archived",n),s}localCopy(e){const t=this,s={...e};return s.steps=e.steps.map(({message:n,...i})=>{const r={...i,message:{...n},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 r.markAsSeen=r.markAsSeen.bind(r),r.markAsInteracted=r.markAsInteracted.bind(r),r.markAsArchived=r.markAsArchived.bind(r),r}),s.activation_location_rules=e.activation_location_rules.map(n=>({...n,pattern:new g.URLPattern({pathname:n.pathname})})),s}buildQueryParams(e={}){const t={...this.targetParams,...e};let s=Object.fromEntries(Object.entries(t).filter(([n,i])=>i!=null));return s=s.data?{...s,data:JSON.stringify(s.data)}:s,s}formatQueryKey(e){const s=Object.keys(e).sort().map(i=>`${encodeURIComponent(i)}=${encodeURIComponent(e[i])}`).join("&"),n=l(this.knock.userId);return s?`${n}?${s}`:n}setStepMessageAttrs(e,t,s){let n;return this.store.setState(i=>{const r=i.guides.map(a=>{if(a.key!==e)return a;const h=a.steps.map(d=>(d.ref!==t||(d.message={...d.message,...s},n=d),d));return{...a,steps:h}});return{...i,guides:r}}),n}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:u([...s.guides,t])}))}replaceOrAddGuide({data:e}){const t=this.localCopy(e.guide);this.store.setState(s=>{let n=!1;const i=s.guides.map(r=>r.key!==t.key?r:(n=!0,t));return{...s,guides:u(n?i:[...i,t])}})}removeGuide({data:e}){this.store.setState(t=>{const s=t.guides.filter(n=>n.key!==e.guide.key);return{...t,guides:s}})}handleLocationChange(){const e=window.location.href;this.store.state.location!==e&&(this.knock.log(`[Guide] Handle Location change: ${e}`),this.store.setState(t=>({...t,location:e})))}listenForLocationChangesFromWindow(){if(window!=null&&window.history){window.addEventListener("popstate",this.handleLocationChange),window.addEventListener("hashchange",this.handleLocationChange);const e=window.history.pushState,t=window.history.replaceState;window.history.pushState=new Proxy(e,{apply:(s,n,i)=>{Reflect.apply(s,n,i),setTimeout(()=>{this.handleLocationChange()},0)}}),window.history.replaceState=new Proxy(t,{apply:(s,n,i)=>{Reflect.apply(s,n,i),setTimeout(()=>{this.handleLocationChange()},0)}}),this.pushStateFn=e,this.replaceStateFn=t}else this.knock.log("[Guide] Unable to access the `window.history` object to detect location changes")}removeEventListeners(){window.removeEventListener("popstate",this.handleLocationChange),window.removeEventListener("hashchange",this.handleLocationChange),this.pushStateFn&&(window.history.pushState=this.pushStateFn,this.pushStateFn=void 0),this.replaceStateFn&&(window.history.replaceState=this.replaceStateFn,this.replaceStateFn=void 0)}}exports.KnockGuideClient=f;exports.guidesApiRootPath=l;
2
2
  //# sourceMappingURL=client.js.map
@@ -1 +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,CA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K,MAAM,GAAG,EAC3D,MAAA,CAAE,GAAGF,EAAO,OAAAhB,CAAO,CAAA,CAC3B,CAAA,CAEL"}
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\";\nimport { URLPattern } from \"urlpattern-polyfill\";\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 GuideActivationLocationRuleData {\n directive: \"allow\" | \"block\";\n pathname: string;\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 activation_location_rules: GuideActivationLocationRuleData[];\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\ninterface KnockGuideActivationLocationRule\n extends GuideActivationLocationRuleData {\n pattern: URLPattern;\n}\n\nexport interface KnockGuide extends GuideData {\n steps: KnockGuideStep[];\n activation_location_rules: KnockGuideActivationLocationRule[];\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 location: string | undefined;\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\ntype ConstructorOpts = {\n trackLocationFromWindow?: boolean;\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 // Original history methods to monkey patch, or restore in cleanups.\n private pushStateFn: History[\"pushState\"] | undefined;\n private replaceStateFn: History[\"replaceState\"] | undefined;\n\n constructor(\n readonly knock: Knock,\n readonly channelId: string,\n readonly targetParams: TargetParams = {},\n readonly options: ConstructorOpts = {},\n ) {\n const { trackLocationFromWindow = true } = options;\n\n const location = trackLocationFromWindow\n ? window?.location.href\n : undefined;\n\n this.store = new Store<StoreState>({\n guides: [],\n queries: {},\n location,\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 if (trackLocationFromWindow) {\n this.listenForLocationChangesFromWindow();\n }\n\n this.knock.log(\"[Guide] Initialized a guide client\");\n }\n\n cleanup() {\n this.unsubscribe();\n this.removeEventListeners();\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 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 const locationRules = guide.activation_location_rules || [];\n\n if (locationRules.length > 0 && state.location) {\n const allowed = locationRules.reduce<boolean | undefined>(\n (acc, rule) => {\n // Any matched block rule prevails so no need to evaluate further\n // as soon as there is one.\n if (acc === false) return false;\n\n // At this point we either have a matched allow rule (acc is true),\n // or no matched rule found yet (acc is undefined).\n\n switch (rule.directive) {\n case \"allow\": {\n // No need to evaluate more allow rules once we matched one\n // since any matched allowed rule means allow.\n if (acc === true) return true;\n\n const matched = rule.pattern.test(state.location);\n return matched ? true : undefined;\n }\n\n case \"block\": {\n // Always test block rules (unless already matched to block)\n // because they'd prevail over matched allow rules.\n const matched = rule.pattern.test(state.location);\n return matched ? false : acc;\n }\n }\n },\n undefined,\n );\n\n if (!allowed) 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 localGuide.activation_location_rules =\n remoteGuide.activation_location_rules.map((rule) => {\n return {\n ...rule,\n pattern: new URLPattern({ pathname: rule.pathname }),\n };\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 private handleLocationChange() {\n const href = window.location.href;\n if (this.store.state.location === href) return;\n\n this.knock.log(`[Guide] Handle Location change: ${href}`);\n\n this.store.setState((state) => ({ ...state, location: href }));\n }\n\n private listenForLocationChangesFromWindow() {\n if (window?.history) {\n // 1. Listen for browser back/forward button clicks.\n window.addEventListener(\"popstate\", this.handleLocationChange);\n\n // 2. Listen for hash changes in case it's used for routing.\n window.addEventListener(\"hashchange\", this.handleLocationChange);\n\n // 3. Monkey-patch history methods to catch programmatic navigation.\n const pushStateFn = window.history.pushState;\n const replaceStateFn = window.history.replaceState;\n\n // Use setTimeout to allow the browser state to potentially settle.\n window.history.pushState = new Proxy(pushStateFn, {\n apply: (target, history, args) => {\n Reflect.apply(target, history, args);\n setTimeout(() => {\n this.handleLocationChange();\n }, 0);\n },\n });\n window.history.replaceState = new Proxy(replaceStateFn, {\n apply: (target, history, args) => {\n Reflect.apply(target, history, args);\n setTimeout(() => {\n this.handleLocationChange();\n }, 0);\n },\n });\n\n // 4. Keep refs to the original handlers so we can restore during cleanup.\n this.pushStateFn = pushStateFn;\n this.replaceStateFn = replaceStateFn;\n } else {\n this.knock.log(\n \"[Guide] Unable to access the `window.history` object to detect location changes\",\n );\n }\n }\n\n private removeEventListeners() {\n window.removeEventListener(\"popstate\", this.handleLocationChange);\n window.removeEventListener(\"hashchange\", this.handleLocationChange);\n\n if (this.pushStateFn) {\n window.history.pushState = this.pushStateFn;\n this.pushStateFn = undefined;\n }\n if (this.replaceStateFn) {\n window.history.replaceState = this.replaceStateFn;\n this.replaceStateFn = undefined;\n }\n }\n}\n"],"names":["sortGuides","guides","a","b","guidesApiRootPath","userId","KnockGuideClient","knock","channelId","targetParams","options","__publicField","trackLocationFromWindow","location","Store","maybeSocket","opts","queryParams","queryKey","maybeQueryStatus","state","queryStatus","data","g","e","params","newChannel","eventType","payload","event","filters","guide","locationRules","acc","rule","step","updatedStep","metadata","ts","remoteGuide","self","localGuide","message","rest","localStep","URLPattern","filterParams","combinedParams","_k","v","queryStr","key","basePath","guideKey","stepRef","attrs","steps","replaced","href","pushStateFn","replaceStateFn","target","history","args"],"mappings":"wTAOMA,EAAcC,GACX,CAAC,GAAGA,CAAM,EAA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