@knocklabs/client 0.17.1 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/cjs/api.js +1 -1
- package/dist/cjs/clients/guide/client.js +1 -1
- package/dist/cjs/clients/guide/client.js.map +1 -1
- package/dist/cjs/knock.js +1 -1
- package/dist/cjs/knock.js.map +1 -1
- package/dist/esm/api.mjs +1 -1
- package/dist/esm/clients/guide/client.mjs +14 -14
- package/dist/esm/clients/guide/client.mjs.map +1 -1
- package/dist/esm/knock.mjs +54 -49
- package/dist/esm/knock.mjs.map +1 -1
- package/dist/types/clients/guide/client.d.ts.map +1 -1
- package/dist/types/clients/guide/types.d.ts +1 -0
- package/dist/types/clients/guide/types.d.ts.map +1 -1
- package/dist/types/interfaces.d.ts +1 -0
- package/dist/types/interfaces.d.ts.map +1 -1
- package/dist/types/knock.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/clients/guide/client.ts +12 -2
- package/src/clients/guide/types.ts +1 -0
- package/src/interfaces.ts +1 -0
- package/src/knock.ts +11 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.18.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 5fc0af9: feat: adds `identificationStrategy` option for user identification control
|
|
8
|
+
|
|
9
|
+
## 0.17.2
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 23b7057: fix: return preview guides even if no other guides are present
|
|
14
|
+
- 1c24f68: fix: filter out inactive guides in preview mode
|
|
15
|
+
|
|
3
16
|
## 0.17.1
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
package/dist/cjs/api.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var a=Object.defineProperty;var n=(t,e,s)=>e in t?a(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var r=(t,e,s)=>n(t,typeof e!="symbol"?e+"":e,s);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("axios"),l=require("axios-retry"),c=require("phoenix"),i=t=>t&&typeof t=="object"&&"default"in t?t:{default:t},d=i(u),o=i(l);class h{constructor(e){r(this,"host");r(this,"apiKey");r(this,"userToken");r(this,"axiosClient");r(this,"socket");this.host=e.host,this.apiKey=e.apiKey,this.userToken=e.userToken||null,this.axiosClient=d.default.create({baseURL:this.host,headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-Knock-User-Token":this.userToken,"X-Knock-Client":this.getKnockClientHeader()}}),typeof window<"u"&&(this.socket=new c.Socket(`${this.host.replace("http","ws")}/ws/v1`,{params:{user_token:this.userToken,api_key:this.apiKey}})),o.default(this.axiosClient,{retries:3,retryCondition:this.canRetryRequest,retryDelay:o.default.exponentialDelay})}async makeRequest(e){try{const s=await this.axiosClient(e);return{statusCode:s.status<300?"ok":"error",body:s.data,error:void 0,status:s.status}}catch(s){return console.error(s),{statusCode:"error",status:500,body:void 0,error:s}}}canRetryRequest(e){return o.default.isNetworkError(e)?!0:e.response?e.response.status>=500&&e.response.status<=599||e.response.status===429:!1}getKnockClientHeader(){return"Knock/ClientJS 0.
|
|
1
|
+
"use strict";var a=Object.defineProperty;var n=(t,e,s)=>e in t?a(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var r=(t,e,s)=>n(t,typeof e!="symbol"?e+"":e,s);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("axios"),l=require("axios-retry"),c=require("phoenix"),i=t=>t&&typeof t=="object"&&"default"in t?t:{default:t},d=i(u),o=i(l);class h{constructor(e){r(this,"host");r(this,"apiKey");r(this,"userToken");r(this,"axiosClient");r(this,"socket");this.host=e.host,this.apiKey=e.apiKey,this.userToken=e.userToken||null,this.axiosClient=d.default.create({baseURL:this.host,headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-Knock-User-Token":this.userToken,"X-Knock-Client":this.getKnockClientHeader()}}),typeof window<"u"&&(this.socket=new c.Socket(`${this.host.replace("http","ws")}/ws/v1`,{params:{user_token:this.userToken,api_key:this.apiKey}})),o.default(this.axiosClient,{retries:3,retryCondition:this.canRetryRequest,retryDelay:o.default.exponentialDelay})}async makeRequest(e){try{const s=await this.axiosClient(e);return{statusCode:s.status<300?"ok":"error",body:s.data,error:void 0,status:s.status}}catch(s){return console.error(s),{statusCode:"error",status:500,body:void 0,error:s}}}canRetryRequest(e){return o.default.isNetworkError(e)?!0:e.response?e.response.status>=500&&e.response.status<=599||e.response.status===429:!1}getKnockClientHeader(){return"Knock/ClientJS 0.18.0"}}exports.default=h;
|
|
2
2
|
//# sourceMappingURL=api.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var m=Object.defineProperty;var v=(a,e,t)=>e in a?m(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var c=(a,e,t)=>v(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const G=require("@tanstack/store"),_=require("urlpattern-polyfill"),d=require("./helpers.js"),b=50,C=30*1e3,I=3,p={GUIDE_KEY:"knock_guide_key",PREVIEW_SESSION_ID:"knock_preview_session_id"},g=()=>{if(typeof window<"u")return window},y=a=>`/v1/users/${a}/guides`,k=()=>{const a=g();if(!a)return{forcedGuideKey:null,previewSessionId:null};const e=new URLSearchParams(a.location.search),t=e.get(p.GUIDE_KEY),s=e.get(p.PREVIEW_SESSION_ID);return{forcedGuideKey:t,previewSessionId:s}},f=(a,e={})=>{const t=new d.SelectionResult,s=d.findDefaultGroup(a.guideGroups);if(!s)return t;const i=[...s.display_sequence],n=a.location;if(a.debug.forcedGuideKey){const r=i.indexOf(a.debug.forcedGuideKey);r>-1&&i.splice(r,1),i.unshift(a.debug.forcedGuideKey)}for(const[r,o]of i.entries()){let u=a.guides[o];a.debug.forcedGuideKey===o&&a.previewGuides[o]&&(u=a.previewGuides[o]),!(!u||!E(u,{location:n,filters:e,debug:a.debug}))&&t.set(r,u)}return t.metadata={guideGroup:s},t},E=(a,{location:e,filters:t={},debug:s={}})=>{if(t.type&&t.type!==a.type||t.key&&t.key!==a.key)return!1;if(s.forcedGuideKey===a.key)return!0;if(a.steps.every(o=>!!o.message.archived_at))return!1;const i=e?d.newUrl(e):void 0,n=a.activation_url_rules||[],r=a.activation_url_patterns||[];if(i&&n.length>0){if(!d.predicateUrlRules(i,n))return!1}else if(i&&r.length>0&&!d.predicateUrlPatterns(i,r))return!1;return!0};class w{constructor(e,t,s={},i={}){c(this,"store");c(this,"socket");c(this,"socketChannel");c(this,"socketChannelTopic");c(this,"socketEventTypes",["guide.added","guide.updated","guide.removed","guide_group.added","guide_group.updated","guide.live_preview_updated"]);c(this,"subscribeRetryCount",0);c(this,"pushStateFn");c(this,"replaceStateFn");c(this,"stage");c(this,"counterIntervalId");c(this,"handleLocationChange",()=>{const e=g();if(!(e!=null&&e.location))return;const t=e.location.href;if(this.store.state.location===t)return;this.knock.log(`[Guide] Handle Location change: ${t}`);const s=this.store.state.debug,i=k();this.setLocation(t,{debug:i}),this.checkDebugStateChanged(s,i)&&(this.knock.log("[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel"),this.fetch(),this.subscribe())});this.knock=e,this.channelId=t,this.targetParams=s,this.options=i;const{trackLocationFromWindow:n=!0}=i,r=g(),o=n?r==null?void 0:r.location.href:void 0,u=k();this.store=new G.Store({guideGroups:[],guideGroupDisplayLogs:{},guides:{},previewGuides:{},queries:{},location:o,counter:0,debug:u});const{socket:h}=this.knock.client();this.socket=h,this.socketChannelTopic=`guides:${t}`,n&&this.listenForLocationChangesFromWindow(),this.startCounterInterval(),this.knock.log("[Guide] Initialized a guide client")}incrementCounter(){this.knock.log("[Guide] Incrementing the counter"),this.store.setState(e=>({...e,counter:e.counter+1}))}startCounterInterval(){const{throttleCheckInterval:e=C}=this.options;this.counterIntervalId=setInterval(()=>{this.knock.log("[Guide] Counter interval tick"),!(this.stage&&this.stage.status!=="closed")&&this.incrementCounter()},e)}clearCounterInterval(){this.counterIntervalId&&(clearInterval(this.counterIntervalId),this.counterIntervalId=void 0)}cleanup(){this.unsubscribe(),this.removeEventListeners(),this.clearGroupStage(),this.clearCounterInterval()}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),i=this.store.state.queries[s];if(i)return i;this.store.setState(r=>({...r,queries:{...r.queries,[s]:{status:"loading"}}}));let n;try{const r=await this.knock.user.getGuides(this.channelId,t);n={status:"ok"};const{entries:o,guide_groups:u,guide_group_display_logs:h}=r;this.store.setState(l=>({...l,guideGroups:(u==null?void 0:u.length)>0?u:[d.mockDefaultGroup(o)],guideGroupDisplayLogs:h||{},guides:d.byKey(o.map(S=>this.localCopy(S))),queries:{...l.queries,[s]:n}}))}catch(r){n={status:"error",error:r},this.store.setState(o=>({...o,queries:{...o.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.store.state.debug,t={...this.targetParams,user_id:this.knock.userId,force_all_guides:e.forcedGuideKey?!0:void 0,preview_session_id:e.previewSessionId||void 0},s=this.socket.channel(this.socketChannelTopic,t);for(const i of this.socketEventTypes)s.on(i,n=>this.handleSocketEvent(n));["closed","errored"].includes(s.state)&&(this.subscribeRetryCount=0,s.join().receive("ok",()=>{this.knock.log("[Guide] Successfully joined channel")}).receive("error",i=>{this.knock.log(`[Guide] Failed to join channel: ${JSON.stringify(i)}`),this.handleChannelJoinError()}).receive("timeout",()=>{this.knock.log("[Guide] Channel join timed out"),this.handleChannelJoinError()})),this.socketChannel=s}handleChannelJoinError(){if(this.subscribeRetryCount>=I){this.knock.log(`[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`),this.unsubscribe();return}this.subscribeRetryCount++}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.addOrReplaceGuide(e);case"guide.updated":return s.eligible?this.addOrReplaceGuide(e):this.removeGuide(e);case"guide.removed":return this.removeGuide(e);case"guide_group.added":case"guide_group.updated":return this.addOrReplaceGuideGroup(e);case"guide.live_preview_updated":return this.updatePreviewGuide(e);default:return}}setLocation(e,t={}){this.clearGroupStage(),this.store.setState(s=>{var n;const i=(n=t==null?void 0:t.debug)!=null&&n.previewSessionId?s.previewGuides:{};return{...s,...t,previewGuides:i,location:e}})}selectGuides(e,t={}){if(Object.keys(e.guides).length===0)return[];this.knock.log(`[Guide] Selecting guides for: ${d.formatFilters(t)}`);const s=f(e,t);return s.size===0?(this.knock.log("[Guide] Selection returned zero result"),[]):[...s.values()]}selectGuide(e,t={}){if(Object.keys(e.guides).length===0)return;this.knock.log(`[Guide] Selecting a guide for: ${d.formatFilters(t)}`);const s=f(e,t);if(s.size===0){this.knock.log("[Guide] Selection returned zero result");return}const[i,n]=[...s][0];if(n.bypass_global_group_limit)return n;const r=d.findDefaultGroup(e.guideGroups),o=e.guideGroupDisplayLogs[d.DEFAULT_GROUP_KEY];if(!(r&&r.display_interval&&o&&d.checkIfThrottled(o,r.display_interval)))switch(this.stage||(this.stage=this.openGroupStage()),this.stage.status){case"open":{this.knock.log(`[Guide] Addng to the group stage: ${n.key}`),this.stage.ordered[i]=n.key;return}case"patch":return this.knock.log(`[Guide] Patching the group stage: ${n.key}`),this.stage.ordered[i]=n.key,this.stage.resolved===n.key?n:void 0;case"closed":return this.stage.resolved===n.key?n:void 0}}openGroupStage(){this.knock.log("[Guide] Opening a new group stage");const{orderResolutionDuration:e=b}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.stage={status:"open",ordered:[],timeoutId:t},this.stage}closePendingGroupStage(){if(!this.stage||this.stage.status==="closed")return;this.knock.log("[Guide] Closing the current group stage"),this.ensureClearTimeout();let e;return this.store.state.debug.forcedGuideKey&&(e=this.stage.ordered.find(t=>t===this.store.state.debug.forcedGuideKey)),e||(e=this.stage.ordered.find(t=>t!==void 0)),this.stage={...this.stage,status:"closed",resolved:e,timeoutId:null},this.stage}patchClosedGroupStage(){var s;if(((s=this.stage)==null?void 0:s.status)!=="closed")return;this.knock.log("[Guide] Patching the current group stage");const{orderResolutionDuration:e=0}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.ensureClearTimeout(),this.stage={...this.stage,status:"patch",ordered:[],timeoutId:t},this.stage}clearGroupStage(){this.stage&&(this.knock.log("[Guide] Clearing the current group stage"),this.ensureClearTimeout(),this.stage=void 0)}ensureClearTimeout(){var e;(e=this.stage)!=null&&e.timeoutId&&clearTimeout(this.stage.timeoutId)}_selectGuide(e,t={}){return this.openGroupStage(),this.selectGuide(e,t),this.closePendingGroupStage(),this.selectGuide(e,t)}async markAsSeen(e,t){if(t.message.seen_at)return;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 i={...this.buildEngagementEventBaseParams(e,s),content:s.content,data:this.targetParams.data,tenant:this.targetParams.tenant};return this.knock.user.markGuideStepAs("seen",i),s}async markAsInteracted(e,t,s){this.knock.log(`[Guide] Marking as interacted (Guide key: ${e.key}, Step ref:${t.ref})`);const i=new Date().toISOString(),n=this.setStepMessageAttrs(e.key,t.ref,{read_at:i,interacted_at:i});if(!n)return;const r={...this.buildEngagementEventBaseParams(e,n),metadata:s};return this.knock.user.markGuideStepAs("interacted",r),n}async markAsArchived(e,t){if(t.message.archived_at)return;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 i=this.buildEngagementEventBaseParams(e,s);return this.knock.user.markGuideStepAs("archived",{...i,unthrottled:e.bypass_global_group_limit}),s}localCopy(e){const t=this,s={...e,getStep(){return t.store.state.debug.forcedGuideKey===this.key?this.steps[0]:this.steps.find(i=>!i.message.archived_at)}};return s.getStep=s.getStep.bind(s),s.steps=e.steps.map(({message:i,...n})=>{const r={...n,message:{...i},markAsSeen(){if(!this.message.seen_at)return t.markAsSeen(s,this)},markAsInteracted({metadata:o}={}){return t.markAsInteracted(s,this,o)},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_url_patterns=e.activation_url_patterns.map(i=>({...i,pattern:new _.URLPattern({pathname:i.pathname})})),s}buildQueryParams(e={}){const t={...this.targetParams,...e};this.store.state.debug.forcedGuideKey&&(t.force_all_guides=!0);let i=Object.fromEntries(Object.entries(t).filter(([n,r])=>r!=null));return i=i.data?{...i,data:JSON.stringify(i.data)}:i,i}formatQueryKey(e){const s=Object.keys(e).sort().map(n=>`${encodeURIComponent(n)}=${encodeURIComponent(e[n])}`).join("&"),i=y(this.knock.userId);return s?`${i}?${s}`:i}setStepMessageAttrs(e,t,s){let i;return s.archived_at&&this.clearGroupStage(),this.store.setState(n=>{const r=n.guides[e];if(!r)return n;const o=r.steps.map(l=>(l.ref!==t||(l.message={...l.message,...s},i=l),l));r.steps=o;const u={...n.guides,[r.key]:r},h=s.archived_at&&!r.bypass_global_group_limit?{...n.guideGroupDisplayLogs,[d.DEFAULT_GROUP_KEY]:s.archived_at}:n.guideGroupDisplayLogs;return{...n,guides:u,guideGroupDisplayLogs:h}}),i}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}}addOrReplaceGuide({data:e}){this.patchClosedGroupStage();const t=this.localCopy(e.guide);this.store.setState(s=>{const i={...s.guides,[t.key]:t};return{...s,guides:i}})}removeGuide({data:e}){this.patchClosedGroupStage(),this.store.setState(t=>{const{[e.guide.key]:s,...i}=t.guides;return{...t,guides:i}})}addOrReplaceGuideGroup({data:e}){this.patchClosedGroupStage(),this.store.setState(t=>{const s=[e.guide_group],i=e.guide_group.display_sequence_unthrottled||[],n=e.guide_group.display_sequence_throttled||[];let r=t.guides;return r=i.reduce((o,u)=>{if(!o[u])return o;const h={...o[u],bypass_global_group_limit:!0};return{...o,[u]:h}},r),r=n.reduce((o,u)=>{if(!o[u])return o;const h={...o[u],bypass_global_group_limit:!1};return{...o,[u]:h}},r),{...t,guides:r,guideGroups:s}})}updatePreviewGuide({data:e}){const t=this.localCopy(e.guide);this.store.setState(s=>{const i={...s.previewGuides,[t.key]:t};return{...s,previewGuides:i}})}checkDebugStateChanged(e,t){return!!e.forcedGuideKey!=!!t.forcedGuideKey||e.previewSessionId!==t.previewSessionId}listenForLocationChangesFromWindow(){const e=g();if(e!=null&&e.history){e.addEventListener("popstate",this.handleLocationChange),e.addEventListener("hashchange",this.handleLocationChange);const t=e.history.pushState,s=e.history.replaceState;e.history.pushState=new Proxy(t,{apply:(i,n,r)=>{Reflect.apply(i,n,r),setTimeout(()=>{this.handleLocationChange()},0)}}),e.history.replaceState=new Proxy(s,{apply:(i,n,r)=>{Reflect.apply(i,n,r),setTimeout(()=>{this.handleLocationChange()},0)}}),this.pushStateFn=t,this.replaceStateFn=s}else this.knock.log("[Guide] Unable to access the `window.history` object to detect location changes")}removeEventListeners(){const e=g();e!=null&&e.history&&(e.removeEventListener("popstate",this.handleLocationChange),e.removeEventListener("hashchange",this.handleLocationChange),this.pushStateFn&&(e.history.pushState=this.pushStateFn,this.pushStateFn=void 0),this.replaceStateFn&&(e.history.replaceState=this.replaceStateFn,this.replaceStateFn=void 0))}}exports.DEBUG_QUERY_PARAMS=p;exports.KnockGuideClient=w;exports.guidesApiRootPath=y;
|
|
1
|
+
"use strict";var m=Object.defineProperty;var v=(u,e,t)=>e in u?m(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var c=(u,e,t)=>v(u,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const G=require("@tanstack/store"),_=require("urlpattern-polyfill"),d=require("./helpers.js"),b=50,C=30*1e3,I=3,p={GUIDE_KEY:"knock_guide_key",PREVIEW_SESSION_ID:"knock_preview_session_id"},g=()=>{if(typeof window<"u")return window},y=u=>`/v1/users/${u}/guides`,k=()=>{const u=g();if(!u)return{forcedGuideKey:null,previewSessionId:null};const e=new URLSearchParams(u.location.search),t=e.get(p.GUIDE_KEY),s=e.get(p.PREVIEW_SESSION_ID);return{forcedGuideKey:t,previewSessionId:s}},f=(u,e={})=>{const t=new d.SelectionResult,s=d.findDefaultGroup(u.guideGroups);if(!s)return t;const i=[...s.display_sequence],n=u.location;if(u.debug.forcedGuideKey){const r=i.indexOf(u.debug.forcedGuideKey);r>-1&&i.splice(r,1),i.unshift(u.debug.forcedGuideKey)}for(const[r,o]of i.entries()){let a=u.guides[o];u.debug.forcedGuideKey===o&&u.previewGuides[o]&&(a=u.previewGuides[o]),!(!a||!E(a,{location:n,filters:e,debug:u.debug}))&&t.set(r,a)}return t.metadata={guideGroup:s},t},E=(u,{location:e,filters:t={},debug:s={}})=>{if(t.type&&t.type!==u.type||t.key&&t.key!==u.key)return!1;if(s.forcedGuideKey===u.key)return!0;if(!u.active||u.steps.every(o=>!!o.message.archived_at))return!1;const i=e?d.newUrl(e):void 0,n=u.activation_url_rules||[],r=u.activation_url_patterns||[];if(i&&n.length>0){if(!d.predicateUrlRules(i,n))return!1}else if(i&&r.length>0&&!d.predicateUrlPatterns(i,r))return!1;return!0};class w{constructor(e,t,s={},i={}){c(this,"store");c(this,"socket");c(this,"socketChannel");c(this,"socketChannelTopic");c(this,"socketEventTypes",["guide.added","guide.updated","guide.removed","guide_group.added","guide_group.updated","guide.live_preview_updated"]);c(this,"subscribeRetryCount",0);c(this,"pushStateFn");c(this,"replaceStateFn");c(this,"stage");c(this,"counterIntervalId");c(this,"handleLocationChange",()=>{const e=g();if(!(e!=null&&e.location))return;const t=e.location.href;if(this.store.state.location===t)return;this.knock.log(`[Guide] Handle Location change: ${t}`);const s=this.store.state.debug,i=k();this.setLocation(t,{debug:i}),this.checkDebugStateChanged(s,i)&&(this.knock.log("[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel"),this.fetch(),this.subscribe())});this.knock=e,this.channelId=t,this.targetParams=s,this.options=i;const{trackLocationFromWindow:n=!0}=i,r=g(),o=n?r==null?void 0:r.location.href:void 0,a=k();this.store=new G.Store({guideGroups:[],guideGroupDisplayLogs:{},guides:{},previewGuides:{},queries:{},location:o,counter:0,debug:a});const{socket:h}=this.knock.client();this.socket=h,this.socketChannelTopic=`guides:${t}`,n&&this.listenForLocationChangesFromWindow(),this.startCounterInterval(),this.knock.log("[Guide] Initialized a guide client")}incrementCounter(){this.knock.log("[Guide] Incrementing the counter"),this.store.setState(e=>({...e,counter:e.counter+1}))}startCounterInterval(){const{throttleCheckInterval:e=C}=this.options;this.counterIntervalId=setInterval(()=>{this.knock.log("[Guide] Counter interval tick"),!(this.stage&&this.stage.status!=="closed")&&this.incrementCounter()},e)}clearCounterInterval(){this.counterIntervalId&&(clearInterval(this.counterIntervalId),this.counterIntervalId=void 0)}cleanup(){this.unsubscribe(),this.removeEventListeners(),this.clearGroupStage(),this.clearCounterInterval()}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),i=this.store.state.queries[s];if(i)return i;this.store.setState(r=>({...r,queries:{...r.queries,[s]:{status:"loading"}}}));let n;try{const r=await this.knock.user.getGuides(this.channelId,t);n={status:"ok"};const{entries:o,guide_groups:a,guide_group_display_logs:h}=r;this.store.setState(l=>({...l,guideGroups:(a==null?void 0:a.length)>0?a:[d.mockDefaultGroup(o)],guideGroupDisplayLogs:h||{},guides:d.byKey(o.map(S=>this.localCopy(S))),queries:{...l.queries,[s]:n}}))}catch(r){n={status:"error",error:r},this.store.setState(o=>({...o,queries:{...o.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.store.state.debug,t={...this.targetParams,user_id:this.knock.userId,force_all_guides:e.forcedGuideKey?!0:void 0,preview_session_id:e.previewSessionId||void 0},s=this.socket.channel(this.socketChannelTopic,t);for(const i of this.socketEventTypes)s.on(i,n=>this.handleSocketEvent(n));["closed","errored"].includes(s.state)&&(this.subscribeRetryCount=0,s.join().receive("ok",()=>{this.knock.log("[Guide] Successfully joined channel")}).receive("error",i=>{this.knock.log(`[Guide] Failed to join channel: ${JSON.stringify(i)}`),this.handleChannelJoinError()}).receive("timeout",()=>{this.knock.log("[Guide] Channel join timed out"),this.handleChannelJoinError()})),this.socketChannel=s}handleChannelJoinError(){if(this.subscribeRetryCount>=I){this.knock.log(`[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`),this.unsubscribe();return}this.subscribeRetryCount++}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.addOrReplaceGuide(e);case"guide.updated":return s.eligible?this.addOrReplaceGuide(e):this.removeGuide(e);case"guide.removed":return this.removeGuide(e);case"guide_group.added":case"guide_group.updated":return this.addOrReplaceGuideGroup(e);case"guide.live_preview_updated":return this.updatePreviewGuide(e);default:return}}setLocation(e,t={}){this.clearGroupStage(),this.store.setState(s=>{var n;const i=(n=t==null?void 0:t.debug)!=null&&n.previewSessionId?s.previewGuides:{};return{...s,...t,previewGuides:i,location:e}})}selectGuides(e,t={}){if(Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0)return[];this.knock.log(`[Guide] Selecting guides for: ${d.formatFilters(t)}`);const s=f(e,t);return s.size===0?(this.knock.log("[Guide] Selection returned zero result"),[]):[...s.values()]}selectGuide(e,t={}){if(Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0)return;this.knock.log(`[Guide] Selecting a guide for: ${d.formatFilters(t)}`);const s=f(e,t);if(s.size===0){this.knock.log("[Guide] Selection returned zero result");return}const[i,n]=[...s][0];if(n.bypass_global_group_limit)return n;const r=d.findDefaultGroup(e.guideGroups),o=e.guideGroupDisplayLogs[d.DEFAULT_GROUP_KEY];if(!(r&&r.display_interval&&o&&d.checkIfThrottled(o,r.display_interval)))switch(this.stage||(this.stage=this.openGroupStage()),this.stage.status){case"open":{this.knock.log(`[Guide] Addng to the group stage: ${n.key}`),this.stage.ordered[i]=n.key;return}case"patch":return this.knock.log(`[Guide] Patching the group stage: ${n.key}`),this.stage.ordered[i]=n.key,this.stage.resolved===n.key?n:void 0;case"closed":return this.stage.resolved===n.key?n:void 0}}openGroupStage(){this.knock.log("[Guide] Opening a new group stage");const{orderResolutionDuration:e=b}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.stage={status:"open",ordered:[],timeoutId:t},this.stage}closePendingGroupStage(){if(!this.stage||this.stage.status==="closed")return;this.knock.log("[Guide] Closing the current group stage"),this.ensureClearTimeout();let e;return this.store.state.debug.forcedGuideKey&&(e=this.stage.ordered.find(t=>t===this.store.state.debug.forcedGuideKey)),e||(e=this.stage.ordered.find(t=>t!==void 0)),this.stage={...this.stage,status:"closed",resolved:e,timeoutId:null},this.stage}patchClosedGroupStage(){var s;if(((s=this.stage)==null?void 0:s.status)!=="closed")return;this.knock.log("[Guide] Patching the current group stage");const{orderResolutionDuration:e=0}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.ensureClearTimeout(),this.stage={...this.stage,status:"patch",ordered:[],timeoutId:t},this.stage}clearGroupStage(){this.stage&&(this.knock.log("[Guide] Clearing the current group stage"),this.ensureClearTimeout(),this.stage=void 0)}ensureClearTimeout(){var e;(e=this.stage)!=null&&e.timeoutId&&clearTimeout(this.stage.timeoutId)}_selectGuide(e,t={}){return this.openGroupStage(),this.selectGuide(e,t),this.closePendingGroupStage(),this.selectGuide(e,t)}async markAsSeen(e,t){if(t.message.seen_at)return;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 i={...this.buildEngagementEventBaseParams(e,s),content:s.content,data:this.targetParams.data,tenant:this.targetParams.tenant};return this.knock.user.markGuideStepAs("seen",i),s}async markAsInteracted(e,t,s){this.knock.log(`[Guide] Marking as interacted (Guide key: ${e.key}, Step ref:${t.ref})`);const i=new Date().toISOString(),n=this.setStepMessageAttrs(e.key,t.ref,{read_at:i,interacted_at:i});if(!n)return;const r={...this.buildEngagementEventBaseParams(e,n),metadata:s};return this.knock.user.markGuideStepAs("interacted",r),n}async markAsArchived(e,t){if(t.message.archived_at)return;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 i=this.buildEngagementEventBaseParams(e,s);return this.knock.user.markGuideStepAs("archived",{...i,unthrottled:e.bypass_global_group_limit}),s}localCopy(e){const t=this,s={...e,getStep(){return t.store.state.debug.forcedGuideKey===this.key?this.steps[0]:this.steps.find(i=>!i.message.archived_at)}};return s.getStep=s.getStep.bind(s),s.steps=e.steps.map(({message:i,...n})=>{const r={...n,message:{...i},markAsSeen(){if(!this.message.seen_at)return t.markAsSeen(s,this)},markAsInteracted({metadata:o}={}){return t.markAsInteracted(s,this,o)},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_url_patterns=e.activation_url_patterns.map(i=>({...i,pattern:new _.URLPattern({pathname:i.pathname})})),s}buildQueryParams(e={}){const t={...this.targetParams,...e};this.store.state.debug.forcedGuideKey&&(t.force_all_guides=!0);let i=Object.fromEntries(Object.entries(t).filter(([n,r])=>r!=null));return i=i.data?{...i,data:JSON.stringify(i.data)}:i,i}formatQueryKey(e){const s=Object.keys(e).sort().map(n=>`${encodeURIComponent(n)}=${encodeURIComponent(e[n])}`).join("&"),i=y(this.knock.userId);return s?`${i}?${s}`:i}setStepMessageAttrs(e,t,s){let i;return s.archived_at&&this.clearGroupStage(),this.store.setState(n=>{const r=n.guides[e];if(!r)return n;const o=r.steps.map(l=>(l.ref!==t||(l.message={...l.message,...s},i=l),l));r.steps=o;const a={...n.guides,[r.key]:r},h=s.archived_at&&!r.bypass_global_group_limit?{...n.guideGroupDisplayLogs,[d.DEFAULT_GROUP_KEY]:s.archived_at}:n.guideGroupDisplayLogs;return{...n,guides:a,guideGroupDisplayLogs:h}}),i}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}}addOrReplaceGuide({data:e}){this.patchClosedGroupStage();const t=this.localCopy(e.guide);this.store.setState(s=>{const i={...s.guides,[t.key]:t};return{...s,guides:i}})}removeGuide({data:e}){this.patchClosedGroupStage(),this.store.setState(t=>{const{[e.guide.key]:s,...i}=t.guides;return{...t,guides:i}})}addOrReplaceGuideGroup({data:e}){this.patchClosedGroupStage(),this.store.setState(t=>{const s=[e.guide_group],i=e.guide_group.display_sequence_unthrottled||[],n=e.guide_group.display_sequence_throttled||[];let r=t.guides;return r=i.reduce((o,a)=>{if(!o[a])return o;const h={...o[a],bypass_global_group_limit:!0};return{...o,[a]:h}},r),r=n.reduce((o,a)=>{if(!o[a])return o;const h={...o[a],bypass_global_group_limit:!1};return{...o,[a]:h}},r),{...t,guides:r,guideGroups:s}})}updatePreviewGuide({data:e}){const t=this.localCopy(e.guide);this.store.setState(s=>{const i={...s.previewGuides,[t.key]:t};return{...s,previewGuides:i}})}checkDebugStateChanged(e,t){return!!e.forcedGuideKey!=!!t.forcedGuideKey||e.previewSessionId!==t.previewSessionId}listenForLocationChangesFromWindow(){const e=g();if(e!=null&&e.history){e.addEventListener("popstate",this.handleLocationChange),e.addEventListener("hashchange",this.handleLocationChange);const t=e.history.pushState,s=e.history.replaceState;e.history.pushState=new Proxy(t,{apply:(i,n,r)=>{Reflect.apply(i,n,r),setTimeout(()=>{this.handleLocationChange()},0)}}),e.history.replaceState=new Proxy(s,{apply:(i,n,r)=>{Reflect.apply(i,n,r),setTimeout(()=>{this.handleLocationChange()},0)}}),this.pushStateFn=t,this.replaceStateFn=s}else this.knock.log("[Guide] Unable to access the `window.history` object to detect location changes")}removeEventListeners(){const e=g();e!=null&&e.history&&(e.removeEventListener("popstate",this.handleLocationChange),e.removeEventListener("hashchange",this.handleLocationChange),this.pushStateFn&&(e.history.pushState=this.pushStateFn,this.pushStateFn=void 0),this.replaceStateFn&&(e.history.replaceState=this.replaceStateFn,this.replaceStateFn=void 0))}}exports.DEBUG_QUERY_PARAMS=p;exports.KnockGuideClient=w;exports.guidesApiRootPath=y;
|
|
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\";\nimport { URLPattern } from \"urlpattern-polyfill\";\n\nimport Knock from \"../../knock\";\n\nimport {\n DEFAULT_GROUP_KEY,\n SelectionResult,\n byKey,\n checkIfThrottled,\n findDefaultGroup,\n formatFilters,\n mockDefaultGroup,\n newUrl,\n predicateUrlPatterns,\n predicateUrlRules,\n} from \"./helpers\";\nimport {\n Any,\n ConstructorOpts,\n DebugState,\n GetGuidesQueryParams,\n GetGuidesResponse,\n GroupStage,\n GuideAddedEvent,\n GuideData,\n GuideGroupAddedEvent,\n GuideGroupUpdatedEvent,\n GuideLivePreviewUpdatedEvent,\n GuideRemovedEvent,\n GuideSocketEvent,\n GuideStepData,\n GuideUpdatedEvent,\n KnockGuide,\n KnockGuideStep,\n MarkAsArchivedParams,\n MarkAsInteractedParams,\n MarkAsSeenParams,\n MarkGuideAsResponse,\n QueryFilterParams,\n QueryStatus,\n SelectFilterParams,\n StepMessageState,\n StoreState,\n TargetParams,\n} from \"./types\";\n\n// How long to wait until we resolve the guides order and determine the\n// prevailing guide.\nconst DEFAULT_ORDER_RESOLUTION_DURATION = 50; // in milliseconds\n\n// How often we should increment the counter to refresh the store state and\n// trigger subscribed callbacks.\nconst DEFAULT_COUNTER_INCREMENT_INTERVAL = 30 * 1000; // in milliseconds\n\n// Maximum number of retry attempts for channel subscription\nconst SUBSCRIBE_RETRY_LIMIT = 3;\n\n// Debug query param keys\nexport const DEBUG_QUERY_PARAMS = {\n GUIDE_KEY: \"knock_guide_key\",\n PREVIEW_SESSION_ID: \"knock_preview_session_id\",\n};\n\n// Return the global window object if defined, so to safely guard against SSR.\nconst checkForWindow = () => {\n if (typeof window !== \"undefined\") {\n return window;\n }\n};\n\nexport const guidesApiRootPath = (userId: string | undefined | null) =>\n `/v1/users/${userId}/guides`;\n\n// Detect debug params like \"knock_guide_key\" from URL.\nconst detectDebugParams = (): DebugState => {\n const win = checkForWindow();\n if (!win) {\n return { forcedGuideKey: null, previewSessionId: null };\n }\n\n const urlParams = new URLSearchParams(win.location.search);\n const forcedGuideKey = urlParams.get(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n const previewSessionId = urlParams.get(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID);\n\n return { forcedGuideKey, previewSessionId };\n};\n\nconst select = (state: StoreState, filters: SelectFilterParams = {}) => {\n // A map of selected guides as values, with its order index as keys.\n const result = new SelectionResult();\n\n const defaultGroup = findDefaultGroup(state.guideGroups);\n if (!defaultGroup) return result;\n\n const displaySequence = [...defaultGroup.display_sequence];\n const location = state.location;\n\n // If in debug mode, put the forced guide at the beginning of the display sequence.\n if (state.debug.forcedGuideKey) {\n const forcedKeyIndex = displaySequence.indexOf(state.debug.forcedGuideKey);\n if (forcedKeyIndex > -1) {\n displaySequence.splice(forcedKeyIndex, 1);\n }\n displaySequence.unshift(state.debug.forcedGuideKey);\n }\n\n for (const [index, guideKey] of displaySequence.entries()) {\n let guide = state.guides[guideKey];\n\n // Use preview guide if it exists and matches the forced guide key\n if (\n state.debug.forcedGuideKey === guideKey &&\n state.previewGuides[guideKey]\n ) {\n guide = state.previewGuides[guideKey];\n }\n\n if (!guide) continue;\n\n const affirmed = predicate(guide, {\n location,\n filters,\n debug: state.debug,\n });\n\n if (!affirmed) continue;\n\n result.set(index, guide);\n }\n\n result.metadata = { guideGroup: defaultGroup };\n return result;\n};\n\ntype PredicateOpts = {\n location?: string | undefined;\n filters?: SelectFilterParams | undefined;\n debug: DebugState;\n};\n\nconst predicate = (\n guide: KnockGuide,\n { location, filters = {}, debug = {} }: PredicateOpts,\n) => {\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 // Bypass filtering if the debugged guide matches the given filters.\n // This should always run AFTER checking the filters but BEFORE\n // checking archived status and location rules.\n if (debug.forcedGuideKey === guide.key) {\n return true;\n }\n\n if (guide.steps.every((s) => !!s.message.archived_at)) {\n return false;\n }\n\n const url = location ? newUrl(location) : undefined;\n\n const urlRules = guide.activation_url_rules || [];\n const urlPatterns = guide.activation_url_patterns || [];\n\n // A guide can have either activation url rules XOR url patterns, but not both.\n if (url && urlRules.length > 0) {\n const allowed = predicateUrlRules(url, urlRules);\n if (!allowed) return false;\n } else if (url && urlPatterns.length > 0) {\n const allowed = predicateUrlPatterns(url, urlPatterns);\n if (!allowed) return false;\n }\n\n return true;\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 = [\n \"guide.added\",\n \"guide.updated\",\n \"guide.removed\",\n \"guide_group.added\",\n \"guide_group.updated\",\n \"guide.live_preview_updated\",\n ];\n private subscribeRetryCount = 0;\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 // Guides that are competing to render are \"staged\" first without rendering\n // and ranked based on its relative order in the group over a duration of time\n // to resolve and render the prevailing one.\n private stage: GroupStage | undefined;\n\n private counterIntervalId: ReturnType<typeof setInterval> | 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 const win = checkForWindow();\n\n const location = trackLocationFromWindow ? win?.location.href : undefined;\n\n const debug = detectDebugParams();\n\n this.store = new Store<StoreState>({\n guideGroups: [],\n guideGroupDisplayLogs: {},\n guides: {},\n previewGuides: {},\n queries: {},\n location,\n // Increment to update the state store and trigger re-selection.\n counter: 0,\n debug,\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 // Start the counter loop to increment at an interval.\n this.startCounterInterval();\n\n this.knock.log(\"[Guide] Initialized a guide client\");\n }\n\n private incrementCounter() {\n this.knock.log(\"[Guide] Incrementing the counter\");\n this.store.setState((state) => ({ ...state, counter: state.counter + 1 }));\n }\n\n private startCounterInterval() {\n const {\n throttleCheckInterval: delay = DEFAULT_COUNTER_INCREMENT_INTERVAL,\n } = this.options;\n\n this.counterIntervalId = setInterval(() => {\n this.knock.log(\"[Guide] Counter interval tick\");\n if (this.stage && this.stage.status !== \"closed\") return;\n\n this.incrementCounter();\n }, delay);\n }\n\n private clearCounterInterval() {\n if (this.counterIntervalId) {\n clearInterval(this.counterIntervalId);\n this.counterIntervalId = undefined;\n }\n }\n\n cleanup() {\n this.unsubscribe();\n this.removeEventListeners();\n this.clearGroupStage();\n this.clearCounterInterval();\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 const { entries, guide_groups: groups, guide_group_display_logs } = data;\n\n this.store.setState((state) => ({\n ...state,\n guideGroups: groups?.length > 0 ? groups : [mockDefaultGroup(entries)],\n guideGroupDisplayLogs: guide_group_display_logs || {},\n guides: byKey(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 debugState = this.store.state.debug;\n const params = {\n ...this.targetParams,\n user_id: this.knock.userId,\n force_all_guides: debugState.forcedGuideKey ? true : undefined,\n preview_session_id: debugState.previewSessionId || undefined,\n };\n\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 // Reset retry count for new subscription attempt\n this.subscribeRetryCount = 0;\n\n newChannel\n .join()\n .receive(\"ok\", () => {\n this.knock.log(\"[Guide] Successfully joined channel\");\n })\n .receive(\"error\", (resp) => {\n this.knock.log(\n `[Guide] Failed to join channel: ${JSON.stringify(resp)}`,\n );\n this.handleChannelJoinError();\n })\n .receive(\"timeout\", () => {\n this.knock.log(\"[Guide] Channel join timed out\");\n this.handleChannelJoinError();\n });\n }\n\n // Track the joined channel.\n this.socketChannel = newChannel;\n }\n\n private handleChannelJoinError() {\n // Prevent phx channel from retrying forever in case of either network or\n // other errors (e.g. auth error, invalid channel etc)\n if (this.subscribeRetryCount >= SUBSCRIBE_RETRY_LIMIT) {\n this.knock.log(\n `[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`,\n );\n this.unsubscribe();\n return;\n }\n\n this.subscribeRetryCount++;\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.addOrReplaceGuide(payload);\n\n case \"guide.updated\":\n return data.eligible\n ? this.addOrReplaceGuide(payload)\n : this.removeGuide(payload);\n\n case \"guide.removed\":\n return this.removeGuide(payload);\n\n case \"guide_group.added\":\n case \"guide_group.updated\":\n return this.addOrReplaceGuideGroup(payload);\n\n case \"guide.live_preview_updated\":\n return this.updatePreviewGuide(payload);\n\n default:\n return;\n }\n }\n\n setLocation(href: string, additionalParams: Partial<StoreState> = {}) {\n // Make sure to clear out the stage.\n this.clearGroupStage();\n\n this.store.setState((state) => {\n // Clear preview guides if no longer in preview mode\n const previewGuides = additionalParams?.debug?.previewSessionId\n ? state.previewGuides\n : {};\n\n return {\n ...state,\n ...additionalParams,\n previewGuides,\n location: href,\n };\n });\n }\n\n //\n // Store selector\n //\n\n selectGuides<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C>[] {\n if (Object.keys(state.guides).length === 0) {\n return [];\n }\n this.knock.log(`[Guide] Selecting guides for: ${formatFilters(filters)}`);\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection returned zero result\");\n return [];\n }\n\n // Return all selected guides, since we cannot apply the one-at-a-time limit\n // or throttle settings, but rather defer to the caller to decide which ones\n // to render. Note\n return [...result.values()];\n }\n\n selectGuide<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C> | undefined {\n if (Object.keys(state.guides).length === 0) {\n return undefined;\n }\n this.knock.log(`[Guide] Selecting a guide for: ${formatFilters(filters)}`);\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection returned zero result\");\n return undefined;\n }\n\n const [index, guide] = [...result][0]!;\n\n // If a guide ignores the group limit, then return immediately to render\n // always.\n if (guide.bypass_global_group_limit) {\n return guide;\n }\n\n // Check if inside the throttle window (i.e. throttled) and if so stop and\n // return undefined.\n const defaultGroup = findDefaultGroup(state.guideGroups);\n const throttleWindowStartedAt =\n state.guideGroupDisplayLogs[DEFAULT_GROUP_KEY];\n\n if (\n defaultGroup &&\n defaultGroup.display_interval &&\n throttleWindowStartedAt\n ) {\n const throttled = checkIfThrottled(\n throttleWindowStartedAt,\n defaultGroup.display_interval,\n );\n if (throttled) return undefined;\n }\n\n // Starting here to the end of this method represents the core logic of how\n // \"group stage\" works. It provides a mechanism for 1) figuring out which\n // guide components are about to render on a page, 2) determining which\n // among them ranks highest in the configured display sequence, and 3)\n // returning only the prevailing guide to render at a time.\n //\n // Imagine N number of components that use the `useGuide()` hook which\n // calls this `selectGuide()` method, and the logic works like this:\n // * The first time this method is called, we don't have an \"open\" group\n // stage, so we open one (this occurs when a new page/route is rendering).\n // * While it is open, we record which guide was selected and its order\n // index from each call, but we do NOT return any guide to render yet.\n // * When a group stage opens, it schedules a timer to close itself. How\n // long this timer waits is configurable. Note, `setTimeout` with 0\n // delay seems to work well for React apps, where we \"yield\" to React\n // for one render cycle and close the group right after.\n // * When a group stage closes, we evaluate which guides were selected and\n // recorded, then determine the winning guide (i.e. the one with the\n // lowest order index value).\n // * Then increment the internal counter to trigger a store state update,\n // which allows `useGuide()` and `selectGuide()` to re-run. This second\n // round of `selectGuide()` calls, occurring when the group stage is\n // closed, results in returning the prevailing guide.\n // * Whenever a user navigates to a new page, we repeat the same process\n // above.\n // * There's a third status called \"patch,\" which is for handling real-time\n // updates received from the API. It's similar to the \"open\" to \"closed\"\n // flow, except we keep the resolved guide in place while we recalculate.\n // This is done so that we don't cause flickers or CLS.\n if (!this.stage) {\n this.stage = this.openGroupStage(); // Assign here to make tsc happy\n }\n\n switch (this.stage.status) {\n case \"open\": {\n this.knock.log(`[Guide] Addng to the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n return undefined;\n }\n\n case \"patch\": {\n this.knock.log(`[Guide] Patching the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n return this.stage.resolved === guide.key ? guide : undefined;\n }\n\n case \"closed\": {\n return this.stage.resolved === guide.key ? guide : undefined;\n }\n }\n }\n\n private openGroupStage() {\n this.knock.log(\"[Guide] Opening a new group stage\");\n\n const {\n orderResolutionDuration: delay = DEFAULT_ORDER_RESOLUTION_DURATION,\n } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n this.stage = {\n status: \"open\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n // Close the current non-closed stage to resolve the prevailing guide up next\n // for display amongst the ones that have been staged.\n private closePendingGroupStage() {\n if (!this.stage || this.stage.status === \"closed\") return;\n\n this.knock.log(\"[Guide] Closing the current group stage\");\n\n // Should have been cleared already since this method should be called as a\n // callback to a setTimeout, but just to be safe.\n this.ensureClearTimeout();\n\n // If in debug mode, try to resolve the forced guide, otherwise return the first non-undefined guide.\n let resolved = undefined;\n if (this.store.state.debug.forcedGuideKey) {\n resolved = this.stage.ordered.find(\n (x) => x === this.store.state.debug.forcedGuideKey,\n );\n }\n\n if (!resolved) {\n resolved = this.stage.ordered.find((x) => x !== undefined);\n }\n\n this.stage = {\n ...this.stage,\n status: \"closed\",\n resolved,\n timeoutId: null,\n };\n\n return this.stage;\n }\n\n // Set the current closed stage status to \"patch\" to allow re-running\n // selections and re-building a group stage with the latest/updated state,\n // while keeping the currently resolved guide in place so that it stays\n // rendered until we are ready to resolve the updated stage and re-render.\n // Note, must be called ahead of updating the state store.\n private patchClosedGroupStage() {\n if (this.stage?.status !== \"closed\") return;\n\n this.knock.log(\"[Guide] Patching the current group stage\");\n\n const { orderResolutionDuration: delay = 0 } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n // Just to be safe.\n this.ensureClearTimeout();\n\n this.stage = {\n ...this.stage,\n status: \"patch\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n private clearGroupStage() {\n if (!this.stage) return;\n\n this.knock.log(\"[Guide] Clearing the current group stage\");\n\n this.ensureClearTimeout();\n this.stage = undefined;\n }\n\n private ensureClearTimeout() {\n if (this.stage?.timeoutId) {\n clearTimeout(this.stage.timeoutId);\n }\n }\n\n // Test helper that opens and closes the group stage to return the select\n // result immediately.\n private _selectGuide(state: StoreState, filters: SelectFilterParams = {}) {\n this.openGroupStage();\n\n this.selectGuide(state, filters);\n this.closePendingGroupStage();\n\n return this.selectGuide(state, filters);\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 if (step.message.seen_at) return;\n\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 if (step.message.archived_at) return;\n\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 {\n ...params,\n unthrottled: guide.bypass_global_group_limit,\n },\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 = {\n ...remoteGuide,\n // Get the next unarchived step.\n getStep() {\n // If debugging this guide, return the first step regardless of archive status\n if (self.store.state.debug.forcedGuideKey === this.key) {\n return this.steps[0];\n }\n\n return this.steps.find((s) => !s.message.archived_at);\n },\n } as KnockGuide;\n\n localGuide.getStep = localGuide.getStep.bind(localGuide);\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_url_patterns =\n remoteGuide.activation_url_patterns.map((rule) => {\n return {\n ...rule,\n pattern: new URLPattern({ pathname: rule.pathname }),\n };\n });\n\n return localGuide;\n }\n\n private buildQueryParams(filterParams: QueryFilterParams = {}) {\n // Combine the target params with the given filter params.\n const combinedParams: GenericData = {\n ...this.targetParams,\n ...filterParams,\n };\n\n // Append debug params\n const debugState = this.store.state.debug;\n if (debugState.forcedGuideKey) {\n combinedParams.force_all_guides = true;\n }\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 // If we are marking as archived, clear the group stage so we can render\n // the next guide in the group.\n if (attrs.archived_at) {\n this.clearGroupStage();\n }\n\n this.store.setState((state) => {\n const guide = state.guides[guideKey];\n if (!guide) return state;\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 // Mutate in place and maintain the same obj ref.\n guide.steps = steps;\n const guides = { ...state.guides, [guide.key]: guide };\n\n // If the guide is subject to throttled settings and we are marking as\n // archived, then update the display logs to start a new throttle window.\n const guideGroupDisplayLogs =\n attrs.archived_at && !guide.bypass_global_group_limit\n ? {\n ...state.guideGroupDisplayLogs,\n [DEFAULT_GROUP_KEY]: attrs.archived_at,\n }\n : state.guideGroupDisplayLogs;\n\n return { ...state, guides, guideGroupDisplayLogs };\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 addOrReplaceGuide({ data }: GuideAddedEvent | GuideUpdatedEvent) {\n this.patchClosedGroupStage();\n\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const guides = { ...state.guides, [guide.key]: guide };\n\n return { ...state, guides };\n });\n }\n\n private removeGuide({ data }: GuideUpdatedEvent | GuideRemovedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n const { [data.guide.key]: _, ...rest } = state.guides;\n return { ...state, guides: rest };\n });\n }\n\n private addOrReplaceGuideGroup({\n data,\n }: GuideGroupAddedEvent | GuideGroupUpdatedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n // Currently we only support a single default global group, so we can just\n // update the list with the added/updated group.\n const guideGroups = [data.guide_group];\n\n // A guide group event can include lists of unthrottled vs throttled guide\n // keys which we can use to bulk update the guides in the store already.\n const unthrottled = data.guide_group.display_sequence_unthrottled || [];\n const throttled = data.guide_group.display_sequence_throttled || [];\n\n let guides = state.guides;\n\n guides = unthrottled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: true };\n return { ...acc, [key]: guide };\n }, guides);\n\n guides = throttled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: false };\n return { ...acc, [key]: guide };\n }, guides);\n\n return { ...state, guides, guideGroups };\n });\n }\n\n private updatePreviewGuide({ data }: GuideLivePreviewUpdatedEvent) {\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const previewGuides = { ...state.previewGuides, [guide.key]: guide };\n return { ...state, previewGuides };\n });\n }\n\n // Define as an arrow func property to always bind this to the class instance.\n private handleLocationChange = () => {\n const win = checkForWindow();\n if (!win?.location) return;\n\n const href = win.location.href;\n if (this.store.state.location === href) return;\n\n this.knock.log(`[Guide] Handle Location change: ${href}`);\n\n // If entering debug mode, fetch all guides.\n const currentDebugParams = this.store.state.debug;\n const newDebugParams = detectDebugParams();\n this.setLocation(href, { debug: newDebugParams });\n\n // If debug state has changed, refetch guides and resubscribe to the websocket channel\n const debugStateChanged = this.checkDebugStateChanged(\n currentDebugParams,\n newDebugParams,\n );\n\n if (debugStateChanged) {\n this.knock.log(\n `[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel`,\n );\n this.fetch();\n this.subscribe();\n }\n };\n\n // Returns whether debug params have changed. For guide key, we only check\n // presence since the exact value has no impact on fetch/subscribe\n private checkDebugStateChanged(a: DebugState, b: DebugState): boolean {\n return (\n Boolean(a.forcedGuideKey) !== Boolean(b.forcedGuideKey) ||\n a.previewSessionId !== b.previewSessionId\n );\n }\n\n private listenForLocationChangesFromWindow() {\n const win = checkForWindow();\n if (win?.history) {\n // 1. Listen for browser back/forward button clicks.\n win.addEventListener(\"popstate\", this.handleLocationChange);\n\n // 2. Listen for hash changes in case it's used for routing.\n win.addEventListener(\"hashchange\", this.handleLocationChange);\n\n // 3. Monkey-patch history methods to catch programmatic navigation.\n const pushStateFn = win.history.pushState;\n const replaceStateFn = win.history.replaceState;\n\n // Use setTimeout to allow the browser state to potentially settle.\n win.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 win.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 const win = checkForWindow();\n if (!win?.history) return;\n\n win.removeEventListener(\"popstate\", this.handleLocationChange);\n win.removeEventListener(\"hashchange\", this.handleLocationChange);\n\n if (this.pushStateFn) {\n win.history.pushState = this.pushStateFn;\n this.pushStateFn = undefined;\n }\n if (this.replaceStateFn) {\n win.history.replaceState = this.replaceStateFn;\n this.replaceStateFn = undefined;\n }\n }\n}\n"],"names":["DEFAULT_ORDER_RESOLUTION_DURATION","DEFAULT_COUNTER_INCREMENT_INTERVAL","SUBSCRIBE_RETRY_LIMIT","DEBUG_QUERY_PARAMS","checkForWindow","guidesApiRootPath","userId","detectDebugParams","win","urlParams","forcedGuideKey","previewSessionId","select","state","filters","result","SelectionResult","defaultGroup","findDefaultGroup","displaySequence","location","forcedKeyIndex","index","guideKey","guide","predicate","debug","s","url","newUrl","urlRules","urlPatterns","predicateUrlRules","predicateUrlPatterns","KnockGuideClient","knock","channelId","targetParams","options","__publicField","href","currentDebugParams","newDebugParams","trackLocationFromWindow","Store","maybeSocket","delay","opts","queryParams","queryKey","maybeQueryStatus","queryStatus","data","entries","groups","guide_group_display_logs","mockDefaultGroup","byKey","g","e","debugState","params","newChannel","eventType","payload","resp","event","additionalParams","previewGuides","_a","formatFilters","throttleWindowStartedAt","DEFAULT_GROUP_KEY","checkIfThrottled","timeoutId","resolved","x","step","updatedStep","metadata","ts","remoteGuide","self","localGuide","message","rest","localStep","rule","URLPattern","filterParams","combinedParams","_k","v","queryStr","key","basePath","stepRef","attrs","steps","guides","guideGroupDisplayLogs","_","guideGroups","unthrottled","throttled","acc","a","b","pushStateFn","replaceStateFn","target","history","args"],"mappings":"kVAmDMA,EAAoC,GAIpCC,EAAqC,GAAK,IAG1CC,EAAwB,EAGjBC,EAAqB,CAChC,UAAW,kBACX,mBAAoB,0BACtB,EAGMC,EAAiB,IAAM,CACvB,GAAA,OAAO,OAAW,IACb,OAAA,MAEX,EAEaC,EAAqBC,GAChC,aAAaA,CAAM,UAGfC,EAAoB,IAAkB,CAC1C,MAAMC,EAAMJ,EAAe,EAC3B,GAAI,CAACI,EACH,MAAO,CAAE,eAAgB,KAAM,iBAAkB,IAAK,EAGxD,MAAMC,EAAY,IAAI,gBAAgBD,EAAI,SAAS,MAAM,EACnDE,EAAiBD,EAAU,IAAIN,EAAmB,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,QAAQ,aAGnCA,EAAI,QAAQ,UAAY,IAAI,MAAMoG,EAAa,CAC7C,MAAO,CAACE,EAAQC,EAASC,IAAS,CACxB,QAAA,MAAMF,EAAQC,EAASC,CAAI,EACnC,WAAW,IAAM,CACf,KAAK,qBAAqB,GACzB,CAAC,CAAA,CACN,CACD,EACDxG,EAAI,QAAQ,aAAe,IAAI,MAAMqG,EAAgB,CACnD,MAAO,CAACC,EAAQC,EAASC,IAAS,CACxB,QAAA,MAAMF,EAAQC,EAASC,CAAI,EACnC,WAAW,IAAM,CACf,KAAK,qBAAqB,GACzB,CAAC,CAAA,CACN,CACD,EAGD,KAAK,YAAcJ,EACnB,KAAK,eAAiBC,CAAA,MAEtB,KAAK,MAAM,IACT,iFACF,CACF,CAGM,sBAAuB,CAC7B,MAAMrG,EAAMJ,EAAe,EACtBI,GAAA,MAAAA,EAAK,UAENA,EAAA,oBAAoB,WAAY,KAAK,oBAAoB,EACzDA,EAAA,oBAAoB,aAAc,KAAK,oBAAoB,EAE3D,KAAK,cACHA,EAAA,QAAQ,UAAY,KAAK,YAC7B,KAAK,YAAc,QAEjB,KAAK,iBACHA,EAAA,QAAQ,aAAe,KAAK,eAChC,KAAK,eAAiB,QACxB,CAEJ"}
|
|
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\nimport {\n DEFAULT_GROUP_KEY,\n SelectionResult,\n byKey,\n checkIfThrottled,\n findDefaultGroup,\n formatFilters,\n mockDefaultGroup,\n newUrl,\n predicateUrlPatterns,\n predicateUrlRules,\n} from \"./helpers\";\nimport {\n Any,\n ConstructorOpts,\n DebugState,\n GetGuidesQueryParams,\n GetGuidesResponse,\n GroupStage,\n GuideAddedEvent,\n GuideData,\n GuideGroupAddedEvent,\n GuideGroupUpdatedEvent,\n GuideLivePreviewUpdatedEvent,\n GuideRemovedEvent,\n GuideSocketEvent,\n GuideStepData,\n GuideUpdatedEvent,\n KnockGuide,\n KnockGuideStep,\n MarkAsArchivedParams,\n MarkAsInteractedParams,\n MarkAsSeenParams,\n MarkGuideAsResponse,\n QueryFilterParams,\n QueryStatus,\n SelectFilterParams,\n StepMessageState,\n StoreState,\n TargetParams,\n} from \"./types\";\n\n// How long to wait until we resolve the guides order and determine the\n// prevailing guide.\nconst DEFAULT_ORDER_RESOLUTION_DURATION = 50; // in milliseconds\n\n// How often we should increment the counter to refresh the store state and\n// trigger subscribed callbacks.\nconst DEFAULT_COUNTER_INCREMENT_INTERVAL = 30 * 1000; // in milliseconds\n\n// Maximum number of retry attempts for channel subscription\nconst SUBSCRIBE_RETRY_LIMIT = 3;\n\n// Debug query param keys\nexport const DEBUG_QUERY_PARAMS = {\n GUIDE_KEY: \"knock_guide_key\",\n PREVIEW_SESSION_ID: \"knock_preview_session_id\",\n};\n\n// Return the global window object if defined, so to safely guard against SSR.\nconst checkForWindow = () => {\n if (typeof window !== \"undefined\") {\n return window;\n }\n};\n\nexport const guidesApiRootPath = (userId: string | undefined | null) =>\n `/v1/users/${userId}/guides`;\n\n// Detect debug params like \"knock_guide_key\" from URL.\nconst detectDebugParams = (): DebugState => {\n const win = checkForWindow();\n if (!win) {\n return { forcedGuideKey: null, previewSessionId: null };\n }\n\n const urlParams = new URLSearchParams(win.location.search);\n const forcedGuideKey = urlParams.get(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n const previewSessionId = urlParams.get(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID);\n\n return { forcedGuideKey, previewSessionId };\n};\n\nconst select = (state: StoreState, filters: SelectFilterParams = {}) => {\n // A map of selected guides as values, with its order index as keys.\n const result = new SelectionResult();\n\n const defaultGroup = findDefaultGroup(state.guideGroups);\n if (!defaultGroup) return result;\n\n const displaySequence = [...defaultGroup.display_sequence];\n const location = state.location;\n\n // If in debug mode, put the forced guide at the beginning of the display sequence.\n if (state.debug.forcedGuideKey) {\n const forcedKeyIndex = displaySequence.indexOf(state.debug.forcedGuideKey);\n if (forcedKeyIndex > -1) {\n displaySequence.splice(forcedKeyIndex, 1);\n }\n displaySequence.unshift(state.debug.forcedGuideKey);\n }\n\n for (const [index, guideKey] of displaySequence.entries()) {\n let guide = state.guides[guideKey];\n\n // Use preview guide if it exists and matches the forced guide key\n if (\n state.debug.forcedGuideKey === guideKey &&\n state.previewGuides[guideKey]\n ) {\n guide = state.previewGuides[guideKey];\n }\n\n if (!guide) continue;\n\n const affirmed = predicate(guide, {\n location,\n filters,\n debug: state.debug,\n });\n\n if (!affirmed) continue;\n\n result.set(index, guide);\n }\n\n result.metadata = { guideGroup: defaultGroup };\n return result;\n};\n\ntype PredicateOpts = {\n location?: string | undefined;\n filters?: SelectFilterParams | undefined;\n debug: DebugState;\n};\n\nconst predicate = (\n guide: KnockGuide,\n { location, filters = {}, debug = {} }: PredicateOpts,\n) => {\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 // Bypass filtering if the debugged guide matches the given filters.\n // This should always run AFTER checking the filters but BEFORE\n // checking archived status and location rules.\n if (debug.forcedGuideKey === guide.key) {\n return true;\n }\n\n if (!guide.active) {\n return false;\n }\n\n if (guide.steps.every((s) => !!s.message.archived_at)) {\n return false;\n }\n\n const url = location ? newUrl(location) : undefined;\n\n const urlRules = guide.activation_url_rules || [];\n const urlPatterns = guide.activation_url_patterns || [];\n\n // A guide can have either activation url rules XOR url patterns, but not both.\n if (url && urlRules.length > 0) {\n const allowed = predicateUrlRules(url, urlRules);\n if (!allowed) return false;\n } else if (url && urlPatterns.length > 0) {\n const allowed = predicateUrlPatterns(url, urlPatterns);\n if (!allowed) return false;\n }\n\n return true;\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 = [\n \"guide.added\",\n \"guide.updated\",\n \"guide.removed\",\n \"guide_group.added\",\n \"guide_group.updated\",\n \"guide.live_preview_updated\",\n ];\n private subscribeRetryCount = 0;\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 // Guides that are competing to render are \"staged\" first without rendering\n // and ranked based on its relative order in the group over a duration of time\n // to resolve and render the prevailing one.\n private stage: GroupStage | undefined;\n\n private counterIntervalId: ReturnType<typeof setInterval> | 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 const win = checkForWindow();\n\n const location = trackLocationFromWindow ? win?.location.href : undefined;\n\n const debug = detectDebugParams();\n\n this.store = new Store<StoreState>({\n guideGroups: [],\n guideGroupDisplayLogs: {},\n guides: {},\n previewGuides: {},\n queries: {},\n location,\n // Increment to update the state store and trigger re-selection.\n counter: 0,\n debug,\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 // Start the counter loop to increment at an interval.\n this.startCounterInterval();\n\n this.knock.log(\"[Guide] Initialized a guide client\");\n }\n\n private incrementCounter() {\n this.knock.log(\"[Guide] Incrementing the counter\");\n this.store.setState((state) => ({ ...state, counter: state.counter + 1 }));\n }\n\n private startCounterInterval() {\n const {\n throttleCheckInterval: delay = DEFAULT_COUNTER_INCREMENT_INTERVAL,\n } = this.options;\n\n this.counterIntervalId = setInterval(() => {\n this.knock.log(\"[Guide] Counter interval tick\");\n if (this.stage && this.stage.status !== \"closed\") return;\n\n this.incrementCounter();\n }, delay);\n }\n\n private clearCounterInterval() {\n if (this.counterIntervalId) {\n clearInterval(this.counterIntervalId);\n this.counterIntervalId = undefined;\n }\n }\n\n cleanup() {\n this.unsubscribe();\n this.removeEventListeners();\n this.clearGroupStage();\n this.clearCounterInterval();\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 const { entries, guide_groups: groups, guide_group_display_logs } = data;\n\n this.store.setState((state) => ({\n ...state,\n guideGroups: groups?.length > 0 ? groups : [mockDefaultGroup(entries)],\n guideGroupDisplayLogs: guide_group_display_logs || {},\n guides: byKey(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 debugState = this.store.state.debug;\n const params = {\n ...this.targetParams,\n user_id: this.knock.userId,\n force_all_guides: debugState.forcedGuideKey ? true : undefined,\n preview_session_id: debugState.previewSessionId || undefined,\n };\n\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 // Reset retry count for new subscription attempt\n this.subscribeRetryCount = 0;\n\n newChannel\n .join()\n .receive(\"ok\", () => {\n this.knock.log(\"[Guide] Successfully joined channel\");\n })\n .receive(\"error\", (resp) => {\n this.knock.log(\n `[Guide] Failed to join channel: ${JSON.stringify(resp)}`,\n );\n this.handleChannelJoinError();\n })\n .receive(\"timeout\", () => {\n this.knock.log(\"[Guide] Channel join timed out\");\n this.handleChannelJoinError();\n });\n }\n\n // Track the joined channel.\n this.socketChannel = newChannel;\n }\n\n private handleChannelJoinError() {\n // Prevent phx channel from retrying forever in case of either network or\n // other errors (e.g. auth error, invalid channel etc)\n if (this.subscribeRetryCount >= SUBSCRIBE_RETRY_LIMIT) {\n this.knock.log(\n `[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`,\n );\n this.unsubscribe();\n return;\n }\n\n this.subscribeRetryCount++;\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.addOrReplaceGuide(payload);\n\n case \"guide.updated\":\n return data.eligible\n ? this.addOrReplaceGuide(payload)\n : this.removeGuide(payload);\n\n case \"guide.removed\":\n return this.removeGuide(payload);\n\n case \"guide_group.added\":\n case \"guide_group.updated\":\n return this.addOrReplaceGuideGroup(payload);\n\n case \"guide.live_preview_updated\":\n return this.updatePreviewGuide(payload);\n\n default:\n return;\n }\n }\n\n setLocation(href: string, additionalParams: Partial<StoreState> = {}) {\n // Make sure to clear out the stage.\n this.clearGroupStage();\n\n this.store.setState((state) => {\n // Clear preview guides if no longer in preview mode\n const previewGuides = additionalParams?.debug?.previewSessionId\n ? state.previewGuides\n : {};\n\n return {\n ...state,\n ...additionalParams,\n previewGuides,\n location: href,\n };\n });\n }\n\n //\n // Store selector\n //\n\n selectGuides<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C>[] {\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n return [];\n }\n this.knock.log(`[Guide] Selecting guides for: ${formatFilters(filters)}`);\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection returned zero result\");\n return [];\n }\n\n // Return all selected guides, since we cannot apply the one-at-a-time limit\n // or throttle settings, but rather defer to the caller to decide which ones\n // to render. Note\n return [...result.values()];\n }\n\n selectGuide<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C> | undefined {\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n return undefined;\n }\n this.knock.log(`[Guide] Selecting a guide for: ${formatFilters(filters)}`);\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection returned zero result\");\n return undefined;\n }\n\n const [index, guide] = [...result][0]!;\n\n // If a guide ignores the group limit, then return immediately to render\n // always.\n if (guide.bypass_global_group_limit) {\n return guide;\n }\n\n // Check if inside the throttle window (i.e. throttled) and if so stop and\n // return undefined.\n const defaultGroup = findDefaultGroup(state.guideGroups);\n const throttleWindowStartedAt =\n state.guideGroupDisplayLogs[DEFAULT_GROUP_KEY];\n\n if (\n defaultGroup &&\n defaultGroup.display_interval &&\n throttleWindowStartedAt\n ) {\n const throttled = checkIfThrottled(\n throttleWindowStartedAt,\n defaultGroup.display_interval,\n );\n if (throttled) return undefined;\n }\n\n // Starting here to the end of this method represents the core logic of how\n // \"group stage\" works. It provides a mechanism for 1) figuring out which\n // guide components are about to render on a page, 2) determining which\n // among them ranks highest in the configured display sequence, and 3)\n // returning only the prevailing guide to render at a time.\n //\n // Imagine N number of components that use the `useGuide()` hook which\n // calls this `selectGuide()` method, and the logic works like this:\n // * The first time this method is called, we don't have an \"open\" group\n // stage, so we open one (this occurs when a new page/route is rendering).\n // * While it is open, we record which guide was selected and its order\n // index from each call, but we do NOT return any guide to render yet.\n // * When a group stage opens, it schedules a timer to close itself. How\n // long this timer waits is configurable. Note, `setTimeout` with 0\n // delay seems to work well for React apps, where we \"yield\" to React\n // for one render cycle and close the group right after.\n // * When a group stage closes, we evaluate which guides were selected and\n // recorded, then determine the winning guide (i.e. the one with the\n // lowest order index value).\n // * Then increment the internal counter to trigger a store state update,\n // which allows `useGuide()` and `selectGuide()` to re-run. This second\n // round of `selectGuide()` calls, occurring when the group stage is\n // closed, results in returning the prevailing guide.\n // * Whenever a user navigates to a new page, we repeat the same process\n // above.\n // * There's a third status called \"patch,\" which is for handling real-time\n // updates received from the API. It's similar to the \"open\" to \"closed\"\n // flow, except we keep the resolved guide in place while we recalculate.\n // This is done so that we don't cause flickers or CLS.\n if (!this.stage) {\n this.stage = this.openGroupStage(); // Assign here to make tsc happy\n }\n\n switch (this.stage.status) {\n case \"open\": {\n this.knock.log(`[Guide] Addng to the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n return undefined;\n }\n\n case \"patch\": {\n this.knock.log(`[Guide] Patching the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n return this.stage.resolved === guide.key ? guide : undefined;\n }\n\n case \"closed\": {\n return this.stage.resolved === guide.key ? guide : undefined;\n }\n }\n }\n\n private openGroupStage() {\n this.knock.log(\"[Guide] Opening a new group stage\");\n\n const {\n orderResolutionDuration: delay = DEFAULT_ORDER_RESOLUTION_DURATION,\n } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n this.stage = {\n status: \"open\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n // Close the current non-closed stage to resolve the prevailing guide up next\n // for display amongst the ones that have been staged.\n private closePendingGroupStage() {\n if (!this.stage || this.stage.status === \"closed\") return;\n\n this.knock.log(\"[Guide] Closing the current group stage\");\n\n // Should have been cleared already since this method should be called as a\n // callback to a setTimeout, but just to be safe.\n this.ensureClearTimeout();\n\n // If in debug mode, try to resolve the forced guide, otherwise return the first non-undefined guide.\n let resolved = undefined;\n if (this.store.state.debug.forcedGuideKey) {\n resolved = this.stage.ordered.find(\n (x) => x === this.store.state.debug.forcedGuideKey,\n );\n }\n\n if (!resolved) {\n resolved = this.stage.ordered.find((x) => x !== undefined);\n }\n\n this.stage = {\n ...this.stage,\n status: \"closed\",\n resolved,\n timeoutId: null,\n };\n\n return this.stage;\n }\n\n // Set the current closed stage status to \"patch\" to allow re-running\n // selections and re-building a group stage with the latest/updated state,\n // while keeping the currently resolved guide in place so that it stays\n // rendered until we are ready to resolve the updated stage and re-render.\n // Note, must be called ahead of updating the state store.\n private patchClosedGroupStage() {\n if (this.stage?.status !== \"closed\") return;\n\n this.knock.log(\"[Guide] Patching the current group stage\");\n\n const { orderResolutionDuration: delay = 0 } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n // Just to be safe.\n this.ensureClearTimeout();\n\n this.stage = {\n ...this.stage,\n status: \"patch\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n private clearGroupStage() {\n if (!this.stage) return;\n\n this.knock.log(\"[Guide] Clearing the current group stage\");\n\n this.ensureClearTimeout();\n this.stage = undefined;\n }\n\n private ensureClearTimeout() {\n if (this.stage?.timeoutId) {\n clearTimeout(this.stage.timeoutId);\n }\n }\n\n // Test helper that opens and closes the group stage to return the select\n // result immediately.\n private _selectGuide(state: StoreState, filters: SelectFilterParams = {}) {\n this.openGroupStage();\n\n this.selectGuide(state, filters);\n this.closePendingGroupStage();\n\n return this.selectGuide(state, filters);\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 if (step.message.seen_at) return;\n\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 if (step.message.archived_at) return;\n\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 {\n ...params,\n unthrottled: guide.bypass_global_group_limit,\n },\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 = {\n ...remoteGuide,\n // Get the next unarchived step.\n getStep() {\n // If debugging this guide, return the first step regardless of archive status\n if (self.store.state.debug.forcedGuideKey === this.key) {\n return this.steps[0];\n }\n\n return this.steps.find((s) => !s.message.archived_at);\n },\n } as KnockGuide;\n\n localGuide.getStep = localGuide.getStep.bind(localGuide);\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_url_patterns =\n remoteGuide.activation_url_patterns.map((rule) => {\n return {\n ...rule,\n pattern: new URLPattern({ pathname: rule.pathname }),\n };\n });\n\n return localGuide;\n }\n\n private buildQueryParams(filterParams: QueryFilterParams = {}) {\n // Combine the target params with the given filter params.\n const combinedParams: GenericData = {\n ...this.targetParams,\n ...filterParams,\n };\n\n // Append debug params\n const debugState = this.store.state.debug;\n if (debugState.forcedGuideKey) {\n combinedParams.force_all_guides = true;\n }\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 // If we are marking as archived, clear the group stage so we can render\n // the next guide in the group.\n if (attrs.archived_at) {\n this.clearGroupStage();\n }\n\n this.store.setState((state) => {\n const guide = state.guides[guideKey];\n if (!guide) return state;\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 // Mutate in place and maintain the same obj ref.\n guide.steps = steps;\n const guides = { ...state.guides, [guide.key]: guide };\n\n // If the guide is subject to throttled settings and we are marking as\n // archived, then update the display logs to start a new throttle window.\n const guideGroupDisplayLogs =\n attrs.archived_at && !guide.bypass_global_group_limit\n ? {\n ...state.guideGroupDisplayLogs,\n [DEFAULT_GROUP_KEY]: attrs.archived_at,\n }\n : state.guideGroupDisplayLogs;\n\n return { ...state, guides, guideGroupDisplayLogs };\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 addOrReplaceGuide({ data }: GuideAddedEvent | GuideUpdatedEvent) {\n this.patchClosedGroupStage();\n\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const guides = { ...state.guides, [guide.key]: guide };\n\n return { ...state, guides };\n });\n }\n\n private removeGuide({ data }: GuideUpdatedEvent | GuideRemovedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n const { [data.guide.key]: _, ...rest } = state.guides;\n return { ...state, guides: rest };\n });\n }\n\n private addOrReplaceGuideGroup({\n data,\n }: GuideGroupAddedEvent | GuideGroupUpdatedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n // Currently we only support a single default global group, so we can just\n // update the list with the added/updated group.\n const guideGroups = [data.guide_group];\n\n // A guide group event can include lists of unthrottled vs throttled guide\n // keys which we can use to bulk update the guides in the store already.\n const unthrottled = data.guide_group.display_sequence_unthrottled || [];\n const throttled = data.guide_group.display_sequence_throttled || [];\n\n let guides = state.guides;\n\n guides = unthrottled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: true };\n return { ...acc, [key]: guide };\n }, guides);\n\n guides = throttled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: false };\n return { ...acc, [key]: guide };\n }, guides);\n\n return { ...state, guides, guideGroups };\n });\n }\n\n private updatePreviewGuide({ data }: GuideLivePreviewUpdatedEvent) {\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const previewGuides = { ...state.previewGuides, [guide.key]: guide };\n return { ...state, previewGuides };\n });\n }\n\n // Define as an arrow func property to always bind this to the class instance.\n private handleLocationChange = () => {\n const win = checkForWindow();\n if (!win?.location) return;\n\n const href = win.location.href;\n if (this.store.state.location === href) return;\n\n this.knock.log(`[Guide] Handle Location change: ${href}`);\n\n // If entering debug mode, fetch all guides.\n const currentDebugParams = this.store.state.debug;\n const newDebugParams = detectDebugParams();\n this.setLocation(href, { debug: newDebugParams });\n\n // If debug state has changed, refetch guides and resubscribe to the websocket channel\n const debugStateChanged = this.checkDebugStateChanged(\n currentDebugParams,\n newDebugParams,\n );\n\n if (debugStateChanged) {\n this.knock.log(\n `[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel`,\n );\n this.fetch();\n this.subscribe();\n }\n };\n\n // Returns whether debug params have changed. For guide key, we only check\n // presence since the exact value has no impact on fetch/subscribe\n private checkDebugStateChanged(a: DebugState, b: DebugState): boolean {\n return (\n Boolean(a.forcedGuideKey) !== Boolean(b.forcedGuideKey) ||\n a.previewSessionId !== b.previewSessionId\n );\n }\n\n private listenForLocationChangesFromWindow() {\n const win = checkForWindow();\n if (win?.history) {\n // 1. Listen for browser back/forward button clicks.\n win.addEventListener(\"popstate\", this.handleLocationChange);\n\n // 2. Listen for hash changes in case it's used for routing.\n win.addEventListener(\"hashchange\", this.handleLocationChange);\n\n // 3. Monkey-patch history methods to catch programmatic navigation.\n const pushStateFn = win.history.pushState;\n const replaceStateFn = win.history.replaceState;\n\n // Use setTimeout to allow the browser state to potentially settle.\n win.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 win.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 const win = checkForWindow();\n if (!win?.history) return;\n\n win.removeEventListener(\"popstate\", this.handleLocationChange);\n win.removeEventListener(\"hashchange\", this.handleLocationChange);\n\n if (this.pushStateFn) {\n win.history.pushState = this.pushStateFn;\n this.pushStateFn = undefined;\n }\n if (this.replaceStateFn) {\n win.history.replaceState = this.replaceStateFn;\n this.replaceStateFn = undefined;\n }\n }\n}\n"],"names":["DEFAULT_ORDER_RESOLUTION_DURATION","DEFAULT_COUNTER_INCREMENT_INTERVAL","SUBSCRIBE_RETRY_LIMIT","DEBUG_QUERY_PARAMS","checkForWindow","guidesApiRootPath","userId","detectDebugParams","win","urlParams","forcedGuideKey","previewSessionId","select","state","filters","result","SelectionResult","defaultGroup","findDefaultGroup","displaySequence","location","forcedKeyIndex","index","guideKey","guide","predicate","debug","s","url","newUrl","urlRules","urlPatterns","predicateUrlRules","predicateUrlPatterns","KnockGuideClient","knock","channelId","targetParams","options","__publicField","href","currentDebugParams","newDebugParams","trackLocationFromWindow","Store","maybeSocket","delay","opts","queryParams","queryKey","maybeQueryStatus","queryStatus","data","entries","groups","guide_group_display_logs","mockDefaultGroup","byKey","g","e","debugState","params","newChannel","eventType","payload","resp","event","additionalParams","previewGuides","_a","formatFilters","throttleWindowStartedAt","DEFAULT_GROUP_KEY","checkIfThrottled","timeoutId","resolved","x","step","updatedStep","metadata","ts","remoteGuide","self","localGuide","message","rest","localStep","rule","URLPattern","filterParams","combinedParams","_k","v","queryStr","key","basePath","stepRef","attrs","steps","guides","guideGroupDisplayLogs","_","guideGroups","unthrottled","throttled","acc","a","b","pushStateFn","replaceStateFn","target","history","args"],"mappings":"kVAmDMA,EAAoC,GAIpCC,EAAqC,GAAK,IAG1CC,EAAwB,EAGjBC,EAAqB,CAChC,UAAW,kBACX,mBAAoB,0BACtB,EAGMC,EAAiB,IAAM,CACvB,GAAA,OAAO,OAAW,IACb,OAAA,MAEX,EAEaC,EAAqBC,GAChC,aAAaA,CAAM,UAGfC,EAAoB,IAAkB,CAC1C,MAAMC,EAAMJ,EAAe,EAC3B,GAAI,CAACI,EACH,MAAO,CAAE,eAAgB,KAAM,iBAAkB,IAAK,EAGxD,MAAMC,EAAY,IAAI,gBAAgBD,EAAI,SAAS,MAAM,EACnDE,EAAiBD,EAAU,IAAIN,EAAmB,SAAS,EAC3DQ,EAAmBF,EAAU,IAAIN,EAAmB,kBAAkB,EAErE,MAAA,CAAE,eAAAO,EAAgB,iBAAAC,CAAiB,CAC5C,EAEMC,EAAS,CA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I,QAAQ,UAAY,IAAI,MAAMoG,EAAa,CAC7C,MAAO,CAACE,EAAQC,EAASC,IAAS,CACxB,QAAA,MAAMF,EAAQC,EAASC,CAAI,EACnC,WAAW,IAAM,CACf,KAAK,qBAAqB,GACzB,CAAC,CAAA,CACN,CACD,EACDxG,EAAI,QAAQ,aAAe,IAAI,MAAMqG,EAAgB,CACnD,MAAO,CAACC,EAAQC,EAASC,IAAS,CACxB,QAAA,MAAMF,EAAQC,EAASC,CAAI,EACnC,WAAW,IAAM,CACf,KAAK,qBAAqB,GACzB,CAAC,CAAA,CACN,CACD,EAGD,KAAK,YAAcJ,EACnB,KAAK,eAAiBC,CAAA,MAEtB,KAAK,MAAM,IACT,iFACF,CACF,CAGM,sBAAuB,CAC7B,MAAMrG,EAAMJ,EAAe,EACtBI,GAAA,MAAAA,EAAK,UAENA,EAAA,oBAAoB,WAAY,KAAK,oBAAoB,EACzDA,EAAA,oBAAoB,aAAc,KAAK,oBAAoB,EAE3D,KAAK,cACHA,EAAA,QAAQ,UAAY,KAAK,YAC7B,KAAK,YAAc,QAEjB,KAAK,iBACHA,EAAA,QAAQ,aAAe,KAAK,eAChC,KAAK,eAAiB,QACxB,CAEJ"}
|
package/dist/cjs/knock.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var h=Object.defineProperty;var
|
|
1
|
+
"use strict";var h=Object.defineProperty;var d=(s,e,i)=>e in s?h(s,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):s[e]=i;var t=(s,e,i)=>d(s,typeof e!="symbol"?e+"":e,i);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const r=require("jwt-decode"),f=require("./api.js"),k=require("./clients/feed/index.js"),g=require("./clients/messages/index.js"),T=require("./clients/ms-teams/index.js"),w=require("./clients/objects/index.js"),y=require("./clients/preferences/index.js"),p=require("./clients/slack/index.js"),x=require("./clients/users/index.js"),m="https://api.knock.app";class C{constructor(e,i={}){t(this,"host");t(this,"apiClient",null);t(this,"userId");t(this,"userToken");t(this,"logLevel");t(this,"tokenExpirationTimer",null);t(this,"feeds",new k.default(this));t(this,"objects",new w.default(this));t(this,"preferences",new y.default(this));t(this,"slack",new p.default(this));t(this,"msTeams",new T.default(this));t(this,"user",new x.default(this));t(this,"messages",new g.default(this));if(this.apiKey=e,this.host=i.host||m,this.logLevel=i.logLevel,this.log("Initialized Knock instance"),this.apiKey&&this.apiKey.startsWith("sk_"))throw new Error("[Knock] You are using your secret API key on the client. Please use the public key.")}client(){return this.apiClient||(this.apiClient=this.createApiClient()),this.apiClient}authenticate(e,i,n){let a=!1;const l=this.apiClient,o=this.getUserId(e),c=(n==null?void 0:n.identificationStrategy)||"inline";if(l&&(this.userId!==o||this.userToken!==i)&&(this.log("userId or userToken changed; reinitializing connections"),this.feeds.teardownInstances(),this.teardown(),a=!0),this.userId=o,this.userToken=i,this.log(`Authenticated with userId ${o}`),this.userToken&&(n==null?void 0:n.onUserTokenExpiring)instanceof Function&&this.maybeScheduleUserTokenExpiration(n.onUserTokenExpiring,n.timeBeforeExpirationInMs),a&&(this.apiClient=this.createApiClient(),this.feeds.reinitializeInstances(),this.log("Reinitialized real-time connections")),c==="skip"){this.log("Skipping inline user identification");return}if(c==="inline"&&typeof e=="object"&&(e!=null&&e.id)){this.log(`Identifying user ${e.id} inline`);const{id:E,...u}=e;this.user.identify(u)}}failIfNotAuthenticated(){if(!this.isAuthenticated())throw new Error("Not authenticated. Please call `authenticate` first.")}isAuthenticated(e=!1){return e?!!(this.userId&&this.userToken):!!this.userId}teardown(){var e;this.tokenExpirationTimer&&clearTimeout(this.tokenExpirationTimer),(e=this.apiClient)!=null&&e.socket&&this.apiClient.socket.isConnected()&&this.apiClient.socket.disconnect()}log(e,i=!1){(this.logLevel==="debug"||i)&&console.log(`[Knock] ${e}`)}createApiClient(){return new f.default({apiKey:this.apiKey,host:this.host,userToken:this.userToken})}async maybeScheduleUserTokenExpiration(e,i=3e4){if(!this.userToken)return;const n=r.jwtDecode(this.userToken),a=(n.exp??0)*1e3,l=Date.now();if(a&&a>l){const o=a-i-l;this.tokenExpirationTimer=setTimeout(async()=>{const c=await e(this.userToken,n);typeof c=="string"&&this.authenticate(this.userId,c,{onUserTokenExpiring:e,timeBeforeExpirationInMs:i})},o)}}getUserId(e){if(typeof e=="string"||!e)return e;if(e!=null&&e.id)return e.id;throw new Error("`user` object must contain an `id` property")}}exports.default=C;
|
|
2
2
|
//# sourceMappingURL=knock.js.map
|
package/dist/cjs/knock.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knock.js","sources":["../../src/knock.ts"],"sourcesContent":["import { jwtDecode } from \"jwt-decode\";\n\nimport ApiClient from \"./api\";\nimport FeedClient from \"./clients/feed\";\nimport MessageClient from \"./clients/messages\";\nimport MsTeamsClient from \"./clients/ms-teams\";\nimport ObjectClient from \"./clients/objects\";\nimport Preferences from \"./clients/preferences\";\nimport SlackClient from \"./clients/slack\";\nimport UserClient from \"./clients/users\";\nimport {\n AuthenticateOptions,\n KnockOptions,\n LogLevel,\n UserId,\n UserIdOrUserWithProperties,\n UserTokenExpiringCallback,\n} from \"./interfaces\";\n\nconst DEFAULT_HOST = \"https://api.knock.app\";\n\nclass Knock {\n public host: string;\n private apiClient: ApiClient | null = null;\n public userId: string | undefined | null;\n public userToken?: string;\n public logLevel?: LogLevel;\n private tokenExpirationTimer: ReturnType<typeof setTimeout> | null = null;\n readonly feeds = new FeedClient(this);\n readonly objects = new ObjectClient(this);\n readonly preferences = new Preferences(this);\n readonly slack = new SlackClient(this);\n readonly msTeams = new MsTeamsClient(this);\n readonly user = new UserClient(this);\n readonly messages = new MessageClient(this);\n\n constructor(\n readonly apiKey: string,\n options: KnockOptions = {},\n ) {\n this.host = options.host || DEFAULT_HOST;\n this.logLevel = options.logLevel;\n\n this.log(\"Initialized Knock instance\");\n\n // Fail loudly if we're using the wrong API key\n if (this.apiKey && this.apiKey.startsWith(\"sk_\")) {\n throw new Error(\n \"[Knock] You are using your secret API key on the client. Please use the public key.\",\n );\n }\n }\n\n client() {\n // Initiate a new API client if we don't have one yet\n if (!this.apiClient) {\n this.apiClient = this.createApiClient();\n }\n\n return this.apiClient;\n }\n\n /**\n * @deprecated Passing `userId` as a `string` is deprecated and will be removed in a future version.\n * Please pass a `user` object instead containing an `id` value.\n * example:\n * ```ts\n * knock.authenticate({ id: \"user_123\" });\n * ```\n */\n authenticate(\n userIdOrUserWithProperties: UserId,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ): never;\n authenticate(\n userIdOrUserWithProperties: UserIdOrUserWithProperties,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ): void;\n authenticate(\n userIdOrUserWithProperties: UserIdOrUserWithProperties,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ) {\n let reinitializeApi = false;\n const currentApiClient = this.apiClient;\n const userId = this.getUserId(userIdOrUserWithProperties);\n\n // If we've previously been initialized and the values have now changed, then we\n // need to reinitialize any stateful connections we have\n if (\n currentApiClient &&\n (this.userId !== userId || this.userToken !== userToken)\n ) {\n this.log(\"userId or userToken changed; reinitializing connections\");\n this.feeds.teardownInstances();\n this.teardown();\n reinitializeApi = true;\n }\n\n this.userId = userId;\n this.userToken = userToken;\n\n this.log(`Authenticated with userId ${userId}`);\n\n if (this.userToken && options?.onUserTokenExpiring instanceof Function) {\n this.maybeScheduleUserTokenExpiration(\n options.onUserTokenExpiring,\n options.timeBeforeExpirationInMs,\n );\n }\n\n // If we get the signal to reinitialize the api client, then we want to create a new client\n // and the reinitialize any existing feed real-time connections we have so everything continues\n // to work with the new credentials we've been given\n if (reinitializeApi) {\n this.apiClient = this.createApiClient();\n this.feeds.reinitializeInstances();\n this.log(\"Reinitialized real-time connections\");\n }\n\n // Inline identify the user if we've been given an object with an id.\n if (\n typeof userIdOrUserWithProperties === \"object\" &&\n userIdOrUserWithProperties?.id\n ) {\n const { id, ...properties } = userIdOrUserWithProperties;\n this.user.identify(properties);\n }\n\n return;\n }\n\n failIfNotAuthenticated() {\n if (!this.isAuthenticated()) {\n throw new Error(\"Not authenticated. Please call `authenticate` first.\");\n }\n }\n\n /*\n Returns whether or this Knock instance is authenticated. Passing `true` will check the presence\n of the userToken as well.\n */\n isAuthenticated(checkUserToken = false) {\n return checkUserToken ? !!(this.userId && this.userToken) : !!this.userId;\n }\n\n // Used to teardown any connected instances\n teardown() {\n if (this.tokenExpirationTimer) {\n clearTimeout(this.tokenExpirationTimer);\n }\n if (this.apiClient?.socket && this.apiClient.socket.isConnected()) {\n this.apiClient.socket.disconnect();\n }\n }\n\n log(message: string, force = false) {\n if (this.logLevel === \"debug\" || force) {\n console.log(`[Knock] ${message}`);\n }\n }\n\n /**\n * Initiates an API client\n */\n private createApiClient() {\n return new ApiClient({\n apiKey: this.apiKey,\n host: this.host,\n userToken: this.userToken,\n });\n }\n\n private async maybeScheduleUserTokenExpiration(\n callbackFn: UserTokenExpiringCallback,\n timeBeforeExpirationInMs: number = 30_000,\n ) {\n if (!this.userToken) return;\n\n const decoded = jwtDecode(this.userToken);\n const expiresAtMs = (decoded.exp ?? 0) * 1000;\n const nowMs = Date.now();\n\n // Expiration is in the future\n if (expiresAtMs && expiresAtMs > nowMs) {\n // Check how long until the token should be regenerated\n // | ----------------- | ----------------------- |\n // ^ now ^ expiration offset ^ expires at\n const msInFuture = expiresAtMs - timeBeforeExpirationInMs - nowMs;\n\n this.tokenExpirationTimer = setTimeout(async () => {\n const newToken = await callbackFn(this.userToken as string, decoded);\n\n // Reauthenticate which will handle reinitializing sockets\n if (typeof newToken === \"string\") {\n this.authenticate(this.userId!, newToken, {\n onUserTokenExpiring: callbackFn,\n timeBeforeExpirationInMs: timeBeforeExpirationInMs,\n });\n }\n }, msInFuture);\n }\n }\n\n /**\n * Returns the user id from the given userIdOrUserWithProperties\n * @param userIdOrUserWithProperties - The user id or user object\n * @returns The user id\n * @throws {Error} If the user object does not contain an `id` property\n */\n private getUserId(userIdOrUserWithProperties: UserIdOrUserWithProperties) {\n if (\n typeof userIdOrUserWithProperties === \"string\" ||\n !userIdOrUserWithProperties\n ) {\n return userIdOrUserWithProperties;\n }\n\n if (userIdOrUserWithProperties?.id) {\n return userIdOrUserWithProperties.id;\n }\n\n throw new Error(\"`user` object must contain an `id` property\");\n }\n}\n\nexport default Knock;\n"],"names":["DEFAULT_HOST","Knock","apiKey","options","__publicField","FeedClient","ObjectClient","Preferences","SlackClient","MsTeamsClient","UserClient","MessageClient","userIdOrUserWithProperties","userToken","reinitializeApi","currentApiClient","userId","id","properties","checkUserToken","_a","message","force","ApiClient","callbackFn","timeBeforeExpirationInMs","decoded","jwtDecode","expiresAtMs","nowMs","msInFuture","newToken"],"mappings":"2lBAmBMA,EAAe,wBAErB,MAAMC,CAAM,CAeV,YACWC,EACTC,EAAwB,GACxB,CAjBKC,EAAA,aACCA,EAAA,iBAA8B,MAC/BA,EAAA,eACAA,EAAA,kBACAA,EAAA,iBACCA,EAAA,4BAA6D,MAC5DA,EAAA,aAAQ,IAAIC,EAAA,QAAW,IAAI,GAC3BD,EAAA,eAAU,IAAIE,EAAA,QAAa,IAAI,GAC/BF,EAAA,mBAAc,IAAIG,EAAA,QAAY,IAAI,GAClCH,EAAA,aAAQ,IAAII,EAAA,QAAY,IAAI,GAC5BJ,EAAA,eAAU,IAAIK,EAAA,QAAc,IAAI,GAChCL,EAAA,YAAO,IAAIM,EAAA,QAAW,IAAI,GAC1BN,EAAA,gBAAW,IAAIO,EAAA,QAAc,IAAI,GAYxC,GATS,KAAA,OAAAT,EAGJ,KAAA,KAAOC,EAAQ,MAAQH,EAC5B,KAAK,SAAWG,EAAQ,SAExB,KAAK,IAAI,4BAA4B,EAGjC,KAAK,QAAU,KAAK,OAAO,WAAW,KAAK,EAC7C,MAAM,IAAI,MACR,qFACF,CACF,CAGF,QAAS,CAEH,OAAC,KAAK,YACH,KAAA,UAAY,KAAK,gBAAgB,GAGjC,KAAK,SAAA,CAqBd,aACES,EACA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AC,EAAmC,IACnC,CACI,GAAA,CAAC,KAAK,UAAW,OAEf,MAAAC,EAAUC,EAAAA,UAAU,KAAK,SAAS,EAClCC,GAAeF,EAAQ,KAAO,GAAK,IACnCG,EAAQ,KAAK,IAAI,EAGnB,GAAAD,GAAeA,EAAcC,EAAO,CAIhC,MAAAC,EAAaF,EAAcH,EAA2BI,EAEvD,KAAA,qBAAuB,WAAW,SAAY,CACjD,MAAME,EAAW,MAAMP,EAAW,KAAK,UAAqBE,CAAO,EAG/D,OAAOK,GAAa,UACjB,KAAA,aAAa,KAAK,OAASA,EAAU,CACxC,oBAAqBP,EACrB,yBAAAC,CAAA,CACD,GAEFK,CAAU,CAAA,CACf,CASM,UAAUlB,EAAwD,CACxE,GACE,OAAOA,GAA+B,UACtC,CAACA,EAEM,OAAAA,EAGT,GAAIA,GAAA,MAAAA,EAA4B,GAC9B,OAAOA,EAA2B,GAG9B,MAAA,IAAI,MAAM,6CAA6C,CAAA,CAEjE"}
|
|
1
|
+
{"version":3,"file":"knock.js","sources":["../../src/knock.ts"],"sourcesContent":["import { jwtDecode } from \"jwt-decode\";\n\nimport ApiClient from \"./api\";\nimport FeedClient from \"./clients/feed\";\nimport MessageClient from \"./clients/messages\";\nimport MsTeamsClient from \"./clients/ms-teams\";\nimport ObjectClient from \"./clients/objects\";\nimport Preferences from \"./clients/preferences\";\nimport SlackClient from \"./clients/slack\";\nimport UserClient from \"./clients/users\";\nimport {\n AuthenticateOptions,\n KnockOptions,\n LogLevel,\n UserId,\n UserIdOrUserWithProperties,\n UserTokenExpiringCallback,\n} from \"./interfaces\";\n\nconst DEFAULT_HOST = \"https://api.knock.app\";\n\nclass Knock {\n public host: string;\n private apiClient: ApiClient | null = null;\n public userId: string | undefined | null;\n public userToken?: string;\n public logLevel?: LogLevel;\n private tokenExpirationTimer: ReturnType<typeof setTimeout> | null = null;\n readonly feeds = new FeedClient(this);\n readonly objects = new ObjectClient(this);\n readonly preferences = new Preferences(this);\n readonly slack = new SlackClient(this);\n readonly msTeams = new MsTeamsClient(this);\n readonly user = new UserClient(this);\n readonly messages = new MessageClient(this);\n\n constructor(\n readonly apiKey: string,\n options: KnockOptions = {},\n ) {\n this.host = options.host || DEFAULT_HOST;\n this.logLevel = options.logLevel;\n\n this.log(\"Initialized Knock instance\");\n\n // Fail loudly if we're using the wrong API key\n if (this.apiKey && this.apiKey.startsWith(\"sk_\")) {\n throw new Error(\n \"[Knock] You are using your secret API key on the client. Please use the public key.\",\n );\n }\n }\n\n client() {\n // Initiate a new API client if we don't have one yet\n if (!this.apiClient) {\n this.apiClient = this.createApiClient();\n }\n\n return this.apiClient;\n }\n\n /**\n * @deprecated Passing `userId` as a `string` is deprecated and will be removed in a future version.\n * Please pass a `user` object instead containing an `id` value.\n * example:\n * ```ts\n * knock.authenticate({ id: \"user_123\" });\n * ```\n */\n authenticate(\n userIdOrUserWithProperties: UserId,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ): never;\n authenticate(\n userIdOrUserWithProperties: UserIdOrUserWithProperties,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ): void;\n authenticate(\n userIdOrUserWithProperties: UserIdOrUserWithProperties,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ) {\n let reinitializeApi = false;\n const currentApiClient = this.apiClient;\n const userId = this.getUserId(userIdOrUserWithProperties);\n const identificationStrategy = options?.identificationStrategy || \"inline\";\n\n // If we've previously been initialized and the values have now changed, then we\n // need to reinitialize any stateful connections we have\n if (\n currentApiClient &&\n (this.userId !== userId || this.userToken !== userToken)\n ) {\n this.log(\"userId or userToken changed; reinitializing connections\");\n this.feeds.teardownInstances();\n this.teardown();\n reinitializeApi = true;\n }\n\n this.userId = userId;\n this.userToken = userToken;\n\n this.log(`Authenticated with userId ${userId}`);\n\n if (this.userToken && options?.onUserTokenExpiring instanceof Function) {\n this.maybeScheduleUserTokenExpiration(\n options.onUserTokenExpiring,\n options.timeBeforeExpirationInMs,\n );\n }\n\n // If we get the signal to reinitialize the api client, then we want to create a new client\n // and the reinitialize any existing feed real-time connections we have so everything continues\n // to work with the new credentials we've been given\n if (reinitializeApi) {\n this.apiClient = this.createApiClient();\n this.feeds.reinitializeInstances();\n this.log(\"Reinitialized real-time connections\");\n }\n\n // We explicitly skip the inline identification if the strategy is set to \"skip\"\n if (identificationStrategy === \"skip\") {\n this.log(\"Skipping inline user identification\");\n return;\n }\n\n // Inline identify the user if we've been given an object with an id\n // and the strategy is set to \"inline\".\n if (\n identificationStrategy === \"inline\" &&\n typeof userIdOrUserWithProperties === \"object\" &&\n userIdOrUserWithProperties?.id\n ) {\n this.log(`Identifying user ${userIdOrUserWithProperties.id} inline`);\n const { id, ...properties } = userIdOrUserWithProperties;\n this.user.identify(properties);\n }\n\n return;\n }\n\n failIfNotAuthenticated() {\n if (!this.isAuthenticated()) {\n throw new Error(\"Not authenticated. Please call `authenticate` first.\");\n }\n }\n\n /*\n Returns whether or this Knock instance is authenticated. Passing `true` will check the presence\n of the userToken as well.\n */\n isAuthenticated(checkUserToken = false) {\n return checkUserToken ? !!(this.userId && this.userToken) : !!this.userId;\n }\n\n // Used to teardown any connected instances\n teardown() {\n if (this.tokenExpirationTimer) {\n clearTimeout(this.tokenExpirationTimer);\n }\n if (this.apiClient?.socket && this.apiClient.socket.isConnected()) {\n this.apiClient.socket.disconnect();\n }\n }\n\n log(message: string, force = false) {\n if (this.logLevel === \"debug\" || force) {\n console.log(`[Knock] ${message}`);\n }\n }\n\n /**\n * Initiates an API client\n */\n private createApiClient() {\n return new ApiClient({\n apiKey: this.apiKey,\n host: this.host,\n userToken: this.userToken,\n });\n }\n\n private async maybeScheduleUserTokenExpiration(\n callbackFn: UserTokenExpiringCallback,\n timeBeforeExpirationInMs: number = 30_000,\n ) {\n if (!this.userToken) return;\n\n const decoded = jwtDecode(this.userToken);\n const expiresAtMs = (decoded.exp ?? 0) * 1000;\n const nowMs = Date.now();\n\n // Expiration is in the future\n if (expiresAtMs && expiresAtMs > nowMs) {\n // Check how long until the token should be regenerated\n // | ----------------- | ----------------------- |\n // ^ now ^ expiration offset ^ expires at\n const msInFuture = expiresAtMs - timeBeforeExpirationInMs - nowMs;\n\n this.tokenExpirationTimer = setTimeout(async () => {\n const newToken = await callbackFn(this.userToken as string, decoded);\n\n // Reauthenticate which will handle reinitializing sockets\n if (typeof newToken === \"string\") {\n this.authenticate(this.userId!, newToken, {\n onUserTokenExpiring: callbackFn,\n timeBeforeExpirationInMs: timeBeforeExpirationInMs,\n });\n }\n }, msInFuture);\n }\n }\n\n /**\n * Returns the user id from the given userIdOrUserWithProperties\n * @param userIdOrUserWithProperties - The user id or user object\n * @returns The user id\n * @throws {Error} If the user object does not contain an `id` property\n */\n private getUserId(userIdOrUserWithProperties: UserIdOrUserWithProperties) {\n if (\n typeof userIdOrUserWithProperties === \"string\" ||\n !userIdOrUserWithProperties\n ) {\n return userIdOrUserWithProperties;\n }\n\n if (userIdOrUserWithProperties?.id) {\n return userIdOrUserWithProperties.id;\n }\n\n throw new Error(\"`user` object must contain an `id` property\");\n }\n}\n\nexport default Knock;\n"],"names":["DEFAULT_HOST","Knock","apiKey","options","__publicField","FeedClient","ObjectClient","Preferences","SlackClient","MsTeamsClient","UserClient","MessageClient","userIdOrUserWithProperties","userToken","reinitializeApi","currentApiClient","userId","identificationStrategy","id","properties","checkUserToken","_a","message","force","ApiClient","callbackFn","timeBeforeExpirationInMs","decoded","jwtDecode","expiresAtMs","nowMs","msInFuture","newToken"],"mappings":"2lBAmBMA,EAAe,wBAErB,MAAMC,CAAM,CAeV,YACWC,EACTC,EAAwB,GACxB,CAjBKC,EAAA,aACCA,EAAA,iBAA8B,MAC/BA,EAAA,eACAA,EAAA,kBACAA,EAAA,iBACCA,EAAA,4BAA6D,MAC5DA,EAAA,aAAQ,IAAIC,EAAA,QAAW,IAAI,GAC3BD,EAAA,eAAU,IAAIE,EAAA,QAAa,IAAI,GAC/BF,EAAA,mBAAc,IAAIG,EAAA,QAAY,IAAI,GA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AAA,CAEjE"}
|
package/dist/esm/api.mjs
CHANGED
|
@@ -53,7 +53,7 @@ class k {
|
|
|
53
53
|
return o.isNetworkError(e) ? !0 : e.response ? e.response.status >= 500 && e.response.status <= 599 || e.response.status === 429 : !1;
|
|
54
54
|
}
|
|
55
55
|
getKnockClientHeader() {
|
|
56
|
-
return "Knock/ClientJS 0.
|
|
56
|
+
return "Knock/ClientJS 0.18.0";
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
59
|
export {
|
|
@@ -3,21 +3,21 @@ var G = (a, e, t) => e in a ? v(a, e, { enumerable: !0, configurable: !0, writab
|
|
|
3
3
|
var d = (a, e, t) => G(a, typeof e != "symbol" ? e + "" : e, t);
|
|
4
4
|
import { Store as _ } from "@tanstack/store";
|
|
5
5
|
import { URLPattern as b } from "urlpattern-polyfill";
|
|
6
|
-
import { byKey as C, mockDefaultGroup as I, formatFilters as g, findDefaultGroup as
|
|
6
|
+
import { byKey as C, mockDefaultGroup as I, formatFilters as g, findDefaultGroup as m, DEFAULT_GROUP_KEY as p, checkIfThrottled as w, SelectionResult as E, newUrl as A, predicateUrlRules as R, predicateUrlPatterns as L } from "./helpers.mjs";
|
|
7
7
|
const P = 50, D = 30 * 1e3, T = 3, k = {
|
|
8
8
|
GUIDE_KEY: "knock_guide_key",
|
|
9
9
|
PREVIEW_SESSION_ID: "knock_preview_session_id"
|
|
10
10
|
}, l = () => {
|
|
11
11
|
if (typeof window < "u")
|
|
12
12
|
return window;
|
|
13
|
-
},
|
|
13
|
+
}, O = (a) => `/v1/users/${a}/guides`, f = () => {
|
|
14
14
|
const a = l();
|
|
15
15
|
if (!a)
|
|
16
16
|
return { forcedGuideKey: null, previewSessionId: null };
|
|
17
17
|
const e = new URLSearchParams(a.location.search), t = e.get(k.GUIDE_KEY), s = e.get(k.PREVIEW_SESSION_ID);
|
|
18
18
|
return { forcedGuideKey: t, previewSessionId: s };
|
|
19
|
-
},
|
|
20
|
-
const t = new E(), s =
|
|
19
|
+
}, y = (a, e = {}) => {
|
|
20
|
+
const t = new E(), s = m(a.guideGroups);
|
|
21
21
|
if (!s) return t;
|
|
22
22
|
const i = [...s.display_sequence], n = a.location;
|
|
23
23
|
if (a.debug.forcedGuideKey) {
|
|
@@ -26,19 +26,19 @@ const P = 50, D = 30 * 1e3, T = 3, k = {
|
|
|
26
26
|
}
|
|
27
27
|
for (const [r, o] of i.entries()) {
|
|
28
28
|
let u = a.guides[o];
|
|
29
|
-
a.debug.forcedGuideKey === o && a.previewGuides[o] && (u = a.previewGuides[o]), !(!u || !
|
|
29
|
+
a.debug.forcedGuideKey === o && a.previewGuides[o] && (u = a.previewGuides[o]), !(!u || !K(u, {
|
|
30
30
|
location: n,
|
|
31
31
|
filters: e,
|
|
32
32
|
debug: a.debug
|
|
33
33
|
})) && t.set(r, u);
|
|
34
34
|
}
|
|
35
35
|
return t.metadata = { guideGroup: s }, t;
|
|
36
|
-
},
|
|
36
|
+
}, K = (a, { location: e, filters: t = {}, debug: s = {} }) => {
|
|
37
37
|
if (t.type && t.type !== a.type || t.key && t.key !== a.key)
|
|
38
38
|
return !1;
|
|
39
39
|
if (s.forcedGuideKey === a.key)
|
|
40
40
|
return !0;
|
|
41
|
-
if (a.steps.every((o) => !!o.message.archived_at))
|
|
41
|
+
if (!a.active || a.steps.every((o) => !!o.message.archived_at))
|
|
42
42
|
return !1;
|
|
43
43
|
const i = e ? A(e) : void 0, n = a.activation_url_rules || [], r = a.activation_url_patterns || [];
|
|
44
44
|
if (i && n.length > 0) {
|
|
@@ -220,17 +220,17 @@ class j {
|
|
|
220
220
|
// Store selector
|
|
221
221
|
//
|
|
222
222
|
selectGuides(e, t = {}) {
|
|
223
|
-
if (Object.keys(e.guides).length === 0)
|
|
223
|
+
if (Object.keys(e.guides).length === 0 && Object.keys(e.previewGuides).length === 0)
|
|
224
224
|
return [];
|
|
225
225
|
this.knock.log(`[Guide] Selecting guides for: ${g(t)}`);
|
|
226
|
-
const s =
|
|
226
|
+
const s = y(e, t);
|
|
227
227
|
return s.size === 0 ? (this.knock.log("[Guide] Selection returned zero result"), []) : [...s.values()];
|
|
228
228
|
}
|
|
229
229
|
selectGuide(e, t = {}) {
|
|
230
|
-
if (Object.keys(e.guides).length === 0)
|
|
230
|
+
if (Object.keys(e.guides).length === 0 && Object.keys(e.previewGuides).length === 0)
|
|
231
231
|
return;
|
|
232
232
|
this.knock.log(`[Guide] Selecting a guide for: ${g(t)}`);
|
|
233
|
-
const s =
|
|
233
|
+
const s = y(e, t);
|
|
234
234
|
if (s.size === 0) {
|
|
235
235
|
this.knock.log("[Guide] Selection returned zero result");
|
|
236
236
|
return;
|
|
@@ -238,7 +238,7 @@ class j {
|
|
|
238
238
|
const [i, n] = [...s][0];
|
|
239
239
|
if (n.bypass_global_group_limit)
|
|
240
240
|
return n;
|
|
241
|
-
const r =
|
|
241
|
+
const r = m(e.guideGroups), o = e.guideGroupDisplayLogs[p];
|
|
242
242
|
if (!(r && r.display_interval && o && w(
|
|
243
243
|
o,
|
|
244
244
|
r.display_interval
|
|
@@ -421,7 +421,7 @@ class j {
|
|
|
421
421
|
formatQueryKey(e) {
|
|
422
422
|
const s = Object.keys(e).sort().map(
|
|
423
423
|
(n) => `${encodeURIComponent(n)}=${encodeURIComponent(e[n])}`
|
|
424
|
-
).join("&"), i =
|
|
424
|
+
).join("&"), i = O(this.knock.userId);
|
|
425
425
|
return s ? `${i}?${s}` : i;
|
|
426
426
|
}
|
|
427
427
|
setStepMessageAttrs(e, t, s) {
|
|
@@ -521,6 +521,6 @@ class j {
|
|
|
521
521
|
export {
|
|
522
522
|
k as DEBUG_QUERY_PARAMS,
|
|
523
523
|
j as KnockGuideClient,
|
|
524
|
-
|
|
524
|
+
O as guidesApiRootPath
|
|
525
525
|
};
|
|
526
526
|
//# sourceMappingURL=client.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","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\nimport {\n DEFAULT_GROUP_KEY,\n SelectionResult,\n byKey,\n checkIfThrottled,\n findDefaultGroup,\n formatFilters,\n mockDefaultGroup,\n newUrl,\n predicateUrlPatterns,\n predicateUrlRules,\n} from \"./helpers\";\nimport {\n Any,\n ConstructorOpts,\n DebugState,\n GetGuidesQueryParams,\n GetGuidesResponse,\n GroupStage,\n GuideAddedEvent,\n GuideData,\n GuideGroupAddedEvent,\n GuideGroupUpdatedEvent,\n GuideLivePreviewUpdatedEvent,\n GuideRemovedEvent,\n GuideSocketEvent,\n GuideStepData,\n GuideUpdatedEvent,\n KnockGuide,\n KnockGuideStep,\n MarkAsArchivedParams,\n MarkAsInteractedParams,\n MarkAsSeenParams,\n MarkGuideAsResponse,\n QueryFilterParams,\n QueryStatus,\n SelectFilterParams,\n StepMessageState,\n StoreState,\n TargetParams,\n} from \"./types\";\n\n// How long to wait until we resolve the guides order and determine the\n// prevailing guide.\nconst DEFAULT_ORDER_RESOLUTION_DURATION = 50; // in milliseconds\n\n// How often we should increment the counter to refresh the store state and\n// trigger subscribed callbacks.\nconst DEFAULT_COUNTER_INCREMENT_INTERVAL = 30 * 1000; // in milliseconds\n\n// Maximum number of retry attempts for channel subscription\nconst SUBSCRIBE_RETRY_LIMIT = 3;\n\n// Debug query param keys\nexport const DEBUG_QUERY_PARAMS = {\n GUIDE_KEY: \"knock_guide_key\",\n PREVIEW_SESSION_ID: \"knock_preview_session_id\",\n};\n\n// Return the global window object if defined, so to safely guard against SSR.\nconst checkForWindow = () => {\n if (typeof window !== \"undefined\") {\n return window;\n }\n};\n\nexport const guidesApiRootPath = (userId: string | undefined | null) =>\n `/v1/users/${userId}/guides`;\n\n// Detect debug params like \"knock_guide_key\" from URL.\nconst detectDebugParams = (): DebugState => {\n const win = checkForWindow();\n if (!win) {\n return { forcedGuideKey: null, previewSessionId: null };\n }\n\n const urlParams = new URLSearchParams(win.location.search);\n const forcedGuideKey = urlParams.get(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n const previewSessionId = urlParams.get(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID);\n\n return { forcedGuideKey, previewSessionId };\n};\n\nconst select = (state: StoreState, filters: SelectFilterParams = {}) => {\n // A map of selected guides as values, with its order index as keys.\n const result = new SelectionResult();\n\n const defaultGroup = findDefaultGroup(state.guideGroups);\n if (!defaultGroup) return result;\n\n const displaySequence = [...defaultGroup.display_sequence];\n const location = state.location;\n\n // If in debug mode, put the forced guide at the beginning of the display sequence.\n if (state.debug.forcedGuideKey) {\n const forcedKeyIndex = displaySequence.indexOf(state.debug.forcedGuideKey);\n if (forcedKeyIndex > -1) {\n displaySequence.splice(forcedKeyIndex, 1);\n }\n displaySequence.unshift(state.debug.forcedGuideKey);\n }\n\n for (const [index, guideKey] of displaySequence.entries()) {\n let guide = state.guides[guideKey];\n\n // Use preview guide if it exists and matches the forced guide key\n if (\n state.debug.forcedGuideKey === guideKey &&\n state.previewGuides[guideKey]\n ) {\n guide = state.previewGuides[guideKey];\n }\n\n if (!guide) continue;\n\n const affirmed = predicate(guide, {\n location,\n filters,\n debug: state.debug,\n });\n\n if (!affirmed) continue;\n\n result.set(index, guide);\n }\n\n result.metadata = { guideGroup: defaultGroup };\n return result;\n};\n\ntype PredicateOpts = {\n location?: string | undefined;\n filters?: SelectFilterParams | undefined;\n debug: DebugState;\n};\n\nconst predicate = (\n guide: KnockGuide,\n { location, filters = {}, debug = {} }: PredicateOpts,\n) => {\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 // Bypass filtering if the debugged guide matches the given filters.\n // This should always run AFTER checking the filters but BEFORE\n // checking archived status and location rules.\n if (debug.forcedGuideKey === guide.key) {\n return true;\n }\n\n if (guide.steps.every((s) => !!s.message.archived_at)) {\n return false;\n }\n\n const url = location ? newUrl(location) : undefined;\n\n const urlRules = guide.activation_url_rules || [];\n const urlPatterns = guide.activation_url_patterns || [];\n\n // A guide can have either activation url rules XOR url patterns, but not both.\n if (url && urlRules.length > 0) {\n const allowed = predicateUrlRules(url, urlRules);\n if (!allowed) return false;\n } else if (url && urlPatterns.length > 0) {\n const allowed = predicateUrlPatterns(url, urlPatterns);\n if (!allowed) return false;\n }\n\n return true;\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 = [\n \"guide.added\",\n \"guide.updated\",\n \"guide.removed\",\n \"guide_group.added\",\n \"guide_group.updated\",\n \"guide.live_preview_updated\",\n ];\n private subscribeRetryCount = 0;\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 // Guides that are competing to render are \"staged\" first without rendering\n // and ranked based on its relative order in the group over a duration of time\n // to resolve and render the prevailing one.\n private stage: GroupStage | undefined;\n\n private counterIntervalId: ReturnType<typeof setInterval> | 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 const win = checkForWindow();\n\n const location = trackLocationFromWindow ? win?.location.href : undefined;\n\n const debug = detectDebugParams();\n\n this.store = new Store<StoreState>({\n guideGroups: [],\n guideGroupDisplayLogs: {},\n guides: {},\n previewGuides: {},\n queries: {},\n location,\n // Increment to update the state store and trigger re-selection.\n counter: 0,\n debug,\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 // Start the counter loop to increment at an interval.\n this.startCounterInterval();\n\n this.knock.log(\"[Guide] Initialized a guide client\");\n }\n\n private incrementCounter() {\n this.knock.log(\"[Guide] Incrementing the counter\");\n this.store.setState((state) => ({ ...state, counter: state.counter + 1 }));\n }\n\n private startCounterInterval() {\n const {\n throttleCheckInterval: delay = DEFAULT_COUNTER_INCREMENT_INTERVAL,\n } = this.options;\n\n this.counterIntervalId = setInterval(() => {\n this.knock.log(\"[Guide] Counter interval tick\");\n if (this.stage && this.stage.status !== \"closed\") return;\n\n this.incrementCounter();\n }, delay);\n }\n\n private clearCounterInterval() {\n if (this.counterIntervalId) {\n clearInterval(this.counterIntervalId);\n this.counterIntervalId = undefined;\n }\n }\n\n cleanup() {\n this.unsubscribe();\n this.removeEventListeners();\n this.clearGroupStage();\n this.clearCounterInterval();\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 const { entries, guide_groups: groups, guide_group_display_logs } = data;\n\n this.store.setState((state) => ({\n ...state,\n guideGroups: groups?.length > 0 ? groups : [mockDefaultGroup(entries)],\n guideGroupDisplayLogs: guide_group_display_logs || {},\n guides: byKey(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 debugState = this.store.state.debug;\n const params = {\n ...this.targetParams,\n user_id: this.knock.userId,\n force_all_guides: debugState.forcedGuideKey ? true : undefined,\n preview_session_id: debugState.previewSessionId || undefined,\n };\n\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 // Reset retry count for new subscription attempt\n this.subscribeRetryCount = 0;\n\n newChannel\n .join()\n .receive(\"ok\", () => {\n this.knock.log(\"[Guide] Successfully joined channel\");\n })\n .receive(\"error\", (resp) => {\n this.knock.log(\n `[Guide] Failed to join channel: ${JSON.stringify(resp)}`,\n );\n this.handleChannelJoinError();\n })\n .receive(\"timeout\", () => {\n this.knock.log(\"[Guide] Channel join timed out\");\n this.handleChannelJoinError();\n });\n }\n\n // Track the joined channel.\n this.socketChannel = newChannel;\n }\n\n private handleChannelJoinError() {\n // Prevent phx channel from retrying forever in case of either network or\n // other errors (e.g. auth error, invalid channel etc)\n if (this.subscribeRetryCount >= SUBSCRIBE_RETRY_LIMIT) {\n this.knock.log(\n `[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`,\n );\n this.unsubscribe();\n return;\n }\n\n this.subscribeRetryCount++;\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.addOrReplaceGuide(payload);\n\n case \"guide.updated\":\n return data.eligible\n ? this.addOrReplaceGuide(payload)\n : this.removeGuide(payload);\n\n case \"guide.removed\":\n return this.removeGuide(payload);\n\n case \"guide_group.added\":\n case \"guide_group.updated\":\n return this.addOrReplaceGuideGroup(payload);\n\n case \"guide.live_preview_updated\":\n return this.updatePreviewGuide(payload);\n\n default:\n return;\n }\n }\n\n setLocation(href: string, additionalParams: Partial<StoreState> = {}) {\n // Make sure to clear out the stage.\n this.clearGroupStage();\n\n this.store.setState((state) => {\n // Clear preview guides if no longer in preview mode\n const previewGuides = additionalParams?.debug?.previewSessionId\n ? state.previewGuides\n : {};\n\n return {\n ...state,\n ...additionalParams,\n previewGuides,\n location: href,\n };\n });\n }\n\n //\n // Store selector\n //\n\n selectGuides<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C>[] {\n if (Object.keys(state.guides).length === 0) {\n return [];\n }\n this.knock.log(`[Guide] Selecting guides for: ${formatFilters(filters)}`);\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection returned zero result\");\n return [];\n }\n\n // Return all selected guides, since we cannot apply the one-at-a-time limit\n // or throttle settings, but rather defer to the caller to decide which ones\n // to render. Note\n return [...result.values()];\n }\n\n selectGuide<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C> | undefined {\n if (Object.keys(state.guides).length === 0) {\n return undefined;\n }\n this.knock.log(`[Guide] Selecting a guide for: ${formatFilters(filters)}`);\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection returned zero result\");\n return undefined;\n }\n\n const [index, guide] = [...result][0]!;\n\n // If a guide ignores the group limit, then return immediately to render\n // always.\n if (guide.bypass_global_group_limit) {\n return guide;\n }\n\n // Check if inside the throttle window (i.e. throttled) and if so stop and\n // return undefined.\n const defaultGroup = findDefaultGroup(state.guideGroups);\n const throttleWindowStartedAt =\n state.guideGroupDisplayLogs[DEFAULT_GROUP_KEY];\n\n if (\n defaultGroup &&\n defaultGroup.display_interval &&\n throttleWindowStartedAt\n ) {\n const throttled = checkIfThrottled(\n throttleWindowStartedAt,\n defaultGroup.display_interval,\n );\n if (throttled) return undefined;\n }\n\n // Starting here to the end of this method represents the core logic of how\n // \"group stage\" works. It provides a mechanism for 1) figuring out which\n // guide components are about to render on a page, 2) determining which\n // among them ranks highest in the configured display sequence, and 3)\n // returning only the prevailing guide to render at a time.\n //\n // Imagine N number of components that use the `useGuide()` hook which\n // calls this `selectGuide()` method, and the logic works like this:\n // * The first time this method is called, we don't have an \"open\" group\n // stage, so we open one (this occurs when a new page/route is rendering).\n // * While it is open, we record which guide was selected and its order\n // index from each call, but we do NOT return any guide to render yet.\n // * When a group stage opens, it schedules a timer to close itself. How\n // long this timer waits is configurable. Note, `setTimeout` with 0\n // delay seems to work well for React apps, where we \"yield\" to React\n // for one render cycle and close the group right after.\n // * When a group stage closes, we evaluate which guides were selected and\n // recorded, then determine the winning guide (i.e. the one with the\n // lowest order index value).\n // * Then increment the internal counter to trigger a store state update,\n // which allows `useGuide()` and `selectGuide()` to re-run. This second\n // round of `selectGuide()` calls, occurring when the group stage is\n // closed, results in returning the prevailing guide.\n // * Whenever a user navigates to a new page, we repeat the same process\n // above.\n // * There's a third status called \"patch,\" which is for handling real-time\n // updates received from the API. It's similar to the \"open\" to \"closed\"\n // flow, except we keep the resolved guide in place while we recalculate.\n // This is done so that we don't cause flickers or CLS.\n if (!this.stage) {\n this.stage = this.openGroupStage(); // Assign here to make tsc happy\n }\n\n switch (this.stage.status) {\n case \"open\": {\n this.knock.log(`[Guide] Addng to the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n return undefined;\n }\n\n case \"patch\": {\n this.knock.log(`[Guide] Patching the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n return this.stage.resolved === guide.key ? guide : undefined;\n }\n\n case \"closed\": {\n return this.stage.resolved === guide.key ? guide : undefined;\n }\n }\n }\n\n private openGroupStage() {\n this.knock.log(\"[Guide] Opening a new group stage\");\n\n const {\n orderResolutionDuration: delay = DEFAULT_ORDER_RESOLUTION_DURATION,\n } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n this.stage = {\n status: \"open\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n // Close the current non-closed stage to resolve the prevailing guide up next\n // for display amongst the ones that have been staged.\n private closePendingGroupStage() {\n if (!this.stage || this.stage.status === \"closed\") return;\n\n this.knock.log(\"[Guide] Closing the current group stage\");\n\n // Should have been cleared already since this method should be called as a\n // callback to a setTimeout, but just to be safe.\n this.ensureClearTimeout();\n\n // If in debug mode, try to resolve the forced guide, otherwise return the first non-undefined guide.\n let resolved = undefined;\n if (this.store.state.debug.forcedGuideKey) {\n resolved = this.stage.ordered.find(\n (x) => x === this.store.state.debug.forcedGuideKey,\n );\n }\n\n if (!resolved) {\n resolved = this.stage.ordered.find((x) => x !== undefined);\n }\n\n this.stage = {\n ...this.stage,\n status: \"closed\",\n resolved,\n timeoutId: null,\n };\n\n return this.stage;\n }\n\n // Set the current closed stage status to \"patch\" to allow re-running\n // selections and re-building a group stage with the latest/updated state,\n // while keeping the currently resolved guide in place so that it stays\n // rendered until we are ready to resolve the updated stage and re-render.\n // Note, must be called ahead of updating the state store.\n private patchClosedGroupStage() {\n if (this.stage?.status !== \"closed\") return;\n\n this.knock.log(\"[Guide] Patching the current group stage\");\n\n const { orderResolutionDuration: delay = 0 } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n // Just to be safe.\n this.ensureClearTimeout();\n\n this.stage = {\n ...this.stage,\n status: \"patch\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n private clearGroupStage() {\n if (!this.stage) return;\n\n this.knock.log(\"[Guide] Clearing the current group stage\");\n\n this.ensureClearTimeout();\n this.stage = undefined;\n }\n\n private ensureClearTimeout() {\n if (this.stage?.timeoutId) {\n clearTimeout(this.stage.timeoutId);\n }\n }\n\n // Test helper that opens and closes the group stage to return the select\n // result immediately.\n private _selectGuide(state: StoreState, filters: SelectFilterParams = {}) {\n this.openGroupStage();\n\n this.selectGuide(state, filters);\n this.closePendingGroupStage();\n\n return this.selectGuide(state, filters);\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 if (step.message.seen_at) return;\n\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 if (step.message.archived_at) return;\n\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 {\n ...params,\n unthrottled: guide.bypass_global_group_limit,\n },\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 = {\n ...remoteGuide,\n // Get the next unarchived step.\n getStep() {\n // If debugging this guide, return the first step regardless of archive status\n if (self.store.state.debug.forcedGuideKey === this.key) {\n return this.steps[0];\n }\n\n return this.steps.find((s) => !s.message.archived_at);\n },\n } as KnockGuide;\n\n localGuide.getStep = localGuide.getStep.bind(localGuide);\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_url_patterns =\n remoteGuide.activation_url_patterns.map((rule) => {\n return {\n ...rule,\n pattern: new URLPattern({ pathname: rule.pathname }),\n };\n });\n\n return localGuide;\n }\n\n private buildQueryParams(filterParams: QueryFilterParams = {}) {\n // Combine the target params with the given filter params.\n const combinedParams: GenericData = {\n ...this.targetParams,\n ...filterParams,\n };\n\n // Append debug params\n const debugState = this.store.state.debug;\n if (debugState.forcedGuideKey) {\n combinedParams.force_all_guides = true;\n }\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 // If we are marking as archived, clear the group stage so we can render\n // the next guide in the group.\n if (attrs.archived_at) {\n this.clearGroupStage();\n }\n\n this.store.setState((state) => {\n const guide = state.guides[guideKey];\n if (!guide) return state;\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 // Mutate in place and maintain the same obj ref.\n guide.steps = steps;\n const guides = { ...state.guides, [guide.key]: guide };\n\n // If the guide is subject to throttled settings and we are marking as\n // archived, then update the display logs to start a new throttle window.\n const guideGroupDisplayLogs =\n attrs.archived_at && !guide.bypass_global_group_limit\n ? {\n ...state.guideGroupDisplayLogs,\n [DEFAULT_GROUP_KEY]: attrs.archived_at,\n }\n : state.guideGroupDisplayLogs;\n\n return { ...state, guides, guideGroupDisplayLogs };\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 addOrReplaceGuide({ data }: GuideAddedEvent | GuideUpdatedEvent) {\n this.patchClosedGroupStage();\n\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const guides = { ...state.guides, [guide.key]: guide };\n\n return { ...state, guides };\n });\n }\n\n private removeGuide({ data }: GuideUpdatedEvent | GuideRemovedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n const { [data.guide.key]: _, ...rest } = state.guides;\n return { ...state, guides: rest };\n });\n }\n\n private addOrReplaceGuideGroup({\n data,\n }: GuideGroupAddedEvent | GuideGroupUpdatedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n // Currently we only support a single default global group, so we can just\n // update the list with the added/updated group.\n const guideGroups = [data.guide_group];\n\n // A guide group event can include lists of unthrottled vs throttled guide\n // keys which we can use to bulk update the guides in the store already.\n const unthrottled = data.guide_group.display_sequence_unthrottled || [];\n const throttled = data.guide_group.display_sequence_throttled || [];\n\n let guides = state.guides;\n\n guides = unthrottled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: true };\n return { ...acc, [key]: guide };\n }, guides);\n\n guides = throttled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: false };\n return { ...acc, [key]: guide };\n }, guides);\n\n return { ...state, guides, guideGroups };\n });\n }\n\n private updatePreviewGuide({ data }: GuideLivePreviewUpdatedEvent) {\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const previewGuides = { ...state.previewGuides, [guide.key]: guide };\n return { ...state, previewGuides };\n });\n }\n\n // Define as an arrow func property to always bind this to the class instance.\n private handleLocationChange = () => {\n const win = checkForWindow();\n if (!win?.location) return;\n\n const href = win.location.href;\n if (this.store.state.location === href) return;\n\n this.knock.log(`[Guide] Handle Location change: ${href}`);\n\n // If entering debug mode, fetch all guides.\n const currentDebugParams = this.store.state.debug;\n const newDebugParams = detectDebugParams();\n this.setLocation(href, { debug: newDebugParams });\n\n // If debug state has changed, refetch guides and resubscribe to the websocket channel\n const debugStateChanged = this.checkDebugStateChanged(\n currentDebugParams,\n newDebugParams,\n );\n\n if (debugStateChanged) {\n this.knock.log(\n `[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel`,\n );\n this.fetch();\n this.subscribe();\n }\n };\n\n // Returns whether debug params have changed. For guide key, we only check\n // presence since the exact value has no impact on fetch/subscribe\n private checkDebugStateChanged(a: DebugState, b: DebugState): boolean {\n return (\n Boolean(a.forcedGuideKey) !== Boolean(b.forcedGuideKey) ||\n a.previewSessionId !== b.previewSessionId\n );\n }\n\n private listenForLocationChangesFromWindow() {\n const win = checkForWindow();\n if (win?.history) {\n // 1. Listen for browser back/forward button clicks.\n win.addEventListener(\"popstate\", this.handleLocationChange);\n\n // 2. Listen for hash changes in case it's used for routing.\n win.addEventListener(\"hashchange\", this.handleLocationChange);\n\n // 3. Monkey-patch history methods to catch programmatic navigation.\n const pushStateFn = win.history.pushState;\n const replaceStateFn = win.history.replaceState;\n\n // Use setTimeout to allow the browser state to potentially settle.\n win.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 win.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 const win = checkForWindow();\n if (!win?.history) return;\n\n win.removeEventListener(\"popstate\", this.handleLocationChange);\n win.removeEventListener(\"hashchange\", this.handleLocationChange);\n\n if (this.pushStateFn) {\n win.history.pushState = this.pushStateFn;\n this.pushStateFn = undefined;\n }\n if (this.replaceStateFn) {\n win.history.replaceState = this.replaceStateFn;\n this.replaceStateFn = undefined;\n }\n }\n}\n"],"names":["DEFAULT_ORDER_RESOLUTION_DURATION","DEFAULT_COUNTER_INCREMENT_INTERVAL","SUBSCRIBE_RETRY_LIMIT","DEBUG_QUERY_PARAMS","checkForWindow","guidesApiRootPath","userId","detectDebugParams","win","urlParams","forcedGuideKey","previewSessionId","select","state","filters","result","SelectionResult","defaultGroup","findDefaultGroup","displaySequence","location","forcedKeyIndex","index","guideKey","guide","predicate","debug","s","url","newUrl","urlRules","urlPatterns","predicateUrlRules","predicateUrlPatterns","KnockGuideClient","knock","channelId","targetParams","options","__publicField","href","currentDebugParams","newDebugParams","trackLocationFromWindow","Store","maybeSocket","delay","opts","queryParams","queryKey","maybeQueryStatus","queryStatus","data","entries","groups","guide_group_display_logs","mockDefaultGroup","byKey","g","e","debugState","params","newChannel","eventType","payload","resp","event","additionalParams","previewGuides","_a","formatFilters","throttleWindowStartedAt","DEFAULT_GROUP_KEY","checkIfThrottled","timeoutId","resolved","x","step","updatedStep","metadata","ts","remoteGuide","self","localGuide","message","rest","localStep","rule","URLPattern","filterParams","combinedParams","_k","v","queryStr","key","basePath","stepRef","attrs","steps","guides","guideGroupDisplayLogs","_","guideGroups","unthrottled","throttled","acc","a","b","pushStateFn","replaceStateFn","target","history","args"],"mappings":";;;;;;AAmDA,MAAMA,IAAoC,IAIpCC,IAAqC,KAAK,KAG1CC,IAAwB,GAGjBC,IAAqB;AAAA,EAChC,WAAW;AAAA,EACX,oBAAoB;AACtB,GAGMC,IAAiB,MAAM;AACvB,MAAA,OAAO,SAAW;AACb,WAAA;AAEX,GAEaC,IAAoB,CAACC,MAChC,aAAaA,CAAM,WAGfC,IAAoB,MAAkB;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AGD,KAAK,cAAcJ,GACnB,KAAK,iBAAiBC;AAAA,IAAA;AAEtB,WAAK,MAAM;AAAA,QACT;AAAA,MACF;AAAA,EACF;AAAA,EAGM,uBAAuB;AAC7B,UAAMrG,IAAMJ,EAAe;AACvB,IAACI,KAAA,QAAAA,EAAK,YAENA,EAAA,oBAAoB,YAAY,KAAK,oBAAoB,GACzDA,EAAA,oBAAoB,cAAc,KAAK,oBAAoB,GAE3D,KAAK,gBACHA,EAAA,QAAQ,YAAY,KAAK,aAC7B,KAAK,cAAc,SAEjB,KAAK,mBACHA,EAAA,QAAQ,eAAe,KAAK,gBAChC,KAAK,iBAAiB;AAAA,EACxB;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"client.mjs","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\nimport {\n DEFAULT_GROUP_KEY,\n SelectionResult,\n byKey,\n checkIfThrottled,\n findDefaultGroup,\n formatFilters,\n mockDefaultGroup,\n newUrl,\n predicateUrlPatterns,\n predicateUrlRules,\n} from \"./helpers\";\nimport {\n Any,\n ConstructorOpts,\n DebugState,\n GetGuidesQueryParams,\n GetGuidesResponse,\n GroupStage,\n GuideAddedEvent,\n GuideData,\n GuideGroupAddedEvent,\n GuideGroupUpdatedEvent,\n GuideLivePreviewUpdatedEvent,\n GuideRemovedEvent,\n GuideSocketEvent,\n GuideStepData,\n GuideUpdatedEvent,\n KnockGuide,\n KnockGuideStep,\n MarkAsArchivedParams,\n MarkAsInteractedParams,\n MarkAsSeenParams,\n MarkGuideAsResponse,\n QueryFilterParams,\n QueryStatus,\n SelectFilterParams,\n StepMessageState,\n StoreState,\n TargetParams,\n} from \"./types\";\n\n// How long to wait until we resolve the guides order and determine the\n// prevailing guide.\nconst DEFAULT_ORDER_RESOLUTION_DURATION = 50; // in milliseconds\n\n// How often we should increment the counter to refresh the store state and\n// trigger subscribed callbacks.\nconst DEFAULT_COUNTER_INCREMENT_INTERVAL = 30 * 1000; // in milliseconds\n\n// Maximum number of retry attempts for channel subscription\nconst SUBSCRIBE_RETRY_LIMIT = 3;\n\n// Debug query param keys\nexport const DEBUG_QUERY_PARAMS = {\n GUIDE_KEY: \"knock_guide_key\",\n PREVIEW_SESSION_ID: \"knock_preview_session_id\",\n};\n\n// Return the global window object if defined, so to safely guard against SSR.\nconst checkForWindow = () => {\n if (typeof window !== \"undefined\") {\n return window;\n }\n};\n\nexport const guidesApiRootPath = (userId: string | undefined | null) =>\n `/v1/users/${userId}/guides`;\n\n// Detect debug params like \"knock_guide_key\" from URL.\nconst detectDebugParams = (): DebugState => {\n const win = checkForWindow();\n if (!win) {\n return { forcedGuideKey: null, previewSessionId: null };\n }\n\n const urlParams = new URLSearchParams(win.location.search);\n const forcedGuideKey = urlParams.get(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n const previewSessionId = urlParams.get(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID);\n\n return { forcedGuideKey, previewSessionId };\n};\n\nconst select = (state: StoreState, filters: SelectFilterParams = {}) => {\n // A map of selected guides as values, with its order index as keys.\n const result = new SelectionResult();\n\n const defaultGroup = findDefaultGroup(state.guideGroups);\n if (!defaultGroup) return result;\n\n const displaySequence = [...defaultGroup.display_sequence];\n const location = state.location;\n\n // If in debug mode, put the forced guide at the beginning of the display sequence.\n if (state.debug.forcedGuideKey) {\n const forcedKeyIndex = displaySequence.indexOf(state.debug.forcedGuideKey);\n if (forcedKeyIndex > -1) {\n displaySequence.splice(forcedKeyIndex, 1);\n }\n displaySequence.unshift(state.debug.forcedGuideKey);\n }\n\n for (const [index, guideKey] of displaySequence.entries()) {\n let guide = state.guides[guideKey];\n\n // Use preview guide if it exists and matches the forced guide key\n if (\n state.debug.forcedGuideKey === guideKey &&\n state.previewGuides[guideKey]\n ) {\n guide = state.previewGuides[guideKey];\n }\n\n if (!guide) continue;\n\n const affirmed = predicate(guide, {\n location,\n filters,\n debug: state.debug,\n });\n\n if (!affirmed) continue;\n\n result.set(index, guide);\n }\n\n result.metadata = { guideGroup: defaultGroup };\n return result;\n};\n\ntype PredicateOpts = {\n location?: string | undefined;\n filters?: SelectFilterParams | undefined;\n debug: DebugState;\n};\n\nconst predicate = (\n guide: KnockGuide,\n { location, filters = {}, debug = {} }: PredicateOpts,\n) => {\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 // Bypass filtering if the debugged guide matches the given filters.\n // This should always run AFTER checking the filters but BEFORE\n // checking archived status and location rules.\n if (debug.forcedGuideKey === guide.key) {\n return true;\n }\n\n if (!guide.active) {\n return false;\n }\n\n if (guide.steps.every((s) => !!s.message.archived_at)) {\n return false;\n }\n\n const url = location ? newUrl(location) : undefined;\n\n const urlRules = guide.activation_url_rules || [];\n const urlPatterns = guide.activation_url_patterns || [];\n\n // A guide can have either activation url rules XOR url patterns, but not both.\n if (url && urlRules.length > 0) {\n const allowed = predicateUrlRules(url, urlRules);\n if (!allowed) return false;\n } else if (url && urlPatterns.length > 0) {\n const allowed = predicateUrlPatterns(url, urlPatterns);\n if (!allowed) return false;\n }\n\n return true;\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 = [\n \"guide.added\",\n \"guide.updated\",\n \"guide.removed\",\n \"guide_group.added\",\n \"guide_group.updated\",\n \"guide.live_preview_updated\",\n ];\n private subscribeRetryCount = 0;\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 // Guides that are competing to render are \"staged\" first without rendering\n // and ranked based on its relative order in the group over a duration of time\n // to resolve and render the prevailing one.\n private stage: GroupStage | undefined;\n\n private counterIntervalId: ReturnType<typeof setInterval> | 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 const win = checkForWindow();\n\n const location = trackLocationFromWindow ? win?.location.href : undefined;\n\n const debug = detectDebugParams();\n\n this.store = new Store<StoreState>({\n guideGroups: [],\n guideGroupDisplayLogs: {},\n guides: {},\n previewGuides: {},\n queries: {},\n location,\n // Increment to update the state store and trigger re-selection.\n counter: 0,\n debug,\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 // Start the counter loop to increment at an interval.\n this.startCounterInterval();\n\n this.knock.log(\"[Guide] Initialized a guide client\");\n }\n\n private incrementCounter() {\n this.knock.log(\"[Guide] Incrementing the counter\");\n this.store.setState((state) => ({ ...state, counter: state.counter + 1 }));\n }\n\n private startCounterInterval() {\n const {\n throttleCheckInterval: delay = DEFAULT_COUNTER_INCREMENT_INTERVAL,\n } = this.options;\n\n this.counterIntervalId = setInterval(() => {\n this.knock.log(\"[Guide] Counter interval tick\");\n if (this.stage && this.stage.status !== \"closed\") return;\n\n this.incrementCounter();\n }, delay);\n }\n\n private clearCounterInterval() {\n if (this.counterIntervalId) {\n clearInterval(this.counterIntervalId);\n this.counterIntervalId = undefined;\n }\n }\n\n cleanup() {\n this.unsubscribe();\n this.removeEventListeners();\n this.clearGroupStage();\n this.clearCounterInterval();\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 const { entries, guide_groups: groups, guide_group_display_logs } = data;\n\n this.store.setState((state) => ({\n ...state,\n guideGroups: groups?.length > 0 ? groups : [mockDefaultGroup(entries)],\n guideGroupDisplayLogs: guide_group_display_logs || {},\n guides: byKey(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 debugState = this.store.state.debug;\n const params = {\n ...this.targetParams,\n user_id: this.knock.userId,\n force_all_guides: debugState.forcedGuideKey ? true : undefined,\n preview_session_id: debugState.previewSessionId || undefined,\n };\n\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 // Reset retry count for new subscription attempt\n this.subscribeRetryCount = 0;\n\n newChannel\n .join()\n .receive(\"ok\", () => {\n this.knock.log(\"[Guide] Successfully joined channel\");\n })\n .receive(\"error\", (resp) => {\n this.knock.log(\n `[Guide] Failed to join channel: ${JSON.stringify(resp)}`,\n );\n this.handleChannelJoinError();\n })\n .receive(\"timeout\", () => {\n this.knock.log(\"[Guide] Channel join timed out\");\n this.handleChannelJoinError();\n });\n }\n\n // Track the joined channel.\n this.socketChannel = newChannel;\n }\n\n private handleChannelJoinError() {\n // Prevent phx channel from retrying forever in case of either network or\n // other errors (e.g. auth error, invalid channel etc)\n if (this.subscribeRetryCount >= SUBSCRIBE_RETRY_LIMIT) {\n this.knock.log(\n `[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`,\n );\n this.unsubscribe();\n return;\n }\n\n this.subscribeRetryCount++;\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.addOrReplaceGuide(payload);\n\n case \"guide.updated\":\n return data.eligible\n ? this.addOrReplaceGuide(payload)\n : this.removeGuide(payload);\n\n case \"guide.removed\":\n return this.removeGuide(payload);\n\n case \"guide_group.added\":\n case \"guide_group.updated\":\n return this.addOrReplaceGuideGroup(payload);\n\n case \"guide.live_preview_updated\":\n return this.updatePreviewGuide(payload);\n\n default:\n return;\n }\n }\n\n setLocation(href: string, additionalParams: Partial<StoreState> = {}) {\n // Make sure to clear out the stage.\n this.clearGroupStage();\n\n this.store.setState((state) => {\n // Clear preview guides if no longer in preview mode\n const previewGuides = additionalParams?.debug?.previewSessionId\n ? state.previewGuides\n : {};\n\n return {\n ...state,\n ...additionalParams,\n previewGuides,\n location: href,\n };\n });\n }\n\n //\n // Store selector\n //\n\n selectGuides<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C>[] {\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n return [];\n }\n this.knock.log(`[Guide] Selecting guides for: ${formatFilters(filters)}`);\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection returned zero result\");\n return [];\n }\n\n // Return all selected guides, since we cannot apply the one-at-a-time limit\n // or throttle settings, but rather defer to the caller to decide which ones\n // to render. Note\n return [...result.values()];\n }\n\n selectGuide<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C> | undefined {\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n return undefined;\n }\n this.knock.log(`[Guide] Selecting a guide for: ${formatFilters(filters)}`);\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection returned zero result\");\n return undefined;\n }\n\n const [index, guide] = [...result][0]!;\n\n // If a guide ignores the group limit, then return immediately to render\n // always.\n if (guide.bypass_global_group_limit) {\n return guide;\n }\n\n // Check if inside the throttle window (i.e. throttled) and if so stop and\n // return undefined.\n const defaultGroup = findDefaultGroup(state.guideGroups);\n const throttleWindowStartedAt =\n state.guideGroupDisplayLogs[DEFAULT_GROUP_KEY];\n\n if (\n defaultGroup &&\n defaultGroup.display_interval &&\n throttleWindowStartedAt\n ) {\n const throttled = checkIfThrottled(\n throttleWindowStartedAt,\n defaultGroup.display_interval,\n );\n if (throttled) return undefined;\n }\n\n // Starting here to the end of this method represents the core logic of how\n // \"group stage\" works. It provides a mechanism for 1) figuring out which\n // guide components are about to render on a page, 2) determining which\n // among them ranks highest in the configured display sequence, and 3)\n // returning only the prevailing guide to render at a time.\n //\n // Imagine N number of components that use the `useGuide()` hook which\n // calls this `selectGuide()` method, and the logic works like this:\n // * The first time this method is called, we don't have an \"open\" group\n // stage, so we open one (this occurs when a new page/route is rendering).\n // * While it is open, we record which guide was selected and its order\n // index from each call, but we do NOT return any guide to render yet.\n // * When a group stage opens, it schedules a timer to close itself. How\n // long this timer waits is configurable. Note, `setTimeout` with 0\n // delay seems to work well for React apps, where we \"yield\" to React\n // for one render cycle and close the group right after.\n // * When a group stage closes, we evaluate which guides were selected and\n // recorded, then determine the winning guide (i.e. the one with the\n // lowest order index value).\n // * Then increment the internal counter to trigger a store state update,\n // which allows `useGuide()` and `selectGuide()` to re-run. This second\n // round of `selectGuide()` calls, occurring when the group stage is\n // closed, results in returning the prevailing guide.\n // * Whenever a user navigates to a new page, we repeat the same process\n // above.\n // * There's a third status called \"patch,\" which is for handling real-time\n // updates received from the API. It's similar to the \"open\" to \"closed\"\n // flow, except we keep the resolved guide in place while we recalculate.\n // This is done so that we don't cause flickers or CLS.\n if (!this.stage) {\n this.stage = this.openGroupStage(); // Assign here to make tsc happy\n }\n\n switch (this.stage.status) {\n case \"open\": {\n this.knock.log(`[Guide] Addng to the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n return undefined;\n }\n\n case \"patch\": {\n this.knock.log(`[Guide] Patching the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n return this.stage.resolved === guide.key ? guide : undefined;\n }\n\n case \"closed\": {\n return this.stage.resolved === guide.key ? guide : undefined;\n }\n }\n }\n\n private openGroupStage() {\n this.knock.log(\"[Guide] Opening a new group stage\");\n\n const {\n orderResolutionDuration: delay = DEFAULT_ORDER_RESOLUTION_DURATION,\n } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n this.stage = {\n status: \"open\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n // Close the current non-closed stage to resolve the prevailing guide up next\n // for display amongst the ones that have been staged.\n private closePendingGroupStage() {\n if (!this.stage || this.stage.status === \"closed\") return;\n\n this.knock.log(\"[Guide] Closing the current group stage\");\n\n // Should have been cleared already since this method should be called as a\n // callback to a setTimeout, but just to be safe.\n this.ensureClearTimeout();\n\n // If in debug mode, try to resolve the forced guide, otherwise return the first non-undefined guide.\n let resolved = undefined;\n if (this.store.state.debug.forcedGuideKey) {\n resolved = this.stage.ordered.find(\n (x) => x === this.store.state.debug.forcedGuideKey,\n );\n }\n\n if (!resolved) {\n resolved = this.stage.ordered.find((x) => x !== undefined);\n }\n\n this.stage = {\n ...this.stage,\n status: \"closed\",\n resolved,\n timeoutId: null,\n };\n\n return this.stage;\n }\n\n // Set the current closed stage status to \"patch\" to allow re-running\n // selections and re-building a group stage with the latest/updated state,\n // while keeping the currently resolved guide in place so that it stays\n // rendered until we are ready to resolve the updated stage and re-render.\n // Note, must be called ahead of updating the state store.\n private patchClosedGroupStage() {\n if (this.stage?.status !== \"closed\") return;\n\n this.knock.log(\"[Guide] Patching the current group stage\");\n\n const { orderResolutionDuration: delay = 0 } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n // Just to be safe.\n this.ensureClearTimeout();\n\n this.stage = {\n ...this.stage,\n status: \"patch\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n private clearGroupStage() {\n if (!this.stage) return;\n\n this.knock.log(\"[Guide] Clearing the current group stage\");\n\n this.ensureClearTimeout();\n this.stage = undefined;\n }\n\n private ensureClearTimeout() {\n if (this.stage?.timeoutId) {\n clearTimeout(this.stage.timeoutId);\n }\n }\n\n // Test helper that opens and closes the group stage to return the select\n // result immediately.\n private _selectGuide(state: StoreState, filters: SelectFilterParams = {}) {\n this.openGroupStage();\n\n this.selectGuide(state, filters);\n this.closePendingGroupStage();\n\n return this.selectGuide(state, filters);\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 if (step.message.seen_at) return;\n\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 if (step.message.archived_at) return;\n\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 {\n ...params,\n unthrottled: guide.bypass_global_group_limit,\n },\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 = {\n ...remoteGuide,\n // Get the next unarchived step.\n getStep() {\n // If debugging this guide, return the first step regardless of archive status\n if (self.store.state.debug.forcedGuideKey === this.key) {\n return this.steps[0];\n }\n\n return this.steps.find((s) => !s.message.archived_at);\n },\n } as KnockGuide;\n\n localGuide.getStep = localGuide.getStep.bind(localGuide);\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_url_patterns =\n remoteGuide.activation_url_patterns.map((rule) => {\n return {\n ...rule,\n pattern: new URLPattern({ pathname: rule.pathname }),\n };\n });\n\n return localGuide;\n }\n\n private buildQueryParams(filterParams: QueryFilterParams = {}) {\n // Combine the target params with the given filter params.\n const combinedParams: GenericData = {\n ...this.targetParams,\n ...filterParams,\n };\n\n // Append debug params\n const debugState = this.store.state.debug;\n if (debugState.forcedGuideKey) {\n combinedParams.force_all_guides = true;\n }\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 // If we are marking as archived, clear the group stage so we can render\n // the next guide in the group.\n if (attrs.archived_at) {\n this.clearGroupStage();\n }\n\n this.store.setState((state) => {\n const guide = state.guides[guideKey];\n if (!guide) return state;\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 // Mutate in place and maintain the same obj ref.\n guide.steps = steps;\n const guides = { ...state.guides, [guide.key]: guide };\n\n // If the guide is subject to throttled settings and we are marking as\n // archived, then update the display logs to start a new throttle window.\n const guideGroupDisplayLogs =\n attrs.archived_at && !guide.bypass_global_group_limit\n ? {\n ...state.guideGroupDisplayLogs,\n [DEFAULT_GROUP_KEY]: attrs.archived_at,\n }\n : state.guideGroupDisplayLogs;\n\n return { ...state, guides, guideGroupDisplayLogs };\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 addOrReplaceGuide({ data }: GuideAddedEvent | GuideUpdatedEvent) {\n this.patchClosedGroupStage();\n\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const guides = { ...state.guides, [guide.key]: guide };\n\n return { ...state, guides };\n });\n }\n\n private removeGuide({ data }: GuideUpdatedEvent | GuideRemovedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n const { [data.guide.key]: _, ...rest } = state.guides;\n return { ...state, guides: rest };\n });\n }\n\n private addOrReplaceGuideGroup({\n data,\n }: GuideGroupAddedEvent | GuideGroupUpdatedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n // Currently we only support a single default global group, so we can just\n // update the list with the added/updated group.\n const guideGroups = [data.guide_group];\n\n // A guide group event can include lists of unthrottled vs throttled guide\n // keys which we can use to bulk update the guides in the store already.\n const unthrottled = data.guide_group.display_sequence_unthrottled || [];\n const throttled = data.guide_group.display_sequence_throttled || [];\n\n let guides = state.guides;\n\n guides = unthrottled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: true };\n return { ...acc, [key]: guide };\n }, guides);\n\n guides = throttled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: false };\n return { ...acc, [key]: guide };\n }, guides);\n\n return { ...state, guides, guideGroups };\n });\n }\n\n private updatePreviewGuide({ data }: GuideLivePreviewUpdatedEvent) {\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const previewGuides = { ...state.previewGuides, [guide.key]: guide };\n return { ...state, previewGuides };\n });\n }\n\n // Define as an arrow func property to always bind this to the class instance.\n private handleLocationChange = () => {\n const win = checkForWindow();\n if (!win?.location) return;\n\n const href = win.location.href;\n if (this.store.state.location === href) return;\n\n this.knock.log(`[Guide] Handle Location change: ${href}`);\n\n // If entering debug mode, fetch all guides.\n const currentDebugParams = this.store.state.debug;\n const newDebugParams = detectDebugParams();\n this.setLocation(href, { debug: newDebugParams });\n\n // If debug state has changed, refetch guides and resubscribe to the websocket channel\n const debugStateChanged = this.checkDebugStateChanged(\n currentDebugParams,\n newDebugParams,\n );\n\n if (debugStateChanged) {\n this.knock.log(\n `[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel`,\n );\n this.fetch();\n this.subscribe();\n }\n };\n\n // Returns whether debug params have changed. For guide key, we only check\n // presence since the exact value has no impact on fetch/subscribe\n private checkDebugStateChanged(a: DebugState, b: DebugState): boolean {\n return (\n Boolean(a.forcedGuideKey) !== Boolean(b.forcedGuideKey) ||\n a.previewSessionId !== b.previewSessionId\n );\n }\n\n private listenForLocationChangesFromWindow() {\n const win = checkForWindow();\n if (win?.history) {\n // 1. Listen for browser back/forward button clicks.\n win.addEventListener(\"popstate\", this.handleLocationChange);\n\n // 2. Listen for hash changes in case it's used for routing.\n win.addEventListener(\"hashchange\", this.handleLocationChange);\n\n // 3. Monkey-patch history methods to catch programmatic navigation.\n const pushStateFn = win.history.pushState;\n const replaceStateFn = win.history.replaceState;\n\n // Use setTimeout to allow the browser state to potentially settle.\n win.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 win.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 const win = checkForWindow();\n if (!win?.history) return;\n\n win.removeEventListener(\"popstate\", this.handleLocationChange);\n win.removeEventListener(\"hashchange\", this.handleLocationChange);\n\n if (this.pushStateFn) {\n win.history.pushState = this.pushStateFn;\n this.pushStateFn = undefined;\n }\n if (this.replaceStateFn) {\n win.history.replaceState = this.replaceStateFn;\n this.replaceStateFn = undefined;\n }\n }\n}\n"],"names":["DEFAULT_ORDER_RESOLUTION_DURATION","DEFAULT_COUNTER_INCREMENT_INTERVAL","SUBSCRIBE_RETRY_LIMIT","DEBUG_QUERY_PARAMS","checkForWindow","guidesApiRootPath","userId","detectDebugParams","win","urlParams","forcedGuideKey","previewSessionId","select","state","filters","result","SelectionResult","defaultGroup","findDefaultGroup","displaySequence","location","forcedKeyIndex","index","guideKey","guide","predicate","debug","s","url","newUrl","urlRules","urlPatterns","predicateUrlRules","predicateUrlPatterns","KnockGuideClient","knock","channelId","targetParams","options","__publicField","href","currentDebugParams","newDebugParams","trackLocationFromWindow","Store","maybeSocket","delay","opts","queryParams","queryKey","maybeQueryStatus","queryStatus","data","entries","groups","guide_group_display_logs","mockDefaultGroup","byKey","g","e","debugState","params","newChannel","eventType","payload","resp","event","additionalParams","previewGuides","_a","formatFilters","throttleWindowStartedAt","DEFAULT_GROUP_KEY","checkIfThrottled","timeoutId","resolved","x","step","updatedStep","metadata","ts","remoteGuide","self","localGuide","message","rest","localStep","rule","URLPattern","filterParams","combinedParams","_k","v","queryStr","key","basePath","stepRef","attrs","steps","guides","guideGroupDisplayLogs","_","guideGroups","unthrottled","throttled","acc","a","b","pushStateFn","replaceStateFn","target","history","args"],"mappings":";;;;;;AAmDA,MAAMA,IAAoC,IAIpCC,IAAqC,KAAK,KAG1CC,IAAwB,GAGjBC,IAAqB;AAAA,EAChC,WAAW;AAAA,EACX,oBAAoB;AACtB,GAGMC,IAAiB,MAAM;AACvB,MAAA,OAAO,SAAW;AACb,WAAA;AAEX,GAEaC,IAAoB,CAACC,MAChC,aAAaA,CAAM,WAGfC,IAAoB,MAAkB;AAC1C,QAAMC,IAAMJ,EAAe;AAC3B,MAAI,CAACI;AACH,WAAO,EAAE,gBAAgB,MAAM,kBAAkB,KAAK;AAGxD,QAAMC,IAAY,IAAI,gBAAgBD,EAAI,SAAS,MAAM,GACnDE,IAAiBD,EAAU,IAAIN,EAAmB,SAAS,GAC3DQ,IAAmBF,EAAU,IAAIN,EAAmB,kBAAkB;AAErE,SAAA,EAAE,gBAAAO,GAAgB,kBAAAC,EAAiB;AAC5C,GAEMC,IAAS,CAACC,GAAmBC,IAA8B,OAAO;AAEhE,QAAAC,IAAS,IAAIC,EAAgB,GAE7BC,IAAeC,EAAiBL,EAAM,WAAW;AACnD,MAAA,CAACI,EAAqB,QAAAF;AAE1B,QAAMI,IAAkB,CAAC,GAAGF,EAAa,gBAAgB,GACnDG,IAAWP,EAAM;AAGnB,MAAAA,EAAM,MAAM,gBAAgB;AAC9B,UAAMQ,IAAiBF,EAAgB,QAAQN,EAAM,MAAM,cAAc;AACzE,IAAIQ,IAAiB,M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|
|
3
|
-
var
|
|
4
|
-
import { jwtDecode as
|
|
2
|
+
var f = (s, i, e) => i in s ? r(s, i, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[i] = e;
|
|
3
|
+
var t = (s, i, e) => f(s, typeof i != "symbol" ? i + "" : i, e);
|
|
4
|
+
import { jwtDecode as u } from "jwt-decode";
|
|
5
5
|
import k from "./api.mjs";
|
|
6
6
|
import m from "./clients/feed/index.mjs";
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import
|
|
10
|
-
import
|
|
7
|
+
import d from "./clients/messages/index.mjs";
|
|
8
|
+
import g from "./clients/ms-teams/index.mjs";
|
|
9
|
+
import p from "./clients/objects/index.mjs";
|
|
10
|
+
import T from "./clients/preferences/index.mjs";
|
|
11
11
|
import w from "./clients/slack/index.mjs";
|
|
12
12
|
import C from "./clients/users/index.mjs";
|
|
13
13
|
const y = "https://api.knock.app";
|
|
14
|
-
class
|
|
15
|
-
constructor(
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
if (this.apiKey =
|
|
14
|
+
class D {
|
|
15
|
+
constructor(i, e = {}) {
|
|
16
|
+
t(this, "host");
|
|
17
|
+
t(this, "apiClient", null);
|
|
18
|
+
t(this, "userId");
|
|
19
|
+
t(this, "userToken");
|
|
20
|
+
t(this, "logLevel");
|
|
21
|
+
t(this, "tokenExpirationTimer", null);
|
|
22
|
+
t(this, "feeds", new m(this));
|
|
23
|
+
t(this, "objects", new p(this));
|
|
24
|
+
t(this, "preferences", new T(this));
|
|
25
|
+
t(this, "slack", new w(this));
|
|
26
|
+
t(this, "msTeams", new g(this));
|
|
27
|
+
t(this, "user", new C(this));
|
|
28
|
+
t(this, "messages", new d(this));
|
|
29
|
+
if (this.apiKey = i, this.host = e.host || y, this.logLevel = e.logLevel, this.log("Initialized Knock instance"), this.apiKey && this.apiKey.startsWith("sk_"))
|
|
30
30
|
throw new Error(
|
|
31
31
|
"[Knock] You are using your secret API key on the client. Please use the public key."
|
|
32
32
|
);
|
|
@@ -34,15 +34,20 @@ class S {
|
|
|
34
34
|
client() {
|
|
35
35
|
return this.apiClient || (this.apiClient = this.createApiClient()), this.apiClient;
|
|
36
36
|
}
|
|
37
|
-
authenticate(
|
|
37
|
+
authenticate(i, e, n) {
|
|
38
38
|
let o = !1;
|
|
39
|
-
const
|
|
40
|
-
if (
|
|
39
|
+
const l = this.apiClient, a = this.getUserId(i), c = (n == null ? void 0 : n.identificationStrategy) || "inline";
|
|
40
|
+
if (l && (this.userId !== a || this.userToken !== e) && (this.log("userId or userToken changed; reinitializing connections"), this.feeds.teardownInstances(), this.teardown(), o = !0), this.userId = a, this.userToken = e, this.log(`Authenticated with userId ${a}`), this.userToken && (n == null ? void 0 : n.onUserTokenExpiring) instanceof Function && this.maybeScheduleUserTokenExpiration(
|
|
41
41
|
n.onUserTokenExpiring,
|
|
42
42
|
n.timeBeforeExpirationInMs
|
|
43
|
-
), o && (this.apiClient = this.createApiClient(), this.feeds.reinitializeInstances(), this.log("Reinitialized real-time connections")),
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
), o && (this.apiClient = this.createApiClient(), this.feeds.reinitializeInstances(), this.log("Reinitialized real-time connections")), c === "skip") {
|
|
44
|
+
this.log("Skipping inline user identification");
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (c === "inline" && typeof i == "object" && (i != null && i.id)) {
|
|
48
|
+
this.log(`Identifying user ${i.id} inline`);
|
|
49
|
+
const { id: A, ...h } = i;
|
|
50
|
+
this.user.identify(h);
|
|
46
51
|
}
|
|
47
52
|
}
|
|
48
53
|
failIfNotAuthenticated() {
|
|
@@ -53,16 +58,16 @@ class S {
|
|
|
53
58
|
Returns whether or this Knock instance is authenticated. Passing `true` will check the presence
|
|
54
59
|
of the userToken as well.
|
|
55
60
|
*/
|
|
56
|
-
isAuthenticated(
|
|
57
|
-
return
|
|
61
|
+
isAuthenticated(i = !1) {
|
|
62
|
+
return i ? !!(this.userId && this.userToken) : !!this.userId;
|
|
58
63
|
}
|
|
59
64
|
// Used to teardown any connected instances
|
|
60
65
|
teardown() {
|
|
61
|
-
var
|
|
62
|
-
this.tokenExpirationTimer && clearTimeout(this.tokenExpirationTimer), (
|
|
66
|
+
var i;
|
|
67
|
+
this.tokenExpirationTimer && clearTimeout(this.tokenExpirationTimer), (i = this.apiClient) != null && i.socket && this.apiClient.socket.isConnected() && this.apiClient.socket.disconnect();
|
|
63
68
|
}
|
|
64
|
-
log(
|
|
65
|
-
(this.logLevel === "debug" ||
|
|
69
|
+
log(i, e = !1) {
|
|
70
|
+
(this.logLevel === "debug" || e) && console.log(`[Knock] ${i}`);
|
|
66
71
|
}
|
|
67
72
|
/**
|
|
68
73
|
* Initiates an API client
|
|
@@ -74,16 +79,16 @@ class S {
|
|
|
74
79
|
userToken: this.userToken
|
|
75
80
|
});
|
|
76
81
|
}
|
|
77
|
-
async maybeScheduleUserTokenExpiration(
|
|
82
|
+
async maybeScheduleUserTokenExpiration(i, e = 3e4) {
|
|
78
83
|
if (!this.userToken) return;
|
|
79
|
-
const n =
|
|
80
|
-
if (o && o >
|
|
81
|
-
const a = o -
|
|
84
|
+
const n = u(this.userToken), o = (n.exp ?? 0) * 1e3, l = Date.now();
|
|
85
|
+
if (o && o > l) {
|
|
86
|
+
const a = o - e - l;
|
|
82
87
|
this.tokenExpirationTimer = setTimeout(async () => {
|
|
83
|
-
const
|
|
84
|
-
typeof
|
|
85
|
-
onUserTokenExpiring:
|
|
86
|
-
timeBeforeExpirationInMs:
|
|
88
|
+
const c = await i(this.userToken, n);
|
|
89
|
+
typeof c == "string" && this.authenticate(this.userId, c, {
|
|
90
|
+
onUserTokenExpiring: i,
|
|
91
|
+
timeBeforeExpirationInMs: e
|
|
87
92
|
});
|
|
88
93
|
}, a);
|
|
89
94
|
}
|
|
@@ -94,15 +99,15 @@ class S {
|
|
|
94
99
|
* @returns The user id
|
|
95
100
|
* @throws {Error} If the user object does not contain an `id` property
|
|
96
101
|
*/
|
|
97
|
-
getUserId(
|
|
98
|
-
if (typeof
|
|
99
|
-
return
|
|
100
|
-
if (
|
|
101
|
-
return
|
|
102
|
+
getUserId(i) {
|
|
103
|
+
if (typeof i == "string" || !i)
|
|
104
|
+
return i;
|
|
105
|
+
if (i != null && i.id)
|
|
106
|
+
return i.id;
|
|
102
107
|
throw new Error("`user` object must contain an `id` property");
|
|
103
108
|
}
|
|
104
109
|
}
|
|
105
110
|
export {
|
|
106
|
-
|
|
111
|
+
D as default
|
|
107
112
|
};
|
|
108
113
|
//# sourceMappingURL=knock.mjs.map
|
package/dist/esm/knock.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knock.mjs","sources":["../../src/knock.ts"],"sourcesContent":["import { jwtDecode } from \"jwt-decode\";\n\nimport ApiClient from \"./api\";\nimport FeedClient from \"./clients/feed\";\nimport MessageClient from \"./clients/messages\";\nimport MsTeamsClient from \"./clients/ms-teams\";\nimport ObjectClient from \"./clients/objects\";\nimport Preferences from \"./clients/preferences\";\nimport SlackClient from \"./clients/slack\";\nimport UserClient from \"./clients/users\";\nimport {\n AuthenticateOptions,\n KnockOptions,\n LogLevel,\n UserId,\n UserIdOrUserWithProperties,\n UserTokenExpiringCallback,\n} from \"./interfaces\";\n\nconst DEFAULT_HOST = \"https://api.knock.app\";\n\nclass Knock {\n public host: string;\n private apiClient: ApiClient | null = null;\n public userId: string | undefined | null;\n public userToken?: string;\n public logLevel?: LogLevel;\n private tokenExpirationTimer: ReturnType<typeof setTimeout> | null = null;\n readonly feeds = new FeedClient(this);\n readonly objects = new ObjectClient(this);\n readonly preferences = new Preferences(this);\n readonly slack = new SlackClient(this);\n readonly msTeams = new MsTeamsClient(this);\n readonly user = new UserClient(this);\n readonly messages = new MessageClient(this);\n\n constructor(\n readonly apiKey: string,\n options: KnockOptions = {},\n ) {\n this.host = options.host || DEFAULT_HOST;\n this.logLevel = options.logLevel;\n\n this.log(\"Initialized Knock instance\");\n\n // Fail loudly if we're using the wrong API key\n if (this.apiKey && this.apiKey.startsWith(\"sk_\")) {\n throw new Error(\n \"[Knock] You are using your secret API key on the client. Please use the public key.\",\n );\n }\n }\n\n client() {\n // Initiate a new API client if we don't have one yet\n if (!this.apiClient) {\n this.apiClient = this.createApiClient();\n }\n\n return this.apiClient;\n }\n\n /**\n * @deprecated Passing `userId` as a `string` is deprecated and will be removed in a future version.\n * Please pass a `user` object instead containing an `id` value.\n * example:\n * ```ts\n * knock.authenticate({ id: \"user_123\" });\n * ```\n */\n authenticate(\n userIdOrUserWithProperties: UserId,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ): never;\n authenticate(\n userIdOrUserWithProperties: UserIdOrUserWithProperties,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ): void;\n authenticate(\n userIdOrUserWithProperties: UserIdOrUserWithProperties,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ) {\n let reinitializeApi = false;\n const currentApiClient = this.apiClient;\n const userId = this.getUserId(userIdOrUserWithProperties);\n\n // If we've previously been initialized and the values have now changed, then we\n // need to reinitialize any stateful connections we have\n if (\n currentApiClient &&\n (this.userId !== userId || this.userToken !== userToken)\n ) {\n this.log(\"userId or userToken changed; reinitializing connections\");\n this.feeds.teardownInstances();\n this.teardown();\n reinitializeApi = true;\n }\n\n this.userId = userId;\n this.userToken = userToken;\n\n this.log(`Authenticated with userId ${userId}`);\n\n if (this.userToken && options?.onUserTokenExpiring instanceof Function) {\n this.maybeScheduleUserTokenExpiration(\n options.onUserTokenExpiring,\n options.timeBeforeExpirationInMs,\n );\n }\n\n // If we get the signal to reinitialize the api client, then we want to create a new client\n // and the reinitialize any existing feed real-time connections we have so everything continues\n // to work with the new credentials we've been given\n if (reinitializeApi) {\n this.apiClient = this.createApiClient();\n this.feeds.reinitializeInstances();\n this.log(\"Reinitialized real-time connections\");\n }\n\n // Inline identify the user if we've been given an object with an id.\n if (\n typeof userIdOrUserWithProperties === \"object\" &&\n userIdOrUserWithProperties?.id\n ) {\n const { id, ...properties } = userIdOrUserWithProperties;\n this.user.identify(properties);\n }\n\n return;\n }\n\n failIfNotAuthenticated() {\n if (!this.isAuthenticated()) {\n throw new Error(\"Not authenticated. Please call `authenticate` first.\");\n }\n }\n\n /*\n Returns whether or this Knock instance is authenticated. Passing `true` will check the presence\n of the userToken as well.\n */\n isAuthenticated(checkUserToken = false) {\n return checkUserToken ? !!(this.userId && this.userToken) : !!this.userId;\n }\n\n // Used to teardown any connected instances\n teardown() {\n if (this.tokenExpirationTimer) {\n clearTimeout(this.tokenExpirationTimer);\n }\n if (this.apiClient?.socket && this.apiClient.socket.isConnected()) {\n this.apiClient.socket.disconnect();\n }\n }\n\n log(message: string, force = false) {\n if (this.logLevel === \"debug\" || force) {\n console.log(`[Knock] ${message}`);\n }\n }\n\n /**\n * Initiates an API client\n */\n private createApiClient() {\n return new ApiClient({\n apiKey: this.apiKey,\n host: this.host,\n userToken: this.userToken,\n });\n }\n\n private async maybeScheduleUserTokenExpiration(\n callbackFn: UserTokenExpiringCallback,\n timeBeforeExpirationInMs: number = 30_000,\n ) {\n if (!this.userToken) return;\n\n const decoded = jwtDecode(this.userToken);\n const expiresAtMs = (decoded.exp ?? 0) * 1000;\n const nowMs = Date.now();\n\n // Expiration is in the future\n if (expiresAtMs && expiresAtMs > nowMs) {\n // Check how long until the token should be regenerated\n // | ----------------- | ----------------------- |\n // ^ now ^ expiration offset ^ expires at\n const msInFuture = expiresAtMs - timeBeforeExpirationInMs - nowMs;\n\n this.tokenExpirationTimer = setTimeout(async () => {\n const newToken = await callbackFn(this.userToken as string, decoded);\n\n // Reauthenticate which will handle reinitializing sockets\n if (typeof newToken === \"string\") {\n this.authenticate(this.userId!, newToken, {\n onUserTokenExpiring: callbackFn,\n timeBeforeExpirationInMs: timeBeforeExpirationInMs,\n });\n }\n }, msInFuture);\n }\n }\n\n /**\n * Returns the user id from the given userIdOrUserWithProperties\n * @param userIdOrUserWithProperties - The user id or user object\n * @returns The user id\n * @throws {Error} If the user object does not contain an `id` property\n */\n private getUserId(userIdOrUserWithProperties: UserIdOrUserWithProperties) {\n if (\n typeof userIdOrUserWithProperties === \"string\" ||\n !userIdOrUserWithProperties\n ) {\n return userIdOrUserWithProperties;\n }\n\n if (userIdOrUserWithProperties?.id) {\n return userIdOrUserWithProperties.id;\n }\n\n throw new Error(\"`user` object must contain an `id` property\");\n }\n}\n\nexport default Knock;\n"],"names":["DEFAULT_HOST","Knock","apiKey","options","__publicField","FeedClient","ObjectClient","Preferences","SlackClient","MsTeamsClient","UserClient","MessageClient","userIdOrUserWithProperties","userToken","reinitializeApi","currentApiClient","userId","id","properties","checkUserToken","_a","message","force","ApiClient","callbackFn","timeBeforeExpirationInMs","decoded","jwtDecode","expiresAtMs","nowMs","msInFuture","newToken"],"mappings":";;;;;;;;;;;;AAmBA,MAAMA,IAAe;AAErB,MAAMC,EAAM;AAAA,EAeV,YACWC,GACTC,IAAwB,IACxB;AAjBK,IAAAC,EAAA;AACC,IAAAA,EAAA,mBAA8B;AAC/B,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACC,IAAAA,EAAA,8BAA6D;AAC5D,IAAAA,EAAA,eAAQ,IAAIC,EAAW,IAAI;AAC3B,IAAAD,EAAA,iBAAU,IAAIE,EAAa,IAAI;AAC/B,IAAAF,EAAA,qBAAc,IAAIG,EAAY,IAAI;AAClC,IAAAH,EAAA,eAAQ,IAAII,EAAY,IAAI;AAC5B,IAAAJ,EAAA,iBAAU,IAAIK,EAAc,IAAI;AAChC,IAAAL,EAAA,cAAO,IAAIM,EAAW,IAAI;AAC1B,IAAAN,EAAA,kBAAW,IAAIO,EAAc,IAAI;AAYxC,QATS,KAAA,SAAAT,GAGJ,KAAA,OAAOC,EAAQ,QAAQH,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K,oBAAoB,IAEpCC,IAAA,KAAK,cAAL,QAAAA,EAAgB,UAAU,KAAK,UAAU,OAAO,iBAC7C,KAAA,UAAU,OAAO,WAAW;AAAA,EACnC;AAAA,EAGF,IAAIC,GAAiBC,IAAQ,IAAO;AAC9B,KAAA,KAAK,aAAa,WAAWA,MACvB,QAAA,IAAI,WAAWD,CAAO,EAAE;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA,EAMM,kBAAkB;AACxB,WAAO,IAAIE,EAAU;AAAA,MACnB,QAAQ,KAAK;AAAA,MACb,MAAM,KAAK;AAAA,MACX,WAAW,KAAK;AAAA,IAAA,CACjB;AAAA,EAAA;AAAA,EAGH,MAAc,iCACZC,GACAC,IAAmC,KACnC;AACI,QAAA,CAAC,KAAK,UAAW;AAEf,UAAAC,IAAUC,EAAU,KAAK,SAAS,GAClCC,KAAeF,EAAQ,OAAO,KAAK,KACnCG,IAAQ,KAAK,IAAI;AAGnB,QAAAD,KAAeA,IAAcC,GAAO;AAIhC,YAAAC,IAAaF,IAAcH,IAA2BI;AAEvD,WAAA,uBAAuB,WAAW,YAAY;AACjD,cAAME,IAAW,MAAMP,EAAW,KAAK,WAAqBE,CAAO;AAG/D,QAAA,OAAOK,KAAa,YACjB,KAAA,aAAa,KAAK,QAASA,GAAU;AAAA,UACxC,qBAAqBP;AAAA,UACrB,0BAAAC;AAAA,QAAA,CACD;AAAA,SAEFK,CAAU;AAAA,IAAA;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASM,UAAUlB,GAAwD;AACxE,QACE,OAAOA,KAA+B,YACtC,CAACA;AAEM,aAAAA;AAGT,QAAIA,KAAA,QAAAA,EAA4B;AAC9B,aAAOA,EAA2B;AAG9B,UAAA,IAAI,MAAM,6CAA6C;AAAA,EAAA;AAEjE;"}
|
|
1
|
+
{"version":3,"file":"knock.mjs","sources":["../../src/knock.ts"],"sourcesContent":["import { jwtDecode } from \"jwt-decode\";\n\nimport ApiClient from \"./api\";\nimport FeedClient from \"./clients/feed\";\nimport MessageClient from \"./clients/messages\";\nimport MsTeamsClient from \"./clients/ms-teams\";\nimport ObjectClient from \"./clients/objects\";\nimport Preferences from \"./clients/preferences\";\nimport SlackClient from \"./clients/slack\";\nimport UserClient from \"./clients/users\";\nimport {\n AuthenticateOptions,\n KnockOptions,\n LogLevel,\n UserId,\n UserIdOrUserWithProperties,\n UserTokenExpiringCallback,\n} from \"./interfaces\";\n\nconst DEFAULT_HOST = \"https://api.knock.app\";\n\nclass Knock {\n public host: string;\n private apiClient: ApiClient | null = null;\n public userId: string | undefined | null;\n public userToken?: string;\n public logLevel?: LogLevel;\n private tokenExpirationTimer: ReturnType<typeof setTimeout> | null = null;\n readonly feeds = new FeedClient(this);\n readonly objects = new ObjectClient(this);\n readonly preferences = new Preferences(this);\n readonly slack = new SlackClient(this);\n readonly msTeams = new MsTeamsClient(this);\n readonly user = new UserClient(this);\n readonly messages = new MessageClient(this);\n\n constructor(\n readonly apiKey: string,\n options: KnockOptions = {},\n ) {\n this.host = options.host || DEFAULT_HOST;\n this.logLevel = options.logLevel;\n\n this.log(\"Initialized Knock instance\");\n\n // Fail loudly if we're using the wrong API key\n if (this.apiKey && this.apiKey.startsWith(\"sk_\")) {\n throw new Error(\n \"[Knock] You are using your secret API key on the client. Please use the public key.\",\n );\n }\n }\n\n client() {\n // Initiate a new API client if we don't have one yet\n if (!this.apiClient) {\n this.apiClient = this.createApiClient();\n }\n\n return this.apiClient;\n }\n\n /**\n * @deprecated Passing `userId` as a `string` is deprecated and will be removed in a future version.\n * Please pass a `user` object instead containing an `id` value.\n * example:\n * ```ts\n * knock.authenticate({ id: \"user_123\" });\n * ```\n */\n authenticate(\n userIdOrUserWithProperties: UserId,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ): never;\n authenticate(\n userIdOrUserWithProperties: UserIdOrUserWithProperties,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ): void;\n authenticate(\n userIdOrUserWithProperties: UserIdOrUserWithProperties,\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ) {\n let reinitializeApi = false;\n const currentApiClient = this.apiClient;\n const userId = this.getUserId(userIdOrUserWithProperties);\n const identificationStrategy = options?.identificationStrategy || \"inline\";\n\n // If we've previously been initialized and the values have now changed, then we\n // need to reinitialize any stateful connections we have\n if (\n currentApiClient &&\n (this.userId !== userId || this.userToken !== userToken)\n ) {\n this.log(\"userId or userToken changed; reinitializing connections\");\n this.feeds.teardownInstances();\n this.teardown();\n reinitializeApi = true;\n }\n\n this.userId = userId;\n this.userToken = userToken;\n\n this.log(`Authenticated with userId ${userId}`);\n\n if (this.userToken && options?.onUserTokenExpiring instanceof Function) {\n this.maybeScheduleUserTokenExpiration(\n options.onUserTokenExpiring,\n options.timeBeforeExpirationInMs,\n );\n }\n\n // If we get the signal to reinitialize the api client, then we want to create a new client\n // and the reinitialize any existing feed real-time connections we have so everything continues\n // to work with the new credentials we've been given\n if (reinitializeApi) {\n this.apiClient = this.createApiClient();\n this.feeds.reinitializeInstances();\n this.log(\"Reinitialized real-time connections\");\n }\n\n // We explicitly skip the inline identification if the strategy is set to \"skip\"\n if (identificationStrategy === \"skip\") {\n this.log(\"Skipping inline user identification\");\n return;\n }\n\n // Inline identify the user if we've been given an object with an id\n // and the strategy is set to \"inline\".\n if (\n identificationStrategy === \"inline\" &&\n typeof userIdOrUserWithProperties === \"object\" &&\n userIdOrUserWithProperties?.id\n ) {\n this.log(`Identifying user ${userIdOrUserWithProperties.id} inline`);\n const { id, ...properties } = userIdOrUserWithProperties;\n this.user.identify(properties);\n }\n\n return;\n }\n\n failIfNotAuthenticated() {\n if (!this.isAuthenticated()) {\n throw new Error(\"Not authenticated. Please call `authenticate` first.\");\n }\n }\n\n /*\n Returns whether or this Knock instance is authenticated. Passing `true` will check the presence\n of the userToken as well.\n */\n isAuthenticated(checkUserToken = false) {\n return checkUserToken ? !!(this.userId && this.userToken) : !!this.userId;\n }\n\n // Used to teardown any connected instances\n teardown() {\n if (this.tokenExpirationTimer) {\n clearTimeout(this.tokenExpirationTimer);\n }\n if (this.apiClient?.socket && this.apiClient.socket.isConnected()) {\n this.apiClient.socket.disconnect();\n }\n }\n\n log(message: string, force = false) {\n if (this.logLevel === \"debug\" || force) {\n console.log(`[Knock] ${message}`);\n }\n }\n\n /**\n * Initiates an API client\n */\n private createApiClient() {\n return new ApiClient({\n apiKey: this.apiKey,\n host: this.host,\n userToken: this.userToken,\n });\n }\n\n private async maybeScheduleUserTokenExpiration(\n callbackFn: UserTokenExpiringCallback,\n timeBeforeExpirationInMs: number = 30_000,\n ) {\n if (!this.userToken) return;\n\n const decoded = jwtDecode(this.userToken);\n const expiresAtMs = (decoded.exp ?? 0) * 1000;\n const nowMs = Date.now();\n\n // Expiration is in the future\n if (expiresAtMs && expiresAtMs > nowMs) {\n // Check how long until the token should be regenerated\n // | ----------------- | ----------------------- |\n // ^ now ^ expiration offset ^ expires at\n const msInFuture = expiresAtMs - timeBeforeExpirationInMs - nowMs;\n\n this.tokenExpirationTimer = setTimeout(async () => {\n const newToken = await callbackFn(this.userToken as string, decoded);\n\n // Reauthenticate which will handle reinitializing sockets\n if (typeof newToken === \"string\") {\n this.authenticate(this.userId!, newToken, {\n onUserTokenExpiring: callbackFn,\n timeBeforeExpirationInMs: timeBeforeExpirationInMs,\n });\n }\n }, msInFuture);\n }\n }\n\n /**\n * Returns the user id from the given userIdOrUserWithProperties\n * @param userIdOrUserWithProperties - The user id or user object\n * @returns The user id\n * @throws {Error} If the user object does not contain an `id` property\n */\n private getUserId(userIdOrUserWithProperties: UserIdOrUserWithProperties) {\n if (\n typeof userIdOrUserWithProperties === \"string\" ||\n !userIdOrUserWithProperties\n ) {\n return userIdOrUserWithProperties;\n }\n\n if (userIdOrUserWithProperties?.id) {\n return userIdOrUserWithProperties.id;\n }\n\n throw new Error(\"`user` object must contain an `id` property\");\n }\n}\n\nexport default Knock;\n"],"names":["DEFAULT_HOST","Knock","apiKey","options","__publicField","FeedClient","ObjectClient","Preferences","SlackClient","MsTeamsClient","UserClient","MessageClient","userIdOrUserWithProperties","userToken","reinitializeApi","currentApiClient","userId","identificationStrategy","id","properties","checkUserToken","_a","message","force","ApiClient","callbackFn","timeBeforeExpirationInMs","decoded","jwtDecode","expiresAtMs","nowMs","msInFuture","newToken"],"mappings":";;;;;;;;;;;;AAmBA,MAAMA,IAAe;AAErB,MAAMC,EAAM;AAAA,EAeV,YACWC,GACTC,IAAwB,IACxB;AAjBK,IAAAC,EAAA;AACC,IAAAA,EAAA,mBAA8B;AAC/B,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACC,IAAAA,EAAA,8BAA6D;AAC5D,IAAAA,EAAA,eAAQ,IAAIC,EAAW,IAAI;AAC3B,IAAAD,EAAA,iBAAU,IAAIE,EAAa,IAAI;AAC/B,IAAAF,EAAA,qBAAc,IAAIG,EAAY,IAAI;AAClC,IAAAH,EAAA,eAAQ,IAAII,EAAY,IAAI;AAC5B,IAAAJ,EAAA,iBAAU,IAAIK,EAAc,IAAI;AAChC,IAAAL,EAAA,cAAO,IAAIM,EAAW,IAAI;AAC1B,IAAAN,EAAA,kBAAW,IAAIO,EAAc,IAAI;AAYxC,QATS,KAAA,SAAAT,GAGJ,KAAA,OAAOC,EAAQ,QAAQH,GAC5B,KAAK,WAAWG,EAAQ,UAExB,KAAK,IAAI,4BAA4B,GAGjC,KAAK,UAAU,KAAK,OAAO,WAAW,KAAK;AAC7C,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,EACF;AAAA,EAGF,SAAS;AAEH,WAAC,KAAK,cACH,KAAA,YAAY,KAAK,gBAAgB,IAGjC,KAAK;AAAA,EAAA;AAAA,EAqBd,aACES,GACAC,GACAV,GACA;AACA,QAAIW,IAAkB;AACtB,UAAMC,IAAmB,KAAK,WACxBC,IAAS,KAAK,UAAUJ,CAA0B,GAClDK,KAAyBd,KAAA,gBAAAA,EAAS,2BAA0B;AAoClE,QA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B;IA+C3B,OAAO,CAAC,8BAA8B;IAatC,OAAO,CAAC,iBAAiB;IAYzB,OAAO,CAAC,WAAW;IASnB,OAAO,CAAC,sBAAsB;IAiC9B,OAAO,CAAC,kBAAkB;IAU1B,OAAO,CAAC,oBAAoB,CA2B1B;IAIF,OAAO,CAAC,sBAAsB;IAO9B,OAAO,CAAC,kCAAkC;IAyC1C,OAAO,CAAC,oBAAoB;CAgB7B"}
|
|
@@ -33,6 +33,7 @@ export interface GuideData<TContent = Any> {
|
|
|
33
33
|
key: string;
|
|
34
34
|
type: string;
|
|
35
35
|
semver: string;
|
|
36
|
+
active: boolean;
|
|
36
37
|
steps: GuideStepData<TContent>[];
|
|
37
38
|
activation_url_rules: GuideActivationUrlRuleData[];
|
|
38
39
|
activation_url_patterns: GuideActivationUrlPatternData[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/clients/guide/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAO/C,MAAM,MAAM,GAAG,GAAG,GAAG,CAAC;AAEtB,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED,MAAM,WAAW,aAAa,CAAC,QAAQ,GAAG,GAAG;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,OAAO,EAAE,gBAAgB,CAAC;IAC1B,OAAO,EAAE,QAAQ,CAAC;CACnB;AAED,M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AY,GAAG;IACzB,IAAI,CAAC,EAAE,WAAW,GAAG,SAAS,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,MAAM,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,CAAC;IACpC,OAAO,EAAE,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAClC,QAAQ,CAAC,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC;IAC7B,SAAS,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,IAAI,CAAC;CACjD,CAAC"}
|
|
@@ -43,6 +43,7 @@ export type UserTokenExpiringCallback = (currentToken: string, decodedToken: Jwt
|
|
|
43
43
|
export interface AuthenticateOptions {
|
|
44
44
|
onUserTokenExpiring?: UserTokenExpiringCallback;
|
|
45
45
|
timeBeforeExpirationInMs?: number;
|
|
46
|
+
identificationStrategy?: "inline" | "skip";
|
|
46
47
|
}
|
|
47
48
|
export interface BulkOperation {
|
|
48
49
|
id: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../../src/interfaces.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,OAAO,KAAK,MAAM,SAAS,CAAC;AAE5B,MAAM,MAAM,QAAQ,GAAG,OAAO,CAAC;AAE/B,MAAM,WAAW,YAAY;IAC3B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,QAAQ,CAAC;CACrB;AAED,MAAM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AC,IAAI,aAAwB;IACrC,QAAQ,CAAC,QAAQ,gBAA2B;gBAGjC,MAAM,EAAE,MAAM,EACvB,OAAO,GAAE,YAAiB;IAe5B,MAAM;IASN;;;;;;;OAOG;IACH,YAAY,CACV,0BAA0B,EAAE,MAAM,EAClC,SAAS,CAAC,EAAE,KAAK,CAAC,WAAW,CAAC,EAC9B,OAAO,CAAC,EAAE,mBAAmB,GAC5B,KAAK;IACR,YAAY,CACV,0BAA0B,EAAE,0BAA0B,EACtD,SAAS,CAAC,EAAE,KAAK,CAAC,WAAW,CAAC,EAC9B,OAAO,CAAC,EAAE,mBAAmB,GAC5B,IAAI;IAiEP,sBAAsB;IAUtB,eAAe,CAAC,cAAc,UAAQ;IAKtC,QAAQ;IASR,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,UAAQ;IAMlC;;OAEG;IACH,OAAO,CAAC,eAAe;YAQT,gCAAgC;IA+B9C;;;;;OAKG;IACH,OAAO,CAAC,SAAS;CAclB;AAED,eAAe,KAAK,CAAC"}
|
package/package.json
CHANGED
|
@@ -160,6 +160,10 @@ const predicate = (
|
|
|
160
160
|
return true;
|
|
161
161
|
}
|
|
162
162
|
|
|
163
|
+
if (!guide.active) {
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
|
|
163
167
|
if (guide.steps.every((s) => !!s.message.archived_at)) {
|
|
164
168
|
return false;
|
|
165
169
|
}
|
|
@@ -466,7 +470,10 @@ export class KnockGuideClient {
|
|
|
466
470
|
state: StoreState,
|
|
467
471
|
filters: SelectFilterParams = {},
|
|
468
472
|
): KnockGuide<C>[] {
|
|
469
|
-
if (
|
|
473
|
+
if (
|
|
474
|
+
Object.keys(state.guides).length === 0 &&
|
|
475
|
+
Object.keys(state.previewGuides).length === 0
|
|
476
|
+
) {
|
|
470
477
|
return [];
|
|
471
478
|
}
|
|
472
479
|
this.knock.log(`[Guide] Selecting guides for: ${formatFilters(filters)}`);
|
|
@@ -488,7 +495,10 @@ export class KnockGuideClient {
|
|
|
488
495
|
state: StoreState,
|
|
489
496
|
filters: SelectFilterParams = {},
|
|
490
497
|
): KnockGuide<C> | undefined {
|
|
491
|
-
if (
|
|
498
|
+
if (
|
|
499
|
+
Object.keys(state.guides).length === 0 &&
|
|
500
|
+
Object.keys(state.previewGuides).length === 0
|
|
501
|
+
) {
|
|
492
502
|
return undefined;
|
|
493
503
|
}
|
|
494
504
|
this.knock.log(`[Guide] Selecting a guide for: ${formatFilters(filters)}`);
|
|
@@ -44,6 +44,7 @@ export interface GuideData<TContent = Any> {
|
|
|
44
44
|
key: string;
|
|
45
45
|
type: string;
|
|
46
46
|
semver: string;
|
|
47
|
+
active: boolean;
|
|
47
48
|
steps: GuideStepData<TContent>[];
|
|
48
49
|
activation_url_rules: GuideActivationUrlRuleData[];
|
|
49
50
|
activation_url_patterns: GuideActivationUrlPatternData[];
|
package/src/interfaces.ts
CHANGED
|
@@ -54,6 +54,7 @@ export type UserTokenExpiringCallback = (
|
|
|
54
54
|
export interface AuthenticateOptions {
|
|
55
55
|
onUserTokenExpiring?: UserTokenExpiringCallback;
|
|
56
56
|
timeBeforeExpirationInMs?: number;
|
|
57
|
+
identificationStrategy?: "inline" | "skip";
|
|
57
58
|
}
|
|
58
59
|
|
|
59
60
|
export interface BulkOperation {
|
package/src/knock.ts
CHANGED
|
@@ -86,6 +86,7 @@ class Knock {
|
|
|
86
86
|
let reinitializeApi = false;
|
|
87
87
|
const currentApiClient = this.apiClient;
|
|
88
88
|
const userId = this.getUserId(userIdOrUserWithProperties);
|
|
89
|
+
const identificationStrategy = options?.identificationStrategy || "inline";
|
|
89
90
|
|
|
90
91
|
// If we've previously been initialized and the values have now changed, then we
|
|
91
92
|
// need to reinitialize any stateful connections we have
|
|
@@ -120,11 +121,20 @@ class Knock {
|
|
|
120
121
|
this.log("Reinitialized real-time connections");
|
|
121
122
|
}
|
|
122
123
|
|
|
123
|
-
//
|
|
124
|
+
// We explicitly skip the inline identification if the strategy is set to "skip"
|
|
125
|
+
if (identificationStrategy === "skip") {
|
|
126
|
+
this.log("Skipping inline user identification");
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Inline identify the user if we've been given an object with an id
|
|
131
|
+
// and the strategy is set to "inline".
|
|
124
132
|
if (
|
|
133
|
+
identificationStrategy === "inline" &&
|
|
125
134
|
typeof userIdOrUserWithProperties === "object" &&
|
|
126
135
|
userIdOrUserWithProperties?.id
|
|
127
136
|
) {
|
|
137
|
+
this.log(`Identifying user ${userIdOrUserWithProperties.id} inline`);
|
|
128
138
|
const { id, ...properties } = userIdOrUserWithProperties;
|
|
129
139
|
this.user.identify(properties);
|
|
130
140
|
}
|