-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.ts
189 lines (160 loc) · 5.49 KB
/
client.ts
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
import * as FingerprintJS from '@fingerprintjs/fingerprintjs-pro'
import { GetOptions } from '@fingerprintjs/fingerprintjs-pro'
import {
CacheKey,
CacheManager,
CacheStub,
DEFAULT_CACHE_LIFE,
ICache,
InMemoryCache,
LocalStorageCache,
MAX_CACHE_LIFE,
SessionStorageCache,
} from './cache'
import { CacheLocation, FpjsClientOptions, VisitorData } from './global'
import * as packageInfo from '../package.json'
const cacheLocationBuilders: Record<CacheLocation, (prefix?: string) => ICache> = {
[CacheLocation.Memory]: () => new InMemoryCache().enclosedCache,
[CacheLocation.LocalStorage]: (prefix) => new LocalStorageCache(prefix),
[CacheLocation.SessionStorage]: (prefix) => new SessionStorageCache(prefix),
[CacheLocation.NoCache]: () => new CacheStub(),
}
const doesBrowserSupportCacheLocation = (cacheLocation: CacheLocation) => {
switch (cacheLocation) {
case CacheLocation.SessionStorage:
try {
window.sessionStorage.getItem('item')
} catch (e) {
return false
}
return true
case CacheLocation.LocalStorage:
try {
window.localStorage.getItem('item')
} catch (e) {
return false
}
return true
default:
return true
}
}
const cacheFactory = (location: CacheLocation) => {
return cacheLocationBuilders[location]
}
export interface CustomAgent {
load: (options: FingerprintJS.LoadOptions) => Promise<FingerprintJS.Agent>
}
export interface FpjsSpaOptions extends FpjsClientOptions {
customAgent?: CustomAgent
}
/**
* FingerprintJS SDK for Single Page Applications
*/
export class FpjsClient {
private cacheManager: CacheManager
private loadOptions: FingerprintJS.LoadOptions
private agent: FingerprintJS.Agent
private agentPromise: Promise<FingerprintJS.Agent> | null
private readonly customAgent?: CustomAgent
readonly cacheLocation?: CacheLocation
private inFlightRequests = new Map<string, Promise<VisitorData>>()
constructor(options: FpjsSpaOptions) {
this.agentPromise = null
this.customAgent = options.customAgent
this.agent = {
get: () => {
throw new Error("FPJSAgent hasn't loaded yet. Make sure to call the init() method first.")
},
}
this.loadOptions = {
...options.loadOptions,
integrationInfo: [...(options.loadOptions.integrationInfo || []), `fingerprintjs-pro-spa/${packageInfo.version}`],
}
if (options.cache && options.cacheLocation) {
console.warn(
'Both `cache` and `cacheLocation` options have been specified in the FpjsClient configuration; ignoring `cacheLocation` and using `cache`.'
)
}
let cache: ICache
if (options.cache) {
cache = options.cache
} else {
this.cacheLocation = options.cacheLocation || CacheLocation.SessionStorage
if (!cacheFactory(this.cacheLocation)) {
throw new Error(`Invalid cache location "${this.cacheLocation}"`)
}
if (!doesBrowserSupportCacheLocation(this.cacheLocation)) {
this.cacheLocation = CacheLocation.Memory
}
cache = cacheFactory(this.cacheLocation)(options.cachePrefix)
}
if (options.cacheTimeInSeconds && options.cacheTimeInSeconds > MAX_CACHE_LIFE) {
throw new Error(`Cache time cannot exceed 86400 seconds (24 hours)`)
}
const cacheTime = options.cacheTimeInSeconds ?? DEFAULT_CACHE_LIFE
this.cacheManager = new CacheManager(cache, cacheTime)
}
/**
* Loads FPJS JS agent with certain settings and stores the instance in memory
* [https://dev.fingerprint.com/docs/js-agent#agent-initialization]
*/
public async init() {
if (!this.agentPromise) {
const agentLoader = this.customAgent ?? FingerprintJS
this.agentPromise = agentLoader
.load(this.loadOptions)
.then((agent) => {
this.agent = agent
return agent
})
.catch((error) => {
this.agentPromise = null
throw error
})
}
return this.agentPromise
}
/**
* Returns visitor identification data based on the request options
* [https://dev.fingerprint.com/docs/js-agent#visitor-identification]
*
* @param options
* @param ignoreCache if set to true a request to the API will be made even if the data is present in cache
*/
public async getVisitorData<TExtended extends boolean>(options: GetOptions<TExtended> = {}, ignoreCache = false) {
const cacheKey = FpjsClient.makeCacheKey(options)
const key = cacheKey.toKey()
if (!this.inFlightRequests.has(key)) {
const promise = this._identify(options, ignoreCache).finally(() => {
this.inFlightRequests.delete(key)
})
this.inFlightRequests.set(key, promise)
}
return (await this.inFlightRequests.get(key)) as VisitorData<TExtended>
}
/**
* Clears visitor data from cache regardless of the cache implementation
*/
public async clearCache() {
await this.cacheManager.clearCache()
}
/**
* Makes a CacheKey object from GetOptions
*/
static makeCacheKey<TExtended extends boolean>(options: GetOptions<TExtended>) {
return new CacheKey<TExtended>(options)
}
private async _identify<TExtended extends boolean>(options: GetOptions<TExtended>, ignoreCache = false) {
const key = FpjsClient.makeCacheKey(options)
if (!ignoreCache) {
const cacheResult = await this.cacheManager.get(key)
if (cacheResult) {
return cacheResult
}
}
const agentResult = await this.agent.get(options)
await this.cacheManager.set(key, agentResult)
return agentResult
}
}