Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(nuxt): use max length + iterations for useCookie timeout #24253

Merged
merged 5 commits into from Nov 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 27 additions & 6 deletions packages/nuxt/src/app/composables/cookie.ts
Expand Up @@ -140,22 +140,43 @@ function writeServerCookie (event: H3Event, name: string, value: any, opts: Cook
}
}

/**
* 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) {
let timeout: NodeJS.Timeout
onScopeDispose(() => { clearTimeout(timeout) })
let elapsed = 0
if (getCurrentScope()) {
onScopeDispose(() => { clearTimeout(timeout) })
}

return customRef((track, 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() }

value = undefined
trigger()
}, timeoutLength)
}

return {
get () {
track()
return value
},
set (newValue) {
clearTimeout(timeout)
timeout = setTimeout(() => {
value = undefined
trigger()
}, delay)
createExpirationTimeout()

value = newValue
trigger()
}
Expand Down