Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@knocklabs/client

Package Overview
Dependencies
Maintainers
1
Versions
79
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@knocklabs/client - npm Package Compare versions

Comparing version 0.10.4 to 0.10.5

6

CHANGELOG.md
# Changelog
## 0.10.5
### Patch Changes
- 044eb0f: fix: check if document is defined before setting up auto socket manager
## 0.10.4

@@ -4,0 +10,0 @@

2

dist/cjs/clients/feed/feed.js

@@ -1,2 +0,2 @@

"use strict";var S=Object.defineProperty;var k=(m,e,t)=>e in m?S(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t;var u=(m,e,t)=>(k(m,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const p=require("eventemitter2"),f=require("../../networkStatus.js"),g=require("./store.js"),_={archived:"exclude"},v=2e3;class y{constructor(e,t,a){u(this,"userFeedId");u(this,"channel");u(this,"broadcaster");u(this,"defaultOptions");u(this,"broadcastChannel");u(this,"disconnectTimer",null);u(this,"hasSubscribedToRealTimeUpdates",!1);u(this,"visibilityChangeHandler",()=>{});u(this,"visibilityChangeListenerConnected",!1);u(this,"store");this.knock=e,this.feedId=t,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=g.default(),this.broadcaster=new p({wildcard:!0,delimiter:"."}),this.defaultOptions={..._,...a},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(){this.knock.log("[Feed] Connecting to real-time service"),this.hasSubscribedToRealTimeUpdates=!0;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{getState:e,setState:t}=this.store,{metadata:a,items:n}=e();if(this.defaultOptions.status==="unseen")t(i=>i.resetStore({...a,total_count:0,unseen_count:0}));else{t(o=>o.setMetadata({...a,unseen_count:0}));const i={seen_at:new Date().toISOString()},l=n.map(o=>o.id);t(o=>o.setItemAttrs(l,i))}const s=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",n),s}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{getState:e,setState:t}=this.store,{metadata:a,items:n}=e();if(this.defaultOptions.status==="unread")t(i=>i.resetStore({...a,total_count:0,unread_count:0}));else{t(o=>o.setMetadata({...a,unread_count:0}));const i={read_at:new Date().toISOString()},l=n.map(o=>o.id);t(o=>o.setItemAttrs(l,i))}const s=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",n),s}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:t,interacted_at:t},"unread_count"),this.makeStatusUpdate(e,"interacted")}async markAsArchived(e){const{getState:t,setState:a}=this.store,n=t(),r=this.defaultOptions.archived==="exclude",s=Array.isArray(e)?e:[e],i=s.map(l=>l.id);if(r){const l=s.filter(c=>!c.seen_at).length,o=s.filter(c=>!c.read_at).length,d={...n.metadata,total_count:n.metadata.total_count-s.length,unseen_count:n.metadata.unseen_count-l,unread_count:n.metadata.unread_count-o},h=n.items.filter(c=>!i.includes(c.id));a(c=>c.setResult({entries:h,meta:d,page_info:c.pageInfo}))}else n.setItemAttrs(i,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{setState:e,getState:t}=this.store,{items:a}=t(),n=this.defaultOptions.archived==="exclude";e(n?s=>s.resetStore():s=>{const i=a.map(l=>l.id);s.setItemAttrs(i,{archived_at:new Date().toISOString()})});const r=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",a),r}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{setState:t,getState:a}=this.store,{networkStatus:n}=a();if(f.isRequestInFlight(n))return;t(d=>d.setNetworkStatus(e.__loadingType??f.NetworkStatus.loading));const r={...this.defaultOptions,...e,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},s=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:r});if(s.statusCode==="error"||!s.body)return t(d=>d.setNetworkStatus(f.NetworkStatus.error)),{status:s.statusCode,data:s.error||s.body};const i={entries:s.body.entries,meta:s.body.meta,page_info:s.body.page_info};if(e.before){const d={shouldSetPage:!1,shouldAppend:!0};t(h=>h.setResult(i,d))}else if(e.after){const d={shouldSetPage:!0,shouldAppend:!0};t(h=>h.setResult(i,d))}else t(d=>d.setResult(i));this.broadcast("messages.new",i);const l=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",o={items:i.entries,metadata:i.meta,event:l};return this.broadcast(o.event,o),{data:i,status:s.statusCode}}async fetchNextPage(){const{getState:e}=this.store,{pageInfo:t}=e();t.after&&this.fetch({after:t.after,__loadingType:f.NetworkStatus.fetchMore})}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({metadata:e}){this.knock.log("[Feed] Received new real-time message");const{getState:t,setState:a}=this.store,{items:n}=t(),r=n[0];a(s=>s.setMetadata(e)),this.fetch({before:r==null?void 0:r.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,a,n){const{getState:r,setState:s}=this.store,i=Array.isArray(e)?e:[e],l=i.map(o=>o.id);if(n){const{metadata:o}=r(),d=i.filter(c=>{switch(t){case"seen":return c.seen_at===null;case"unseen":return c.seen_at!==null;case"read":case"interacted":return c.read_at===null;case"unread":return c.read_at!==null;default:return!0}}),h=t.startsWith("un")?d.length:-d.length;s(c=>c.setMetadata({...o,[n]:Math.max(0,o[n]+h)}))}s(o=>o.setItemAttrs(l,a))}async makeStatusUpdate(e,t){const a=Array.isArray(e)?e:[e],n=a.map(s=>s.id),r=await this.knock.messages.batchUpdateStatuses(n,t);return this.emitEvent(t,a),r}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 a=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:a})}catch(a){console.warn(`Could not broadcast ${e}, got error: ${a}`)}}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&&(e.isConnected()||e.connect(),this.channel.join()))}setupAutoSocketManager(){this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}teardownAutoSocketManager(){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 a;const e=this.defaultOptions.auto_manage_socket_connection_delay??v,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var n;(n=t.socket)==null||n.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(a=t.socket)!=null&&a.isConnected()||this.initializeRealtimeConnection())}}exports.default=y;
"use strict";var p=Object.defineProperty;var S=(m,e,t)=>e in m?p(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t;var u=(m,e,t)=>(S(m,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),f=require("../../networkStatus.js"),g=require("./store.js"),_={archived:"exclude"},v=2e3;class y{constructor(e,t,a){u(this,"userFeedId");u(this,"channel");u(this,"broadcaster");u(this,"defaultOptions");u(this,"broadcastChannel");u(this,"disconnectTimer",null);u(this,"hasSubscribedToRealTimeUpdates",!1);u(this,"visibilityChangeHandler",()=>{});u(this,"visibilityChangeListenerConnected",!1);u(this,"store");this.knock=e,this.feedId=t,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=g.default(),this.broadcaster=new k({wildcard:!0,delimiter:"."}),this.defaultOptions={..._,...a},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(){this.knock.log("[Feed] Connecting to real-time service"),this.hasSubscribedToRealTimeUpdates=!0;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{getState:e,setState:t}=this.store,{metadata:a,items:n}=e();if(this.defaultOptions.status==="unseen")t(i=>i.resetStore({...a,total_count:0,unseen_count:0}));else{t(o=>o.setMetadata({...a,unseen_count:0}));const i={seen_at:new Date().toISOString()},l=n.map(o=>o.id);t(o=>o.setItemAttrs(l,i))}const s=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",n),s}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{getState:e,setState:t}=this.store,{metadata:a,items:n}=e();if(this.defaultOptions.status==="unread")t(i=>i.resetStore({...a,total_count:0,unread_count:0}));else{t(o=>o.setMetadata({...a,unread_count:0}));const i={read_at:new Date().toISOString()},l=n.map(o=>o.id);t(o=>o.setItemAttrs(l,i))}const s=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",n),s}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:t,interacted_at:t},"unread_count"),this.makeStatusUpdate(e,"interacted")}async markAsArchived(e){const{getState:t,setState:a}=this.store,n=t(),r=this.defaultOptions.archived==="exclude",s=Array.isArray(e)?e:[e],i=s.map(l=>l.id);if(r){const l=s.filter(c=>!c.seen_at).length,o=s.filter(c=>!c.read_at).length,d={...n.metadata,total_count:n.metadata.total_count-s.length,unseen_count:n.metadata.unseen_count-l,unread_count:n.metadata.unread_count-o},h=n.items.filter(c=>!i.includes(c.id));a(c=>c.setResult({entries:h,meta:d,page_info:c.pageInfo}))}else n.setItemAttrs(i,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{setState:e,getState:t}=this.store,{items:a}=t(),n=this.defaultOptions.archived==="exclude";e(n?s=>s.resetStore():s=>{const i=a.map(l=>l.id);s.setItemAttrs(i,{archived_at:new Date().toISOString()})});const r=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",a),r}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{setState:t,getState:a}=this.store,{networkStatus:n}=a();if(f.isRequestInFlight(n))return;t(d=>d.setNetworkStatus(e.__loadingType??f.NetworkStatus.loading));const r={...this.defaultOptions,...e,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},s=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:r});if(s.statusCode==="error"||!s.body)return t(d=>d.setNetworkStatus(f.NetworkStatus.error)),{status:s.statusCode,data:s.error||s.body};const i={entries:s.body.entries,meta:s.body.meta,page_info:s.body.page_info};if(e.before){const d={shouldSetPage:!1,shouldAppend:!0};t(h=>h.setResult(i,d))}else if(e.after){const d={shouldSetPage:!0,shouldAppend:!0};t(h=>h.setResult(i,d))}else t(d=>d.setResult(i));this.broadcast("messages.new",i);const l=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",o={items:i.entries,metadata:i.meta,event:l};return this.broadcast(o.event,o),{data:i,status:s.statusCode}}async fetchNextPage(){const{getState:e}=this.store,{pageInfo:t}=e();t.after&&this.fetch({after:t.after,__loadingType:f.NetworkStatus.fetchMore})}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({metadata:e}){this.knock.log("[Feed] Received new real-time message");const{getState:t,setState:a}=this.store,{items:n}=t(),r=n[0];a(s=>s.setMetadata(e)),this.fetch({before:r==null?void 0:r.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,a,n){const{getState:r,setState:s}=this.store,i=Array.isArray(e)?e:[e],l=i.map(o=>o.id);if(n){const{metadata:o}=r(),d=i.filter(c=>{switch(t){case"seen":return c.seen_at===null;case"unseen":return c.seen_at!==null;case"read":case"interacted":return c.read_at===null;case"unread":return c.read_at!==null;default:return!0}}),h=t.startsWith("un")?d.length:-d.length;s(c=>c.setMetadata({...o,[n]:Math.max(0,o[n]+h)}))}s(o=>o.setItemAttrs(l,a))}async makeStatusUpdate(e,t){const a=Array.isArray(e)?e:[e],n=a.map(s=>s.id),r=await this.knock.messages.batchUpdateStatuses(n,t);return this.emitEvent(t,a),r}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 a=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:a})}catch(a){console.warn(`Could not broadcast ${e}, got error: ${a}`)}}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&&(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 a;const e=this.defaultOptions.auto_manage_socket_connection_delay??v,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var n;(n=t.socket)==null||n.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(a=t.socket)!=null&&a.isConnected()||this.initializeRealtimeConnection())}}exports.default=y;
//# sourceMappingURL=feed.js.map
{
"name": "@knocklabs/client",
"version": "0.10.4",
"version": "0.10.5",
"description": "The clientside library for interacting with Knock",

@@ -5,0 +5,0 @@ "homepage": "https://github.com/knocklabs/javascript/tree/main/packages/client",

@@ -732,3 +732,8 @@ import EventEmitter from "eventemitter2";

private setupAutoSocketManager() {
if (this.visibilityChangeListenerConnected) return;
if (
typeof document === "undefined" ||
this.visibilityChangeListenerConnected
) {
return;
}

@@ -741,2 +746,4 @@ this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);

private teardownAutoSocketManager() {
if (typeof document === "undefined") return;
document.removeEventListener(

@@ -743,0 +750,0 @@ "visibilitychange",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc