import type { CookieOptions , ICookies } from '@tinkoff/browser-cookies' ; import { Cookies } from '@tinkoff/browser-cookies' ; import type { CookieManager as Interface , CookieSetOptions } from './tokens' ; import { calculateExpires , trimSubdomains } from './utils' ; const checkCookieEnabled = ( ) => { const testCookieName = 'testcookiesenabled' ; document . cookie = testCookieName ; if ( document . cookie . indexOf ( testCookieName ) > - 1 ) { document . cookie = `${ testCookieName }; expires=Thu, 01 Jan 1970 00:00:01 GMT'` ; return true ; } return false ; } ; class CookiesFallback implements ICookies { cache : Record < string , string > ; constructor ( ) { this . cache = Object . create ( null ) ; } get ( name ) { return this . cache [ name ] || undefined ; } set ( name , value ) { this . cache [ name ] = value ; } erase ( name ) { delete this . cache [ name ] ; } all ( ) { return this . cache ; } } export class CookieManager implements Interface { private cookies : ICookies ; constructor ( { cookieOptions = { } } = { } ) { this . cookies = checkCookieEnabled ( ) ? new Cookies ( { secure : window . location . protocol === 'https:' , ... cookieOptions , } ) : new CookiesFallback ( ) ; } get ( name ) { return this . cookies . get ( name ) || undefined ; } set ( { name , value , noSubdomains , ... options } ) { this . cookies . set ( name , value , { ... options , expires : calculateExpires ( options . expires ) , domain : noSubdomains ? trimSubdomains ( options . domain || window . location . hostname ) : options . domain , } ) ; } all ( ) { return this . cookies . all ( ) ; } remove ( name , options ? ) { return this . cookies . erase ( name , options ) ; } }