@knocklabs/client 0.11.4 → 0.12.0-rc.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -6
  3. package/dist/cjs/api.js.map +1 -1
  4. package/dist/cjs/clients/feed/feed.js.map +1 -1
  5. package/dist/cjs/clients/feed/index.js.map +1 -1
  6. package/dist/cjs/clients/feed/store.js +1 -1
  7. package/dist/cjs/clients/feed/store.js.map +1 -1
  8. package/dist/cjs/clients/feed/utils.js.map +1 -1
  9. package/dist/cjs/clients/messages/index.js.map +1 -1
  10. package/dist/cjs/clients/ms-teams/index.js.map +1 -1
  11. package/dist/cjs/clients/objects/index.js.map +1 -1
  12. package/dist/cjs/clients/preferences/index.js.map +1 -1
  13. package/dist/cjs/clients/slack/index.js.map +1 -1
  14. package/dist/cjs/clients/users/index.js.map +1 -1
  15. package/dist/cjs/knock.js.map +1 -1
  16. package/dist/cjs/networkStatus.js.map +1 -1
  17. package/dist/esm/api.mjs.map +1 -1
  18. package/dist/esm/clients/feed/feed.mjs.map +1 -1
  19. package/dist/esm/clients/feed/index.mjs.map +1 -1
  20. package/dist/esm/clients/feed/store.mjs +18 -22
  21. package/dist/esm/clients/feed/store.mjs.map +1 -1
  22. package/dist/esm/clients/feed/utils.mjs.map +1 -1
  23. package/dist/esm/clients/messages/index.mjs.map +1 -1
  24. package/dist/esm/clients/ms-teams/index.mjs.map +1 -1
  25. package/dist/esm/clients/objects/index.mjs.map +1 -1
  26. package/dist/esm/clients/preferences/index.mjs.map +1 -1
  27. package/dist/esm/clients/slack/index.mjs.map +1 -1
  28. package/dist/esm/clients/users/index.mjs.map +1 -1
  29. package/dist/esm/knock.mjs.map +1 -1
  30. package/dist/esm/networkStatus.mjs.map +1 -1
  31. package/dist/types/clients/feed/feed.d.ts.map +1 -1
  32. package/dist/types/clients/feed/store.d.ts +1 -1
  33. package/dist/types/clients/feed/store.d.ts.map +1 -1
  34. package/package.json +3 -3
  35. package/src/clients/feed/feed.ts +1 -2
  36. package/src/clients/feed/store.ts +2 -8
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.0-rc.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0fc5f2d: [JS] Support React 19 in React SDKs
8
+
3
9
  ## 0.11.4
4
10
 
5
11
  ### Patch Changes
package/README.md CHANGED
@@ -111,21 +111,18 @@ const { items } = feedClient.store.getState();
111
111
  ### Reading the feed store state (in React)
112
112
 
113
113
  ```typescript
114
- // The feed store uses zustand
115
- import create from "zustand";
116
-
117
114
  // Initialize the feed as in above examples
118
115
  const feedClient = knockClient.feeds.initialize(
119
116
  process.env.KNOCK_FEED_CHANNEL_ID,
120
117
  );
121
118
 
122
- const useFeedStore = create(feedClient.store);
119
+ const feedStore = feedClient.store;
123
120
 
124
121
  // Retrieves all of the items
125
- const items = useFeedStore((state) => state.items);
122
+ const items = feedStore.getState().items;
126
123
 
127
124
  // Retrieve the badge counts
128
- const meta = useFeedStore((state) => state.metadata);
125
+ const meta = feedStore.getState().metadata;
129
126
  ```
130
127
 
131
128
  ### Marking items as read, seen, or archived
@@ -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 },\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\nexport default ApiClient;\n"],"names":["ApiClient","options","__publicField","axios","Socket","axiosRetry","req","result","e","error"],"mappings":"6ZAmBA,MAAMA,CAAU,CAQd,YAAYC,EAA2B,CAP/BC,EAAA,aACAA,EAAA,eACAA,EAAA,kBACAA,EAAA,oBAEDA,EAAA,eAGL,KAAK,KAAOD,EAAQ,KACpB,KAAK,OAASA,EAAQ,OACjB,KAAA,UAAYA,EAAQ,WAAa,KAGjC,KAAA,YAAcE,UAAM,OAAO,CAC9B,QAAS,KAAK,KACd,QAAS,CACP,OAAQ,mBACR,eAAgB,mBAChB,cAAe,UAAU,KAAK,MAAM,GACpC,qBAAsB,KAAK,SAC7B,CAAA,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,MAChB,CAAA,CACD,GAGHC,EAAA,QAAW,KAAK,YAAa,CAC3B,QAAS,EACT,eAAgB,KAAK,gBACrB,WAAYA,EAAW,QAAA,gBAAA,CACxB,CACH,CAEA,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,MAAA,QAIVC,EAAY,CACnB,eAAQ,MAAMA,CAAC,EAER,CACL,WAAY,QACZ,OAAQ,IACR,KAAM,OACN,MAAOA,CAAA,CAEX,CACF,CAEQ,gBAAgBC,EAAmB,CAErC,OAAAJ,EAAA,QAAW,eAAeI,CAAK,EAC1B,GAGJA,EAAM,SAMPA,EAAM,SAAS,QAAU,KAAOA,EAAM,SAAS,QAAU,KAKzDA,EAAM,SAAS,SAAW,IATrB,EAcX,CACF"}
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 },\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\nexport default ApiClient;\n"],"names":["ApiClient","options","__publicField","axios","Socket","axiosRetry","req","result","e","error"],"mappings":"6ZAmBA,MAAMA,CAAU,CAQd,YAAYC,EAA2B,CAP/BC,EAAA,aACAA,EAAA,eACAA,EAAA,kBACAA,EAAA,oBAEDA,EAAA,eAGL,KAAK,KAAOD,EAAQ,KACpB,KAAK,OAASA,EAAQ,OACjB,KAAA,UAAYA,EAAQ,WAAa,KAGjC,KAAA,YAAcE,UAAM,OAAO,CAC9B,QAAS,KAAK,KACd,QAAS,CACP,OAAQ,mBACR,eAAgB,mBAChB,cAAe,UAAU,KAAK,MAAM,GACpC,qBAAsB,KAAK,SAAA,CAC7B,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,MAAA,CAChB,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,CAEX"}
@@ -1 +1 @@
1
- {"version":3,"file":"feed.js","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { Channel } from \"phoenix\";\nimport { StoreApi } from \"zustand\";\n\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nclass Feed {\n private userFeedId: string;\n private channel?: Channel;\n private broadcaster: EventEmitter;\n private defaultOptions: FeedClientOptions;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n ) {\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = { ...feedClientDefaults, ...options };\n\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize() {\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n if (this.channel) {\n this.channel.leave();\n this.channel.off(\"new-message\");\n }\n\n this.teardownAutoSocketManager();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n const maybeSocket = this.knock.client().socket;\n\n // Connect the socket only if we don't already have a connection\n if (maybeSocket && !maybeSocket.isConnected()) {\n maybeSocket.connect();\n }\n\n // Only join the channel if we're not already in a joining state\n if (this.channel && [\"closed\", \"errored\"].includes(this.channel.state)) {\n this.channel.join();\n }\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // Always include the default params, if they have been set\n const queryParams = {\n ...this.defaultOptions,\n ...options,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage() {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({\n metadata,\n }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n // Optimistically set the badge counts\n state.setMetadata(metadata);\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // Tnis is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n const { socket: maybeSocket } = this.knock.client();\n\n // In server environments we might not have a socket connection\n if (!maybeSocket) return;\n\n // Reinitialize channel connections incase the socket changed\n this.channel = maybeSocket.channel(\n `feeds:${this.userFeedId}`,\n this.defaultOptions,\n );\n\n this.channel.on(\"new-message\", (resp) => this.onNewMessageReceived(resp));\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setupAutoSocketManager();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n if (!maybeSocket.isConnected()) maybeSocket.connect();\n this.channel.join();\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setupAutoSocketManager() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private teardownAutoSocketManager() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n this.initializeRealtimeConnection();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","Feed","knock","feedId","options","__publicField","createStore","EventEmitter","maybeSocket","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","e","payload","stringifiedPayload","resp","disconnectDelay","client","_a"],"mappings":"4aAgCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAEjC,MAAMC,CAAK,CAcT,YACWC,EACAC,EACTC,EACA,CAjBMC,EAAA,mBACAA,EAAA,gBACAA,EAAA,oBACAA,EAAA,uBACAA,EAAA,yBACAA,EAAA,uBAAwD,MACxDA,EAAA,sCAA0C,IAC1CA,EAAA,+BAAsC,IAAM,CAAA,GAC5CA,EAAA,yCAA6C,IAG9CA,EAAA,cAGI,KAAA,MAAAH,EACA,KAAA,OAAAC,EAGT,KAAK,OAASA,EACT,KAAA,WAAa,KAAK,kBACvB,KAAK,MAAQG,EAAAA,UACR,KAAA,YAAc,IAAIC,UAAa,CAAE,SAAU,GAAM,UAAW,IAAK,EACtE,KAAK,eAAiB,CAAE,GAAGR,EAAoB,GAAGK,CAAQ,EAE1D,KAAK,MAAM,IAAI,wCAAwCD,CAAM,EAAE,EAG/D,K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,IAGL,KAAK,QAAUA,EAAY,QACzB,SAAS,KAAK,UAAU,GACxB,KAAK,cAAA,EAGF,KAAA,QAAQ,GAAG,cAAgBuC,GAAS,KAAK,qBAAqBA,CAAI,CAAC,EAEpE,KAAK,eAAe,+BACtB,KAAK,uBAAuB,EAK1B,KAAK,gCAAkC,KAAK,MAAM,oBAC/CvC,EAAY,YAAY,KAAe,QAAQ,EACpD,KAAK,QAAQ,QAEjB,CAMQ,wBAAyB,CAE7B,OAAO,SAAa,KACpB,KAAK,oCAKP,KAAK,wBAA0B,KAAK,uBAAuB,KAAK,IAAI,EACpE,KAAK,kCAAoC,GAChC,SAAA,iBAAiB,mBAAoB,KAAK,uBAAuB,EAC5E,CAEQ,2BAA4B,CAC9B,OAAO,SAAa,MAEf,SAAA,oBACP,mBACA,KAAK,uBAAA,EAEP,KAAK,kCAAoC,GAC3C,CAEQ,UACN8B,EAQAxB,EACA,CAEA,KAAK,YAAY,KAAK,SAASwB,CAAI,GAAI,CAAE,MAAAxB,EAAO,EAChD,KAAK,YAAY,KAAK,SAASwB,CAAI,GAAI,CAAE,MAAAxB,EAAO,EAEhD,KAAK,qBAAqB,SAASwB,CAAI,GAAI,CAAE,MAAAxB,EAAO,CACtD,CAEQ,wBAAyB,OACzB,MAAAkC,EACJ,KAAK,eAAe,qCACpBhD,EAEIiD,EAAS,KAAK,MAAM,OAAO,EAE7B,SAAS,kBAAoB,SAE1B,KAAA,gBAAkB,WAAW,IAAM,QACtCC,EAAAD,EAAO,SAAP,MAAAC,EAAe,aACf,KAAK,gBAAkB,MACtBF,CAAe,EACT,SAAS,kBAAoB,YAGlC,KAAK,kBACP,aAAa,KAAK,eAAe,EACjC,KAAK,gBAAkB,OAIpBE,EAAAD,EAAO,SAAP,MAAAC,EAAe,eAClB,KAAK,6BAA6B,EAGxC,CACF"}
1
+ {"version":3,"file":"feed.js","sources":["../../../../src/clients/feed/feed.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport EventEmitter from \"eventemitter2\";\nimport { Channel } from \"phoenix\";\nimport type { StoreApi } from \"zustand\";\n\nimport Knock from \"../../knock\";\nimport { NetworkStatus, isRequestInFlight } from \"../../networkStatus\";\nimport {\n BulkUpdateMessagesInChannelProperties,\n MessageEngagementStatus,\n} from \"../messages/interfaces\";\n\nimport {\n FeedClientOptions,\n FeedItem,\n FeedMetadata,\n FeedResponse,\n FetchFeedOptions,\n} from \"./interfaces\";\nimport createStore from \"./store\";\nimport {\n BindableFeedEvent,\n FeedEvent,\n FeedEventCallback,\n FeedEventPayload,\n FeedItemOrItems,\n FeedMessagesReceivedPayload,\n FeedRealTimeCallback,\n FeedStoreState,\n} from \"./types\";\n\n// Default options to apply\nconst feedClientDefaults: Pick<FeedClientOptions, \"archived\"> = {\n archived: \"exclude\",\n};\n\nconst DEFAULT_DISCONNECT_DELAY = 2000;\n\nclass Feed {\n private userFeedId: string;\n private channel?: Channel;\n private broadcaster: EventEmitter;\n private defaultOptions: FeedClientOptions;\n private broadcastChannel!: BroadcastChannel | null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private hasSubscribedToRealTimeUpdates: boolean = false;\n private visibilityChangeHandler: () => void = () => {};\n private visibilityChangeListenerConnected: boolean = false;\n\n // The raw store instance, used for binding in React and other environments\n public store: StoreApi<FeedStoreState>;\n\n constructor(\n readonly knock: Knock,\n readonly feedId: string,\n options: FeedClientOptions,\n ) {\n this.feedId = feedId;\n this.userFeedId = this.buildUserFeedId();\n this.store = createStore();\n this.broadcaster = new EventEmitter({ wildcard: true, delimiter: \".\" });\n this.defaultOptions = { ...feedClientDefaults, ...options };\n\n this.knock.log(`[Feed] Initialized a feed on channel ${feedId}`);\n\n // Attempt to setup a realtime connection (does not join)\n this.initializeRealtimeConnection();\n\n this.setupBroadcastChannel();\n }\n\n /**\n * Used to reinitialize a current feed instance, which is useful when reauthenticating users\n */\n reinitialize() {\n // Reinitialize the user feed id incase the userId changed\n this.userFeedId = this.buildUserFeedId();\n\n // Reinitialize the real-time connection\n this.initializeRealtimeConnection();\n\n // Reinitialize our broadcast channel\n this.setupBroadcastChannel();\n }\n\n /**\n * Cleans up a feed instance by destroying the store and disconnecting\n * an open socket connection.\n */\n teardown() {\n this.knock.log(\"[Feed] Tearing down feed instance\");\n\n if (this.channel) {\n this.channel.leave();\n this.channel.off(\"new-message\");\n }\n\n this.teardownAutoSocketManager();\n\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n }\n }\n\n /** Tears down an instance and removes it entirely from the feed manager */\n dispose() {\n this.knock.log(\"[Feed] Disposing of feed instance\");\n this.teardown();\n this.broadcaster.removeAllListeners();\n this.knock.feeds.removeInstance(this);\n }\n\n /*\n Initializes a real-time connection to Knock, connecting the websocket for the\n current ApiClient instance if the socket is not already connected.\n */\n listenForUpdates() {\n this.knock.log(\"[Feed] Connecting to real-time service\");\n\n this.hasSubscribedToRealTimeUpdates = true;\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\n \"[Feed] User is not authenticated, skipping listening for updates\",\n );\n return;\n }\n\n const maybeSocket = this.knock.client().socket;\n\n // Connect the socket only if we don't already have a connection\n if (maybeSocket && !maybeSocket.isConnected()) {\n maybeSocket.connect();\n }\n\n // Only join the channel if we're not already in a joining state\n if (this.channel && [\"closed\", \"errored\"].includes(this.channel.state)) {\n this.channel.join();\n }\n }\n\n /* Binds a handler to be invoked when event occurs */\n on(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.on(eventName, callback);\n }\n\n off(\n eventName: BindableFeedEvent,\n callback: FeedEventCallback | FeedRealTimeCallback,\n ) {\n this.broadcaster.off(eventName, callback);\n }\n\n getState() {\n return this.store.getState();\n }\n\n async markAsSeen(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"seen\",\n { seen_at: now },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"seen\");\n }\n\n async markAllAsSeen() {\n // To mark all of the messages as seen we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unseen_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unseen`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnseen = this.defaultOptions.status === \"unseen\";\n\n // If we're looking at the unseen view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnseen) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unseen_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unseen_count: 0 });\n\n const attrs = { seen_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"seen\");\n this.emitEvent(\"all_seen\", items);\n\n return result;\n }\n\n async markAsUnseen(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unseen\",\n { seen_at: null },\n \"unseen_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unseen\");\n }\n\n async markAsRead(itemOrItems: FeedItemOrItems) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"read\",\n { read_at: now },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"read\");\n }\n\n async markAllAsRead() {\n // To mark all of the messages as read we:\n // 1. Optimistically update *everything* we have in the store\n // 2. We decrement the `unread_count` to zero optimistically\n // 3. We issue the API call to the endpoint\n //\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unread_count` to be what it was.\n //\n // Note: here we optimistically handle the case whereby the feed is scoped to show only `unread`\n // items by removing everything from view.\n const { metadata, items, ...state } = this.store.getState();\n\n const isViewingOnlyUnread = this.defaultOptions.status === \"unread\";\n\n // If we're looking at the unread view, then we want to remove all of the items optimistically\n // from the store given that nothing should be visible. We do this by resetting the store state\n // and setting the current metadata counts to 0\n if (isViewingOnlyUnread) {\n state.resetStore({\n ...metadata,\n total_count: 0,\n unread_count: 0,\n });\n } else {\n // Otherwise we want to update the metadata and mark all of the items in the store as seen\n state.setMetadata({ ...metadata, unread_count: 0 });\n\n const attrs = { read_at: new Date().toISOString() };\n const itemIds = items.map((item) => item.id);\n\n state.setItemAttrs(itemIds, attrs);\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"read\");\n this.emitEvent(\"all_read\", items);\n\n return result;\n }\n\n async markAsUnread(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"unread\",\n { read_at: null },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"unread\");\n }\n\n async markAsInteracted(\n itemOrItems: FeedItemOrItems,\n metadata?: Record<string, string>,\n ) {\n const now = new Date().toISOString();\n this.optimisticallyPerformStatusUpdate(\n itemOrItems,\n \"interacted\",\n {\n read_at: now,\n interacted_at: now,\n },\n \"unread_count\",\n );\n\n return this.makeStatusUpdate(itemOrItems, \"interacted\", metadata);\n }\n\n /*\n Marking one or more items as archived should:\n\n - Decrement the badge count for any unread / unseen items\n - Remove the item from the feed list when the `archived` flag is \"exclude\" (default)\n\n TODO: how do we handle rollbacks?\n */\n async markAsArchived(itemOrItems: FeedItemOrItems) {\n const state = this.store.getState();\n\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n\n const itemIds: string[] = items.map((item) => item.id);\n\n /*\n In the code here we want to optimistically update counts and items\n that are persisted such that we can display updates immediately on the feed\n without needing to make a network request.\n\n Note: right now this does *not* take into account offline handling or any extensive retry\n logic, so rollbacks aren't considered. That probably needs to be a future consideration for\n this library.\n\n Scenarios to consider:\n\n ## Feed scope to archived *only*\n\n - Counts should not be decremented\n - Items should not be removed\n\n ## Feed scoped to exclude archived items (the default)\n\n - Counts should be decremented\n - Items should be removed\n\n ## Feed scoped to include archived items as well\n\n - Counts should not be decremented\n - Items should not be removed\n */\n\n if (shouldOptimisticallyRemoveItems) {\n // If any of the items are unseen or unread, then capture as we'll want to decrement\n // the counts for these in the metadata we have\n const unseenCount = items.filter((i) => !i.seen_at).length;\n const unreadCount = items.filter((i) => !i.read_at).length;\n\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n // Ensure that the counts don't ever go below 0 on archiving where the client state\n // gets out of sync with the server state\n total_count: Math.max(0, state.metadata.total_count - items.length),\n unseen_count: Math.max(0, state.metadata.unseen_count - unseenCount),\n unread_count: Math.max(0, state.metadata.unread_count - unreadCount),\n };\n\n // Remove the archiving entries\n const entriesToSet = state.items.filter(\n (item) => !itemIds.includes(item.id),\n );\n\n state.setResult({\n entries: entriesToSet,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n return this.makeStatusUpdate(itemOrItems, \"archived\");\n }\n\n async markAllAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Reset the store to clear out all of items and reset the badge count\n state.resetStore();\n } else {\n // Mark all the entries being updated as archived either way so the state is correct\n const itemIds = items.map((i) => i.id);\n state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n this.emitEvent(\"all_archived\", items);\n\n return result;\n }\n\n async markAllReadAsArchived() {\n // Note: there is the potential for a race condition here because the bulk\n // update is an async method, so if a new message comes in during this window before\n // the update has been processed we'll effectively reset the `unseen_count` to be what it was.\n const { items, ...state } = this.store.getState();\n // Filter items to only include those that are unread\n const unreadItems = items.filter((item) => item.read_at === null);\n // Mark all the unread items as archived and read\n const itemIds = unreadItems.map((i) => i.id);\n state.setItemAttrs(itemIds, {\n archived_at: new Date().toISOString(),\n });\n\n // Here if we're looking at a feed that excludes all of the archived items by default then we\n // will want to optimistically remove all of the items from the feed as they are now all excluded\n const shouldOptimisticallyRemoveItems =\n this.defaultOptions.archived === \"exclude\";\n\n if (shouldOptimisticallyRemoveItems) {\n // Remove all the read items from the store and reset the badge count\n const remainingItems = items.filter((item) => !itemIds.includes(item.id));\n // Build the new metadata\n const updatedMetadata = {\n ...state.metadata,\n total_count: remainingItems.length,\n unread_count: 0,\n };\n\n state.setResult({\n entries: remainingItems,\n meta: updatedMetadata,\n page_info: state.pageInfo,\n });\n }\n\n // Issue the API request to the bulk status change API\n const result = await this.makeBulkStatusUpdate(\"archive\");\n // this.emitEvent(\"all_archived\", readItems);\n\n return result;\n }\n\n async markAsUnarchived(itemOrItems: FeedItemOrItems) {\n this.optimisticallyPerformStatusUpdate(itemOrItems, \"unarchived\", {\n archived_at: null,\n });\n\n return this.makeStatusUpdate(itemOrItems, \"unarchived\");\n }\n\n /* Fetches the feed content, appending it to the store */\n async fetch(options: FetchFeedOptions = {}) {\n const { networkStatus, ...state } = this.store.getState();\n\n // If the user is not authenticated, then do nothing\n if (!this.knock.isAuthenticated()) {\n this.knock.log(\"[Feed] User is not authenticated, skipping fetch\");\n return;\n }\n\n // If there's an existing request in flight, then do nothing\n if (isRequestInFlight(networkStatus)) {\n this.knock.log(\"[Feed] Request is in flight, skipping fetch\");\n return;\n }\n\n // Set the loading type based on the request type it is\n state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading);\n\n // Always include the default params, if they have been set\n const queryParams = {\n ...this.defaultOptions,\n ...options,\n // Unset options that should not be sent to the API\n __loadingType: undefined,\n __fetchSource: undefined,\n __experimentalCrossBrowserUpdates: undefined,\n auto_manage_socket_connection: undefined,\n auto_manage_socket_connection_delay: undefined,\n };\n\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.knock.userId}/feeds/${this.feedId}`,\n params: queryParams,\n });\n\n if (result.statusCode === \"error\" || !result.body) {\n state.setNetworkStatus(NetworkStatus.error);\n\n return {\n status: result.statusCode,\n data: result.error || result.body,\n };\n }\n\n const response = {\n entries: result.body.entries,\n meta: result.body.meta,\n page_info: result.body.page_info,\n };\n\n if (options.before) {\n const opts = { shouldSetPage: false, shouldAppend: true };\n state.setResult(response, opts);\n } else if (options.after) {\n const opts = { shouldSetPage: true, shouldAppend: true };\n state.setResult(response, opts);\n } else {\n state.setResult(response);\n }\n\n // Legacy `messages.new` event, should be removed in a future version\n this.broadcast(\"messages.new\", response);\n\n // Broadcast the appropriate event type depending on the fetch source\n const feedEventType: FeedEvent =\n options.__fetchSource === \"socket\"\n ? \"items.received.realtime\"\n : \"items.received.page\";\n\n const eventPayload = {\n items: response.entries as FeedItem[],\n metadata: response.meta as FeedMetadata,\n event: feedEventType,\n };\n\n this.broadcast(eventPayload.event, eventPayload);\n\n return { data: response, status: result.statusCode };\n }\n\n async fetchNextPage() {\n // Attempts to fetch the next page of results (if we have any)\n const { pageInfo } = this.store.getState();\n\n if (!pageInfo.after) {\n // Nothing more to fetch\n return;\n }\n\n this.fetch({\n after: pageInfo.after,\n __loadingType: NetworkStatus.fetchMore,\n });\n }\n\n private broadcast(\n eventName: FeedEvent,\n data: FeedResponse | FeedEventPayload,\n ) {\n this.broadcaster.emit(eventName, data);\n }\n\n // Invoked when a new real-time message comes in from the socket\n private async onNewMessageReceived({\n metadata,\n }: FeedMessagesReceivedPayload) {\n this.knock.log(\"[Feed] Received new real-time message\");\n // Handle the new message coming in\n const { items, ...state } = this.store.getState();\n const currentHead: FeedItem | undefined = items[0];\n // Optimistically set the badge counts\n state.setMetadata(metadata);\n // Fetch the items before the current head (if it exists)\n this.fetch({ before: currentHead?.__cursor, __fetchSource: \"socket\" });\n }\n\n private buildUserFeedId() {\n return `${this.feedId}:${this.knock.userId}`;\n }\n\n private optimisticallyPerformStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n attrs: object,\n badgeCountAttr?: \"unread_count\" | \"unseen_count\",\n ) {\n const state = this.store.getState();\n const normalizedItems = Array.isArray(itemOrItems)\n ? itemOrItems\n : [itemOrItems];\n const itemIds = normalizedItems.map((item) => item.id);\n\n if (badgeCountAttr) {\n const { metadata } = state;\n\n // We only want to update the counts of items that have not already been counted towards the\n // badge count total to avoid updating the badge count unnecessarily.\n const itemsToUpdate = normalizedItems.filter((item) => {\n switch (type) {\n case \"seen\":\n return item.seen_at === null;\n case \"unseen\":\n return item.seen_at !== null;\n case \"read\":\n case \"interacted\":\n return item.read_at === null;\n case \"unread\":\n return item.read_at !== null;\n default:\n return true;\n }\n });\n\n // Tnis is a hack to determine the direction of whether we're\n // adding or removing from the badge count\n const direction = type.startsWith(\"un\")\n ? itemsToUpdate.length\n : -itemsToUpdate.length;\n\n state.setMetadata({\n ...metadata,\n [badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction),\n });\n }\n\n // Update the items with the given attributes\n state.setItemAttrs(itemIds, attrs);\n }\n\n private async makeStatusUpdate(\n itemOrItems: FeedItemOrItems,\n type: MessageEngagementStatus | \"unread\" | \"unseen\" | \"unarchived\",\n metadata?: Record<string, string>,\n ) {\n // Always treat items as a batch to use the corresponding batch endpoint\n const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];\n const itemIds = items.map((item) => item.id);\n\n const result = await this.knock.messages.batchUpdateStatuses(\n itemIds,\n type,\n { metadata },\n );\n\n // Emit the event that these items had their statuses changed\n // Note: we do this after the update to ensure that the server event actually completed\n this.emitEvent(type, items);\n\n return result;\n }\n\n private async makeBulkStatusUpdate(\n status: BulkUpdateMessagesInChannelProperties[\"status\"],\n ) {\n // The base scope for the call should take into account all of the options currently\n // set on the feed, as well as being scoped for the current user. We do this so that\n // we ONLY make changes to the messages that are currently in view on this feed, and not\n // all messages that exist.\n const options = {\n user_ids: [this.knock.userId!],\n engagement_status:\n this.defaultOptions.status !== \"all\"\n ? this.defaultOptions.status\n : undefined,\n archived: this.defaultOptions.archived,\n has_tenant: this.defaultOptions.has_tenant,\n tenants: this.defaultOptions.tenant\n ? [this.defaultOptions.tenant]\n : undefined,\n };\n\n return await this.knock.messages.bulkUpdateAllStatusesInChannel({\n channelId: this.feedId,\n status,\n options,\n });\n }\n\n private setupBroadcastChannel() {\n // Attempt to bind to listen to other events from this feed in different tabs\n // Note: here we ensure `self` is available (it's not in server rendered envs)\n this.broadcastChannel =\n typeof self !== \"undefined\" && \"BroadcastChannel\" in self\n ? new BroadcastChannel(`knock:feed:${this.userFeedId}`)\n : null;\n\n // Opt into receiving updates from _other tabs for the same user / feed_ via the broadcast\n // channel (iff it's enabled and exists)\n if (\n this.broadcastChannel &&\n this.defaultOptions.__experimentalCrossBrowserUpdates === true\n ) {\n this.broadcastChannel.onmessage = (e) => {\n switch (e.data.type) {\n case \"items:archived\":\n case \"items:unarchived\":\n case \"items:seen\":\n case \"items:unseen\":\n case \"items:read\":\n case \"items:unread\":\n case \"items:all_read\":\n case \"items:all_seen\":\n case \"items:all_archived\":\n // When items are updated in any other tab, simply refetch to get the latest state\n // to make sure that the state gets updated accordingly. In the future here we could\n // maybe do this optimistically without the fetch.\n return this.fetch();\n default:\n return null;\n }\n };\n }\n }\n\n private broadcastOverChannel(type: string, payload: GenericData) {\n // The broadcastChannel may not be available in non-browser environments\n if (!this.broadcastChannel) {\n return;\n }\n\n // Here we stringify our payload and try and send as JSON such that we\n // don't get any `An object could not be cloned` errors when trying to broadcast\n try {\n const stringifiedPayload = JSON.parse(JSON.stringify(payload));\n\n this.broadcastChannel.postMessage({\n type,\n payload: stringifiedPayload,\n });\n } catch (e) {\n console.warn(`Could not broadcast ${type}, got error: ${e}`);\n }\n }\n\n private initializeRealtimeConnection() {\n const { socket: maybeSocket } = this.knock.client();\n\n // In server environments we might not have a socket connection\n if (!maybeSocket) return;\n\n // Reinitialize channel connections incase the socket changed\n this.channel = maybeSocket.channel(\n `feeds:${this.userFeedId}`,\n this.defaultOptions,\n );\n\n this.channel.on(\"new-message\", (resp) => this.onNewMessageReceived(resp));\n\n if (this.defaultOptions.auto_manage_socket_connection) {\n this.setupAutoSocketManager();\n }\n\n // If we're initializing but they have previously opted to listen to real-time updates\n // then we will automatically reconnect on their behalf\n if (this.hasSubscribedToRealTimeUpdates && this.knock.isAuthenticated()) {\n if (!maybeSocket.isConnected()) maybeSocket.connect();\n this.channel.join();\n }\n }\n\n /**\n * Listen for changes to document visibility and automatically disconnect\n * or reconnect the socket after a delay\n */\n private setupAutoSocketManager() {\n if (\n typeof document === \"undefined\" ||\n this.visibilityChangeListenerConnected\n ) {\n return;\n }\n\n this.visibilityChangeHandler = this.handleVisibilityChange.bind(this);\n this.visibilityChangeListenerConnected = true;\n document.addEventListener(\"visibilitychange\", this.visibilityChangeHandler);\n }\n\n private teardownAutoSocketManager() {\n if (typeof document === \"undefined\") return;\n\n document.removeEventListener(\n \"visibilitychange\",\n this.visibilityChangeHandler,\n );\n this.visibilityChangeListenerConnected = false;\n }\n\n private emitEvent(\n type:\n | MessageEngagementStatus\n | \"all_read\"\n | \"all_seen\"\n | \"all_archived\"\n | \"unread\"\n | \"unseen\"\n | \"unarchived\",\n items: FeedItem[],\n ) {\n // Handle both `items.` and `items:` format for events for compatibility reasons\n this.broadcaster.emit(`items.${type}`, { items });\n this.broadcaster.emit(`items:${type}`, { items });\n // Internal events only need `items:`\n this.broadcastOverChannel(`items:${type}`, { items });\n }\n\n private handleVisibilityChange() {\n const disconnectDelay =\n this.defaultOptions.auto_manage_socket_connection_delay ??\n DEFAULT_DISCONNECT_DELAY;\n\n const client = this.knock.client();\n\n if (document.visibilityState === \"hidden\") {\n // When the tab is hidden, clean up the socket connection after a delay\n this.disconnectTimer = setTimeout(() => {\n client.socket?.disconnect();\n this.disconnectTimer = null;\n }, disconnectDelay);\n } else if (document.visibilityState === \"visible\") {\n // When the tab is visible, clear the disconnect timer if active to cancel disconnecting\n // This handles cases where the tab is only briefly hidden to avoid unnecessary disconnects\n if (this.disconnectTimer) {\n clearTimeout(this.disconnectTimer);\n this.disconnectTimer = null;\n }\n\n // If the socket is not connected, try to reconnect\n if (!client.socket?.isConnected()) {\n this.initializeRealtimeConnection();\n }\n }\n }\n}\n\nexport default Feed;\n"],"names":["feedClientDefaults","DEFAULT_DISCONNECT_DELAY","Feed","knock","feedId","options","__publicField","createStore","EventEmitter","maybeSocket","eventName","callback","itemOrItems","now","metadata","items","state","attrs","itemIds","item","result","shouldOptimisticallyRemoveItems","unseenCount","i","unreadCount","updatedMetadata","entriesToSet","remainingItems","networkStatus","isRequestInFlight","NetworkStatus","queryParams","response","opts","feedEventType","eventPayload","pageInfo","data","currentHead","type","badgeCountAttr","normalizedItems","itemsToUpdate","direction","status","e","payload","stringifiedPayload","resp","disconnectDelay","client","_a"],"mappings":"4aAgCMA,EAA0D,CAC9D,SAAU,SACZ,EAEMC,EAA2B,IAEjC,MAAMC,CAAK,CAcT,YACWC,EACAC,EACTC,EACA,CAjBMC,EAAA,mBACAA,EAAA,gBACAA,EAAA,oBACAA,EAAA,uBACAA,EAAA,yBACAA,EAAA,uBAAwD,MACxDA,EAAA,sCAA0C,IAC1CA,EAAA,+BAAsC,IAAM,CAAC,GAC7CA,EAAA,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AAS,KAAK,MAAM,OAAO,EAE7B,SAAS,kBAAoB,SAE1B,KAAA,gBAAkB,WAAW,IAAM,QACtCC,EAAAD,EAAO,SAAP,MAAAC,EAAe,aACf,KAAK,gBAAkB,MACtBF,CAAe,EACT,SAAS,kBAAoB,YAGlC,KAAK,kBACP,aAAa,KAAK,eAAe,EACjC,KAAK,gBAAkB,OAIpBE,EAAAD,EAAO,SAAP,MAAAC,EAAe,eAClB,KAAK,6BAA6B,EAEtC,CAEJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/clients/feed/index.ts"],"sourcesContent":["import Knock from \"../../knock\";\n\nimport Feed from \"./feed\";\nimport { FeedClientOptions } from \"./interfaces\";\n\nclass FeedClient {\n private instance: Knock;\n private feedInstances: Feed[] = [];\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n initialize(feedChannelId: string, options: FeedClientOptions = {}) {\n const feedInstance = new Feed(this.instance, feedChannelId, options);\n this.feedInstances.push(feedInstance);\n\n return feedInstance;\n }\n\n removeInstance(feed: Feed) {\n this.feedInstances = this.feedInstances.filter((f) => f !== feed);\n }\n\n teardownInstances() {\n for (const feed of this.feedInstances) {\n feed.teardown();\n }\n }\n\n reinitializeInstances() {\n for (const feed of this.feedInstances) {\n feed.reinitialize();\n }\n }\n}\n\nexport { Feed };\nexport default FeedClient;\n"],"names":["FeedClient","instance","__publicField","feedChannelId","options","feedInstance","Feed","feed","f"],"mappings":"6SAKA,MAAMA,CAAW,CAIf,YAAYC,EAAiB,CAHrBC,EAAA,iBACAA,EAAA,qBAAwB,CAAA,GAG9B,KAAK,SAAWD,CAClB,CAEA,WAAWE,EAAuBC,EAA6B,GAAI,CACjE,MAAMC,EAAe,IAAIC,UAAK,KAAK,SAAUH,EAAeC,CAAO,EAC9D,YAAA,cAAc,KAAKC,CAAY,EAE7BA,CACT,CAEA,eAAeE,EAAY,CACzB,KAAK,cAAgB,KAAK,cAAc,OAAQC,GAAMA,IAAMD,CAAI,CAClE,CAEA,mBAAoB,CACP,UAAAA,KAAQ,KAAK,cACtBA,EAAK,SAAS,CAElB,CAEA,uBAAwB,CACX,UAAAA,KAAQ,KAAK,cACtBA,EAAK,aAAa,CAEtB,CACF"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/clients/feed/index.ts"],"sourcesContent":["import Knock from \"../../knock\";\n\nimport Feed from \"./feed\";\nimport { FeedClientOptions } from \"./interfaces\";\n\nclass FeedClient {\n private instance: Knock;\n private feedInstances: Feed[] = [];\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n initialize(feedChannelId: string, options: FeedClientOptions = {}) {\n const feedInstance = new Feed(this.instance, feedChannelId, options);\n this.feedInstances.push(feedInstance);\n\n return feedInstance;\n }\n\n removeInstance(feed: Feed) {\n this.feedInstances = this.feedInstances.filter((f) => f !== feed);\n }\n\n teardownInstances() {\n for (const feed of this.feedInstances) {\n feed.teardown();\n }\n }\n\n reinitializeInstances() {\n for (const feed of this.feedInstances) {\n feed.reinitialize();\n }\n }\n}\n\nexport { Feed };\nexport default FeedClient;\n"],"names":["FeedClient","instance","__publicField","feedChannelId","options","feedInstance","Feed","feed","f"],"mappings":"6SAKA,MAAMA,CAAW,CAIf,YAAYC,EAAiB,CAHrBC,EAAA,iBACAA,EAAA,qBAAwB,CAAC,GAG/B,KAAK,SAAWD,CAAA,CAGlB,WAAWE,EAAuBC,EAA6B,GAAI,CACjE,MAAMC,EAAe,IAAIC,EAAA,QAAK,KAAK,SAAUH,EAAeC,CAAO,EAC9D,YAAA,cAAc,KAAKC,CAAY,EAE7BA,CAAA,CAGT,eAAeE,EAAY,CACzB,KAAK,cAAgB,KAAK,cAAc,OAAQC,GAAMA,IAAMD,CAAI,CAAA,CAGlE,mBAAoB,CACP,UAAAA,KAAQ,KAAK,cACtBA,EAAK,SAAS,CAChB,CAGF,uBAAwB,CACX,UAAAA,KAAQ,KAAK,cACtBA,EAAK,aAAa,CACpB,CAEJ"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("zustand/vanilla"),r=require("../../networkStatus.js"),c=require("./utils.js"),f=t=>t&&typeof t=="object"&&"default"in t?t:{default:t},d=f(i),p=typeof d.default=="function"?d.default:d.default.default;function S(t){const e=c.deduplicateItems(t);return c.sortItems(e)}const m={shouldSetPage:!0,shouldAppend:!1},l={items:[],metadata:{total_count:0,unread_count:0,unseen_count:0},pageInfo:{before:null,after:null,page_size:50}};function g(){return p(t=>({...l,networkStatus:r.NetworkStatus.ready,loading:!1,setNetworkStatus:e=>t(()=>({networkStatus:e,loading:e===r.NetworkStatus.loading})),setResult:({entries:e,meta:s,page_info:n},a=m)=>t(o=>({items:a.shouldAppend?S(o.items.concat(e)):e,metadata:s,pageInfo:a.shouldSetPage?n:o.pageInfo,loading:!1,networkStatus:r.NetworkStatus.ready})),setMetadata:e=>t(()=>({metadata:e})),resetStore:(e=l.metadata)=>t(()=>({...l,metadata:e})),setItemAttrs:(e,s)=>{const n=e.reduce((a,o)=>({...a,[o]:s}),{});return t(a=>({items:a.items.map(u=>n[u.id]?{...u,...n[u.id]}:u)}))}}))}exports.default=g;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("zustand"),n=require("../../networkStatus.js"),l=require("./utils.js");function c(e){const t=l.deduplicateItems(e);return l.sortItems(t)}const S={shouldSetPage:!0,shouldAppend:!1},d={items:[],metadata:{total_count:0,unread_count:0,unseen_count:0},pageInfo:{before:null,after:null,page_size:50}};function p(){return i.createStore()(e=>({...d,networkStatus:n.NetworkStatus.ready,loading:!1,setNetworkStatus:t=>e(()=>({networkStatus:t,loading:t===n.NetworkStatus.loading})),setResult:({entries:t,meta:o,page_info:u},a=S)=>e(r=>({items:a.shouldAppend?c(r.items.concat(t)):t,metadata:o,pageInfo:a.shouldSetPage?u:r.pageInfo,loading:!1,networkStatus:n.NetworkStatus.ready})),setMetadata:t=>e(()=>({metadata:t})),resetStore:(t=d.metadata)=>e(()=>({...d,metadata:t})),setItemAttrs:(t,o)=>{const u=t.reduce((a,r)=>({...a,[r]:o}),{});return e(a=>({items:a.items.map(s=>u[s.id]?{...s,...u[s.id]}:s)}))}}))}exports.default=p;
2
2
  //# sourceMappingURL=store.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sources":["../../../../src/clients/feed/store.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport zustand from \"zustand/vanilla\";\n\nimport { NetworkStatus } from \"../../networkStatus\";\n\nimport { FeedItem } from \"./interfaces\";\nimport { FeedStoreState } from \"./types\";\nimport { deduplicateItems, sortItems } from \"./utils\";\n\n// Get the correct Zustand function. Caused by some issues in v3 exports\n// https://github.com/pmndrs/zustand/issues/334\nconst create: typeof zustand =\n // @ts-expect-error workaround for issue above\n typeof zustand === \"function\" ? zustand : zustand.default;\n\nfunction processItems(items: FeedItem[]) {\n const deduped = deduplicateItems(items);\n const sorted = sortItems(deduped);\n\n return sorted;\n}\n\nconst defaultSetResultOptions = {\n shouldSetPage: true,\n shouldAppend: false,\n};\n\nconst initialStoreState = {\n items: [],\n metadata: {\n total_count: 0,\n unread_count: 0,\n unseen_count: 0,\n },\n pageInfo: {\n before: null,\n after: null,\n page_size: 50,\n },\n};\n\nexport default function createStore() {\n return create<FeedStoreState>((set) => ({\n // Keeps track of all of the items loaded\n ...initialStoreState,\n // The network status indicates what's happening with the request\n networkStatus: NetworkStatus.ready,\n loading: false,\n\n setNetworkStatus: (networkStatus: NetworkStatus) =>\n set(() => ({\n networkStatus,\n loading: networkStatus === NetworkStatus.loading,\n })),\n\n setResult: (\n { entries, meta, page_info },\n options = defaultSetResultOptions,\n ) =>\n set((state) => {\n // We resort the list on set, so concating everything is fine (if a bit suboptimal)\n const items = options.shouldAppend\n ? processItems(state.items.concat(entries as FeedItem<GenericData>[]))\n : entries;\n\n return {\n items,\n metadata: meta,\n pageInfo: options.shouldSetPage ? page_info : state.pageInfo,\n loading: false,\n networkStatus: NetworkStatus.ready,\n };\n }),\n\n setMetadata: (metadata) => set(() => ({ metadata })),\n\n resetStore: (metadata = initialStoreState.metadata) =>\n set(() => ({ ...initialStoreState, metadata })),\n\n setItemAttrs: (itemIds, attrs) => {\n // Create a map for the items to the updates to be made\n const itemUpdatesMap: { [id: string]: object } = itemIds.reduce(\n (acc, itemId) => ({ ...acc, [itemId]: attrs }),\n {},\n );\n\n return set((state) => {\n const items = state.items.map((item) => {\n if (itemUpdatesMap[item.id]) {\n return { ...item, ...itemUpdatesMap[item.id] };\n }\n\n return item;\n });\n\n return { items };\n });\n },\n }));\n}\n"],"names":["create","zustand","processItems","items","deduped","deduplicateItems","sortItems","defaultSetResultOptions","initialStoreState","createStore","set","NetworkStatus","networkStatus","entries","meta","page_info","options","state","metadata","itemIds","attrs","itemUpdatesMap","acc","itemId","item"],"mappings":"0QAWMA,EAEJ,OAAOC,WAAY,WAAaA,EAAA,QAAUA,EAAQ,QAAA,QAEpD,SAASC,EAAaC,EAAmB,CACjC,MAAAC,EAAUC,mBAAiBF,CAAK,EAG/B,OAFQG,YAAUF,CAAO,CAGlC,CAEA,MAAMG,EAA0B,CAC9B,cAAe,GACf,aAAc,EAChB,EAEMC,EAAoB,CACxB,MAAO,CAAC,EACR,SAAU,CACR,YAAa,EACb,aAAc,EACd,aAAc,CAChB,EACA,SAAU,CACR,OAAQ,KACR,MAAO,KACP,UAAW,EACb,CACF,EAEA,SAAwBC,GAAc,CAC7B,OAAAT,EAAwBU,IAAS,CAEtC,GAAGF,EAEH,cAAeG,EAAc,cAAA,MAC7B,QAAS,GAET,iBAAmBC,GACjBF,EAAI,KAAO,CAAA,cACTE,EACA,QAASA,IAAkBD,EAAAA,cAAc,OAAA,EACzC,EAEJ,UAAW,CACT,CAAE,QAAAE,EAAS,KAAAC,EAAM,UAAAC,GACjBC,EAAUT,IAEVG,EAAKO,IAMI,CACL,MALYD,EAAQ,aAClBd,EAAae,EAAM,MAAM,OAAOJ,CAAkC,CAAC,EACnEA,EAIF,SAAUC,EACV,SAAUE,EAAQ,cAAgBD,EAAYE,EAAM,SACpD,QAAS,GACT,cAAeN,EAAc,cAAA,KAAA,EAEhC,EAEH,YAAcO,GAAaR,EAAI,KAAO,CAAE,SAAAQ,CAAW,EAAA,EAEnD,WAAY,CAACA,EAAWV,EAAkB,WACxCE,EAAI,KAAO,CAAE,GAAGF,EAAmB,SAAAU,CAAA,EAAW,EAEhD,aAAc,CAACC,EAASC,IAAU,CAEhC,MAAMC,EAA2CF,EAAQ,OACvD,CAACG,EAAKC,KAAY,CAAE,GAAGD,EAAK,CAACC,CAAM,EAAGH,IACtC,CAAC,CAAA,EAGI,OAAAV,EAAKO,IASH,CAAE,MARKA,EAAM,MAAM,IAAKO,GACzBH,EAAeG,EAAK,EAAE,EACjB,CAAE,GAAGA,EAAM,GAAGH,EAAeG,EAAK,EAAE,GAGtCA,CACR,CAEc,EAChB,CACH,CACA,EAAA,CACJ"}
1
+ {"version":3,"file":"store.js","sources":["../../../../src/clients/feed/store.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport { createStore as createVanillaZustandStore } from \"zustand\";\n\nimport { NetworkStatus } from \"../../networkStatus\";\n\nimport { FeedItem } from \"./interfaces\";\nimport { FeedStoreState } from \"./types\";\nimport { deduplicateItems, sortItems } from \"./utils\";\n\nfunction processItems(items: FeedItem[]) {\n const deduped = deduplicateItems(items);\n const sorted = sortItems(deduped);\n\n return sorted;\n}\n\nconst defaultSetResultOptions = {\n shouldSetPage: true,\n shouldAppend: false,\n};\n\nconst initialStoreState = {\n items: [],\n metadata: {\n total_count: 0,\n unread_count: 0,\n unseen_count: 0,\n },\n pageInfo: {\n before: null,\n after: null,\n page_size: 50,\n },\n};\n\nexport default function createStore() {\n return createVanillaZustandStore<FeedStoreState>()((set) => ({\n // Keeps track of all of the items loaded\n ...initialStoreState,\n // The network status indicates what's happening with the request\n networkStatus: NetworkStatus.ready,\n loading: false,\n\n setNetworkStatus: (networkStatus: NetworkStatus) =>\n set(() => ({\n networkStatus,\n loading: networkStatus === NetworkStatus.loading,\n })),\n\n setResult: (\n { entries, meta, page_info },\n options = defaultSetResultOptions,\n ) =>\n set((state) => {\n // We resort the list on set, so concating everything is fine (if a bit suboptimal)\n const items = options.shouldAppend\n ? processItems(state.items.concat(entries as FeedItem<GenericData>[]))\n : entries;\n\n return {\n items,\n metadata: meta,\n pageInfo: options.shouldSetPage ? page_info : state.pageInfo,\n loading: false,\n networkStatus: NetworkStatus.ready,\n };\n }),\n\n setMetadata: (metadata) => set(() => ({ metadata })),\n\n resetStore: (metadata = initialStoreState.metadata) =>\n set(() => ({ ...initialStoreState, metadata })),\n\n setItemAttrs: (itemIds, attrs) => {\n // Create a map for the items to the updates to be made\n const itemUpdatesMap: { [id: string]: object } = itemIds.reduce(\n (acc, itemId) => ({ ...acc, [itemId]: attrs }),\n {},\n );\n\n return set((state) => {\n const items = state.items.map((item) => {\n if (itemUpdatesMap[item.id]) {\n return { ...item, ...itemUpdatesMap[item.id] };\n }\n\n return item;\n });\n\n return { items };\n });\n },\n }));\n}\n"],"names":["processItems","items","deduped","deduplicateItems","sortItems","defaultSetResultOptions","initialStoreState","createStore","createVanillaZustandStore","set","NetworkStatus","networkStatus","entries","meta","page_info","options","state","metadata","itemIds","attrs","itemUpdatesMap","acc","itemId","item"],"mappings":"mMASA,SAASA,EAAaC,EAAmB,CACjC,MAAAC,EAAUC,mBAAiBF,CAAK,EAG/B,OAFQG,YAAUF,CAAO,CAGlC,CAEA,MAAMG,EAA0B,CAC9B,cAAe,GACf,aAAc,EAChB,EAEMC,EAAoB,CACxB,MAAO,CAAC,EACR,SAAU,CACR,YAAa,EACb,aAAc,EACd,aAAc,CAChB,EACA,SAAU,CACR,OAAQ,KACR,MAAO,KACP,UAAW,EAAA,CAEf,EAEA,SAAwBC,GAAc,CAC7B,OAAAC,EAAA,YAAA,EAA6CC,IAAS,CAE3D,GAAGH,EAEH,cAAeI,EAAc,cAAA,MAC7B,QAAS,GAET,iBAAmBC,GACjBF,EAAI,KAAO,CAAA,cACTE,EACA,QAASA,IAAkBD,gBAAc,OAAA,EACzC,EAEJ,UAAW,CACT,CAAE,QAAAE,EAAS,KAAAC,EAAM,UAAAC,GACjBC,EAAUV,IAEVI,EAAKO,IAMI,CACL,MALYD,EAAQ,aAClBf,EAAagB,EAAM,MAAM,OAAOJ,CAAkC,CAAC,EACnEA,EAIF,SAAUC,EACV,SAAUE,EAAQ,cAAgBD,EAAYE,EAAM,SACpD,QAAS,GACT,cAAeN,EAAAA,cAAc,KAC/B,EACD,EAEH,YAAcO,GAAaR,EAAI,KAAO,CAAE,SAAAQ,CAAW,EAAA,EAEnD,WAAY,CAACA,EAAWX,EAAkB,WACxCG,EAAI,KAAO,CAAE,GAAGH,EAAmB,SAAAW,CAAA,EAAW,EAEhD,aAAc,CAACC,EAASC,IAAU,CAEhC,MAAMC,EAA2CF,EAAQ,OACvD,CAACG,EAAKC,KAAY,CAAE,GAAGD,EAAK,CAACC,CAAM,EAAGH,IACtC,CAAA,CACF,EAEO,OAAAV,EAAKO,IASH,CAAE,MARKA,EAAM,MAAM,IAAKO,GACzBH,EAAeG,EAAK,EAAE,EACjB,CAAE,GAAGA,EAAM,GAAGH,EAAeG,EAAK,EAAE,CAAE,EAGxCA,CACR,CAEc,EAChB,CAAA,CACH,EACA,CACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../../../src/clients/feed/utils.ts"],"sourcesContent":["import { FeedItem } from \"./interfaces\";\n\nexport function deduplicateItems(items: FeedItem[]): FeedItem[] {\n const seen: Record<string, boolean> = {};\n const values: FeedItem[] = [];\n\n return items.reduce((acc, item) => {\n if (seen[item.id]) {\n return acc;\n }\n\n seen[item.id] = true;\n return [...acc, item];\n }, values);\n}\n\nexport function sortItems(items: FeedItem[]) {\n return items.sort((a, b) => {\n return (\n new Date(b.inserted_at).getTime() - new Date(a.inserted_at).getTime()\n );\n });\n}\n"],"names":["deduplicateItems","items","seen","values","acc","item","sortItems","a","b"],"mappings":"gFAEO,SAASA,EAAiBC,EAA+B,CAC9D,MAAMC,EAAgC,CAAA,EAChCC,EAAqB,CAAA,EAE3B,OAAOF,EAAM,OAAO,CAACG,EAAKC,IACpBH,EAAKG,EAAK,EAAE,EACPD,GAGJF,EAAAG,EAAK,EAAE,EAAI,GACT,CAAC,GAAGD,EAAKC,CAAI,GACnBF,CAAM,CACX,CAEO,SAASG,EAAUL,EAAmB,CAC3C,OAAOA,EAAM,KAAK,CAACM,EAAGC,IAElB,IAAI,KAAKA,EAAE,WAAW,EAAE,QAAA,EAAY,IAAI,KAAKD,EAAE,WAAW,EAAE,QAAQ,CAEvE,CACH"}
1
+ {"version":3,"file":"utils.js","sources":["../../../../src/clients/feed/utils.ts"],"sourcesContent":["import { FeedItem } from \"./interfaces\";\n\nexport function deduplicateItems(items: FeedItem[]): FeedItem[] {\n const seen: Record<string, boolean> = {};\n const values: FeedItem[] = [];\n\n return items.reduce((acc, item) => {\n if (seen[item.id]) {\n return acc;\n }\n\n seen[item.id] = true;\n return [...acc, item];\n }, values);\n}\n\nexport function sortItems(items: FeedItem[]) {\n return items.sort((a, b) => {\n return (\n new Date(b.inserted_at).getTime() - new Date(a.inserted_at).getTime()\n );\n });\n}\n"],"names":["deduplicateItems","items","seen","values","acc","item","sortItems","a","b"],"mappings":"gFAEO,SAASA,EAAiBC,EAA+B,CAC9D,MAAMC,EAAgC,CAAC,EACjCC,EAAqB,CAAC,EAE5B,OAAOF,EAAM,OAAO,CAACG,EAAKC,IACpBH,EAAKG,EAAK,EAAE,EACPD,GAGJF,EAAAG,EAAK,EAAE,EAAI,GACT,CAAC,GAAGD,EAAKC,CAAI,GACnBF,CAAM,CACX,CAEO,SAASG,EAAUL,EAAmB,CAC3C,OAAOA,EAAM,KAAK,CAACM,EAAGC,IAElB,IAAI,KAAKA,EAAE,WAAW,EAAE,UAAY,IAAI,KAAKD,EAAE,WAAW,EAAE,QAAQ,CAEvE,CACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/clients/messages/index.ts"],"sourcesContent":["import { ApiResponse } from \"../../api\";\nimport { BulkOperation } from \"../../interfaces\";\nimport Knock from \"../../knock\";\n\nimport {\n BulkUpdateMessagesInChannelProperties,\n Message,\n MessageEngagementStatus,\n UpdateMessageStatusOptions,\n} from \"./interfaces\";\n\nclass MessageClient {\n private knock: Knock;\n\n constructor(knock: Knock) {\n this.knock = knock;\n }\n\n async get(messageId: string): Promise<Message> {\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/messages/${messageId}`,\n });\n\n return this.handleResponse<Message>(result);\n }\n\n async updateStatus(\n messageId: string,\n status: MessageEngagementStatus,\n options?: UpdateMessageStatusOptions,\n ): Promise<Message> {\n // Metadata is only required for the \"interacted\" status\n const payload =\n status === \"interacted\" && options\n ? { metadata: options.metadata }\n : undefined;\n\n const result = await this.knock.client().makeRequest({\n method: \"PUT\",\n url: `/v1/messages/${messageId}/${status}`,\n data: payload,\n });\n\n return this.handleResponse<Message>(result);\n }\n\n async removeStatus(\n messageId: string,\n status: Exclude<MessageEngagementStatus, \"interacted\">,\n ): Promise<Message> {\n const result = await this.knock.client().makeRequest({\n method: \"DELETE\",\n url: `/v1/messages/${messageId}/${status}`,\n });\n\n return this.handleResponse<Message>(result);\n }\n\n async batchUpdateStatuses(\n messageIds: string[],\n status: MessageEngagementStatus | \"unseen\" | \"unread\" | \"unarchived\",\n options?: UpdateMessageStatusOptions,\n ): Promise<Message[]> {\n // Metadata is only required for the \"interacted\" status\n const additionalPayload =\n status === \"interacted\" && options ? { metadata: options.metadata } : {};\n\n const result = await this.knock.client().makeRequest({\n method: \"POST\",\n url: `/v1/messages/batch/${status}`,\n data: { message_ids: messageIds, ...additionalPayload },\n });\n\n return this.handleResponse<Message[]>(result);\n }\n\n async bulkUpdateAllStatusesInChannel({\n channelId,\n status,\n options,\n }: BulkUpdateMessagesInChannelProperties): Promise<BulkOperation> {\n const result = await this.knock.client().makeRequest({\n method: \"POST\",\n url: `/v1/channels/${channelId}/messages/bulk/${status}`,\n data: options,\n });\n\n return this.handleResponse<BulkOperation>(result);\n }\n\n private handleResponse<T = unknown>(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n if (response.error?.response?.status < 500) {\n return response.error || response.body;\n }\n throw new Error(response.error || response.body);\n }\n\n return response.body as T;\n }\n}\n\nexport default MessageClient;\n"],"names":["MessageClient","knock","__publicField","messageId","result","status","options","payload","messageIds","additionalPayload","channelId","response","_b","_a"],"mappings":"gRAWA,MAAMA,CAAc,CAGlB,YAAYC,EAAc,CAFlBC,EAAA,cAGN,KAAK,MAAQD,CACf,CAEA,MAAM,IAAIE,EAAqC,CAC7C,MAAMC,EAAS,MAAM,KAAK,MAAM,OAAA,EAAS,YAAY,CACnD,OAAQ,MACR,IAAK,gBAAgBD,CAAS,EAAA,CAC/B,EAEM,OAAA,KAAK,eAAwBC,CAAM,CAC5C,CAEA,MAAM,aACJD,EACAE,EACAC,EACkB,CAEZ,MAAAC,EACJF,IAAW,cAAgBC,EACvB,CAAE,SAAUA,EAAQ,UACpB,OAEAF,EAAS,MAAM,KAAK,MAAM,OAAA,EAAS,YAAY,CACnD,OAAQ,MACR,IAAK,gBAAgBD,CAAS,IAAIE,CAAM,GACxC,KAAME,CAAA,CACP,EAEM,OAAA,KAAK,eAAwBH,CAAM,CAC5C,CAEA,MAAM,aACJD,EACAE,EACkB,CAClB,MAAMD,EAAS,MAAM,KAAK,MAAM,OAAA,EAAS,YAAY,CACnD,OAAQ,SACR,IAAK,gBAAgBD,CAAS,IAAIE,CAAM,EAAA,CACzC,EAEM,OAAA,KAAK,eAAwBD,CAAM,CAC5C,CAEA,MAAM,oBACJI,EACAH,EACAC,EACoB,CAEd,MAAAG,EACJJ,IAAW,cAAgBC,EAAU,CAAE,SAAUA,EAAQ,QAAS,EAAI,GAElEF,EAAS,MAAM,KAAK,MAAM,OAAA,EAAS,YAAY,CACnD,OAAQ,OACR,IAAK,sBAAsBC,CAAM,GACjC,KAAM,CAAE,YAAaG,EAAY,GAAGC,CAAkB,CAAA,CACvD,EAEM,OAAA,KAAK,eAA0BL,CAAM,CAC9C,CAEA,MAAM,+BAA+B,CACnC,UAAAM,EACA,OAAAL,EACA,QAAAC,CAAA,EACgE,CAChE,MAAMF,EAAS,MAAM,KAAK,MAAM,OAAA,EAAS,YAAY,CACnD,OAAQ,OACR,IAAK,gBAAgBM,CAAS,kBAAkBL,CAAM,GACtD,KAAMC,CAAA,CACP,EAEM,OAAA,KAAK,eAA8BF,CAAM,CAClD,CAEQ,eAA4BO,EAAuB,SACrD,GAAAA,EAAS,aAAe,QAAS,CACnC,KAAIC,GAAAC,EAAAF,EAAS,QAAT,YAAAE,EAAgB,WAAhB,YAAAD,EAA0B,QAAS,IAC9B,OAAAD,EAAS,OAASA,EAAS,KAEpC,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,CACjD,CAEA,OAAOA,EAAS,IAClB,CACF"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/clients/messages/index.ts"],"sourcesContent":["import { ApiResponse } from \"../../api\";\nimport { BulkOperation } from \"../../interfaces\";\nimport Knock from \"../../knock\";\n\nimport {\n BulkUpdateMessagesInChannelProperties,\n Message,\n MessageEngagementStatus,\n UpdateMessageStatusOptions,\n} from \"./interfaces\";\n\nclass MessageClient {\n private knock: Knock;\n\n constructor(knock: Knock) {\n this.knock = knock;\n }\n\n async get(messageId: string): Promise<Message> {\n const result = await this.knock.client().makeRequest({\n method: \"GET\",\n url: `/v1/messages/${messageId}`,\n });\n\n return this.handleResponse<Message>(result);\n }\n\n async updateStatus(\n messageId: string,\n status: MessageEngagementStatus,\n options?: UpdateMessageStatusOptions,\n ): Promise<Message> {\n // Metadata is only required for the \"interacted\" status\n const payload =\n status === \"interacted\" && options\n ? { metadata: options.metadata }\n : undefined;\n\n const result = await this.knock.client().makeRequest({\n method: \"PUT\",\n url: `/v1/messages/${messageId}/${status}`,\n data: payload,\n });\n\n return this.handleResponse<Message>(result);\n }\n\n async removeStatus(\n messageId: string,\n status: Exclude<MessageEngagementStatus, \"interacted\">,\n ): Promise<Message> {\n const result = await this.knock.client().makeRequest({\n method: \"DELETE\",\n url: `/v1/messages/${messageId}/${status}`,\n });\n\n return this.handleResponse<Message>(result);\n }\n\n async batchUpdateStatuses(\n messageIds: string[],\n status: MessageEngagementStatus | \"unseen\" | \"unread\" | \"unarchived\",\n options?: UpdateMessageStatusOptions,\n ): Promise<Message[]> {\n // Metadata is only required for the \"interacted\" status\n const additionalPayload =\n status === \"interacted\" && options ? { metadata: options.metadata } : {};\n\n const result = await this.knock.client().makeRequest({\n method: \"POST\",\n url: `/v1/messages/batch/${status}`,\n data: { message_ids: messageIds, ...additionalPayload },\n });\n\n return this.handleResponse<Message[]>(result);\n }\n\n async bulkUpdateAllStatusesInChannel({\n channelId,\n status,\n options,\n }: BulkUpdateMessagesInChannelProperties): Promise<BulkOperation> {\n const result = await this.knock.client().makeRequest({\n method: \"POST\",\n url: `/v1/channels/${channelId}/messages/bulk/${status}`,\n data: options,\n });\n\n return this.handleResponse<BulkOperation>(result);\n }\n\n private handleResponse<T = unknown>(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n if (response.error?.response?.status < 500) {\n return response.error || response.body;\n }\n throw new Error(response.error || response.body);\n }\n\n return response.body as T;\n }\n}\n\nexport default MessageClient;\n"],"names":["MessageClient","knock","__publicField","messageId","result","status","options","payload","messageIds","additionalPayload","channelId","response","_b","_a"],"mappings":"gRAWA,MAAMA,CAAc,CAGlB,YAAYC,EAAc,CAFlBC,EAAA,cAGN,KAAK,MAAQD,CAAA,CAGf,MAAM,IAAIE,EAAqC,CAC7C,MAAMC,EAAS,MAAM,KAAK,MAAM,OAAA,EAAS,YAAY,CACnD,OAAQ,MACR,IAAK,gBAAgBD,CAAS,EAAA,CAC/B,EAEM,OAAA,KAAK,eAAwBC,CAAM,CAAA,CAG5C,MAAM,aACJD,EACAE,EACAC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pB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/clients/ms-teams/index.ts"],"sourcesContent":["import { ApiResponse } from \"../../api\";\nimport { AuthCheckInput, RevokeAccessTokenInput } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport { TENANT_OBJECT_COLLECTION } from \"../objects/constants\";\n\nimport {\n GetMsTeamsChannelsInput,\n GetMsTeamsChannelsResponse,\n GetMsTeamsTeamsInput,\n GetMsTeamsTeamsResponse,\n} from \"./interfaces\";\n\nclass MsTeamsClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n async authCheck({ tenant: tenantId, knockChannelId }: AuthCheckInput) {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/ms-teams/${knockChannelId}/auth_check`,\n params: {\n ms_teams_tenant_object: {\n object_id: tenantId,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n async getTeams(\n input: GetMsTeamsTeamsInput,\n ): Promise<GetMsTeamsTeamsResponse> {\n const { knockChannelId, tenant: tenantId } = input;\n const queryOptions = input.queryOptions || {};\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/ms-teams/${knockChannelId}/teams`,\n params: {\n ms_teams_tenant_object: {\n object_id: tenantId,\n collection: TENANT_OBJECT_COLLECTION,\n },\n query_options: {\n $filter: queryOptions.$filter,\n $select: queryOptions.$select,\n $top: queryOptions.$top,\n $skiptoken: queryOptions.$skiptoken,\n },\n },\n });\n\n return this.handleResponse(result);\n }\n\n async getChannels(\n input: GetMsTeamsChannelsInput,\n ): Promise<GetMsTeamsChannelsResponse> {\n const { knockChannelId, teamId, tenant: tenantId } = input;\n const queryOptions = input.queryOptions || {};\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/ms-teams/${knockChannelId}/channels`,\n params: {\n ms_teams_tenant_object: {\n object_id: tenantId,\n collection: TENANT_OBJECT_COLLECTION,\n },\n team_id: teamId,\n query_options: {\n $filter: queryOptions.$filter,\n $select: queryOptions.$select,\n },\n },\n });\n\n return this.handleResponse(result);\n }\n\n async revokeAccessToken({\n tenant: tenantId,\n knockChannelId,\n }: RevokeAccessTokenInput) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/providers/ms-teams/${knockChannelId}/revoke_access`,\n params: {\n ms_teams_tenant_object: {\n object_id: tenantId,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n private handleResponse(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n if (response.error?.response?.status < 500) {\n return response.error || response.body;\n }\n throw new Error(response.error || response.body);\n }\n\n return response.body;\n }\n}\n\nexport default MsTeamsClient;\n"],"names":["MsTeamsClient","instance","__publicField","tenantId","knockChannelId","result","TENANT_OBJECT_COLLECTION","input","queryOptions","teamId","response","_b","_a"],"mappings":"2TAYA,MAAMA,CAAc,CAGlB,YAAYC,EAAiB,CAFrBC,EAAA,iBAGN,KAAK,SAAWD,CAClB,CAEA,MAAM,UAAU,CAAE,OAAQE,EAAU,eAAAC,GAAkC,CACpE,MAAMC,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,0BAA0BD,CAAc,cAC7C,OAAQ,CACN,uBAAwB,CACtB,UAAWD,EACX,WAAYG,EAAA,wBACd,EACA,WAAYF,CACd,CAAA,CACD,EAEM,OAAA,KAAK,eAAeC,CAAM,CACnC,CAEA,MAAM,SACJE,EACkC,CAClC,KAAM,CAAE,eAAAH,EAAgB,OAAQD,CAAA,EAAaI,EACvCC,EAAeD,EAAM,cAAgB,GAErCF,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,0BAA0BD,CAAc,SAC7C,OAAQ,CACN,uBAAwB,CACtB,UAAWD,EACX,WAAYG,EAAA,wBACd,EACA,cAAe,CACb,QAASE,EAAa,QACtB,QAASA,EAAa,QACtB,KAAMA,EAAa,KACnB,WAAYA,EAAa,UAC3B,CACF,CAAA,CACD,EAEM,OAAA,KAAK,eAAeH,CAAM,CACnC,CAEA,MAAM,YACJE,EACqC,CACrC,KAAM,CAAE,eAAAH,EAAgB,OAAAK,EAAQ,OAAQN,GAAaI,EAC/CC,EAAeD,EAAM,cAAgB,GAErCF,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,0BAA0BD,CAAc,YAC7C,OAAQ,CACN,uBAAwB,CACtB,UAAWD,EACX,WAAYG,EAAA,wBACd,EACA,QAASG,EACT,cAAe,CACb,QAASD,EAAa,QACtB,QAASA,EAAa,OACxB,CACF,CAAA,CACD,EAEM,OAAA,KAAK,eAAeH,CAAM,CACnC,CAEA,MAAM,kBAAkB,CACtB,OAAQF,EACR,eAAAC,CAAA,EACyB,CACzB,MAAMC,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,0BAA0BD,CAAc,iBAC7C,OAAQ,CACN,uBAAwB,CACtB,UAAWD,EACX,WAAYG,EAAA,wBACd,EACA,WAAYF,CACd,CAAA,CACD,EAEM,OAAA,KAAK,eAAeC,CAAM,CACnC,CAEQ,eAAeK,EAAuB,SACxC,GAAAA,EAAS,aAAe,QAAS,CACnC,KAAIC,GAAAC,EAAAF,EAAS,QAAT,YAAAE,EAAgB,WAAhB,YAAAD,EAA0B,QAAS,IAC9B,OAAAD,EAAS,OAASA,EAAS,KAEpC,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,CACjD,CAEA,OAAOA,EAAS,IAClB,CACF"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/clients/ms-teams/index.ts"],"sourcesContent":["import { ApiResponse } from \"../../api\";\nimport { AuthCheckInput, RevokeAccessTokenInput } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport { TENANT_OBJECT_COLLECTION } from \"../objects/constants\";\n\nimport {\n GetMsTeamsChannelsInput,\n GetMsTeamsChannelsResponse,\n GetMsTeamsTeamsInput,\n GetMsTeamsTeamsResponse,\n} from \"./interfaces\";\n\nclass MsTeamsClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n async authCheck({ tenant: tenantId, knockChannelId }: AuthCheckInput) {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/ms-teams/${knockChannelId}/auth_check`,\n params: {\n ms_teams_tenant_object: {\n object_id: tenantId,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n async getTeams(\n input: GetMsTeamsTeamsInput,\n ): Promise<GetMsTeamsTeamsResponse> {\n const { knockChannelId, tenant: tenantId } = input;\n const queryOptions = input.queryOptions || {};\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/ms-teams/${knockChannelId}/teams`,\n params: {\n ms_teams_tenant_object: {\n object_id: tenantId,\n collection: TENANT_OBJECT_COLLECTION,\n },\n query_options: {\n $filter: queryOptions.$filter,\n $select: queryOptions.$select,\n $top: queryOptions.$top,\n $skiptoken: queryOptions.$skiptoken,\n },\n },\n });\n\n return this.handleResponse(result);\n }\n\n async getChannels(\n input: GetMsTeamsChannelsInput,\n ): Promise<GetMsTeamsChannelsResponse> {\n const { knockChannelId, teamId, tenant: tenantId } = input;\n const queryOptions = input.queryOptions || {};\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/ms-teams/${knockChannelId}/channels`,\n params: {\n ms_teams_tenant_object: {\n object_id: tenantId,\n collection: TENANT_OBJECT_COLLECTION,\n },\n team_id: teamId,\n query_options: {\n $filter: queryOptions.$filter,\n $select: queryOptions.$select,\n },\n },\n });\n\n return this.handleResponse(result);\n }\n\n async revokeAccessToken({\n tenant: tenantId,\n knockChannelId,\n }: RevokeAccessTokenInput) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/providers/ms-teams/${knockChannelId}/revoke_access`,\n params: {\n ms_teams_tenant_object: {\n object_id: tenantId,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n private handleResponse(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n if (response.error?.response?.status < 500) {\n return response.error || response.body;\n }\n throw new Error(response.error || response.body);\n }\n\n return response.body;\n }\n}\n\nexport default MsTeamsClient;\n"],"names":["MsTeamsClient","instance","__publicField","tenantId","knockChannelId","result","TENANT_OBJECT_COLLECTION","input","queryOptions","teamId","response","_b","_a"],"mappings":"2TAYA,MAAMA,CAAc,CAGlB,YAAYC,EAAiB,CAFrBC,EAAA,iBAGN,KAAK,SAAWD,CAAA,CAGlB,MAAM,UAAU,CAAE,OAAQE,EAAU,eAAAC,GAAkC,CACpE,MAAMC,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,0BAA0BD,CAAc,cAC7C,OAAQ,CACN,uBAAwB,CACtB,UAAWD,EACX,WAAYG,EAAAA,wBACd,EACA,WAAYF,CAAA,CACd,CACD,EAEM,OAAA,KAAK,eAAeC,CAAM,CAAA,CAGnC,MAAM,SACJE,EACkC,CAClC,KAAM,CAAE,eAAAH,EAAgB,OAAQD,CAAa,EAAAI,EACvCC,EAAeD,EAAM,cAAgB,CAAC,EAEtCF,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,0BAA0BD,CAAc,SAC7C,OAAQ,CACN,uBAAwB,CACtB,UAAWD,EACX,WAAYG,EAAAA,wBACd,EACA,cAAe,CACb,QAASE,EAAa,QACtB,QAASA,EAAa,QACtB,KAAMA,EAAa,KACnB,WAAYA,EAAa,UAAA,CAC3B,CACF,CACD,EAEM,OAAA,KAAK,eAAeH,CAAM,CAAA,CAGnC,MAAM,YACJE,EACqC,CACrC,KAAM,CAAE,eAAAH,EAAgB,OAAAK,EAAQ,OAAQN,CAAa,EAAAI,EAC/CC,EAAeD,EAAM,cAAgB,CAAC,EAEtCF,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,0BAA0BD,CAAc,YAC7C,OAAQ,CACN,uBAAwB,CACtB,UAAWD,EACX,WAAYG,EAAAA,wBACd,EACA,QAASG,EACT,cAAe,CACb,QAASD,EAAa,QACtB,QAASA,EAAa,OAAA,CACxB,CACF,CACD,EAEM,OAAA,KAAK,eAAeH,CAAM,CAAA,CAGnC,MAAM,kBAAkB,CACtB,OAAQF,EACR,eAAAC,CAAA,EACyB,CACzB,MAAMC,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,0BAA0BD,CAAc,iBAC7C,OAAQ,CACN,uBAAwB,CACtB,UAAWD,EACX,WAAYG,EAAAA,wBACd,EACA,WAAYF,CAAA,CACd,CACD,EAEM,OAAA,KAAK,eAAeC,CAAM,CAAA,CAG3B,eAAeK,EAAuB,SACxC,GAAAA,EAAS,aAAe,QAAS,CACnC,KAAIC,GAAAC,EAAAF,EAAS,QAAT,YAAAE,EAAgB,WAAhB,YAAAD,EAA0B,QAAS,IAC9B,OAAAD,EAAS,OAASA,EAAS,KAEpC,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,CAAA,CAGjD,OAAOA,EAAS,IAAA,CAEpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/clients/objects/index.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\n\nimport { ApiResponse } from \"../../api\";\nimport { ChannelData } from \"../../interfaces\";\nimport Knock from \"../../knock\";\n\ntype GetChannelDataInput = {\n objectId: string;\n collection: string;\n channelId: string;\n};\n\ntype SetChannelDataInput = {\n objectId: string;\n collection: string;\n channelId: string;\n data: GenericData;\n};\n\nclass ObjectClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n async getChannelData<T = GenericData>({\n collection,\n objectId,\n channelId,\n }: GetChannelDataInput) {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/objects/${collection}/${objectId}/channel_data/${channelId}`,\n });\n\n return this.handleResponse<ChannelData<T>>(result);\n }\n\n async setChannelData({\n objectId,\n collection,\n channelId,\n data,\n }: SetChannelDataInput) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `v1/objects/${collection}/${objectId}/channel_data/${channelId}`,\n data: { data },\n });\n\n return this.handleResponse(result);\n }\n\n private handleResponse<T>(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n throw new Error(response.error || response.body);\n }\n\n return response.body as T;\n }\n}\n\nexport default ObjectClient;\n"],"names":["ObjectClient","instance","__publicField","collection","objectId","channelId","result","data","response"],"mappings":"gRAmBA,MAAMA,CAAa,CAGjB,YAAYC,EAAiB,CAFrBC,EAAA,iBAGN,KAAK,SAAWD,CAClB,CACA,MAAM,eAAgC,CACpC,WAAAE,EACA,SAAAC,EACA,UAAAC,CAAA,EACsB,CACtB,MAAMC,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,eAAeH,CAAU,IAAIC,CAAQ,iBAAiBC,CAAS,EAAA,CACrE,EAEM,OAAA,KAAK,eAA+BC,CAAM,CACnD,CAEA,MAAM,eAAe,CACnB,SAAAF,EACA,WAAAD,EACA,UAAAE,EACA,KAAAE,CAAA,EACsB,CACtB,MAAMD,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,cAAcH,CAAU,IAAIC,CAAQ,iBAAiBC,CAAS,GACnE,KAAM,CAAE,KAAAE,CAAK,CAAA,CACd,EAEM,OAAA,KAAK,eAAeD,CAAM,CACnC,CAEQ,eAAkBE,EAAuB,CAC3C,GAAAA,EAAS,aAAe,QAC1B,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,EAGjD,OAAOA,EAAS,IAClB,CACF"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/clients/objects/index.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\n\nimport { ApiResponse } from \"../../api\";\nimport { ChannelData } from \"../../interfaces\";\nimport Knock from \"../../knock\";\n\ntype GetChannelDataInput = {\n objectId: string;\n collection: string;\n channelId: string;\n};\n\ntype SetChannelDataInput = {\n objectId: string;\n collection: string;\n channelId: string;\n data: GenericData;\n};\n\nclass ObjectClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n async getChannelData<T = GenericData>({\n collection,\n objectId,\n channelId,\n }: GetChannelDataInput) {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/objects/${collection}/${objectId}/channel_data/${channelId}`,\n });\n\n return this.handleResponse<ChannelData<T>>(result);\n }\n\n async setChannelData({\n objectId,\n collection,\n channelId,\n data,\n }: SetChannelDataInput) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `v1/objects/${collection}/${objectId}/channel_data/${channelId}`,\n data: { data },\n });\n\n return this.handleResponse(result);\n }\n\n private handleResponse<T>(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n throw new Error(response.error || response.body);\n }\n\n return response.body as T;\n }\n}\n\nexport default ObjectClient;\n"],"names":["ObjectClient","instance","__publicField","collection","objectId","channelId","result","data","response"],"mappings":"gRAmBA,MAAMA,CAAa,CAGjB,YAAYC,EAAiB,CAFrBC,EAAA,iBAGN,KAAK,SAAWD,CAAA,CAElB,MAAM,eAAgC,CACpC,WAAAE,EACA,SAAAC,EACA,UAAAC,CAAA,EACsB,CACtB,MAAMC,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,eAAeH,CAAU,IAAIC,CAAQ,iBAAiBC,CAAS,EAAA,CACrE,EAEM,OAAA,KAAK,eAA+BC,CAAM,CAAA,CAGnD,MAAM,eAAe,CACnB,SAAAF,EACA,WAAAD,EACA,UAAAE,EACA,KAAAE,CAAA,EACsB,CACtB,MAAMD,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,cAAcH,CAAU,IAAIC,CAAQ,iBAAiBC,CAAS,GACnE,KAAM,CAAE,KAAAE,CAAK,CAAA,CACd,EAEM,OAAA,KAAK,eAAeD,CAAM,CAAA,CAG3B,eAAkBE,EAAuB,CAC3C,GAAAA,EAAS,aAAe,QAC1B,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,EAGjD,OAAOA,EAAS,IAAA,CAEpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/clients/preferences/index.ts"],"sourcesContent":["import { ChannelType } from \"@knocklabs/types\";\n\nimport { ApiResponse } from \"../../api\";\nimport Knock from \"../../knock\";\n\nimport {\n ChannelTypePreferences,\n PreferenceOptions,\n PreferenceSet,\n SetPreferencesProperties,\n WorkflowPreferenceSetting,\n WorkflowPreferences,\n} from \"./interfaces\";\n\nconst DEFAULT_PREFERENCE_SET_ID = \"default\";\n\nfunction buildUpdateParam(param: WorkflowPreferenceSetting) {\n if (typeof param === \"object\") {\n return param;\n }\n\n return { subscribed: param };\n}\n\nclass Preferences {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n /**\n * @deprecated Use `user.getAllPreferences()` instead\n */\n async getAll() {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences`,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.getPreferences()` instead\n */\n async get(options: PreferenceOptions = {}) {\n this.instance.failIfNotAuthenticated();\n\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async set(\n preferenceSet: SetPreferencesProperties,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n data: preferenceSet,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setChannelTypes(\n channelTypePreferences: ChannelTypePreferences,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/channel_types`,\n data: channelTypePreferences,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setChannelType(\n channelType: ChannelType,\n setting: boolean,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/channel_types/${channelType}`,\n data: { subscribed: setting },\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setWorkflows(\n workflowPreferences: WorkflowPreferences,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/workflows`,\n data: workflowPreferences,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setWorkflow(\n workflowKey: string,\n setting: WorkflowPreferenceSetting,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n const params = buildUpdateParam(setting);\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/workflows/${workflowKey}`,\n data: params,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setCategories(\n categoryPreferences: WorkflowPreferences,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/categories`,\n data: categoryPreferences,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setCategory(\n categoryKey: string,\n setting: WorkflowPreferenceSetting,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n const params = buildUpdateParam(setting);\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/categories/${categoryKey}`,\n data: params,\n });\n\n return this.handleResponse(result);\n }\n\n private handleResponse(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n throw new Error(response.error || response.body);\n }\n\n return response.body as PreferenceSet;\n }\n}\n\nexport default Preferences;\n"],"names":["DEFAULT_PREFERENCE_SET_ID","buildUpdateParam","param","Preferences","instance","__publicField","result","options","preferenceSetId","preferenceSet","channelTypePreferences","channelType","setting","workflowPre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AAC,EAAkBD,EAAQ,eAAiBP,EAC3Ce,EAASd,EAAiBW,CAAO,EAEjCN,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,gBAAgBE,CAAe,eAAeS,CAAW,GAC/F,KAAMF,CAAA,CACP,EAEM,OAAA,KAAK,eAAeT,CAAM,CACnC,CAEQ,eAAeY,EAAuB,CACxC,GAAAA,EAAS,aAAe,QAC1B,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,EAGjD,OAAOA,EAAS,IAClB,CACF"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/clients/preferences/index.ts"],"sourcesContent":["import { ChannelType } from \"@knocklabs/types\";\n\nimport { ApiResponse } from \"../../api\";\nimport Knock from \"../../knock\";\n\nimport {\n ChannelTypePreferences,\n PreferenceOptions,\n PreferenceSet,\n SetPreferencesProperties,\n WorkflowPreferenceSetting,\n WorkflowPreferences,\n} from \"./interfaces\";\n\nconst DEFAULT_PREFERENCE_SET_ID = \"default\";\n\nfunction buildUpdateParam(param: WorkflowPreferenceSetting) {\n if (typeof param === \"object\") {\n return param;\n }\n\n return { subscribed: param };\n}\n\nclass Preferences {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n /**\n * @deprecated Use `user.getAllPreferences()` instead\n */\n async getAll() {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences`,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.getPreferences()` instead\n */\n async get(options: PreferenceOptions = {}) {\n this.instance.failIfNotAuthenticated();\n\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async set(\n preferenceSet: SetPreferencesProperties,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n data: preferenceSet,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setChannelTypes(\n channelTypePreferences: ChannelTypePreferences,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/channel_types`,\n data: channelTypePreferences,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setChannelType(\n channelType: ChannelType,\n setting: boolean,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/channel_types/${channelType}`,\n data: { subscribed: setting },\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setWorkflows(\n workflowPreferences: WorkflowPreferences,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/workflows`,\n data: workflowPreferences,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setWorkflow(\n workflowKey: string,\n setting: WorkflowPreferenceSetting,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n const params = buildUpdateParam(setting);\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/workflows/${workflowKey}`,\n data: params,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setCategories(\n categoryPreferences: WorkflowPreferences,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/categories`,\n data: categoryPreferences,\n });\n\n return this.handleResponse(result);\n }\n\n /**\n * @deprecated Use `user.setPreferences(preferenceSet, options)` instead\n */\n async setCategory(\n categoryKey: string,\n setting: WorkflowPreferenceSetting,\n options: PreferenceOptions = {},\n ) {\n this.instance.failIfNotAuthenticated();\n\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n const params = buildUpdateParam(setting);\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}/categories/${categoryKey}`,\n data: params,\n });\n\n return this.handleResponse(result);\n }\n\n private handleResponse(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n throw new Error(response.error || response.body);\n }\n\n return response.body as PreferenceSet;\n }\n}\n\nexport default Preferences;\n"],"names":["DEFAULT_PREFERENCE_SET_ID","buildUpdateParam","param","Preferences","instance","__publicField","result","options","preferenceSetId","preferenceSet","channelTypePreferences","channelType","setting","workflowPreferences","workflowKey","params","categoryPreferences","categoryKey","response"],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,EACAL,EACAL,EAA6B,CAAA,EAC7B,CACA,KAAK,SAAS,uBAAuB,EAE/B,MAAAC,EAAkBD,EAAQ,eAAiBP,EAC3Ce,EAASd,EAAiBW,CAAO,EAEjCN,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,gBAAgBE,CAAe,eAAeS,CAAW,GAC/F,KAAMF,CAAA,CACP,EAEM,OAAA,KAAK,eAAeT,CAAM,CAAA,CAG3B,eAAeY,EAAuB,CACxC,GAAAA,EAAS,aAAe,QAC1B,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,EAGjD,OAAOA,EAAS,IAAA,CAEpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/clients/slack/index.ts"],"sourcesContent":["import { ApiResponse } from \"../../api\";\nimport { AuthCheckInput, RevokeAccessTokenInput } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport { TENANT_OBJECT_COLLECTION } from \"../objects/constants\";\n\nimport { GetSlackChannelsInput, GetSlackChannelsResponse } from \"./interfaces\";\n\nclass SlackClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n async authCheck({ tenant, knockChannelId }: AuthCheckInput) {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/slack/${knockChannelId}/auth_check`,\n params: {\n access_token_object: {\n object_id: tenant,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n async getChannels(\n input: GetSlackChannelsInput,\n ): Promise<GetSlackChannelsResponse> {\n const { knockChannelId, tenant } = input;\n const queryOptions = input.queryOptions || {};\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/slack/${knockChannelId}/channels`,\n params: {\n access_token_object: {\n object_id: tenant,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n query_options: {\n cursor: queryOptions.cursor,\n limit: queryOptions.limit,\n exclude_archived: queryOptions.excludeArchived,\n team_id: queryOptions.teamId,\n types: queryOptions.types,\n },\n },\n });\n\n return this.handleResponse(result);\n }\n\n async revokeAccessToken({ tenant, knockChannelId }: RevokeAccessTokenInput) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/providers/slack/${knockChannelId}/revoke_access`,\n params: {\n access_token_object: {\n object_id: tenant,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n private handleResponse(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n if (response.error?.response?.status < 500) {\n return response.error || response.body;\n }\n throw new Error(response.error || response.body);\n }\n\n return response.body;\n }\n}\n\nexport default SlackClient;\n"],"names":["SlackClient","instance","__publicField","tenant","knockChannelId","result","TENANT_OBJECT_COLLECTION","input","queryOptions","response","_b","_a"],"mappings":"2TAOA,MAAMA,CAAY,CAGhB,YAAYC,EAAiB,CAFrBC,EAAA,iBAGN,KAAK,SAAWD,CAClB,CAEA,MAAM,UAAU,CAAE,OAAAE,EAAQ,eAAAC,GAAkC,CAC1D,MAAMC,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,uBAAuBD,CAAc,cAC1C,OAAQ,CACN,oBAAqB,CACnB,UAAWD,EACX,WAAYG,EAAA,wBACd,EACA,WAAYF,CACd,CAAA,CACD,EAEM,OAAA,KAAK,eAAeC,CAAM,CACnC,CAEA,MAAM,YACJE,EACmC,CAC7B,KAAA,CAAE,eAAAH,EAAgB,OAAAD,CAAW,EAAAI,EAC7BC,EAAeD,EAAM,cAAgB,GAErCF,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,uBAAuBD,CAAc,YAC1C,OAAQ,CACN,oBAAqB,CACnB,UAAWD,EACX,WAAYG,EAAA,wBACd,EACA,WAAYF,EACZ,cAAe,CACb,OAAQI,EAAa,OACrB,MAAOA,EAAa,MACpB,iBAAkBA,EAAa,gBAC/B,QAASA,EAAa,OACtB,MAAOA,EAAa,KACtB,CACF,CAAA,CACD,EAEM,OAAA,KAAK,eAAeH,CAAM,CACnC,CAEA,MAAM,kBAAkB,CAAE,OAAAF,EAAQ,eAAAC,GAA0C,CAC1E,MAAMC,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,uBAAuBD,CAAc,iBAC1C,OAAQ,CACN,oBAAqB,CACnB,UAAWD,EACX,WAAYG,EAAA,wBACd,EACA,WAAYF,CACd,CAAA,CACD,EAEM,OAAA,KAAK,eAAeC,CAAM,CACnC,CAEQ,eAAeI,EAAuB,SACxC,GAAAA,EAAS,aAAe,QAAS,CACnC,KAAIC,GAAAC,EAAAF,EAAS,QAAT,YAAAE,EAAgB,WAAhB,YAAAD,EAA0B,QAAS,IAC9B,OAAAD,EAAS,OAASA,EAAS,KAEpC,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,CACjD,CAEA,OAAOA,EAAS,IAClB,CACF"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/clients/slack/index.ts"],"sourcesContent":["import { ApiResponse } from \"../../api\";\nimport { AuthCheckInput, RevokeAccessTokenInput } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport { TENANT_OBJECT_COLLECTION } from \"../objects/constants\";\n\nimport { GetSlackChannelsInput, GetSlackChannelsResponse } from \"./interfaces\";\n\nclass SlackClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n async authCheck({ tenant, knockChannelId }: AuthCheckInput) {\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/slack/${knockChannelId}/auth_check`,\n params: {\n access_token_object: {\n object_id: tenant,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n async getChannels(\n input: GetSlackChannelsInput,\n ): Promise<GetSlackChannelsResponse> {\n const { knockChannelId, tenant } = input;\n const queryOptions = input.queryOptions || {};\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/providers/slack/${knockChannelId}/channels`,\n params: {\n access_token_object: {\n object_id: tenant,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n query_options: {\n cursor: queryOptions.cursor,\n limit: queryOptions.limit,\n exclude_archived: queryOptions.excludeArchived,\n team_id: queryOptions.teamId,\n types: queryOptions.types,\n },\n },\n });\n\n return this.handleResponse(result);\n }\n\n async revokeAccessToken({ tenant, knockChannelId }: RevokeAccessTokenInput) {\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/providers/slack/${knockChannelId}/revoke_access`,\n params: {\n access_token_object: {\n object_id: tenant,\n collection: TENANT_OBJECT_COLLECTION,\n },\n channel_id: knockChannelId,\n },\n });\n\n return this.handleResponse(result);\n }\n\n private handleResponse(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n if (response.error?.response?.status < 500) {\n return response.error || response.body;\n }\n throw new Error(response.error || response.body);\n }\n\n return response.body;\n }\n}\n\nexport default SlackClient;\n"],"names":["SlackClient","instance","__publicField","tenant","knockChannelId","result","TENANT_OBJECT_COLLECTION","input","queryOptions","response","_b","_a"],"mappings":"2TAOA,MAAMA,CAAY,CAGhB,YAAYC,EAAiB,CAFrBC,EAAA,iBAGN,KAAK,SAAWD,CAAA,CAGlB,MAAM,UAAU,CAAE,OAAAE,EAAQ,eAAAC,GAAkC,CAC1D,MAAMC,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,uBAAuBD,CAAc,cAC1C,OAAQ,CACN,oBAAqB,CACnB,UAAWD,EACX,WAAYG,EAAAA,wBACd,EACA,WAAYF,CAAA,CACd,CACD,EAEM,OAAA,KAAK,eAAeC,CAAM,CAAA,CAGnC,MAAM,YACJE,EACmC,CAC7B,KAAA,CAAE,eAAAH,EAAgB,OAAAD,CAAA,EAAWI,EAC7BC,EAAeD,EAAM,cAAgB,CAAC,EAEtCF,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,uBAAuBD,CAAc,YAC1C,OAAQ,CACN,oBAAqB,CACnB,UAAWD,EACX,WAAYG,EAAAA,wBACd,EACA,WAAYF,EACZ,cAAe,CACb,OAAQI,EAAa,OACrB,MAAOA,EAAa,MACpB,iBAAkBA,EAAa,gBAC/B,QAASA,EAAa,OACtB,MAAOA,EAAa,KAAA,CACtB,CACF,CACD,EAEM,OAAA,KAAK,eAAeH,CAAM,CAAA,CAGnC,MAAM,kBAAkB,CAAE,OAAAF,EAAQ,eAAAC,GAA0C,CAC1E,MAAMC,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,uBAAuBD,CAAc,iBAC1C,OAAQ,CACN,oBAAqB,CACnB,UAAWD,EACX,WAAYG,EAAAA,wBACd,EACA,WAAYF,CAAA,CACd,CACD,EAEM,OAAA,KAAK,eAAeC,CAAM,CAAA,CAG3B,eAAeI,EAAuB,SACxC,GAAAA,EAAS,aAAe,QAAS,CACnC,KAAIC,GAAAC,EAAAF,EAAS,QAAT,YAAAE,EAAgB,WAAhB,YAAAD,EAA0B,QAAS,IAC9B,OAAAD,EAAS,OAASA,EAAS,KAEpC,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,CAAA,CAGjD,OAAOA,EAAS,IAAA,CAEpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../src/clients/users/index.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\n\nimport { ApiResponse } from \"../../api\";\nimport { ChannelData, User } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport {\n GetPreferencesOptions,\n PreferenceOptions,\n PreferenceSet,\n SetPreferencesProperties,\n} from \"../preferences/interfaces\";\n\nimport { GetChannelDataInput, SetChannelDataInput } from \"./interfaces\";\n\nconst DEFAULT_PREFERENCE_SET_ID = \"default\";\n\nclass UserClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n async get() {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}`,\n });\n\n return this.handleResponse<User>(result);\n }\n\n async identify(props: GenericData = {}) {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}`,\n params: props,\n });\n\n return this.handleResponse<User>(result);\n }\n\n async getAllPreferences() {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences`,\n });\n\n return this.handleResponse<PreferenceSet[]>(result);\n }\n\n async getPreferences(\n options: GetPreferencesOptions = {},\n ): Promise<PreferenceSet> {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n params: { tenant: options.tenant },\n });\n\n return this.handleResponse<PreferenceSet>(result);\n }\n\n async setPreferences(\n preferenceSet: SetPreferencesProperties,\n options: PreferenceOptions = {},\n ): Promise<PreferenceSet> {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n data: preferenceSet,\n });\n\n return this.handleResponse<PreferenceSet>(result);\n }\n\n async getChannelData<T = GenericData>(params: GetChannelDataInput) {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/channel_data/${params.channelId}`,\n });\n\n return this.handleResponse<ChannelData<T>>(result);\n }\n\n async setChannelData<T = GenericData>({\n channelId,\n channelData,\n }: SetChannelDataInput) {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/channel_data/${channelId}`,\n data: { data: channelData },\n });\n\n return this.handleResponse<ChannelData<T>>(result);\n }\n\n private handleResponse<T>(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n throw new Error(response.error || response.body);\n }\n\n return response.body as T;\n }\n}\n\nexport default UserClient;\n"],"names":["DEFAULT_PREFERENCE_SET_ID","UserClient","instance","__publicField","result","props","options","preferenceSetId","preferenceSet","params","channelId","channelData","response"],"mappings":"gRAcA,MAAMA,EAA4B,UAElC,MAAMC,CAAW,CAGf,YAAYC,EAAiB,CAFrBC,EAAA,iBAGN,KAAK,SAAWD,CAClB,CAEA,MAAM,KAAM,CACV,KAAK,SAAS,yBAEd,MAAME,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,EAAA,CACvC,EAEM,OAAA,KAAK,eAAqBA,CAAM,CACzC,CAEA,MAAM,SAASC,EAAqB,GAAI,CACtC,KAAK,SAAS,yBAEd,MAAMD,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,GACtC,OAAQC,CAAA,CACT,EAEM,OAAA,KAAK,eAAqBD,CAAM,CACzC,CAEA,MAAM,mBAAoB,CACxB,KAAK,SAAS,yBAEd,MAAMA,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,cAAA,CACvC,EAEM,OAAA,KAAK,eAAgCA,CAAM,CACpD,CAEA,MAAM,eACJE,EAAiC,GACT,CACxB,KAAK,SAAS,yBACR,MAAAC,EAAkBD,EAAQ,eAAiBN,EAE3CI,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,gBAAgBG,CAAe,GACrE,OAAQ,CAAE,OAAQD,EAAQ,MAAO,CAAA,CAClC,EAEM,OAAA,KAAK,eAA8BF,CAAM,CAClD,CAEA,MAAM,eACJI,EACAF,EAA6B,GACL,CACxB,KAAK,SAAS,yBACR,MAAAC,EAAkBD,EAAQ,eAAiBN,EAE3CI,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,gBAAgBG,CAAe,GACrE,KAAMC,CAAA,CACP,EAEM,OAAA,KAAK,eAA8BJ,CAAM,CAClD,CAEA,MAAM,eAAgCK,EAA6B,CACjE,KAAK,SAAS,yBAEd,MAAML,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,iBAAiBK,EAAO,SAAS,EAAA,CACxE,EAEM,OAAA,KAAK,eAA+BL,CAAM,CACnD,CAEA,MAAM,eAAgC,CACpC,UAAAM,EACA,YAAAC,CAAA,EACsB,CACtB,KAAK,SAAS,yBAEd,MAAMP,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,iBAAiBM,CAAS,GAChE,KAAM,CAAE,KAAMC,CAAY,CAAA,CAC3B,EAEM,OAAA,KAAK,eAA+BP,CAAM,CACnD,CAEQ,eAAkBQ,EAAuB,CAC3C,GAAAA,EAAS,aAAe,QAC1B,MAAM,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,EAGjD,OAAOA,EAAS,IAClB,CACF"}
1
+ {"version":3,"file":"index.js","sources":["../../../../src/clients/users/index.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\n\nimport { ApiResponse } from \"../../api\";\nimport { ChannelData, User } from \"../../interfaces\";\nimport Knock from \"../../knock\";\nimport {\n GetPreferencesOptions,\n PreferenceOptions,\n PreferenceSet,\n SetPreferencesProperties,\n} from \"../preferences/interfaces\";\n\nimport { GetChannelDataInput, SetChannelDataInput } from \"./interfaces\";\n\nconst DEFAULT_PREFERENCE_SET_ID = \"default\";\n\nclass UserClient {\n private instance: Knock;\n\n constructor(instance: Knock) {\n this.instance = instance;\n }\n\n async get() {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}`,\n });\n\n return this.handleResponse<User>(result);\n }\n\n async identify(props: GenericData = {}) {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}`,\n params: props,\n });\n\n return this.handleResponse<User>(result);\n }\n\n async getAllPreferences() {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences`,\n });\n\n return this.handleResponse<PreferenceSet[]>(result);\n }\n\n async getPreferences(\n options: GetPreferencesOptions = {},\n ): Promise<PreferenceSet> {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n params: { tenant: options.tenant },\n });\n\n return this.handleResponse<PreferenceSet>(result);\n }\n\n async setPreferences(\n preferenceSet: SetPreferencesProperties,\n options: PreferenceOptions = {},\n ): Promise<PreferenceSet> {\n this.instance.failIfNotAuthenticated();\n const preferenceSetId = options.preferenceSet || DEFAULT_PREFERENCE_SET_ID;\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/preferences/${preferenceSetId}`,\n data: preferenceSet,\n });\n\n return this.handleResponse<PreferenceSet>(result);\n }\n\n async getChannelData<T = GenericData>(params: GetChannelDataInput) {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"GET\",\n url: `/v1/users/${this.instance.userId}/channel_data/${params.channelId}`,\n });\n\n return this.handleResponse<ChannelData<T>>(result);\n }\n\n async setChannelData<T = GenericData>({\n channelId,\n channelData,\n }: SetChannelDataInput) {\n this.instance.failIfNotAuthenticated();\n\n const result = await this.instance.client().makeRequest({\n method: \"PUT\",\n url: `/v1/users/${this.instance.userId}/channel_data/${channelId}`,\n data: { data: channelData },\n });\n\n return this.handleResponse<ChannelData<T>>(result);\n }\n\n private handleResponse<T>(response: ApiResponse) {\n if (response.statusCode === \"error\") {\n throw new Error(response.error || response.body);\n }\n\n return response.body as T;\n }\n}\n\nexport default UserClient;\n"],"names":["DEFAULT_PREFERENCE_SET_ID","UserClient","instance","__publicField","result","props","options","preferenceSetId","preferenceSet","params","channelId","channelData","response"],"mappings":"gRAcA,MAAMA,EAA4B,UAElC,MAAMC,CAAW,CAGf,YAAYC,EAAiB,CAFrBC,EAAA,iBAGN,KAAK,SAAWD,CAAA,CAGlB,MAAM,KAAM,CACV,KAAK,SAAS,uBAAuB,EAErC,MAAME,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,EAAA,CACvC,EAEM,OAAA,KAAK,eAAqBA,CAAM,CAAA,CAGzC,MAAM,SAASC,EAAqB,GAAI,CACtC,KAAK,SAAS,uBAAuB,EAErC,MAAMD,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,aAAa,KAAK,SAAS,MAAM,GACtC,OAAQC,CAAA,CACT,EAEM,OAAA,KAAK,eAAqBD,CAAM,CAAA,CAGzC,MAAM,mBAAoB,CACxB,KAAK,SAAS,uBAAuB,EAErC,MAAMA,EAAS,MAAM,KAAK,SAAS,OAAA,EAAS,YAAY,CACtD,OAAQ,MACR,IAAK,a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M,IAAI,MAAMA,EAAS,OAASA,EAAS,IAAI,EAGjD,OAAOA,EAAS,IAAA,CAEpB"}
@@ -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 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 Authenticates the current user. In non-sandbox environments\n the userToken must be specified.\n */\n authenticate(\n userId: Knock[\"userId\"],\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ) {\n let reinitializeApi = false;\n const currentApiClient = this.apiClient;\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 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) {\n if (this.logLevel === \"debug\") {\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\nexport default Knock;\n"],"names":["DEFAULT_HOST","Knock","apiKey","options","__publicField","FeedClient","ObjectClient","Preferences","SlackClient","MsTeamsClient","UserClient","MessageClient","userId","userToken","reinitializeApi","checkUserToken","_a","message","ApiClient","callbackFn","timeBeforeExpirationInMs","decoded","jwtDecode","expiresAtMs","nowMs","msInFuture","newToken"],"mappings":"2lBAiBMA,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,UAAW,IAAI,GAC3BD,EAAA,eAAU,IAAIE,UAAa,IAAI,GAC/BF,EAAA,mBAAc,IAAIG,UAAY,IAAI,GAClCH,EAAA,aAAQ,IAAII,UAAY,IAAI,GAC5BJ,EAAA,eAAU,IAAIK,UAAc,IAAI,GAChCL,EAAA,YAAO,IAAIM,UAAW,IAAI,GAC1BN,EAAA,gBAAW,IAAIO,UAAc,IAAI,GAYxC,GATS,KAAA,OAAAT,EAGJ,KAAA,KAAOC,EAAQ,MAAQH,EAC5B,KAAK,SAAWG,EAAQ,SAExB,KAAK,IAAI,4BAA4B,EAGjC,KAAK,QAAU,KAAK,OAAO,WAAW,KAAK,EAC7C,MAAM,IAAI,MACR,qFAAA,C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AcC,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,CACf,CACF,CACF"}
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 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 Authenticates the current user. In non-sandbox environments\n the userToken must be specified.\n */\n authenticate(\n userId: Knock[\"userId\"],\n userToken?: Knock[\"userToken\"],\n options?: AuthenticateOptions,\n ) {\n let reinitializeApi = false;\n const currentApiClient = this.apiClient;\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 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) {\n if (this.logLevel === \"debug\") {\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\nexport default Knock;\n"],"names":["DEFAULT_HOST","Knock","apiKey","options","__publicField","FeedClient","ObjectClient","Preferences","SlackClient","MsTeamsClient","UserClient","MessageClient","userId","userToken","reinitializeApi","checkUserToken","_a","message","ApiClient","callbackFn","timeBeforeExpirationInMs","decoded","jwtDecode","expiresAtMs","nowMs","msInFuture","newToken"],"mappings":"2lBAiBMA,EAAe,wBAErB,MAAMC,CAAM,CAeV,YACWC,EACTC,EAAwB,GACxB,CAjBKC,EAAA,aACCA,EAAA,iBAA8B,MAC/BA,EAAA,eACAA,EAAA,kBACAA,EAAA,iBACCA,EAAA,4BAA6D,MAC5DA,EAAA,aAAQ,IAAIC,EAAA,QAAW,IAAI,GAC3BD,EAAA,eAAU,IAAIE,EAAA,QAAa,IAAI,GAC/BF,EAAA,mBAAc,IAAIG,EAAA,QAAY,IAAI,GAClCH,EAAA,aAAQ,IAAII,EAAA,QAAY,IAAI,GAC5BJ,EAAA,eAAU,IAAIK,EAAA,QAAc,IAAI,GAChCL,EAAA,YAAO,IAAIM,EAAA,QAAW,IAAI,GAC1BN,EAAA,gBAAW,I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,KAAK,OACb,KAAM,KAAK,KACX,UAAW,KAAK,SAAA,CACjB,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,CAEJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"networkStatus.js","sources":["../../src/networkStatus.ts"],"sourcesContent":["export enum NetworkStatus {\n // Performing a top level loading operation\n loading = \"loading\",\n\n // Performing a fetch more on some already loaded data\n fetchMore = \"fetchMore\",\n\n // No operation is currently in progress\n ready = \"ready\",\n\n // The last operation failed with an error\n error = \"error\",\n}\n\nexport function isRequestInFlight(networkStatus: NetworkStatus): boolean {\n return [NetworkStatus.loading, NetworkStatus.fetchMore].includes(\n networkStatus,\n );\n}\n"],"names":["NetworkStatus","isRequestInFlight","networkStatus"],"mappings":"gFAAY,IAAAA,GAAAA,IAEVA,EAAA,QAAU,UAGVA,EAAA,UAAY,YAGZA,EAAA,MAAQ,QAGRA,EAAA,MAAQ,QAXEA,IAAAA,GAAA,CAAA,CAAA,EAcL,SAASC,EAAkBC,EAAuC,CAChE,MAAA,CAAC,UAAuB,WAAA,EAAyB,SACtDA,CAAA,CAEJ"}
1
+ {"version":3,"file":"networkStatus.js","sources":["../../src/networkStatus.ts"],"sourcesContent":["export enum NetworkStatus {\n // Performing a top level loading operation\n loading = \"loading\",\n\n // Performing a fetch more on some already loaded data\n fetchMore = \"fetchMore\",\n\n // No operation is currently in progress\n ready = \"ready\",\n\n // The last operation failed with an error\n error = \"error\",\n}\n\nexport function isRequestInFlight(networkStatus: NetworkStatus): boolean {\n return [NetworkStatus.loading, NetworkStatus.fetchMore].includes(\n networkStatus,\n );\n}\n"],"names":["NetworkStatus","isRequestInFlight","networkStatus"],"mappings":"gFAAY,IAAAA,GAAAA,IAEVA,EAAA,QAAU,UAGVA,EAAA,UAAY,YAGZA,EAAA,MAAQ,QAGRA,EAAA,MAAQ,QAXEA,IAAAA,GAAA,CAAA,CAAA,EAcL,SAASC,EAAkBC,EAAuC,CAChE,MAAA,CAAC,UAAuB,WAAA,EAAyB,SACtDA,CACF,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"api.mjs","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 },\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\nexport default ApiClient;\n"],"names":["ApiClient","options","__publicField","axios","Socket","axiosRetry","req","result","e","error"],"mappings":";;;;;;AAmBA,MAAMA,EAAU;AAAA,EAQd,YAAYC,GAA2B;AAP/B,IAAAC,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AAED,IAAAA,EAAA;AAGL,SAAK,OAAOD,EAAQ,MACpB,KAAK,SAASA,EAAQ,QACjB,KAAA,YAAYA,EAAQ,aAAa,MAGjC,KAAA,cAAcE,EAAM,OAAO;AAAA,MAC9B,SAAS,KAAK;AAAA,MACd,SAAS;AAAA,QACP,QAAQ;AAAA,QACR,gBAAgB;AAAA,QAChB,eAAe,UAAU,KAAK,MAAM;AAAA,QACpC,sBAAsB,KAAK;AAAA,MAC7B;AAAA,IAAA,CACD,GAEG,OAAO,SAAW,QACf,KAAA,SAAS,IAAIC,EAAO,GAAG,KAAK,KAAK,QAAQ,QAAQ,IAAI,CAAC,UAAU;AAAA,MACnE,QAAQ;AAAA,QACN,YAAY,KAAK;AAAA,QACjB,SAAS,KAAK;AAAA,MAChB;AAAA,IAAA,CACD,IAGHC,EAAW,KAAK,aAAa;AAAA,MAC3B,SAAS;AAAA,MACT,gBAAgB,KAAK;AAAA,MACrB,YAAYA,EAAW;AAAA,IAAA,CACxB;AAAA,EACH;AAAA,EAEA,MAAM,YAAYC,GAA+C;AAC3D,QAAA;AACF,YAAMC,IAAS,MAAM,KAAK,YAAYD,CAAG;AAElC,aAAA;AAAA,QACL,YAAYC,EAAO,SAAS,MAAM,OAAO;AAAA,QACzC,MAAMA,EAAO;AAAA,QACb,OAAO;AAAA,QACP,QAAQA,EAAO;AAAA,MAAA;AAAA,aAIVC,GAAY;AACnB,qBAAQ,MAAMA,CAAC,GAER;AAAA,QACL,YAAY;AAAA,QACZ,QAAQ;AAAA,QACR,MAAM;AAAA,QACN,OAAOA;AAAA,MAAA;AAAA,IAEX;AAAA,EACF;AAAA,EAEQ,gBAAgBC,GAAmB;AAErC,WAAAJ,EAAW,eAAeI,CAAK,IAC1B,KAGJA,EAAM,WAMPA,EAAM,SAAS,UAAU,OAAOA,EAAM,SAAS,UAAU,OAKzDA,EAAM,SAAS,WAAW,MATrB;AAAA,EAcX;AACF;"}
1
+ {"version":3,"file":"api.mjs","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 },\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\nexport default ApiClient;\n"],"names":["ApiClient","options","__publicField","axios","Socket","axiosRetry","req","result","e","error"],"mappings":";;;;;;AAmBA,MAAMA,EAAU;AAAA,EAQd,YAAYC,GAA2B;AAP/B,IAAAC,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AAED,IAAAA,EAAA;AAGL,SAAK,OAAOD,EAAQ,MACpB,KAAK,SAASA,EAAQ,QACjB,KAAA,YAAYA,EAAQ,aAAa,MAGjC,KAAA,cAAcE,EAAM,OAAO;AAAA,MAC9B,SAAS,KAAK;AAAA,MACd,SAAS;AAAA,QACP,QAAQ;AAAA,QACR,gBAAgB;AAAA,QAChB,eAAe,UAAU,KAAK,MAAM;AAAA,Q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