-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.js
More file actions
431 lines (400 loc) · 10.4 KB
/
storage.js
File metadata and controls
431 lines (400 loc) · 10.4 KB
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// MIT License
// Copyright (c) 2026 Open2b
// See the LICENSE file for full text.
import { decodeBase64, encodeBase64 } from './utils.js'
const storeNotSupported = new Error('store is not supported')
const warnMsg = 'Krenalis: cannot stringify traits'
class Storage {
#key
#store
#userStore
#groupStore
constructor(writeKey, options) {
const prefix = `krenalis.${writeKey.slice(0, 7)}.`
this.#key = {
anonymousId: prefix + 'anonymousId',
userId: prefix + 'userId',
groupId: prefix + 'groupId',
traits: {
user: prefix + 'userTraits',
group: prefix + 'groupTraits',
},
session: prefix + 'session',
suspended: prefix + 'suspended',
}
this.#store = this.#makeStore(options.stores, options.cookie)
this.#userStore = options.user.storage.stores == null
? this.#store
: this.#makeStore(options.user.storage.stores, options.cookie)
this.#groupStore = options.group.storage.stores == null
? this.#store
: this.#makeStore(options.group.storage.stores, options.cookie)
}
anonymousId() {
return this.#userStore.get(this.#key.anonymousId)
}
groupId() {
return this.#groupStore.get(this.#key.groupId)
}
removeSuspended() {
this.#userStore.delete(this.#key.suspended)
}
restore() {
let session, anonymousId, userTraits, groupId, groupTraits
const suspended = this.#userStore.get(this.#key.suspended)
if (suspended != null) {
;[session, anonymousId, userTraits, groupId, groupTraits] = JSON.parse(suspended)
}
if (session == null) {
session = [null, 0, false]
}
this.setSession(...session)
this.setAnonymousId(anonymousId)
this.setTraits('user', userTraits)
this.setGroupId(groupId)
this.setTraits('group', groupTraits)
this.#userStore.delete(this.#key.suspended)
}
session() {
const session = this.#store.get(this.#key.session)
if (session == null) {
return [null, 0, false]
}
return JSON.parse(session)
}
traits(kind) {
const store = kind === 'user' ? this.#userStore : this.#groupStore
const traits = store.get(this.#key.traits[kind])
if (traits == null) {
return {}
}
return JSON.parse(traits)
}
setAnonymousId(id) {
if (id == null) {
this.#userStore.delete(this.#key.anonymousId)
return
}
this.#userStore.set(this.#key.anonymousId, id)
}
setGroupId(id) {
if (id == null) {
this.#groupStore.delete(this.#key.groupId)
return
}
this.#groupStore.set(this.#key.groupId, id)
}
setSession(id, expiration, start) {
if (id == null) {
this.#store.delete(this.#key.session)
return
}
this.#store.set(this.#key.session, JSON.stringify([id, expiration, start]))
}
setTraits(kind, traits) {
if (typeof kind !== 'string') {
throw new Error('kind is ' + (typeof kind))
}
const store = kind === 'user' ? this.#userStore : this.#groupStore
if (traits == null) {
store.delete(this.#key.traits[kind])
return
}
const type = typeof traits
if (type !== 'object') {
console.warn(`${warnMsg}: traits is a ${type}`)
return
}
if (Array.isArray(traits)) {
console.warn(`${warnMsg}: ${kind} traits is an array`)
return
}
let value
try {
value = JSON.stringify(traits)
} catch (error) {
console.warn(`${warnMsg}: ${error.message}`)
return
}
this.#store.set(this.#key.traits[kind], value)
}
setUserId(id) {
if (id == null) {
this.#userStore.delete(this.#key.userId)
} else {
this.#userStore.set(this.#key.userId, id)
}
}
suspend() {
const session = this.session()
const anonymousId = this.anonymousId()
const userTraits = this.traits('user')
const groupId = this.groupId()
const groupTraits = this.traits('group')
const suspended = [session, anonymousId, userTraits, groupId, groupTraits]
this.#userStore.set(this.#key.suspended, JSON.stringify(suspended))
}
userId() {
return this.#userStore.get(this.#key.userId)
}
#makeStore(stores, cookie) {
let store = null
for (let i = 0; i < stores.length; i++) {
try {
let s
switch (stores[i]) {
case 'cookie':
s = new cookieStore(cookie)
break
case 'localStorage':
s = new webStore(localStorage)
break
case 'sessionStorage':
s = new webStore(sessionStorage)
break
case 'memory':
s = new memoryStore()
}
if (store == null) {
store = s
} else {
store = new multiStore([store, s])
}
} catch (error) {
if (error !== storeNotSupported) {
throw error
}
}
}
if (store == null) {
return new noStore()
}
return new base64Store(store)
}
}
// base64Store is a store that stores the key/value pairs in another store
// encoding and decoding the values in base64.
class base64Store {
#store
constructor(store) {
this.#store = store
}
get(key) {
let value = this.#store.get(key)
if (value != null) {
try {
value = decodeBase64(value)
} catch {
value = null
}
}
return value
}
set(key, value) {
this.#store.set(key, encodeBase64(value))
}
delete(key) {
this.#store.delete(key)
}
}
// cookieStore stores key/value pairs in cookies.
class cookieStore {
#domain
#maxAge
#path
#sameSite
#secure
// constructor returns a new cookieStore given the following options:
//
// * domain, if not null or empty, specifies the domain to use for cookies.
// If it is empty, cookies are restricted to the exact domain where they
// were created. If not empty, the cookies' domain will be set to the
// smallest subdomain of the page's domain, or possibly the page's domain
// itself, where cookie setting is supported.
//
// * maxAge is the value in milliseconds used for the 'expires' attribute.
//
// * path is the value used in the 'path' attribute.
//
// * sameSite determines the value for the 'SameSite' attribute, which can
// be set to 'lax', 'strict', or 'none'.
//
// * secure, if it is set to true, will add the 'secure' attribute.
//
// If cookies are not supported, it raises an exception with the error
// storeNotSupported.
constructor(options) {
if (document?.cookie == null) {
// Only in tests.
throw storeNotSupported
}
this.#domain = options.domain
this.#maxAge = options.maxAge
this.#path = options.path
this.#sameSite = options.sameSite
this.#secure = options.secure
this.#check()
}
get(key) {
const s = document.cookie
const cookies = s.length > 0 ? s.split('; ') : []
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i]
const p = cookie.indexOf('=')
if (p === key.length && cookie.substring(0, p) === key) {
let value = null
try {
value = globalThis.decodeURIComponent(cookie.substring(p + 1))
} catch {
// value contains an invalid escape sequence.
}
return value
}
}
return null
}
set(key, value) {
try {
value = globalThis.encodeURIComponent(value)
} catch {
// value contains a lone surrogate.
return null
}
const expires = new Date(Date.now() + this.#maxAge).toUTCString()
document.cookie = `${key}=${value}; expires=${expires}; path=${this.#path}; samesite=${this.#sameSite}` +
`${this.#secure ? '; secure' : ''}${this.#domain === '' ? '' : `; domain=${this.#domain}`}`
}
delete(key) {
document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${this.#path}; samesite=${this.#sameSite}` +
`${this.#domain === '' ? '' : `; domain=${this.#domain}`}`
}
// check checks whether the cookies are available, and if the domain is
// null, it determines the domain of the cookies.
#check() {
const hostnames = () => {
if (this.#domain != null) {
return [this.#domain]
}
const hostname = globalThis.location.hostname
const components = hostname.split('.')
// Note that if the domain ends with a dot, it should be left as is because some browsers,
// such as Chrome and Firefox, treat domains with and without dots as distinct.
if (components.length < 3) {
return [hostname] // top-level, second-level domain, or IPv6
}
const c = components[0][0]
if ('0' <= c && c <= '9') {
return [hostname] // IPv4
}
const names = []
for (let i = 2; i < components.length + 1; i++) {
names.push(components.slice(-i).join('.'))
}
return names
}
const domains = hostnames()
const key = '__test__'
const value = String(Math.floor(Math.random() * 100000000))
for (let i = 0; i < domains.length; i++) {
this.#domain = domains[i]
this.set(key, value)
if (this.get(key) === value) {
this.delete(key)
return
}
}
throw storeNotSupported
}
}
// memoryStore stores key/value pairs in memory.
class memoryStore {
#data = {}
get(key) {
const value = this.#data[key]
return value == null ? null : value
}
set(key, value) {
this.#data[key] = value
}
delete(key) {
delete (this.#data[key])
}
}
// multiStore stores key/value pairs across multiple stores. The get method
// retrieves the key from the first store, the set method updates the key in
// all stores, and the delete method removes the key from all stores.
class multiStore {
#stores
// constructor returns a new multiStore that stores key/value pairs in
// the provided stores.
constructor(stores) {
this.#stores = stores
}
get(key) {
let value = null
for (let i = 0; i < this.#stores.length; i++) {
value = this.#stores[i].get(key)
if (value != null) {
break
}
}
return value
}
set(key, value) {
for (let i = 0; i < this.#stores.length; i++) {
this.#stores[i].set(key, value)
}
}
delete(key) {
for (let i = 0; i < this.#stores.length; i++) {
this.#stores[i].delete(key)
}
}
}
// noStore is a store that does not store key/value pairs.
class noStore {
get() {
return null
}
set() {}
delete() {}
}
// webStore stores key/value pairs in a Web Storage.
class webStore {
#storage
// constructor returns a new webStore based on the provided Web Storage,
// such as localStorage or sessionStorage. If the provided storage cannot be
// used, it raises an exception with the storeNotSupported error.
constructor(storage) {
try {
storage.setItem('__test__', '')
storage.removeItem('__test__')
} catch {
throw storeNotSupported
}
this.#storage = storage
}
get(key) {
try {
return this.#storage.getItem(key)
} catch {
return null
}
}
set(key, value) {
try {
this.#storage.setItem(key, value)
} catch {
// Nothing to do.
}
}
delete(key) {
try {
this.#storage.removeItem(key)
} catch {
// Nothing to do.
}
}
}
export default Storage
export { base64Store, cookieStore, memoryStore, multiStore, noStore, webStore }