|
|
import { |
|
|
getCurrentUser, |
|
|
recordTracksEvent, |
|
|
getTracksAnonymousUserId, |
|
|
getTracksLoadPromise, |
|
|
} from '@automattic/calypso-analytics'; |
|
|
import { logError } from './log-error'; |
|
|
|
|
|
|
|
|
declare const window: undefined | ( Window & typeof globalThis ); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const immediateStartSetInterval = ( f: () => void, intervalMs: number ) => { |
|
|
f(); |
|
|
return setInterval( f, intervalMs ); |
|
|
}; |
|
|
|
|
|
let initializeAnonIdPromise: null | Promise< string | null > = null; |
|
|
const anonIdPollingIntervalMilliseconds = 50; |
|
|
const anonIdPollingIntervalMaxAttempts = 100; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export const initializeAnonId = async (): Promise< string | null > => { |
|
|
if ( typeof window === 'undefined' ) { |
|
|
logError( { message: 'Trying to initialize anonId outside of a browser context.' } ); |
|
|
return null; |
|
|
} |
|
|
|
|
|
recordTracksEvent( 'calypso_explat_initialization' ); |
|
|
|
|
|
let attempt = 0; |
|
|
initializeAnonIdPromise = new Promise( ( res ) => { |
|
|
let anonIdPollingInterval: NodeJS.Timeout; |
|
|
|
|
|
anonIdPollingInterval = immediateStartSetInterval( () => { |
|
|
const anonId = getTracksAnonymousUserId(); |
|
|
if ( typeof anonId === 'string' && anonId !== '' ) { |
|
|
clearInterval( anonIdPollingInterval ); |
|
|
res( anonId ); |
|
|
return; |
|
|
} |
|
|
|
|
|
if ( anonIdPollingIntervalMaxAttempts - 1 <= attempt || getCurrentUser() ) { |
|
|
clearInterval( anonIdPollingInterval ); |
|
|
res( null ); |
|
|
return; |
|
|
} |
|
|
attempt = attempt + 1; |
|
|
}, anonIdPollingIntervalMilliseconds ); |
|
|
|
|
|
|
|
|
getTracksLoadPromise().catch( () => { |
|
|
clearInterval( anonIdPollingInterval ); |
|
|
res( null ); |
|
|
} ); |
|
|
} ); |
|
|
|
|
|
return initializeAnonIdPromise; |
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export const getAnonId = async (): Promise< string | null > => { |
|
|
if ( typeof window === 'undefined' ) { |
|
|
logError( { message: 'Trying to getAnonId in non browser context.' } ); |
|
|
return null; |
|
|
} |
|
|
|
|
|
if ( initializeAnonIdPromise === null ) { |
|
|
logError( { message: 'AnonId initialization should have started before this function call.' } ); |
|
|
} |
|
|
|
|
|
try { |
|
|
return await initializeAnonIdPromise; |
|
|
} catch ( e ) { |
|
|
|
|
|
|
|
|
|
|
|
} |
|
|
|
|
|
return null; |
|
|
}; |
|
|
|