/** 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 { if (!verifiedId) throw new ValidationError('verifiedId must be provided') const subject = this.subject if (subject?.anonymousId) { try { await this.mergeSubjects(subject.anonymousId, verifiedId) } catch (error: any) { if (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 { if (!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) { if (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 { 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 { const id = subjectId || this.subject?.id return await this.httpClient.get(`/consents/unified/${id}`, { headers: this._getRegionHeaders }) } async saveProfile({ email, profile }: SaveProfilePayload): Promise { const data = { email, profile } const result = await this.httpClient.post('/subjects/profile', data) return result.verifiedId } async verifySubjectProfile({ email, verificationCode }: VerifySubjectProfilePayload): Promise { const data = { email, code: verificationCode } const response = await this.httpClient.post(`/subjects/profile/verify`, data) return response.verifiedId } async hasConsents(payload: HasConsentsPayload = {}): Promise { 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 { 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 { if (!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 { await this.httpClient.post(`/subjects/merge`, { sourceSubjectId, targetSubjectId, }) } }