@knocklabs/client 0.19.2 → 0.19.4
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 +24 -0
- package/dist/cjs/api.js +1 -1
- package/dist/cjs/api.js.map +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 +2 -2
- package/dist/cjs/knock.js.map +1 -1
- package/dist/esm/api.mjs +20 -17
- package/dist/esm/api.mjs.map +1 -1
- package/dist/esm/clients/guide/client.mjs +4 -3
- package/dist/esm/clients/guide/client.mjs.map +1 -1
- package/dist/esm/knock.mjs +20 -18
- package/dist/esm/knock.mjs.map +1 -1
- package/dist/types/api.d.ts +2 -0
- package/dist/types/api.d.ts.map +1 -1
- package/dist/types/clients/guide/client.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 +1 -0
- package/dist/types/knock.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/api.ts +5 -0
- package/src/clients/guide/client.ts +2 -1
- package/src/interfaces.ts +1 -0
- package/src/knock.ts +3 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.19.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- a56bf70: [guide] include a tenant param for all engagement update requests
|
|
8
|
+
|
|
9
|
+
## 0.19.3
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 571abb1: Add `branch` option to `Knock` client
|
|
14
|
+
|
|
15
|
+
The `Knock` client now accepts a `branch` option. To use `Knock` with a branch,
|
|
16
|
+
set the `apiKey` param to your development environment's API key and set the
|
|
17
|
+
`branch` option to the slug of an existing branch.
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
import Knock from "@knocklabs/client";
|
|
21
|
+
|
|
22
|
+
const knock = new Knock(process.env.KNOCK_PUBLIC_API_KEY, {
|
|
23
|
+
branch: "my-branch-slug",
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
3
27
|
## 0.19.2
|
|
4
28
|
|
|
5
29
|
### Patch Changes
|
package/dist/cjs/api.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var i=Object.defineProperty;var o=(t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var r=(t,e,s)=>o(t,typeof e!="symbol"?e+"":e,s);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("axios"),c=require("axios-retry"),l=require("phoenix"),n=t=>t&&typeof t=="object"&&"default"in t?t:{default:t},h=n(u),a=n(c);class d{constructor(e){r(this,"host");r(this,"apiKey");r(this,"userToken");r(this,"branch");r(this,"axiosClient");r(this,"socket");this.host=e.host,this.apiKey=e.apiKey,this.userToken=e.userToken||null,this.branch=e.branch||null,this.axiosClient=h.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(),"X-Knock-Branch":this.branch}}),typeof window<"u"&&(this.socket=new l.Socket(`${this.host.replace("http","ws")}/ws/v1`,{params:{user_token:this.userToken,api_key:this.apiKey,branch_slug:this.branch}})),a.default(this.axiosClient,{retries:3,retryCondition:this.canRetryRequest,retryDelay:a.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 a.default.isNetworkError(e)?!0:e.response?e.response.status>=500&&e.response.status<=599||e.response.status===429:!1}getKnockClientHeader(){return"Knock/ClientJS 0.19.4"}}exports.default=d;
|
|
2
2
|
//# sourceMappingURL=api.js.map
|
package/dist/cjs/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","sources":["../../src/api.ts"],"sourcesContent":["import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from \"axios\";\nimport axiosRetry from \"axios-retry\";\nimport { Socket } from \"phoenix\";\n\ntype ApiClientOptions = {\n host: string;\n apiKey: string;\n userToken: string | undefined;\n};\n\nexport interface ApiResponse {\n // eslint-disable-next-line\n error?: any;\n // eslint-disable-next-line\n body?: any;\n statusCode: \"ok\" | \"error\";\n status: number;\n}\n\nclass ApiClient {\n private host: string;\n private apiKey: string;\n private userToken: string | null;\n private axiosClient: AxiosInstance;\n\n public socket: Socket | undefined;\n\n constructor(options: ApiClientOptions) {\n this.host = options.host;\n this.apiKey = options.apiKey;\n this.userToken = options.userToken || null;\n\n // Create a retryable axios client\n this.axiosClient = axios.create({\n baseURL: this.host,\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n \"X-Knock-User-Token\": this.userToken,\n \"X-Knock-Client\": this.getKnockClientHeader(),\n },\n });\n\n if (typeof window !== \"undefined\") {\n this.socket = new Socket(`${this.host.replace(\"http\", \"ws\")}/ws/v1`, {\n params: {\n user_token: this.userToken,\n api_key: this.apiKey,\n },\n });\n }\n\n axiosRetry(this.axiosClient, {\n retries: 3,\n retryCondition: this.canRetryRequest,\n retryDelay: axiosRetry.exponentialDelay,\n });\n }\n\n async makeRequest(req: AxiosRequestConfig): Promise<ApiResponse> {\n try {\n const result = await this.axiosClient(req);\n\n return {\n statusCode: result.status < 300 ? \"ok\" : \"error\",\n body: result.data,\n error: undefined,\n status: result.status,\n };\n\n // eslint:disable-next-line\n } catch (e: unknown) {\n console.error(e);\n\n return {\n statusCode: \"error\",\n status: 500,\n body: undefined,\n error: e,\n };\n }\n }\n\n private canRetryRequest(error: AxiosError) {\n // Retry Network Errors.\n if (axiosRetry.isNetworkError(error)) {\n return true;\n }\n\n if (!error.response) {\n // Cannot determine if the request can be retried\n return false;\n }\n\n // Retry Server Errors (5xx).\n if (error.response.status >= 500 && error.response.status <= 599) {\n return true;\n }\n\n // Retry if rate limited.\n if (error.response.status === 429) {\n return true;\n }\n\n return false;\n }\n\n private getKnockClientHeader() {\n // Note: we're following format used in our Stainless SDKs:\n // https://github.com/knocklabs/knock-node/blob/main/src/client.ts#L335\n // If we add the env var to turbo.json, it caches it so the version\n // never actually updates.\n // eslint-disable-next-line turbo/no-undeclared-env-vars\n return `Knock/ClientJS ${process.env.CLIENT_PACKAGE_VERSION}`;\n }\n}\n\nexport default ApiClient;\n"],"names":["ApiClient","options","__publicField","axios","Socket","axiosRetry","req","result","e","error"],"mappings":"
|
|
1
|
+
{"version":3,"file":"api.js","sources":["../../src/api.ts"],"sourcesContent":["import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from \"axios\";\nimport axiosRetry from \"axios-retry\";\nimport { Socket } from \"phoenix\";\n\ntype ApiClientOptions = {\n host: string;\n apiKey: string;\n userToken: string | undefined;\n branch?: string;\n};\n\nexport interface ApiResponse {\n // eslint-disable-next-line\n error?: any;\n // eslint-disable-next-line\n body?: any;\n statusCode: \"ok\" | \"error\";\n status: number;\n}\n\nclass ApiClient {\n private host: string;\n private apiKey: string;\n private userToken: string | null;\n private branch: string | null;\n private axiosClient: AxiosInstance;\n\n public socket: Socket | undefined;\n\n constructor(options: ApiClientOptions) {\n this.host = options.host;\n this.apiKey = options.apiKey;\n this.userToken = options.userToken || null;\n this.branch = options.branch || null;\n\n // Create a retryable axios client\n this.axiosClient = axios.create({\n baseURL: this.host,\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n \"X-Knock-User-Token\": this.userToken,\n \"X-Knock-Client\": this.getKnockClientHeader(),\n \"X-Knock-Branch\": this.branch,\n },\n });\n\n if (typeof window !== \"undefined\") {\n this.socket = new Socket(`${this.host.replace(\"http\", \"ws\")}/ws/v1`, {\n params: {\n user_token: this.userToken,\n api_key: this.apiKey,\n branch_slug: this.branch,\n },\n });\n }\n\n axiosRetry(this.axiosClient, {\n retries: 3,\n retryCondition: this.canRetryRequest,\n retryDelay: axiosRetry.exponentialDelay,\n });\n }\n\n async makeRequest(req: AxiosRequestConfig): Promise<ApiResponse> {\n try {\n const result = await this.axiosClient(req);\n\n return {\n statusCode: result.status < 300 ? \"ok\" : \"error\",\n body: result.data,\n error: undefined,\n status: result.status,\n };\n\n // eslint:disable-next-line\n } catch (e: unknown) {\n console.error(e);\n\n return {\n statusCode: \"error\",\n status: 500,\n body: undefined,\n error: e,\n };\n }\n }\n\n private canRetryRequest(error: AxiosError) {\n // Retry Network Errors.\n if (axiosRetry.isNetworkError(error)) {\n return true;\n }\n\n if (!error.response) {\n // Cannot determine if the request can be retried\n return false;\n }\n\n // Retry Server Errors (5xx).\n if (error.response.status >= 500 && error.response.status <= 599) {\n return true;\n }\n\n // Retry if rate limited.\n if (error.response.status === 429) {\n return true;\n }\n\n return false;\n }\n\n private getKnockClientHeader() {\n // Note: we're following format used in our Stainless SDKs:\n // https://github.com/knocklabs/knock-node/blob/main/src/client.ts#L335\n // If we add the env var to turbo.json, it caches it so the version\n // never actually updates.\n // eslint-disable-next-line turbo/no-undeclared-env-vars\n return `Knock/ClientJS ${process.env.CLIENT_PACKAGE_VERSION}`;\n }\n}\n\nexport default ApiClient;\n"],"names":["ApiClient","options","__publicField","axios","Socket","axiosRetry","req","result","e","error"],"mappings":"6ZAoBA,MAAMA,CAAU,CASd,YAAYC,EAA2B,CAR/BC,EAAA,aACAA,EAAA,eACAA,EAAA,kBACAA,EAAA,eACAA,EAAA,oBAEDA,EAAA,eAGL,KAAK,KAAOD,EAAQ,KACpB,KAAK,OAASA,EAAQ,OACjB,KAAA,UAAYA,EAAQ,WAAa,KACjC,KAAA,OAASA,EAAQ,QAAU,KAG3B,KAAA,YAAcE,UAAM,OAAO,CAC9B,QAAS,KAAK,KACd,QAAS,CACP,OAAQ,mBACR,eAAgB,mBAChB,cAAe,UAAU,KAAK,MAAM,GACpC,qBAAsB,KAAK,UAC3B,iBAAkB,KAAK,qBAAqB,EAC5C,iBAAkB,KAAK,MAAA,CACzB,CACD,EAEG,OAAO,OAAW,MACf,KAAA,OAAS,IAAIC,EAAA,OAAO,GAAG,KAAK,KAAK,QAAQ,OAAQ,IAAI,CAAC,SAAU,CACnE,OAAQ,CACN,WAAY,KAAK,UACjB,QAAS,KAAK,OACd,YAAa,KAAK,MAAA,CACpB,CACD,GAGHC,EAAA,QAAW,KAAK,YAAa,CAC3B,QAAS,EACT,eAAgB,KAAK,gBACrB,WAAYA,EAAAA,QAAW,gBAAA,CACxB,CAAA,CAGH,MAAM,YAAYC,EAA+C,CAC3D,GAAA,CACF,MAAMC,EAAS,MAAM,KAAK,YAAYD,CAAG,EAElC,MAAA,CACL,WAAYC,EAAO,OAAS,IAAM,KAAO,QACzC,KAAMA,EAAO,KACb,MAAO,OACP,OAAQA,EAAO,MACjB,QAGOC,EAAY,CACnB,eAAQ,MAAMA,CAAC,EAER,CACL,WAAY,QACZ,OAAQ,IACR,KAAM,OACN,MAAOA,CACT,CAAA,CACF,CAGM,gBAAgBC,EAAmB,CAErC,OAAAJ,EAAA,QAAW,eAAeI,CAAK,EAC1B,GAGJA,EAAM,SAMPA,EAAM,SAAS,QAAU,KAAOA,EAAM,SAAS,QAAU,KAKzDA,EAAM,SAAS,SAAW,IATrB,EAaF,CAGD,sBAAuB,CAMtB,MAAA,uBAAoD,CAE/D"}
|
|
@@ -1,2 +1,2 @@
|
|
|
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 _=require("@tanstack/store"),b=require("urlpattern-polyfill"),d=require("./helpers.js"),I=50,C=30*1e3,E=3,g={GUIDE_KEY:"knock_guide_key",PREVIEW_SESSION_ID:"knock_preview_session_id"},k="knock_guide_debug",p=()=>{if(typeof window<"u")return window},G=u=>`/v1/users/${u}/guides`,f=()=>{const u=p();if(!u)return{forcedGuideKey:null,previewSessionId:null};const e=new URLSearchParams(u.location.search),t=e.get(g.GUIDE_KEY),s=e.get(g.PREVIEW_SESSION_ID);if(t||s){if(u.localStorage)try{const r={forcedGuideKey:t,previewSessionId:s};u.localStorage.setItem(k,JSON.stringify(r))}catch{}return{forcedGuideKey:t,previewSessionId:s}}let i=null,n=null;if(u.localStorage)try{const r=u.localStorage.getItem(k);if(r){const o=w(r);i=o.forcedGuideKey,n=o.previewSessionId}}catch{}return{forcedGuideKey:i,previewSessionId:n}},w=u=>{try{const e=JSON.parse(u);return{forcedGuideKey:(e==null?void 0:e.forcedGuideKey)??null,previewSessionId:(e==null?void 0:e.previewSessionId)??null}}catch{return{forcedGuideKey:null,previewSessionId:null}}},S=(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||!R(a,{location:n,filters:e,debug:u.debug}))&&t.set(r,a)}return t.metadata={guideGroup:s},t},R=(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 P{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",()=>{this.knock.log("[Guide] .handleLocationChange");const e=p();if(!(e!=null&&e.location))return;const t=e.location.href;if(this.store.state.location===t)return;this.knock.log(`[Guide] Detected a location change: ${t}`);const s=this.store.state.debug,i=f();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,throttleCheckInterval:r=C}=i,o=p(),a=n?o==null?void 0:o.location.href:void 0,l=f();this.store=new _.Store({guideGroups:[],guideGroupDisplayLogs:{},guides:{},previewGuides:{},queries:{},location:a,counter:0,debug:l});const{socket:h}=this.knock.client();this.socket=h,this.socketChannelTopic=`guides:${t}`,n&&this.listenForLocationChangesFromWindow(),r&&this.startCounterInterval(r),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(e){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.removeLocationChangeEventListeners(),this.clearGroupStage(),this.clearCounterInterval()}async fetch(e){this.knock.log("[Guide] .fetch"),this.knock.failIfNotAuthenticated();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{this.knock.log("[Guide] Fetching all eligible guides");const r=await this.knock.user.getGuides(this.channelId,t);n={status:"ok"};const{entries:o,guide_groups:a,guide_group_display_logs:l}=r;this.knock.log("[Guide] Loading fetched guides"),this.store.setState(h=>({...h,guideGroups:(a==null?void 0:a.length)>0?a:[d.mockDefaultGroup(o)],guideGroupDisplayLogs:l||{},guides:d.byKey(o.map(y=>this.localCopy(y))),queries:{...h.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>=E){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.knock.log(`[Guide] .setLocation (loc=${e})`),this.clearGroupStage(),this.knock.log("[Guide] Updating the tracked location"),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}})}exitDebugMode(){this.knock.log("[Guide] Exiting debug mode");const e=p();if(e!=null&&e.localStorage)try{e.localStorage.removeItem(k)}catch{}if(this.store.setState(t=>({...t,debug:{forcedGuideKey:null,previewSessionId:null},previewGuides:{}})),e){const t=new URL(e.location.href);(t.searchParams.has(g.GUIDE_KEY)||t.searchParams.has(g.PREVIEW_SESSION_ID))&&(t.searchParams.delete(g.GUIDE_KEY),t.searchParams.delete(g.PREVIEW_SESSION_ID),e.location.href=t.toString())}}selectGuides(e,t={}){if(this.knock.log(`[Guide] .selectGuides (filters: ${d.formatFilters(t)}; state: ${d.formatState(e)})`),Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0)return this.knock.log("[Guide] Exiting selection (no guides)"),[];const s=S(e,t);return s.size===0?(this.knock.log("[Guide] Selection returned zero result"),[]):[...s.values()]}selectGuide(e,t={}){if(this.knock.log(`[Guide] .selectGuide (filters: ${d.formatFilters(t)}; state: ${d.formatState(e)})`),Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0){this.knock.log("[Guide] Exiting selection (no guides)");return}const s=S(e,t);if(s.size===0){this.knock.log("[Guide] Selection found zero result");return}const[i,n]=[...s][0];if(this.knock.log(`[Guide] Selection found: \`${n.key}\` (total: ${s.size})`),n.bypass_global_group_limit)return this.knock.log(`[Guide] Returning the unthrottled guide: ${n.key}`),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)){this.knock.log(`[Guide] Throttling the selected guide: ${n.key}`);return}switch(this.stage||(this.stage=this.openGroupStage()),this.stage.status){case"open":{this.knock.log(`[Guide] Adding to the group stage: ${n.key}`),this.stage.ordered[i]=n.key;return}case"patch":{this.knock.log(`[Guide] Patching the group stage: ${n.key}`),this.stage.ordered[i]=n.key;const a=this.stage.resolved===n.key?n:void 0;return this.knock.log(`[Guide] Returning \`${a==null?void 0:a.key}\` (stage: ${d.formatGroupStage(this.stage)})`),a}case"closed":{const a=this.stage.resolved===n.key?n:void 0;return this.knock.log(`[Guide] Returning \`${a==null?void 0:a.key}\` (stage: ${d.formatGroupStage(this.stage)})`),a}}}openGroupStage(){this.knock.log("[Guide] Opening a new group stage");const{orderResolutionDuration:e=I}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.stage={status:"open",ordered:[],timeoutId:t},this.stage}closePendingGroupStage(){if(this.knock.log("[Guide] .closePendingGroupStage"),!this.stage||this.stage.status==="closed")return;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.knock.log(`[Guide] Closing the current group stage: resolved=${e}`),this.stage={...this.stage,status:"closed",resolved:e,timeoutId:null},this.stage}patchClosedGroupStage(){var s;if(this.knock.log("[Guide] .patchClosedGroupStage"),((s=this.stage)==null?void 0:s.status)!=="closed")return;const{orderResolutionDuration:e=0}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.ensureClearTimeout(),this.knock.log("[Guide] Patching the current group stage"),this.stage={...this.stage,status:"patch",ordered:[],timeoutId:t},this.stage}clearGroupStage(){this.knock.log("[Guide] .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 b.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=G(this.knock.userId);return s?`${i}?${s}`:i}setStepMessageAttrs(e,t,s){let i;return s.archived_at&&this.clearGroupStage(),this.store.setState(n=>{let r=n.guides[e];if(!r)return n;const o=r.steps.map(h=>(h.ref!==t||(h.message={...h.message,...s},i=h),h));r=i?{...r,steps:o}:r;const a={...n.guides,[r.key]:r},l=s.archived_at&&!r.bypass_global_group_limit?{...n.guideGroupDisplayLogs,[d.DEFAULT_GROUP_KEY]:s.archived_at}:n.guideGroupDisplayLogs;return{...n,guides:a,guideGroupDisplayLogs:l}}),i}buildEngagementEventBaseParams(e,t){return{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 l={...o[a],bypass_global_group_limit:!0};return{...o,[a]:l}},r),r=n.reduce((o,a)=>{if(!o[a])return o;const l={...o[a],bypass_global_group_limit:!1};return{...o,[a]:l}},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=p();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")}removeLocationChangeEventListeners(){const e=p();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=g;exports.KnockGuideClient=P;exports.guidesApiRootPath=G;
|
|
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 _=require("@tanstack/store"),b=require("urlpattern-polyfill"),d=require("./helpers.js"),I=50,C=30*1e3,E=3,g={GUIDE_KEY:"knock_guide_key",PREVIEW_SESSION_ID:"knock_preview_session_id"},k="knock_guide_debug",p=()=>{if(typeof window<"u")return window},G=u=>`/v1/users/${u}/guides`,f=()=>{const u=p();if(!u)return{forcedGuideKey:null,previewSessionId:null};const e=new URLSearchParams(u.location.search),t=e.get(g.GUIDE_KEY),s=e.get(g.PREVIEW_SESSION_ID);if(t||s){if(u.localStorage)try{const r={forcedGuideKey:t,previewSessionId:s};u.localStorage.setItem(k,JSON.stringify(r))}catch{}return{forcedGuideKey:t,previewSessionId:s}}let i=null,n=null;if(u.localStorage)try{const r=u.localStorage.getItem(k);if(r){const o=w(r);i=o.forcedGuideKey,n=o.previewSessionId}}catch{}return{forcedGuideKey:i,previewSessionId:n}},w=u=>{try{const e=JSON.parse(u);return{forcedGuideKey:(e==null?void 0:e.forcedGuideKey)??null,previewSessionId:(e==null?void 0:e.previewSessionId)??null}}catch{return{forcedGuideKey:null,previewSessionId:null}}},S=(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||!R(a,{location:n,filters:e,debug:u.debug}))&&t.set(r,a)}return t.metadata={guideGroup:s},t},R=(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 P{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",()=>{this.knock.log("[Guide] .handleLocationChange");const e=p();if(!(e!=null&&e.location))return;const t=e.location.href;if(this.store.state.location===t)return;this.knock.log(`[Guide] Detected a location change: ${t}`);const s=this.store.state.debug,i=f();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,throttleCheckInterval:r=C}=i,o=p(),a=n?o==null?void 0:o.location.href:void 0,l=f();this.store=new _.Store({guideGroups:[],guideGroupDisplayLogs:{},guides:{},previewGuides:{},queries:{},location:a,counter:0,debug:l});const{socket:h}=this.knock.client();this.socket=h,this.socketChannelTopic=`guides:${t}`,n&&this.listenForLocationChangesFromWindow(),r&&this.startCounterInterval(r),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(e){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.removeLocationChangeEventListeners(),this.clearGroupStage(),this.clearCounterInterval()}async fetch(e){this.knock.log("[Guide] .fetch"),this.knock.failIfNotAuthenticated();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{this.knock.log("[Guide] Fetching all eligible guides");const r=await this.knock.user.getGuides(this.channelId,t);n={status:"ok"};const{entries:o,guide_groups:a,guide_group_display_logs:l}=r;this.knock.log("[Guide] Loading fetched guides"),this.store.setState(h=>({...h,guideGroups:(a==null?void 0:a.length)>0?a:[d.mockDefaultGroup(o)],guideGroupDisplayLogs:l||{},guides:d.byKey(o.map(y=>this.localCopy(y))),queries:{...h.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>=E){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.knock.log(`[Guide] .setLocation (loc=${e})`),this.clearGroupStage(),this.knock.log("[Guide] Updating the tracked location"),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}})}exitDebugMode(){this.knock.log("[Guide] Exiting debug mode");const e=p();if(e!=null&&e.localStorage)try{e.localStorage.removeItem(k)}catch{}if(this.store.setState(t=>({...t,debug:{forcedGuideKey:null,previewSessionId:null},previewGuides:{}})),e){const t=new URL(e.location.href);(t.searchParams.has(g.GUIDE_KEY)||t.searchParams.has(g.PREVIEW_SESSION_ID))&&(t.searchParams.delete(g.GUIDE_KEY),t.searchParams.delete(g.PREVIEW_SESSION_ID),e.location.href=t.toString())}}selectGuides(e,t={}){if(this.knock.log(`[Guide] .selectGuides (filters: ${d.formatFilters(t)}; state: ${d.formatState(e)})`),Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0)return this.knock.log("[Guide] Exiting selection (no guides)"),[];const s=S(e,t);return s.size===0?(this.knock.log("[Guide] Selection returned zero result"),[]):[...s.values()]}selectGuide(e,t={}){if(this.knock.log(`[Guide] .selectGuide (filters: ${d.formatFilters(t)}; state: ${d.formatState(e)})`),Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0){this.knock.log("[Guide] Exiting selection (no guides)");return}const s=S(e,t);if(s.size===0){this.knock.log("[Guide] Selection found zero result");return}const[i,n]=[...s][0];if(this.knock.log(`[Guide] Selection found: \`${n.key}\` (total: ${s.size})`),n.bypass_global_group_limit)return this.knock.log(`[Guide] Returning the unthrottled guide: ${n.key}`),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)){this.knock.log(`[Guide] Throttling the selected guide: ${n.key}`);return}switch(this.stage||(this.stage=this.openGroupStage()),this.stage.status){case"open":{this.knock.log(`[Guide] Adding to the group stage: ${n.key}`),this.stage.ordered[i]=n.key;return}case"patch":{this.knock.log(`[Guide] Patching the group stage: ${n.key}`),this.stage.ordered[i]=n.key;const a=this.stage.resolved===n.key?n:void 0;return this.knock.log(`[Guide] Returning \`${a==null?void 0:a.key}\` (stage: ${d.formatGroupStage(this.stage)})`),a}case"closed":{const a=this.stage.resolved===n.key?n:void 0;return this.knock.log(`[Guide] Returning \`${a==null?void 0:a.key}\` (stage: ${d.formatGroupStage(this.stage)})`),a}}}openGroupStage(){this.knock.log("[Guide] Opening a new group stage");const{orderResolutionDuration:e=I}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.stage={status:"open",ordered:[],timeoutId:t},this.stage}closePendingGroupStage(){if(this.knock.log("[Guide] .closePendingGroupStage"),!this.stage||this.stage.status==="closed")return;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.knock.log(`[Guide] Closing the current group stage: resolved=${e}`),this.stage={...this.stage,status:"closed",resolved:e,timeoutId:null},this.stage}patchClosedGroupStage(){var s;if(this.knock.log("[Guide] .patchClosedGroupStage"),((s=this.stage)==null?void 0:s.status)!=="closed")return;const{orderResolutionDuration:e=0}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.ensureClearTimeout(),this.knock.log("[Guide] Patching the current group stage"),this.stage={...this.stage,status:"patch",ordered:[],timeoutId:t},this.stage}clearGroupStage(){this.knock.log("[Guide] .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};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 b.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=G(this.knock.userId);return s?`${i}?${s}`:i}setStepMessageAttrs(e,t,s){let i;return s.archived_at&&this.clearGroupStage(),this.store.setState(n=>{let r=n.guides[e];if(!r)return n;const o=r.steps.map(h=>(h.ref!==t||(h.message={...h.message,...s},i=h),h));r=i?{...r,steps:o}:r;const a={...n.guides,[r.key]:r},l=s.archived_at&&!r.bypass_global_group_limit?{...n.guideGroupDisplayLogs,[d.DEFAULT_GROUP_KEY]:s.archived_at}:n.guideGroupDisplayLogs;return{...n,guides:a,guideGroupDisplayLogs:l}}),i}buildEngagementEventBaseParams(e,t){return{channel_id:e.channel_id,guide_key:e.key,guide_id:e.id,guide_step_ref:t.ref,tenant:this.targetParams.tenant}}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 l={...o[a],bypass_global_group_limit:!0};return{...o,[a]:l}},r),r=n.reduce((o,a)=>{if(!o[a])return o;const l={...o[a],bypass_global_group_limit:!1};return{...o,[a]:l}},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=p();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")}removeLocationChangeEventListeners(){const e=p();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=g;exports.KnockGuideClient=P;exports.guidesApiRootPath=G;
|
|
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 formatGroupStage,\n formatState,\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\nconst DEBUG_STORAGE_KEY = \"knock_guide_debug\";\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 from URL or local storage\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 urlGuideKey = urlParams.get(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n const urlPreviewSessionId = urlParams.get(\n DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID,\n );\n\n // If URL params exist, persist them to localStorage and return them\n if (urlGuideKey || urlPreviewSessionId) {\n if (win.localStorage) {\n try {\n const debugState = {\n forcedGuideKey: urlGuideKey,\n previewSessionId: urlPreviewSessionId,\n };\n win.localStorage.setItem(DEBUG_STORAGE_KEY, JSON.stringify(debugState));\n } catch {\n // Silently fail in privacy mode\n }\n }\n return {\n forcedGuideKey: urlGuideKey,\n previewSessionId: urlPreviewSessionId,\n };\n }\n\n // Check local storage if no URL params\n let storedGuideKey = null;\n let storedPreviewSessionId = null;\n\n if (win.localStorage) {\n try {\n const storedDebugState = win.localStorage.getItem(DEBUG_STORAGE_KEY);\n if (storedDebugState) {\n const parsedDebugState = safeJsonParseDebugParams(storedDebugState);\n storedGuideKey = parsedDebugState.forcedGuideKey;\n storedPreviewSessionId = parsedDebugState.previewSessionId;\n }\n } catch {\n // Silently fail in privacy mode\n }\n }\n\n return {\n forcedGuideKey: storedGuideKey,\n previewSessionId: storedPreviewSessionId,\n };\n};\n\nconst safeJsonParseDebugParams = (value: string): DebugState => {\n try {\n const parsed = JSON.parse(value);\n return {\n forcedGuideKey: parsed?.forcedGuideKey ?? null,\n previewSessionId: parsed?.previewSessionId ?? null,\n };\n } catch {\n return {\n forcedGuideKey: null,\n previewSessionId: null,\n };\n }\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 {\n trackLocationFromWindow = true,\n throttleCheckInterval = DEFAULT_COUNTER_INCREMENT_INTERVAL,\n } = 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 if (throttleCheckInterval) {\n // Start the counter loop to increment at an interval.\n this.startCounterInterval(throttleCheckInterval);\n }\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(delay: number) {\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.removeLocationChangeEventListeners();\n this.clearGroupStage();\n this.clearCounterInterval();\n }\n\n async fetch(opts?: { filters?: QueryFilterParams }) {\n this.knock.log(\"[Guide] .fetch\");\n this.knock.failIfNotAuthenticated();\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 this.knock.log(\"[Guide] Fetching all eligible guides\");\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.knock.log(\"[Guide] Loading fetched guides\");\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 this.knock.log(`[Guide] .setLocation (loc=${href})`);\n\n // Make sure to clear out the stage.\n this.clearGroupStage();\n\n this.knock.log(\"[Guide] Updating the tracked location\");\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 exitDebugMode() {\n this.knock.log(\"[Guide] Exiting debug mode\");\n\n // Clear localStorage debug params\n const win = checkForWindow();\n if (win?.localStorage) {\n try {\n win.localStorage.removeItem(DEBUG_STORAGE_KEY);\n } catch {\n // Silently fail in privacy mode\n }\n }\n\n // Clear debug state from store\n this.store.setState((state) => ({\n ...state,\n debug: { forcedGuideKey: null, previewSessionId: null },\n previewGuides: {}, // Clear preview guides when exiting debug mode\n }));\n\n // Remove URL query params if present\n // Only update the URL if params need to be cleared to avoid unnecessary navigations\n if (win) {\n const url = new URL(win.location.href);\n if (\n url.searchParams.has(DEBUG_QUERY_PARAMS.GUIDE_KEY) ||\n url.searchParams.has(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID)\n ) {\n url.searchParams.delete(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n url.searchParams.delete(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID);\n win.location.href = url.toString();\n }\n }\n }\n\n //\n // Store selector\n //\n\n selectGuides<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C>[] {\n this.knock.log(\n `[Guide] .selectGuides (filters: ${formatFilters(filters)}; state: ${formatState(state)})`,\n );\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n this.knock.log(\"[Guide] Exiting selection (no guides)\");\n return [];\n }\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 this.knock.log(\n `[Guide] .selectGuide (filters: ${formatFilters(filters)}; state: ${formatState(state)})`,\n );\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n this.knock.log(\"[Guide] Exiting selection (no guides)\");\n return undefined;\n }\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection found zero result\");\n return undefined;\n }\n\n const [index, guide] = [...result][0]!;\n this.knock.log(\n `[Guide] Selection found: \\`${guide.key}\\` (total: ${result.size})`,\n );\n\n // If a guide ignores the group limit, then return immediately to render\n // always.\n if (guide.bypass_global_group_limit) {\n this.knock.log(`[Guide] Returning the unthrottled guide: ${guide.key}`);\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) {\n this.knock.log(`[Guide] Throttling the selected guide: ${guide.key}`);\n return undefined;\n }\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] Adding 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\n const ret = this.stage.resolved === guide.key ? guide : undefined;\n this.knock.log(\n `[Guide] Returning \\`${ret?.key}\\` (stage: ${formatGroupStage(this.stage)})`,\n );\n return ret;\n }\n\n case \"closed\": {\n const ret = this.stage.resolved === guide.key ? guide : undefined;\n this.knock.log(\n `[Guide] Returning \\`${ret?.key}\\` (stage: ${formatGroupStage(this.stage)})`,\n );\n return ret;\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 this.knock.log(\"[Guide] .closePendingGroupStage\");\n if (!this.stage || this.stage.status === \"closed\") return;\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.knock.log(\n `[Guide] Closing the current group stage: resolved=${resolved}`,\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 this.knock.log(\"[Guide] .patchClosedGroupStage\");\n if (this.stage?.status !== \"closed\") return;\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.knock.log(\"[Guide] Patching the current group stage\");\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 this.knock.log(\"[Guide] .clearGroupStage\");\n if (!this.stage) return;\n\n this.knock.log(\"[Guide] Clearing the current group stage\");\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 let 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 // If updated, return the guide as a new object so useStore can trigger.\n guide = updatedStep ? { ...guide, steps } : guide;\n\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 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 this.knock.log(`[Guide] .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] Detected a location change: ${href}`);\n\n // If entering debug mode, fetch all guides.\n const currentDebugParams = this.store.state.debug;\n const newDebugParams = detectDebugParams();\n\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 removeLocationChangeEventListeners() {\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","DEBUG_STORAGE_KEY","checkForWindow","guidesApiRootPath","userId","detectDebugParams","win","urlParams","urlGuideKey","urlPreviewSessionId","debugState","storedGuideKey","storedPreviewSessionId","storedDebugState","parsedDebugState","safeJsonParseDebugParams","value","parsed","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","throttleCheckInterval","Store","maybeSocket","delay","opts","queryParams","queryKey","maybeQueryStatus","queryStatus","data","entries","groups","guide_group_display_logs","mockDefaultGroup","byKey","g","e","params","newChannel","eventType","payload","resp","event","additionalParams","previewGuides","_a","formatFilters","formatState","throttleWindowStartedAt","DEFAULT_GROUP_KEY","checkIfThrottled","ret","formatGroupStage","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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eC,EAAwB,CAElE,MAAA,EAAQD,EAAE,gBAAoB,EAAQC,EAAE,gBACxCD,EAAE,mBAAqBC,EAAE,gBAAA,CAIrB,oCAAqC,CAC3C,MAAM9G,EAAMJ,EAAe,EAC3B,GAAII,GAAA,MAAAA,EAAK,QAAS,CAEZA,EAAA,iBAAiB,WAAY,KAAK,oBAAoB,EAGtDA,EAAA,iBAAiB,aAAc,KAAK,oBAAoB,EAGtD,MAAA+G,EAAc/G,EAAI,QAAQ,UAC1BgH,EAAiBhH,EAAI,QAAQ,aAGnCA,EAAI,QAAQ,UAAY,IAAI,MAAM+G,EAAa,CAC7C,MAAO,CAACE,EAAQC,EAASC,IAAS,CACxB,QAAA,MAAMF,EAAQC,EAASC,CAAI,EACnC,WAAW,IAAM,CACf,KAAK,qBAAqB,GACzB,CAAC,CAAA,CACN,CACD,EACDnH,EAAI,QAAQ,aAAe,IAAI,MAAMgH,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,CAGF,oCAAqC,CACnC,MAAMhH,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 formatGroupStage,\n formatState,\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\nconst DEBUG_STORAGE_KEY = \"knock_guide_debug\";\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 from URL or local storage\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 urlGuideKey = urlParams.get(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n const urlPreviewSessionId = urlParams.get(\n DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID,\n );\n\n // If URL params exist, persist them to localStorage and return them\n if (urlGuideKey || urlPreviewSessionId) {\n if (win.localStorage) {\n try {\n const debugState = {\n forcedGuideKey: urlGuideKey,\n previewSessionId: urlPreviewSessionId,\n };\n win.localStorage.setItem(DEBUG_STORAGE_KEY, JSON.stringify(debugState));\n } catch {\n // Silently fail in privacy mode\n }\n }\n return {\n forcedGuideKey: urlGuideKey,\n previewSessionId: urlPreviewSessionId,\n };\n }\n\n // Check local storage if no URL params\n let storedGuideKey = null;\n let storedPreviewSessionId = null;\n\n if (win.localStorage) {\n try {\n const storedDebugState = win.localStorage.getItem(DEBUG_STORAGE_KEY);\n if (storedDebugState) {\n const parsedDebugState = safeJsonParseDebugParams(storedDebugState);\n storedGuideKey = parsedDebugState.forcedGuideKey;\n storedPreviewSessionId = parsedDebugState.previewSessionId;\n }\n } catch {\n // Silently fail in privacy mode\n }\n }\n\n return {\n forcedGuideKey: storedGuideKey,\n previewSessionId: storedPreviewSessionId,\n };\n};\n\nconst safeJsonParseDebugParams = (value: string): DebugState => {\n try {\n const parsed = JSON.parse(value);\n return {\n forcedGuideKey: parsed?.forcedGuideKey ?? null,\n previewSessionId: parsed?.previewSessionId ?? null,\n };\n } catch {\n return {\n forcedGuideKey: null,\n previewSessionId: null,\n };\n }\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 {\n trackLocationFromWindow = true,\n throttleCheckInterval = DEFAULT_COUNTER_INCREMENT_INTERVAL,\n } = 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 if (throttleCheckInterval) {\n // Start the counter loop to increment at an interval.\n this.startCounterInterval(throttleCheckInterval);\n }\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(delay: number) {\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.removeLocationChangeEventListeners();\n this.clearGroupStage();\n this.clearCounterInterval();\n }\n\n async fetch(opts?: { filters?: QueryFilterParams }) {\n this.knock.log(\"[Guide] .fetch\");\n this.knock.failIfNotAuthenticated();\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 this.knock.log(\"[Guide] Fetching all eligible guides\");\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.knock.log(\"[Guide] Loading fetched guides\");\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 this.knock.log(`[Guide] .setLocation (loc=${href})`);\n\n // Make sure to clear out the stage.\n this.clearGroupStage();\n\n this.knock.log(\"[Guide] Updating the tracked location\");\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 exitDebugMode() {\n this.knock.log(\"[Guide] Exiting debug mode\");\n\n // Clear localStorage debug params\n const win = checkForWindow();\n if (win?.localStorage) {\n try {\n win.localStorage.removeItem(DEBUG_STORAGE_KEY);\n } catch {\n // Silently fail in privacy mode\n }\n }\n\n // Clear debug state from store\n this.store.setState((state) => ({\n ...state,\n debug: { forcedGuideKey: null, previewSessionId: null },\n previewGuides: {}, // Clear preview guides when exiting debug mode\n }));\n\n // Remove URL query params if present\n // Only update the URL if params need to be cleared to avoid unnecessary navigations\n if (win) {\n const url = new URL(win.location.href);\n if (\n url.searchParams.has(DEBUG_QUERY_PARAMS.GUIDE_KEY) ||\n url.searchParams.has(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID)\n ) {\n url.searchParams.delete(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n url.searchParams.delete(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID);\n win.location.href = url.toString();\n }\n }\n }\n\n //\n // Store selector\n //\n\n selectGuides<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C>[] {\n this.knock.log(\n `[Guide] .selectGuides (filters: ${formatFilters(filters)}; state: ${formatState(state)})`,\n );\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n this.knock.log(\"[Guide] Exiting selection (no guides)\");\n return [];\n }\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 this.knock.log(\n `[Guide] .selectGuide (filters: ${formatFilters(filters)}; state: ${formatState(state)})`,\n );\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n this.knock.log(\"[Guide] Exiting selection (no guides)\");\n return undefined;\n }\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection found zero result\");\n return undefined;\n }\n\n const [index, guide] = [...result][0]!;\n this.knock.log(\n `[Guide] Selection found: \\`${guide.key}\\` (total: ${result.size})`,\n );\n\n // If a guide ignores the group limit, then return immediately to render\n // always.\n if (guide.bypass_global_group_limit) {\n this.knock.log(`[Guide] Returning the unthrottled guide: ${guide.key}`);\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) {\n this.knock.log(`[Guide] Throttling the selected guide: ${guide.key}`);\n return undefined;\n }\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] Adding 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\n const ret = this.stage.resolved === guide.key ? guide : undefined;\n this.knock.log(\n `[Guide] Returning \\`${ret?.key}\\` (stage: ${formatGroupStage(this.stage)})`,\n );\n return ret;\n }\n\n case \"closed\": {\n const ret = this.stage.resolved === guide.key ? guide : undefined;\n this.knock.log(\n `[Guide] Returning \\`${ret?.key}\\` (stage: ${formatGroupStage(this.stage)})`,\n );\n return ret;\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 this.knock.log(\"[Guide] .closePendingGroupStage\");\n if (!this.stage || this.stage.status === \"closed\") return;\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.knock.log(\n `[Guide] Closing the current group stage: resolved=${resolved}`,\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 this.knock.log(\"[Guide] .patchClosedGroupStage\");\n if (this.stage?.status !== \"closed\") return;\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.knock.log(\"[Guide] Patching the current group stage\");\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 this.knock.log(\"[Guide] .clearGroupStage\");\n if (!this.stage) return;\n\n this.knock.log(\"[Guide] Clearing the current group stage\");\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 };\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 let 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 // If updated, return the guide as a new object so useStore can trigger.\n guide = updatedStep ? { ...guide, steps } : guide;\n\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 channel_id: guide.channel_id,\n guide_key: guide.key,\n guide_id: guide.id,\n guide_step_ref: step.ref,\n // Can be used for scoping guide messages.\n tenant: this.targetParams.tenant,\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 this.knock.log(`[Guide] .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] Detected a location change: ${href}`);\n\n // If entering debug mode, fetch all guides.\n const currentDebugParams = this.store.state.debug;\n const newDebugParams = detectDebugParams();\n\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 removeLocationChangeEventListeners() {\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","DEBUG_STORAGE_KEY","checkForWindow","guidesApiRootPath","userId","detectDebugParams","win","urlParams","urlGuideKey","urlPreviewSessionId","debugState","storedGuideKey","storedPreviewSessionId","storedDebugState","parsedDebugState","safeJsonParseDebugParams","value","parsed","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","throttleCheckInterval","Store","maybeSocket","delay","opts","queryParams","queryKey","maybeQueryStatus","queryStatus","data","entries","groups","guide_group_display_logs","mockDefaultGroup","byKey","g","e","params","newChannel","eventType","payload","resp","event","additionalParams","previewGuides","_a","formatFilters","formatState","throttleWindowStartedAt","DEFAULT_GROUP_KEY","checkIfThrottled","ret","formatGroupStage","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":"kVAqDMA,EAAoC,GAIpCC,EAAqC,GAAK,IAG1CC,EAAwB,EAGjBC,EAAqB,CAChC,UAAW,kBACX,mBAAoB,0BACtB,EAEMC,EAAoB,oBAGpBC,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,EA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,EAASC,IAAS,CACxB,QAAA,MAAMF,EAAQC,EAASC,CAAI,EACnC,WAAW,IAAM,CACf,KAAK,qBAAqB,GACzB,CAAC,CAAA,CACN,CACD,EACDnH,EAAI,QAAQ,aAAe,IAAI,MAAMgH,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,CAGF,oCAAqC,CACnC,MAAMhH,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,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
${
|
|
1
|
+
"use strict";var d=Object.defineProperty;var f=(s,e,i)=>e in s?d(s,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):s[e]=i;var t=(s,e,i)=>f(s,typeof e!="symbol"?e+"":e,i);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("jwt-decode"),g=require("./api.js"),T=require("./clients/feed/index.js"),w=require("./clients/messages/index.js"),y=require("./clients/ms-teams/index.js"),x=require("./clients/objects/index.js"),p=require("./clients/preferences/index.js"),m=require("./clients/slack/index.js"),C=require("./clients/users/index.js"),E="https://api.knock.app";class b{constructor(e,i={}){t(this,"host");t(this,"apiClient",null);t(this,"userId");t(this,"userToken");t(this,"logLevel");t(this,"branch");t(this,"tokenExpirationTimer",null);t(this,"feeds",new T.default(this));t(this,"objects",new x.default(this));t(this,"preferences",new p.default(this));t(this,"slack",new m.default(this));t(this,"msTeams",new y.default(this));t(this,"user",new C.default(this));t(this,"messages",new w.default(this));if(this.apiKey=e,this.host=i.host||E,this.logLevel=i.logLevel,this.branch=i.branch||void 0,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:A,...u}=e;this.user.identify(u).catch(h=>{const r=h instanceof Error?h.message:"Unknown error";this.log(`Error identifying user ${e.id} inline:
|
|
2
|
+
${r}`)})}}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 g.default({apiKey:this.apiKey,host:this.host,userToken:this.userToken,branch:this.branch})}async maybeScheduleUserTokenExpiration(e,i=3e4){if(!this.userToken)return;const n=k.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}}exports.default=b;
|
|
3
3
|
//# 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 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).catch((err) => {\n const errorMessage =\n err instanceof Error ? err.message : \"Unknown error\";\n\n this.log(\n `Error identifying user ${userIdOrUserWithProperties.id} inline:\\n${errorMessage}`,\n );\n });\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 return undefined;\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","err","errorMessage","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,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}
|
|
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 public readonly branch?: string;\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 this.branch = options.branch || undefined;\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).catch((err) => {\n const errorMessage =\n err instanceof Error ? err.message : \"Unknown error\";\n\n this.log(\n `Error identifying user ${userIdOrUserWithProperties.id} inline:\\n${errorMessage}`,\n );\n });\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 branch: this.branch,\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 return undefined;\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","err","errorMessage","checkUserToken","_a","message","force","ApiClient","callbackFn","timeBeforeExpirationInMs","decoded","jwtDecode","expiresAtMs","nowMs","msInFuture","newToken"],"mappings":"2lBAmBMA,EAAe,wBAErB,MAAMC,CAAM,CAgBV,YACWC,EACTC,EAAwB,GACxB,CAlBKC,EAAA,aACCA,EAAA,iBAA8B,MAC/BA,EAAA,eACAA,EAAA,kBACAA,EAAA,iBACSA,EAAA,eACRA,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,GAaxC,GAVS,KAAA,OAAAT,EAGJ,KAAA,KAAOC,EAAQ,MAAQH,EAC5B,KAAK,SAAWG,EAAQ,SACnB,KAAA,OAASA,EAAQ,QAAU,OAEhC,KAAK,IAAI,4BAA4B,EAGjC,KAAK,QAAU,KAAK,OAAO,WAAW,KAAK,EAC7C,MAAM,IAAI,MACR,qFACF,CACF,CAGF,QAAS,CAEH,OAAC,KAAK,YACH,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K,sBACP,aAAa,KAAK,oBAAoB,GAEpCC,EAAA,KAAK,YAAL,MAAAA,EAAgB,QAAU,KAAK,UAAU,OAAO,eAC7C,KAAA,UAAU,OAAO,WAAW,CACnC,CAGF,IAAIC,EAAiBC,EAAQ,GAAO,EAC9B,KAAK,WAAa,SAAWA,IACvB,QAAA,IAAI,WAAWD,CAAO,EAAE,CAClC,CAMM,iBAAkB,CACxB,OAAO,IAAIE,EAAAA,QAAU,CACnB,OAAQ,KAAK,OACb,KAAM,KAAK,KACX,UAAW,KAAK,UAChB,OAAQ,KAAK,MAAA,CACd,CAAA,CAGH,MAAc,iCACZC,EACAC,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,UAAUrB,EAAwD,CACxE,GACE,OAAOA,GAA+B,UACtC,CAACA,EAEM,OAAAA,EAGT,GAAIA,GAAA,MAAAA,EAA4B,GAC9B,OAAOA,EAA2B,EAG7B,CAEX"}
|
package/dist/esm/api.mjs
CHANGED
|
@@ -1,34 +1,37 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var
|
|
4
|
-
import
|
|
5
|
-
import
|
|
1
|
+
var n = Object.defineProperty;
|
|
2
|
+
var a = (r, e, t) => e in r ? n(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
|
|
3
|
+
var s = (r, e, t) => a(r, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
import o from "axios";
|
|
5
|
+
import i from "axios-retry";
|
|
6
6
|
import { Socket as u } from "phoenix";
|
|
7
7
|
class k {
|
|
8
8
|
constructor(e) {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
this
|
|
9
|
+
s(this, "host");
|
|
10
|
+
s(this, "apiKey");
|
|
11
|
+
s(this, "userToken");
|
|
12
|
+
s(this, "branch");
|
|
13
|
+
s(this, "axiosClient");
|
|
14
|
+
s(this, "socket");
|
|
15
|
+
this.host = e.host, this.apiKey = e.apiKey, this.userToken = e.userToken || null, this.branch = e.branch || null, this.axiosClient = o.create({
|
|
15
16
|
baseURL: this.host,
|
|
16
17
|
headers: {
|
|
17
18
|
Accept: "application/json",
|
|
18
19
|
"Content-Type": "application/json",
|
|
19
20
|
Authorization: `Bearer ${this.apiKey}`,
|
|
20
21
|
"X-Knock-User-Token": this.userToken,
|
|
21
|
-
"X-Knock-Client": this.getKnockClientHeader()
|
|
22
|
+
"X-Knock-Client": this.getKnockClientHeader(),
|
|
23
|
+
"X-Knock-Branch": this.branch
|
|
22
24
|
}
|
|
23
25
|
}), typeof window < "u" && (this.socket = new u(`${this.host.replace("http", "ws")}/ws/v1`, {
|
|
24
26
|
params: {
|
|
25
27
|
user_token: this.userToken,
|
|
26
|
-
api_key: this.apiKey
|
|
28
|
+
api_key: this.apiKey,
|
|
29
|
+
branch_slug: this.branch
|
|
27
30
|
}
|
|
28
|
-
})),
|
|
31
|
+
})), i(this.axiosClient, {
|
|
29
32
|
retries: 3,
|
|
30
33
|
retryCondition: this.canRetryRequest,
|
|
31
|
-
retryDelay:
|
|
34
|
+
retryDelay: i.exponentialDelay
|
|
32
35
|
});
|
|
33
36
|
}
|
|
34
37
|
async makeRequest(e) {
|
|
@@ -50,10 +53,10 @@ class k {
|
|
|
50
53
|
}
|
|
51
54
|
}
|
|
52
55
|
canRetryRequest(e) {
|
|
53
|
-
return
|
|
56
|
+
return i.isNetworkError(e) ? !0 : e.response ? e.response.status >= 500 && e.response.status <= 599 || e.response.status === 429 : !1;
|
|
54
57
|
}
|
|
55
58
|
getKnockClientHeader() {
|
|
56
|
-
return "Knock/ClientJS 0.19.
|
|
59
|
+
return "Knock/ClientJS 0.19.4";
|
|
57
60
|
}
|
|
58
61
|
}
|
|
59
62
|
export {
|