Skip to content

Add URL Metric mutation helpers to extension initialization API #1951

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

Merged

Conversation

ShyamGadde
Copy link
Contributor

@ShyamGadde ShyamGadde commented Mar 21, 2025

Summary

Fixes #1930

Relevant technical choices

  • Exposed URL Metric mutation helpers (getRootData, extendRootData, getElementData, extendElementData) in the initialize args to match what was already available in finalize args
  • Moved client extension initialization logic down to occur after the urlMetric definition
  • Updated extensions (Image Prioritizer and Embed Optimizer) to use these helpers directly during initialization
  • Eliminated need for storing temporary data and the finalize phase in extensions
  • Emits a deprecation warning if the client extensions includes a finalize function

@ShyamGadde ShyamGadde added [Type] Enhancement A suggestion for improvement of an existing feature [Plugin] Optimization Detective Issues for the Optimization Detective plugin labels Mar 21, 2025
Comment on lines 56 to 67
/**
* Detected LCP external background image candidates.
*
* @type {Array<{
* url: string,
* tag: string,
* id: string|null,
* class: string|null,
* }>}
*/
const externalBackgroundImages = [];

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we even need this anymore? I think we can remove this and then replace this:

externalBackgroundImages.push( externalBackgroundImage );

With:

	log(
		'Detected external background image for LCP element:',
		externalBackgroundImage
	);
	extendRootData( { lcpElementExternalBackgroundImage: externalBackgroundImage } );

Note that this handleLCPMetric could get called multiple times as new LCP candidates are expected.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 8e5b031.

Comment on lines 736 to 796
// Finalize extensions.
if ( extensions.size > 0 ) {
/** @type {Promise[]} */
const extensionFinalizePromises = [];

/** @type {string[]} */
const finalizingExtensionModuleUrls = [];

for ( const [
extensionModuleUrl,
extension,
] of extensions.entries() ) {
if ( extension.finalize instanceof Function ) {
const extensionLogger = createLogger(
isDebug,
`[Optimization Detective: ${
extension.name || 'Unnamed Extension'
}]`
);

try {
const finalizePromise = extension.finalize( {
isDebug,
...extensionLogger,
getRootData,
getElementData,
extendElementData,
extendRootData,
} );
if ( finalizePromise instanceof Promise ) {
extensionFinalizePromises.push( finalizePromise );
finalizingExtensionModuleUrls.push(
extensionModuleUrl
);
}
} catch ( err ) {
error(
`Unable to start finalizing extension '${ extensionModuleUrl }':`,
err
);
}
}
}

// Wait for all extensions to finish finalizing.
const settledFinalizePromises = await Promise.allSettled(
extensionFinalizePromises
);
for ( const [
i,
settledFinalizePromise,
] of settledFinalizePromises.entries() ) {
if ( settledFinalizePromise.status === 'rejected' ) {
error(
`Failed to finalize extension '${ finalizingExtensionModuleUrls[ i ] }':`,
settledFinalizePromise.reason
);
}
}
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to keep this for now, especially since existing plugins are using this, but also because we're in beta so we can't just remove something. We can deprecate it, however. For example, of extension.finalize instanceof Function is truthy, then we can emit a deprecation warning:

extensionLogger.warn( 'Use of the finalize function in extensions is deprecated. Please refactor your extension to use the initialize function instead, and update the URL Metric data as soon as a change is detected rather than waiting until finalization.' );

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in b2b48b3.

@ShyamGadde ShyamGadde marked this pull request as ready for review March 24, 2025 14:30
@ShyamGadde ShyamGadde requested a review from westonruter March 24, 2025 14:31
Copy link

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Co-authored-by: ShyamGadde <[email protected]>
Co-authored-by: westonruter <[email protected]>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

@westonruter
Copy link
Member

@ShyamGadde I just realized that since the these functions are newly exposed among the InitializeArgs that we need to ensure that Image Prioritizer and Embed Optimizer are updated to require 1.0.0-beta4. See fb7e35c.

I've also improved typing in 2f20963.

Please review and test the additional changes to ensure they're working as expected.

Copy link

codecov bot commented Mar 26, 2025

Codecov Report

Attention: Patch coverage is 75.00000% with 1 line in your changes missing coverage. Please review.

Project coverage is 72.24%. Comparing base (ee3fe25) to head (9f079eb).
Report is 13 commits behind head on trunk.

Files with missing lines Patch % Lines
plugins/optimization-detective/load.php 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##            trunk    #1951   +/-   ##
=======================================
  Coverage   72.24%   72.24%           
=======================================
  Files          85       85           
  Lines        6953     6953           
=======================================
  Hits         5023     5023           
  Misses       1930     1930           
Flag Coverage Δ
multisite 72.24% <75.00%> (ø)
single 40.67% <75.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ShyamGadde
Copy link
Contributor Author

Thanks for catching that! I've tested them and it's working correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Plugin] Optimization Detective Issues for the Optimization Detective plugin [Type] Enhancement A suggestion for improvement of an existing feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

URL Metric mutation helpers should be exposed in initialize args to match finalize args
2 participants