-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
105 lines (93 loc) · 2.2 KB
/
index.js
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
export default class Cookie
{
/**
* Make a new Cookie instance.
*
* @param {string} namespace
* @return {void}
*/
constructor(namespace = '')
{
this.namespace = namespace;
}
/**
* Set a cookie value for the given key.
*
* @param {string} key
* @param {string} value
* @param {Date|string|null} expires
* @param {string} path
* @param {object} options
* @return {void}
*/
set(key, value, expires = null, path = '/', options = {})
{
key = this._qualify(key);
const cookie = {
[key]: value,
expires: expires instanceof Date ? expires.toUTCString() : expires,
path,
SameSite: 'Lax',
Secure: true,
...options,
};
document.cookie = Object.entries(cookie)
.reduce((stack, entry) => stack.concat(entry.join('=')), [])
.join('; ');
}
/**
* Get the cookie with the given key.
*
* @param {string} key
* @param {mixed} value
* @return {mixed}
*/
get(key, value = null)
{
key = this._escape(this._qualify(key));
const cookie = document.cookie.match(new RegExp('(^| )' + key + '=([^;]+)'));
return (cookie && cookie[2]) ? cookie[2] : value;
}
/**
* Determine if the given cookie exists.
*
* @param {string} key
* @return {bool}
*/
isset(key)
{
key = this._escape(this._qualify(key));
return document.cookie.match(new RegExp('(^| )' + key + '=([^;]+)')) !== null;
}
/**
* Remove the given cookie.
*
* @param {string} key
* @return {void}
*/
remove(key)
{
key = this._qualify(key);
this.set(key, null, 'Thu, 01 Jan 1970 00:00:01 GMT');
}
/**
* Qualify the given key.
*
* @param {string} key
* @return {string}
*/
_qualify(key)
{
return this.namespace + key;
}
/**
* Esacpe the given key.
*
* @param {string} key
* @return {string}
*/
_escape(key)
{
return key = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
}