Back

80.26% Statements 61/76
86.79% Branches 46/53
80% Functions 8/10
80.26% Lines 61/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366                            1x 1x                                                                                                                                                                                         12x 12x 1x   11x 11x               10x 1x   9x 3x   6x 6x   3x 1x                                                                               61x                   61x 7x                                             54x 54x       54x                                       6x         53x 1x 1x   52x       51x 1x 50x 2x                             11x 11x   11x 2x   9x 2x   7x 1x   6x 2x   4x 2x   2x                     2x 2x       2x         2x 1x       1x                   2x 2x   2x 2x 2x 2x 2x                                                                     6x 2x   4x 2x   2x    
import { __ } from '@wordpress/i18n';
import api from './api';
import { castToNumber } from './utils/cast-to-number';
import { castToString } from './utils/cast-to-string';
import { isJsonObject, JSONObject } from './utils/json-types';
import pollPromise from './utils/poll-promise';
import { standardizeError } from './utils/standardize-error';
 
export { standardizeError };
 
// Four minutes covers the large majority of successful runs, including queue
// and poll overhead. Over the seven days to 26 August 2026, about 0.9% of
// production runs took longer than two minutes and about 0.04% took longer
// than four. A timeout here therefore does not mean the run failed.
const pollTimeout = 4 * 60 * 1000;
const pollInterval = 5 * 1000;
 
type SpeedScores = {
	mobile: number;
	desktop: number;
};
 
type SpeedScoresSet = {
	current: SpeedScores;
	noBoost: SpeedScores | null;
	isStale: boolean;
};
 
interface ScoreValue {
	score: number;
	value: number;
}
 
interface SpeedHistoryDimension {
	mobile_overall_score: number;
	desktop_overall_score: number;
	mobile_lcp: ScoreValue;
	desktop_lcp: ScoreValue;
	mobile_tbt: ScoreValue;
	desktop_tbt: ScoreValue;
	mobile_cls: ScoreValue;
	desktop_cls: ScoreValue;
	mobile_si: ScoreValue;
	desktop_si: ScoreValue;
	mobile_tti: ScoreValue;
	desktop_tti: ScoreValue;
	mobile_fcp: ScoreValue;
	desktop_fcp: ScoreValue;
}
 
interface SpeedHistoryPeriod {
	timestamp: number;
	dimensions: SpeedHistoryDimension[];
}
 
interface SpeedHistoryResponse {
	data: {
		_meta: {
			start: number;
			end: number;
		};
		periods: SpeedHistoryPeriod[];
	};
}
 
type ParsedApiResponse = {
	status: string;
	scores?: SpeedScoresSet;
};
 
type SpeedScoresRequestOptions = {
	signal?: AbortSignal;
	onPending?: () => void;
};
 
/**
 * Request speed scores for this site, polling until completion or cancellation.
 *
 * @param {boolean}     force             - Force regenerate speed scores.
 * @param {string}      rootUrl           - Root URL for the HTTP request.
 * @param {string}      siteUrl           - URL of the site.
 * @param {string}      nonce             - Nonce to use for authentication.
 * @param {object}      options           - Request options.
 * @param {AbortSignal} options.signal    - Stop polling without aborting an in-flight HTTP request.
 * @param {Function}    options.onPending - Called once if the site is still measuring, before polling starts.
 * @return {SpeedScoresSet | undefined} Speed scores, or undefined when aborted.
 */
export function requestSpeedScores(
	force: boolean | undefined,
	rootUrl: string,
	siteUrl: string,
	nonce: string,
	options?: undefined
): Promise< SpeedScoresSet >;
export function requestSpeedScores(
	force: boolean | undefined,
	rootUrl: string,
	siteUrl: string,
	nonce: string,
	options?: SpeedScoresRequestOptions
): Promise< SpeedScoresSet | undefined >;
export async function requestSpeedScores(
	force = false,
	rootUrl: string,
	siteUrl: string,
	nonce: string,
	options?: SpeedScoresRequestOptions
): Promise< SpeedScoresSet | undefined > {
	const signal = options?.signal;
	if ( signal?.aborted ) {
		return;
	}
	try {
		const response = parseResponse(
			await api.post(
				rootUrl,
				force ? '/speed-scores/refresh' : '/speed-scores',
				{ url: siteUrl },
				nonce
			)
		);
		if ( signal?.aborted ) {
			return;
		}
		if ( response.scores ) {
			return response.scores;
		}
		options?.onPending?.();
		return await pollRequest( rootUrl, siteUrl, nonce, signal );
	} catch ( error ) {
		if ( ! signal?.aborted ) {
			throw error;
		}
	}
}
 
/**
 * Get SpeedScores gistory to render the Graph.  Will automatically
 * poll for a response until the task is done, returning a SpeedHistory object.
 *
 * @param {string} rootUrl - Root URL for the HTTP request.
 * @param {string} siteUrl - URL of the site.
 * @param {string} nonce   - Nonce to use for authentication.
 * @return {SpeedHistoryResponse} Speed score history returned by the server.
 */
export async function requestSpeedScoresHistory(
	rootUrl: string,
	siteUrl: string,
	nonce: string
): Promise< SpeedHistoryResponse > {
	const end = new Date().getTime();
	const start = end - 1000 * 60 * 60 * 24 * 30; // 30 days ago
	// Request metrics
	const response = await api.post< SpeedHistoryResponse >(
		rootUrl,
		'/speed-scores-history',
		{ start, end },
		nonce
	);
	return response;
}
 
/**
 * Helper method for parsing a response from a speed score API request. Returns
 * scores (if ready), and a status (success|pending|error).
 *
 * @param {JSONObject} response - API response to parse
 * @return {ParsedApiResponse} API response, processed.
 */
function parseResponse( response: JSONObject ): ParsedApiResponse {
	// Handle an explicit error
	Iif ( response.error ) {
		const defaultErrorMessage = __(
			'An unknown error occurred while requesting metrics',
			'boost-score-api'
		);
 
		throw standardizeError( response.error, defaultErrorMessage );
	}
 
	// Check if ready.
	if ( isJsonObject( response.scores ) ) {
		return {
			status: 'success',
			scores: {
				current: isJsonObject( response.scores.current )
					? {
							mobile: castToNumber( response.scores.current.mobile, 0 ),
							desktop: castToNumber( response.scores.current.desktop, 0 ),
						}
					: {
							mobile: 0,
							desktop: 0,
						},
				noBoost: isJsonObject( response.scores.noBoost )
					? {
							mobile: castToNumber( response.scores.noBoost.mobile, 0 ),
							desktop: castToNumber( response.scores.noBoost.desktop, 0 ),
						}
					: null,
				isStale: !! response.scores.isStale,
			},
		};
	}
 
	const requestStatus = castToString( response.status );
	Iif ( ! requestStatus ) {
		throw new Error( __( 'Invalid response while requesting metrics', 'boost-score-api' ) );
	}
 
	return {
		status: requestStatus,
	};
}
 
/**
 * Poll a speed score request for results, timing out if it takes too long.
 *
 * @param {string}      rootUrl - Root URL of the site to request metrics for
 * @param {string}      siteUrl - Site URL to request metrics for
 * @param {string}      nonce   - Nonce to use for authentication
 * @param {AbortSignal} signal  - Signal to stop polling.
 * @return {SpeedScoresSet | undefined} Speed scores, or undefined when aborted.
 */
async function pollRequest(
	rootUrl: string,
	siteUrl: string,
	nonce: string,
	signal?: AbortSignal
): Promise< SpeedScoresSet | undefined > {
	return pollPromise< SpeedScoresSet | undefined >( {
		timeout: pollTimeout,
		interval: pollInterval,
		timeoutError: __( 'Timed out while waiting for speed-score.', 'boost-score-api' ),
		callback: async resolve => {
			if ( signal?.aborted ) {
				resolve( undefined );
				return;
			}
			const response = parseResponse(
				await api.post( rootUrl, '/speed-scores', { url: siteUrl }, nonce )
			);
 
			if ( signal?.aborted ) {
				resolve( undefined );
			} else if ( response.scores ) {
				resolve( response.scores );
			}
		},
	} );
}
 
/**
 * Given a mobile and desktop score, return a letter summarizing the overall
 * score.
 *
 * @param {number} mobile  - Mobile speed score
 * @param {number} desktop - Desktop speed score
 * @return {string} letter score
 */
export function getScoreLetter( mobile: number, desktop: number ): string {
	const sum = mobile + desktop;
	const averageScore = sum / 2;
 
	if ( averageScore > 90 ) {
		return 'A';
	}
	if ( averageScore > 75 ) {
		return 'B';
	}
	if ( averageScore > 50 ) {
		return 'C';
	}
	if ( averageScore > 35 ) {
		return 'D';
	}
	if ( averageScore > 25 ) {
		return 'E';
	}
	return 'F';
}
 
/**
 * Find out if site scores changed. We fire a popout modal if they improve or worsen.
 * The message varies depending on the results of the speed scores so lets modify this
 *
 * @param {SpeedScoresSet} scores - Speed scores returned by the server.
 * @return {boolean} true if scores changed.
 */
export function didScoresChange( scores: SpeedScoresSet ): boolean {
	const current = scores.current;
	const noBoost = scores.noBoost;
 
	// lets make this a little bit more readable. If one of the scores is null.
	// then the scores haven't changed. So return false.
	Iif ( null == current || null == noBoost ) {
		return false;
	}
 
	// if either the mobile or the desktop scores have changed. Return true.
	if ( current.mobile !== noBoost.mobile || current.desktop !== noBoost.desktop ) {
		return true;
	}
 
	//else if reach here then the scores are the same.
	return false;
}
 
/**
 * Determine the change in scores to pass through to other functions.
 *
 * @param {SpeedScoresSet} scores - Speed scores returned by the server.
 * @return {number} - The change in scores in percentage.
 */
export function getScoreMovementPercentage( scores: SpeedScoresSet ): number {
	const current = scores.current;
	const noBoost = scores.noBoost;
 
	Eif ( current !== null && noBoost !== null ) {
		const currentScore = scores.current.mobile + scores.current.desktop;
		const noBoostScore = scores.noBoost.mobile + scores.noBoost.desktop;
		const change = currentScore / noBoostScore - 1;
		return Math.round( change * 100 );
	}
	return 0;
}
 
/**
 * Determine the number of days since the last timestamp.
 *
 * @param {number} timestamp - the timestamp returned by the server.
 * @return {number} - The number of days.
 */
export function calculateDaysSince( timestamp: number ): number {
	// Create Date objects for the provided timestamp and the current date
	const providedDate = new Date( timestamp );
	const currentDate = new Date();
 
	// Calculate the difference in milliseconds between the two dates
	const differenceInMilliseconds = currentDate.valueOf() - providedDate.valueOf();
 
	// Convert milliseconds to days
	const millisecondsInADay = 24 * 60 * 60 * 1000;
	const differenceInDays = Math.floor( differenceInMilliseconds / millisecondsInADay );
 
	return differenceInDays;
}
 
export type ScoreTier = 'good' | 'medium' | 'poor';
 
/**
 * The tier a speed score falls in.
 *
 * @param {number} score - Speed score, 0 to 100.
 * @return {ScoreTier} The tier.
 */
export function getScoreTier( score: number ): ScoreTier {
	if ( score > 70 ) {
		return 'good';
	}
	if ( score > 50 ) {
		return 'medium';
	}
	return 'poor';
}