|
|
import config from '@automattic/calypso-config'; |
|
|
import superagent from 'superagent'; |
|
|
|
|
|
const IS_SERVER = typeof document === 'undefined'; |
|
|
|
|
|
interface BeaconBase { |
|
|
name: string; |
|
|
isLegacy?: boolean; |
|
|
} |
|
|
|
|
|
interface CountingBeacon extends BeaconBase { |
|
|
value?: number; |
|
|
type: 'counting'; |
|
|
} |
|
|
|
|
|
interface TimingBeacon extends BeaconBase { |
|
|
value: number; |
|
|
type: 'timing'; |
|
|
} |
|
|
|
|
|
export type BeaconData = CountingBeacon | TimingBeacon; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function createBeacon( calypsoSection: string, { name, value, type, isLegacy }: BeaconData ) { |
|
|
const event = name.replace( '-', '_' ); |
|
|
|
|
|
|
|
|
if ( type === 'counting' ) { |
|
|
value ??= 1; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
const hierarchyString = isLegacy ? '' : `.${ IS_SERVER ? 'server' : 'client' }`; |
|
|
|
|
|
return `calypso.${ config( |
|
|
'boom_analytics_key' |
|
|
) }${ hierarchyString }.${ calypsoSection }.${ event }:${ value }|${ |
|
|
type === 'timing' ? 'ms' : 'c' |
|
|
}`; |
|
|
} |
|
|
|
|
|
export function createStatsdURL( calypsoSection: string, events: BeaconData[] | BeaconData ) { |
|
|
if ( ! Array.isArray( events ) ) { |
|
|
events = [ events ]; |
|
|
} |
|
|
|
|
|
const section = calypsoSection.replace( /[.:-]/g, '_' ); |
|
|
const json = JSON.stringify( { |
|
|
beacons: events.map( ( event ) => createBeacon( section, event ) ), |
|
|
} ); |
|
|
|
|
|
const [ encodedSection, encodedJson ] = [ section, json ].map( encodeURIComponent ); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return `https://pixel.wp.com/boom.gif?v=calypso&u=${ encodedSection }&json=${ encodedJson }`; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function logServerEvent( calypsoSection: string, events: BeaconData[] | BeaconData ) { |
|
|
calypsoSection ??= 'unknown'; |
|
|
if ( typeof window === 'undefined' && config( 'server_side_boom_analytics_enabled' ) ) { |
|
|
superagent.get( createStatsdURL( calypsoSection, events ) ).end(); |
|
|
} |
|
|
} |
|
|
|