{"version":3,"sources":["../src/utils/getGatewayEndpoint.ts","../src/NaluriChat.ts"],"names":["getGatewayEndpoint","environment","SupportedEnvironments","NaluriChatError","NaluriChat","_NaluriChat","apiKey","apiSecret","onRefreshTokenError","AccountApi","timeoutMs","ChatInstance","authorizationCode","user","eventsApi","EVENTS","invariant","ChatApi","GatewayApi","startRefreshTokenOnInterval","tokenStore","refreshToken","error","stopRefreshTokenOnInterval","userId","data","GetRoomsDocument","room","messageFragement_default","useFragment","ChatFieldsFragmentDoc","UserFieldsFragmentDoc","userFragement_default","meta","err","channelId","ChatChannel","onReceive","chatCache","NewMessageDocument","newMessage","rooms","roomData","isMe","currentUnread","unread","newMessageRef","existing","readField","merged","ref","a","b","aCreatedAt","existingCount","returnNewMessage","newRoom","errorValue","coachId","CoachListStatus","filters","NaluriChat_default"],"mappings":";4oBAGO,SAASA,EAAmBC,EAAoC,CACrE,OAAQA,EAAa,CACnB,KAAKC,EAAsB,IACzB,MAAO,sCACT,KAAKA,EAAsB,IACzB,MAAO,0CACT,KAAKA,EAAsB,KACzB,MAAO,kCACT,QACE,MAAM,IAAIC,EAAgB,CACxB,QAAS,gCACT,KAAM,MACR,CAAC,CACL,CACF,CC4CA,IAAMC,EAAN,MAAMC,CAAW,CAIC,OAKA,UAKA,YAKA,oBAMhB,OAAe,aAEP,gBAEA,gBAEA,mBAEA,oBAEA,SAEA,aAEA,SAAW,IAAI,IAKf,YAAY,CAClB,OAAAC,EACA,UAAAC,EACA,YAAAN,EACA,oBAAAO,CACF,EAAsB,CAEpB,KAAK,OAASF,EAGd,KAAK,UAAYC,GAAa,GAE9B,KAAK,YAAcN,GAAeC,EAAsB,IAEpDM,IAAqB,KAAK,oBAAsBA,GAEpD,KAAK,gBAAkB,IAAIC,EAAW,CACpC,OAAAH,EACA,OAAQN,EAAmB,KAAK,WAAW,EAC3C,oBAAqB,KAAK,mBAC5B,CAAC,CACH,CASA,OAAc,WAAW,CACvB,OAAAM,EACA,UAAAC,EACA,UAAAG,E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,KAAM,MACR,CAAC,EAGCW,EAAU,QAAQ,GAAGA,EAAU,MAAMC,EAAO,WAAW,EAE3D,GAAI,CACF,OAAO,MAAM,KAAK,mBAAmB,aAAa6C,CAAO,CAC3D,OAAS1B,EAAK,CACZ,MAAIpB,EAAU,QAAQ,GACpBA,EAAU,MAAMC,EAAO,kBAAmB,CAAE,MAAOmB,CAAI,CAAC,EAEpD,IAAI/B,EAAgB,CACxB,QAAS,mCAAqC+B,EAC9C,KAAM,MACR,CAAC,CACH,CACF,CAEQ,OAAQ,CACdI,GAAW,MAAM,CACf,eAAgB,EAClB,CAAC,EAED,KAAK,SAAW,OAChB,KAAK,gBAAkB,OACvB,KAAK,mBAAqB,OAE1Bf,EAA2B,EAEvBT,EAAU,QAAQ,GAAGA,EAAU,QAAQ,EAE3CM,EAAW,MAAM,CACnB,CAEA,SAAU,CACR,KAAK,MAAM,EACXf,EAAW,aAAe,MAC5B,CACF,EAEOwD,GAAQzD","sourcesContent":["import { SupportedEnvironments } from '@/config/environment';\nimport { NaluriChatError } from '@/errors';\n\nexport function getGatewayEndpoint(environment: SupportedEnvironments) {\n  switch (environment) {\n    case SupportedEnvironments.DEV:\n      return 'https://chat-gateway.dev.naluri.net';\n    case SupportedEnvironments.SIT:\n      return 'https://chat-gateway.staging.naluri.net';\n    case SupportedEnvironments.PROD:\n      return 'https://chat-gateway.naluri.net';\n    default:\n      throw new NaluriChatError({\n        message: `Environment is not supported.`,\n        code: '4010',\n      });\n  }\n}\n","import { Subscription } from 'zen-observable-ts';\nimport { SupportedEnvironments } from '@/config/environment';\nimport { NaluriChatError } from '@/errors';\nimport { invariant } from '@/utils/invariant';\n\nimport { AccountApi } from './api/account.api';\nimport { chatCache, ChatApi } from './api/chat.api';\nimport { eventsApi, EVENTS } from './api/events.api';\nimport { GatewayApi } from './api/gateway.api';\nimport { CoachListStatus } from './constants';\nimport { ChatChannel } from './core/chatChannel';\nimport { useFragment } from './generated';\nimport {\n  ChatFieldsFragment,\n  ChatFieldsFragmentDoc,\n  ChatResultsFieldFragment,\n  GetRoomsDocument,\n  GetRoomsQuery,\n  GetRoomsQueryVariables,\n  NewMessageDocument,\n  NewMessageSubscription,\n  UserFieldsFragmentDoc,\n} from './generated/graphql';\nimport messagesFragment from './lib/messageFragement';\nimport userFragment from './lib/userFragement';\nimport type {\n  AccountUser,\n  CoachProfile,\n  NaluriChatLoginOptions,\n  Channel,\n  ChannelType,\n  NaluriLogout,\n  NewMessageData,\n  SubscriptionCallback,\n  CoachListFilters,\n} from './types';\n\nimport { getGatewayEndpoint } from './utils/getGatewayEndpoint';\nimport {\n  startRefreshTokenOnInterval,\n  stopRefreshTokenOnInterval,\n} from './utils/startRefreshTokenOnInterval';\n\nimport { tokenStore } from './utils/tokenStore';\n\n/**\n * Naluri Chat Sdk constructor options\n */\nexport interface NaluriChatOptions {\n  apiKey: string;\n  apiSecret?: string;\n  timeoutMs?: number;\n  environment?: SupportedEnvironments;\n  onRefreshTokenError?: () => Promise<void>;\n}\n\n/**\n * Naluri Chat Sdk\n * @constructor\n * @param {NaluriChatOptions} options\n */\nclass NaluriChat {\n  /**\n   * Api key of naluri chat\n   */\n  public readonly apiKey: string;\n\n  /**\n   * Secret key of naluri chat\n   */\n  public readonly apiSecret: string;\n\n  /**\n   * Environment, default to SIT\n   */\n  public readonly environment: SupportedEnvironments;\n\n  /**\n   * Function to be called when refresh token fails\n   */\n  public readonly onRefreshTokenError?: () => Promise<void>;\n\n  /**\n   * @private\n   * Initialized chat instance\n   */\n  private static chatInstance?: NaluriChat;\n\n  private accountInstance: AccountApi;\n\n  private chatApiInstance?: ChatApi;\n\n  private gatewayApiInstance?: GatewayApi;\n\n  private chatChannelInstance?: ChatChannel;\n\n  private senderId?: string;\n\n  private subscription?: Subscription;\n\n  private lastKeys = new Map<string, string[]>();\n\n  /**\n   * @private use getInstance method instead\n   */\n  private constructor({\n    apiKey,\n    apiSecret,\n    environment,\n    onRefreshTokenError,\n  }: NaluriChatOptions) {\n    /** @readonly */\n    this.apiKey = apiKey;\n\n    /** @readonly */\n    this.apiSecret = apiSecret ?? '';\n\n    this.environment = environment ?? SupportedEnvironments.SIT;\n\n    if (onRefreshTokenError) this.onRefreshTokenError = onRefreshTokenError;\n\n    this.accountInstance = new AccountApi({\n      apiKey,\n      apiUrl: getGatewayEndpoint(this.environment),\n      onRefreshTokenError: this.onRefreshTokenError,\n    });\n  }\n\n  /**\n   * [IMPORTANT]: Initialise this first before using any other methods\n   * Initialize a new Naluri Chat instance\n   * @returns {NaluriChat}\n   * @param {string} apikey\n   * @throws {NaluriChatError}\n   */\n  public static initialize({\n    apiKey,\n    apiSecret,\n    timeoutMs,\n    environment,\n    onRefreshTokenError,\n  }: NaluriChatOptions): void {\n    if (typeof apiKey !== 'string' || !apiKey) {\n      throw new NaluriChatError({\n        message: `Please initialize Naluri Chat with api key.`,\n        code: '4001',\n      });\n    }\n\n    if (this.chatInstance) {\n      return;\n    }\n\n    const ChatInstance = new NaluriChat({\n      apiKey,\n      apiSecret,\n      environment,\n      timeoutMs,\n      onRefreshTokenError,\n    });\n\n    this.chatInstance = ChatInstance;\n  }\n\n  /**\n   * Gets a new Naluri Chat instance\n   * @returns {NaluriChat}\n   * @throws {NaluriChatError} If didn't intialize chat.\n   */\n  public static getInstance(): NaluriChat {\n    if (!this.chatInstance) {\n      throw new NaluriChatError({\n        message: `Chat instance is not initialized. Please use the initialize method first.`,\n        code: '4002',\n      });\n    }\n\n    return this.chatInstance;\n  }\n\n  /**\n   * Login user to chat\n   * @param {NaluriChatLoginOptions} options\n   * @returns {PromiseLike<AccountUser>}\n   * @throws {NaluriChatError} if failed to login user\n   */\n  async login({\n    authorizationCode,\n  }: NaluriChatLoginOptions): Promise<AccountUser> {\n    const { user } = await this.accountInstance.login(authorizationCode);\n    if (!user) {\n      if (eventsApi.isReady())\n        eventsApi.track(EVENTS.LOGIN_ERROR, {\n          error: 'Failed to login user',\n        });\n\n      throw new NaluriChatError({\n        message: `Naluri couldn't login with this 'authorizationCode', Please contact admin.`,\n        code: '4003',\n      });\n    }\n\n    invariant(\n      !!user.chatUserId,\n      'Missing chatUserId from the API, please contact admin'\n    );\n\n    this.chatApiInstance = new ChatApi({\n      accountApi: this.accountInstance,\n      onRefreshTokenError: this.onRefreshTokenError,\n    });\n\n    this.senderId = user.chatUserId;\n    this.gatewayApiInstance = new GatewayApi({\n      apiUrl: getGatewayEndpoint(this.environment),\n      apiKey: this.apiKey,\n      accountApi: this.accountInstance,\n      onRefreshTokenError: this.onRefreshTokenError,\n    });\n\n    if (this.environment !== SupportedEnvironments.DEV) {\n      eventsApi.init(user.id, getGatewayEndpoint(this.environment));\n\n      eventsApi.identify({\n        // eslint-disable-next-line camelcase\n        tenant_id: user.tenantId,\n        country: user.country,\n        language: user.preferredLanguage,\n      });\n    }\n\n    await startRefreshTokenOnInterval(\n      this.accountInstance,\n      tokenStore,\n      this.onRefreshTokenError\n    );\n\n    return user;\n  }\n\n  /**\n   * Logout user from chat\n   * @returns {PromiseLike<void>}\n   * @throws NaluriChatError if failed to logout user\n   */\n  async logout(): Promise<NaluriLogout> {\n    const refreshToken = tokenStore.getItem('refreshToken');\n    if (eventsApi.isReady()) eventsApi.track(EVENTS.LOGOUT);\n\n    try {\n      await this.accountInstance.logout(refreshToken);\n    } catch (error) {\n      if (eventsApi.isReady()) eventsApi.track(EVENTS.LOGOUT_ERROR, { error });\n\n      throw new NaluriChatError({\n        message: 'Failed to logout user',\n        code: '4004',\n      });\n    } finally {\n      this.reset();\n      tokenStore.clear();\n      stopRefreshTokenOnInterval();\n    }\n    return { success: true };\n  }\n\n  /**\n   * Gets chat channels\n   * @returns {PromiseLike<Channel[]>}\n   * @throws NaluriChatError if chat instance is not initialized\n   */\n  async getAllChannels({ userId }: { userId?: string } = {}): Promise<\n    Channel[]\n  > {\n    if (!this.chatApiInstance) {\n      throw new NaluriChatError({\n        message:\n          'Chat instance is not initialized. Please use the initialize method first.',\n        code: '4002',\n      });\n    }\n\n    if (eventsApi.isReady()) eventsApi.track(EVENTS.GET_CHANNELS);\n\n    try {\n      const { data } = await this.chatApiInstance.query<\n        GetRoomsQuery,\n        GetRoomsQueryVariables\n      >({\n        query: GetRoomsDocument,\n        variables: {\n          isChat: true,\n          filter: userId,\n        },\n        fetchPolicy: 'network-only',\n      });\n      if (data?.rooms) {\n        return data.rooms.map((room) => ({\n          id: room.id,\n          name: room.name,\n          lastMessageId: room.last_chat_id ?? undefined,\n          status: room.status ?? undefined,\n          type: room.type as ChannelType,\n          createdAt: room.created_at,\n          updatedAt: room.updated_at,\n          unreadCount: room.unread ?? 0,\n          chat: room.last_chat\n            ? messagesFragment(\n                useFragment(ChatFieldsFragmentDoc, room.last_chat),\n                this.senderId\n              )\n            : undefined,\n          users: useFragment(UserFieldsFragmentDoc, room.users).map((user) =>\n            userFragment(user)\n          ),\n          metadata: room.metadata?.length\n            ? room.metadata?.map((meta) => ({\n                key: meta.key,\n                value: meta.value,\n              }))\n            : undefined,\n        }));\n      }\n    } catch (err) {\n      if (eventsApi.isReady())\n        eventsApi.track(EVENTS.GET_CHANNELS_ERROR, { error: err });\n\n      throw new NaluriChatError({\n        message: 'Chat getAllChannels method error. ' + err,\n        code: '4005',\n      });\n    }\n    throw new NaluriChatError({\n      message: 'Chat getAllChannels method error. ',\n      code: '4005',\n    });\n  }\n\n  /**\n   * Gets a chat channel instance\n   * @param {{ channelId: string }} channelOptions\n   * @returns {ChatChannel}\n   * @throws NaluriChatError if chat instance is not initialized\n   */\n  getChannel({ channelId }: { channelId: string }): ChatChannel {\n    if (!this.chatApiInstance) {\n      throw new NaluriChatError({\n        message:\n          'Chat instance is not initialized. Please use the initialize method first.',\n        code: '4002',\n      });\n    }\n\n    if (!this.senderId) {\n      throw new NaluriChatError({\n        message:\n          'Sender id is not initialized. Please use the login method first.',\n        code: '4002',\n      });\n    }\n\n    if (!channelId) {\n      throw new NaluriChatError({\n        message: `\"channelId\" is requires. Please field in the channel id. Channel id provided: ${channelId}`,\n        code: '4002',\n      });\n    }\n\n    invariant(\n      channelId,\n      'ChannelId is requires. Please field in the channel id.'\n    );\n\n    this.chatChannelInstance = new ChatChannel({\n      chatClient: this.chatApiInstance,\n      gatewayClient: this.gatewayApiInstance,\n      accountClient: this.accountInstance,\n      eventsClient: eventsApi,\n      senderId: this.senderId,\n      roomId: channelId,\n      lastKeys: this.lastKeys,\n    });\n\n    return this.chatChannelInstance;\n  }\n\n  /**\n   * subscribe method to all channel\n   * @param {SubscriptionCallback} params\n   * @returns {Subscription}\n   * @throws NaluriChatError if error\n   */\n  subscribe(onReceive: SubscriptionCallback): Subscription | undefined {\n    if (!this.chatApiInstance || !chatCache) {\n      throw new NaluriChatError({\n        message:\n          'Chat instance is not initialized. Please use the initialize method first.',\n        code: '4002',\n      });\n    }\n    this.subscription = this.chatApiInstance\n      ?.subscribe<NewMessageSubscription>({\n        query: NewMessageDocument,\n      })\n      .subscribe({\n        next: (data: NewMessageData) => {\n          const newMessage = useFragment(\n            ChatFieldsFragmentDoc,\n            data.data.newMessage\n          );\n\n          const rooms = chatCache.readQuery<\n            GetRoomsQuery,\n            GetRoomsQueryVariables\n          >({\n            query: GetRoomsDocument,\n            variables: {\n              isChat: true,\n            },\n          });\n\n          const roomData = rooms?.rooms?.find(\n            (room) => room.id === newMessage.room_id\n          );\n\n          const isMe = newMessage.sender_id === this.senderId;\n          const currentUnread = roomData?.unread ?? 0;\n          const unread = !isMe ? currentUnread + 1 : currentUnread;\n\n          if (roomData) {\n            chatCache.writeQuery<GetRoomsQuery, GetRoomsQueryVariables>({\n              query: GetRoomsDocument,\n              variables: {\n                isChat: true,\n              },\n              data: {\n                rooms: rooms?.rooms?.map((room) => {\n                  if (room.id === newMessage.room_id) {\n                    return {\n                      ...room,\n                      // eslint-disable-next-line camelcase\n                      last_chat: newMessage,\n                      // eslint-disable-next-line camelcase\n                      last_chat_id: newMessage.id,\n                      // eslint-disable-next-line camelcase\n                      updated_at: newMessage.updated_at,\n                      unread,\n                    };\n                  }\n                  return room;\n                }),\n              },\n            });\n          } else {\n            // message is not part of the chat channel rooms, do not fire callback\n            return;\n          }\n\n          const newMessageRef = chatCache.writeFragment<ChatFieldsFragment>({\n            id: `Chat:{\"id\": \"${newMessage.id}\"}`,\n            fragment: {\n              ...ChatFieldsFragmentDoc,\n              definitions: [\n                ...ChatFieldsFragmentDoc.definitions,\n                ...UserFieldsFragmentDoc.definitions,\n              ],\n            },\n            fragmentName: 'ChatFields',\n            data: newMessage,\n          });\n\n          chatCache.modify({\n            id: `ChatResults:{\"room_id\":\"${newMessage.room_id}\"}`,\n            fields: {\n              chats(\n                existing: ChatResultsFieldFragment['chats'] = [],\n                { readField }\n              ) {\n                const merged = existing ? [...existing] : [];\n\n                if (\n                  merged.find(\n                    (ref) => readField<string>('id', ref) === newMessage.id\n                  )\n                ) {\n                  return merged;\n                }\n\n                merged.push(newMessageRef as any);\n\n                merged.sort((a, b) => {\n                  const aCreatedAt = new Date(\n                    readField<string>('created_at', a)\n                  );\n                  const bCreatedAt = new Date(\n                    readField<string>('created_at', b)\n                  );\n                  return bCreatedAt.getTime() - aCreatedAt.getTime();\n                });\n\n                return merged;\n              },\n              count(existingCount = 0) {\n                return existingCount + 1;\n              },\n            },\n          });\n\n          const returnNewMessage = messagesFragment(newMessage, this.senderId);\n\n          const newRoom = {\n            ...roomData,\n            lastMessageId: returnNewMessage.id,\n            // eslint-disable-next-line camelcase\n            updatedAt: returnNewMessage.updatedAt,\n            chat: returnNewMessage,\n            unreadCount: unread,\n          };\n\n          delete newRoom.last_chat; // delete to avoid confusion\n          delete newRoom.last_chat_id;\n          delete newRoom.updated_at;\n          delete newRoom.unread;\n\n          onReceive({ data: newRoom, connected: true });\n        },\n        error(errorValue) {\n          if (eventsApi.isReady())\n            eventsApi.track(EVENTS.CHANNEL_LISTING_SUBSCRIPTION_ERROR, {\n              error: errorValue,\n            });\n\n          onReceive({\n            error: new NaluriChatError({\n              message: `Channel list ${errorValue}`,\n              code: '4006',\n            }),\n            connected: false,\n          });\n        },\n        complete() {\n          onReceive({ connected: false });\n        },\n        start() {\n          onReceive({ connected: true });\n        },\n      });\n\n    return this.subscription;\n  }\n\n  /**\n   * Gets Coach Profile\n   * @returns {PromiseLike<CoachProfile>}\n   * @throws NaluriChatError if chat instance is not initialized\n   */\n  async getCoachProfile(coachId: string): Promise<CoachProfile> {\n    if (!this.chatApiInstance || !this.gatewayApiInstance || !this.senderId) {\n      throw new NaluriChatError({\n        message:\n          'Chat not initialized properly. Please use the login method first.',\n        code: '4002',\n      });\n    }\n\n    if (!coachId) {\n      throw new NaluriChatError({\n        message: `\"coachId\" is required. Please field in the coach id. Coach id provided: ${coachId}`,\n        code: '4002',\n      });\n    }\n\n    if (eventsApi.isReady()) eventsApi.track(EVENTS.GET_COACH_PROFILE);\n\n    try {\n      return (\n        await this.gatewayApiInstance.getCoachList({\n          coachId,\n          status: CoachListStatus.ALL,\n        })\n      )[0];\n    } catch (err) {\n      if (eventsApi.isReady())\n        eventsApi.track(EVENTS.GET_COACH_PROFILE_ERROR, { error: err });\n\n      throw new NaluriChatError({\n        message: `Chat getCoachProfile method error: ${err}`,\n        code: '4008',\n      });\n    }\n  }\n\n  /**\n   * Get coaches list details in the group channel.\n   * @returns {PromiseLike<CoachProfile[]>}\n   * @throws NaluriChatError if chat instance is not initialized\n   */\n  async getCoachList(filters?: CoachListFilters): Promise<CoachProfile[]> {\n    if (!this.gatewayApiInstance) {\n      throw new NaluriChatError({\n        message:\n          'Chat not initialized properly. Please use the login method first.',\n        code: '4002',\n      });\n    }\n\n    if (eventsApi.isReady()) eventsApi.track(EVENTS.GET_COACHES);\n\n    try {\n      return await this.gatewayApiInstance.getCoachList(filters);\n    } catch (err) {\n      if (eventsApi.isReady())\n        eventsApi.track(EVENTS.GET_COACHES_ERROR, { error: err });\n\n      throw new NaluriChatError({\n        message: 'Chat getCoachList method error. ' + err,\n        code: '4011',\n      });\n    }\n  }\n\n  private reset() {\n    chatCache?.reset({\n      discardWatches: true,\n    });\n\n    this.senderId = undefined;\n    this.chatApiInstance = undefined;\n    this.gatewayApiInstance = undefined;\n\n    stopRefreshTokenOnInterval();\n\n    if (eventsApi.isReady()) eventsApi.cleanup();\n\n    tokenStore.clear();\n  }\n\n  destroy() {\n    this.reset();\n    NaluriChat.chatInstance = undefined;\n  }\n}\n\nexport default NaluriChat;\n"]}