-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
cookie.ts
218 lines (184 loc) · 7.18 KB
/
cookie.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
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
import type { Ref } from 'vue'
import { customRef, getCurrentScope, nextTick, onScopeDispose, ref, watch } from 'vue'
import type { CookieParseOptions, CookieSerializeOptions } from 'cookie-es'
import { parse, serialize } from 'cookie-es'
import { deleteCookie, getCookie, getRequestHeader, setCookie } from 'h3'
import type { H3Event } from 'h3'
import destr from 'destr'
import { isEqual } from 'ohash'
import { klona } from 'klona'
import { useNuxtApp } from '../nuxt'
import { useRequestEvent } from './ssr'
// @ts-expect-error virtual import
import { cookieStore } from '#build/nuxt.config.mjs'
type _CookieOptions = Omit<CookieSerializeOptions & CookieParseOptions, 'decode' | 'encode'>
export interface CookieOptions<T = any> extends _CookieOptions {
decode?(value: string): T
encode?(value: T): string
default?: () => T | Ref<T>
watch?: boolean | 'shallow'
readonly?: boolean
}
export interface CookieRef<T> extends Ref<T> {}
const CookieDefaults = {
path: '/',
watch: true,
decode: val => destr(decodeURIComponent(val)),
encode: val => encodeURIComponent(typeof val === 'string' ? val : JSON.stringify(val))
} satisfies CookieOptions<any>
const store = import.meta.client && cookieStore ? window.cookieStore : undefined
/** @since 3.0.0 */
export function useCookie<T = string | null | undefined> (name: string, _opts?: CookieOptions<T> & { readonly?: false }): CookieRef<T>
export function useCookie<T = string | null | undefined> (name: string, _opts: CookieOptions<T> & { readonly: true }): Readonly<CookieRef<T>>
export function useCookie<T = string | null | undefined> (name: string, _opts?: CookieOptions<T>): CookieRef<T> {
const opts = { ...CookieDefaults, ..._opts }
const cookies = readRawCookies(opts) || {}
let delay: number | undefined
if (opts.maxAge !== undefined) {
delay = opts.maxAge * 1000 // convert to ms for setTimeout
} else if (opts.expires) {
// getTime() already returns time in ms
delay = opts.expires.getTime() - Date.now()
}
const hasExpired = delay !== undefined && delay <= 0
const cookieValue = klona(hasExpired ? undefined : (cookies[name] as any) ?? opts.default?.())
// use a custom ref to expire the cookie on client side otherwise use basic ref
const cookie = import.meta.client && delay && !hasExpired
? cookieRef<T | undefined>(cookieValue, delay, opts.watch && opts.watch !== 'shallow')
: ref<T | undefined>(cookieValue)
if (import.meta.dev && hasExpired) {
console.warn(`[nuxt] not setting cookie \`${name}\` as it has already expired.`)
}
if (import.meta.client) {
const channel = store || typeof BroadcastChannel === 'undefined' ? null : new BroadcastChannel(`nuxt:cookies:${name}`)
const callback = () => {
if (opts.readonly || isEqual(cookie.value, cookies[name])) { return }
writeClientCookie(name, cookie.value, opts as CookieSerializeOptions)
cookies[name] = klona(cookie.value)
channel?.postMessage({ value: opts.encode(cookie.value as T) })
}
const handleChange = (data: { value?: any, refresh?: boolean }) => {
const value = data.refresh ? readRawCookies(opts)?.[name] : opts.decode(data.value)
watchPaused = true
cookies[name] = cookie.value = value
nextTick(() => { watchPaused = false })
}
let watchPaused = false
if (getCurrentScope()) {
onScopeDispose(() => {
watchPaused = true
callback()
channel?.close()
})
}
if (store) {
store.onchange = (event) => {
const cookie = event.changed.find((c: any) => c.name === name)
if (cookie) { handleChange({ value: cookie.value }) }
}
} else if (channel) {
channel.onmessage = ({ data }) => handleChange(data)
}
if (opts.watch) {
watch(cookie, () => {
if (watchPaused) { return }
callback()
},
{ deep: opts.watch !== 'shallow' })
} else {
callback()
}
} else if (import.meta.server) {
const nuxtApp = useNuxtApp()
const writeFinalCookieValue = () => {
if (opts.readonly || isEqual(cookie.value, cookies[name])) { return }
writeServerCookie(useRequestEvent(nuxtApp)!, name, cookie.value, opts as CookieOptions<any>)
}
const unhook = nuxtApp.hooks.hookOnce('app:rendered', writeFinalCookieValue)
nuxtApp.hooks.hookOnce('app:error', () => {
unhook() // don't write cookie subsequently when app:rendered is called
return writeFinalCookieValue()
})
}
return cookie as CookieRef<T>
}
/** @since 3.10.0 */
export function refreshCookie (name: string) {
if (store || typeof BroadcastChannel === 'undefined') { return }
new BroadcastChannel(`nuxt:cookies:${name}`)?.postMessage({ refresh: true })
}
function readRawCookies (opts: CookieOptions = {}): Record<string, unknown> | undefined {
if (import.meta.server) {
return parse(getRequestHeader(useRequestEvent()!, 'cookie') || '', opts)
} else if (import.meta.client) {
return parse(document.cookie, opts)
}
}
function serializeCookie (name: string, value: any, opts: CookieSerializeOptions = {}) {
if (value === null || value === undefined) {
return serialize(name, value, { ...opts, maxAge: -1 })
}
return serialize(name, value, opts)
}
function writeClientCookie (name: string, value: any, opts: CookieSerializeOptions = {}) {
if (import.meta.client) {
document.cookie = serializeCookie(name, value, opts)
}
}
function writeServerCookie (event: H3Event, name: string, value: any, opts: CookieSerializeOptions = {}) {
if (event) {
// update if value is set
if (value !== null && value !== undefined) {
return setCookie(event, name, value, opts)
}
// delete if cookie exists in browser and value is null/undefined
if (getCookie(event, name) !== undefined) {
return deleteCookie(event, name, opts)
}
// else ignore if cookie doesn't exist in browser and value is null/undefined
}
}
/**
* The maximum value allowed on a timeout delay.
*
* Reference: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value
*/
const MAX_TIMEOUT_DELAY = 2_147_483_647
// custom ref that will update the value to undefined if the cookie expires
function cookieRef<T> (value: T | undefined, delay: number, shouldWatch: boolean) {
let timeout: NodeJS.Timeout
let unsubscribe: (() => void) | undefined
let elapsed = 0
const internalRef = shouldWatch ? ref(value) : { value }
if (getCurrentScope()) {
onScopeDispose(() => {
unsubscribe?.()
clearTimeout(timeout)
})
}
return customRef((track, trigger) => {
if (shouldWatch) { unsubscribe = watch(internalRef, trigger) }
function createExpirationTimeout () {
clearTimeout(timeout)
const timeRemaining = delay - elapsed
const timeoutLength = timeRemaining < MAX_TIMEOUT_DELAY ? timeRemaining : MAX_TIMEOUT_DELAY
timeout = setTimeout(() => {
elapsed += timeoutLength
if (elapsed < delay) { return createExpirationTimeout() }
internalRef.value = undefined
trigger()
}, timeoutLength)
}
return {
get () {
track()
return internalRef.value
},
set (newValue) {
createExpirationTimeout()
internalRef.value = newValue
trigger()
}
}
})
}