All files / src WireWheelClient.ts

71.42% Statements 50/70
65.38% Branches 17/26
80% Functions 12/15
73.13% Lines 49/67

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202    2x   2x     2x   2x       2x                                                                   2x       16x 16x 16x 16x       16x 3x     16x       5x                                             2x   2x 2x   2x 1x 1x               2x 2x 2x       1x 1x 1x       11x             5x               5x         5x   5x 5x 5x       1x   1x       1x 1x 1x       1x 1x 1x       4x   4x 4x 1x   3x 3x       1x 1x                                                      
/** WireWheel Client to interact with the API
 */
import { HttpClient } from '@wirewheel/cmp/src/HttpClient'
import { ClientConfig } from '@wirewheel/cmp/src/entities/ClientConfig'
import { Subject } from '@wirewheel/cmp/src/entities/Subject'
import { Session } from '@wirewheel/cmp/src/entities/Session'
import { Action } from './entities/Action'
import { ValidationError } from '@wirewheel/cmp/src/errors/ValidationError'
import { GetUnifiedConsentResponse } from '@wirewheel/cmp/src/entities/GetUnifiedConsentResponse'
import { isBrowser } from '@wirewheel/cmp/src/utils/isBrowser'
import { Channel } from '@wirewheel/cmp/src/entities/Channel'
import { EmbeddedHandler } from '@wirewheel/cmp/src/EmbeddedHandler'
import { PersistentStore } from '@wirewheel/cmp/src/modules/PersistentStore'
import { PersistentStoreFactory } from '@wirewheel/cmp/src/modules/PersistentStoreFactory'
 
export type HasConsentsPayload = {
  subjectId?: string
}
 
export type SaveProfilePayload = {
  email: string
  profile?: any
}
 
export type VerifySubjectProfilePayload = {
  email: string
  verificationCode: string
}
 
export type CreateConsentPayload = {
  subject?: Subject
  actions: Action[]
  attributes?: {
    [key: string]: any
  }
  tags?: string[]
  compliance?: {
    privacyPolicy?: {
      version?: string
      url: string
    }
    gpc?: 1
  }
  overrideCountryCode?: string
  overrideRegionCode?: string
}
 
export class WireWheelClient {
  private readonly httpClient: HttpClient
  private readonly store: PersistentStore
 
  constructor(private readonly config: ClientConfig, private readonly embeddedHandler?: EmbeddedHandler) {
    const { token, apiUrl, cookieConfig } = config
    this.httpClient = HttpClient.create({ apiUrl, token })
    this.store = PersistentStoreFactory.getStore(cookieConfig)
  }
 
  static new(config: ClientConfig, embeddedHandler?: EmbeddedHandler): WireWheelClient {
    if (isBrowser()) {
      PersistentStoreFactory.getStore(config.cookieConfig).getOrCreateSubject()
    }
 
    return new WireWheelClient(config, embeddedHandler)
  }
 
  get subject(): Subject | undefined {
    return this.store.getSubject()
  }
 
  async login(verifiedId: string): Promise<void> {
    Iif (!verifiedId) throw new ValidationError('verifiedId must be provided')
 
    const subject = this.subject
    Iif (subject?.anonymousId) {
      try {
        await this.mergeSubjects(subject.anonymousId, verifiedId)
      } catch (error: any) {
        Iif (error.status !== 404) {
          console.log('Something went wrong while merging subjects')
          throw error
        }
      }
    }
    const newSubject = Subject.verified(verifiedId)
    this.store.setSubject(newSubject)
    this.embeddedHandler?.login(newSubject)
  }
 
  async loginFromSession(sessionId: string): Promise<Session> {
    Iif (!sessionId) throw new ValidationError('sessionId must be provided')
 
    const response = await this.httpClient.get(`/sessions/${sessionId}`, { headers: this._getRegionHeaders })
    const { subject } = response
 
    if (this.subject?.anonymousId) {
      try {
        await this.mergeSubjects(this.subject.anonymousId, subject.verifiedId)
      } catch (error: any) {
        Iif (error.status !== 404) {
          console.log('Something went wrong while merging subjects')
          throw error
        }
      }
    }
    const newSubject = Subject.verified(subject.verifiedId)
    this.store.setSubject(newSubject)
    return response
  }
 
  logout(): void {
    const subject = Subject.anonymous()
    this.store.setSubject(subject)
    this.embeddedHandler?.logout(subject)
  }
 
  private get _getRegionHeaders(): any {
    return {
      ...(this.config.overrideCountryCode && { 'x-country-code-override': this.config.overrideCountryCode }),
      ...(this.config.overrideRegionCode && { 'x-region-code-override': this.config.overrideRegionCode }),
    }
  }
 
  async createConsent(payload: CreateConsentPayload): Promise<string> {
    const data = {
      subject: payload.subject || this.subject,
      actions: payload.actions,
      tags: payload.tags || [],
      attributes: payload.attributes,
      compliance: payload.compliance,
    }
 
    const headers = {
      ...(payload.overrideCountryCode && { 'x-country-code-override': payload.overrideCountryCode }),
      ...(payload.overrideRegionCode && { 'x-region-code-override': payload.overrideRegionCode }),
    }
 
    const combinedHeaders = { ...this._getRegionHeaders, ...headers }
 
    const { statusText } = await this.httpClient.post('/consents', data, { headers: combinedHeaders })
    this.embeddedHandler?.createConsent(data.actions)
    return statusText
  }
 
  async getUnifiedConsent(subjectId?: string): Promise<GetUnifiedConsentResponse> {
    const id = subjectId || this.subject?.id
 
    return await this.httpClient.get(`/consents/unified/${id}`, { headers: this._getRegionHeaders })
  }
 
  async saveProfile({ email, profile }: SaveProfilePayload): Promise<void> {
    const data = { email, profile }
    const result = await this.httpClient.post('/subjects/profile', data)
    return result.verifiedId
  }
 
  async verifySubjectProfile({ email, verificationCode }: VerifySubjectProfilePayload): Promise<string> {
    const data = { email, code: verificationCode }
    const response = await this.httpClient.post(`/subjects/profile/verify`, data)
    return response.verifiedId
  }
 
  async hasConsents(payload: HasConsentsPayload = {}): Promise<boolean> {
    const { subjectId } = payload
 
    const id = subjectId || this.subject?.id
    if (!id) {
      throw new ValidationError('Missing subjectId')
    }
    const response = await this.httpClient.get(`/consents/check/${id}`, { headers: this._getRegionHeaders })
    return response.exists
  }
 
  async getProfileVerificationCode(email: string): Promise<string> {
    const response = await this.httpClient.post('/subjects/profile/verification-code', { email })
    return response.code
  }
 
  /**
   * Retrieves the channel config given a channelId
   * @param channelId
   * @returns {Channel}
   */
  async getChannelConfig(channelId: string): Promise<Channel> {
    Iif (!channelId) {
      throw new Error('The channelId is required')
    }
    return await this.httpClient.get(`/channels/${channelId}`)
  }
 
  /**
   * Merges the consents of the source subject into the target subject.
   * @param sourceSubjectId
   * @param targetSubjectId
   */
  async mergeSubjects(sourceSubjectId: string, targetSubjectId: string): Promise<void> {
    await this.httpClient.post(`/subjects/merge`, {
      sourceSubjectId,
      targetSubjectId,
    })
  }
}