Skip to content

Conversation

@acicovic
Copy link
Collaborator

@acicovic acicovic commented May 19, 2025

Description

Attention: This PR contains rough code. As I'm signing off, I'm leaving it so others can review it or continue the work to improve or complete it.

What this PR does:

  • Adds the infrastructure to support the check-auth endpoint on the Suggestions API. This is needed so we can query the endpoint and get back results from it. The check-auth endpoint can be used to asses whether a particular Site ID has access to TB or the Suggestions API altogether.
  • Using the above infrastructure, it displays messages within the Content Helper section in the Settings page. Currently we show a message in 3 cases:
    1. No API Secret is set.
    2. Site ID has no authorization to use the Suggestions API.
    3. Site ID has no authorization to use Traffic Boost.

Improvement/fix opportunities:

  • I noticed here that integration tests fail.
  • Some comments/DocBlocks might be off (e.g. pasted from elsewhere).
  • Code could possibly be wordy or repetitive in places.
  • I'm noticing that there's something wrong with the Settings page (lack of padding or margin - quite visible in the recrawl section), and I also could not make any styling added to admin-settings.scss work. I do think messages need a bit of styling enhancement.
  • There might be other issues as I've been looking on this for a good part of the day and missing fresh eyes.

Summary by CodeRabbit

  • New Features
    • Added an authorization check for Content Helper features, including Suggestions API and Traffic Boost, with clear status messages displayed in the admin settings.
    • Introduced a new API endpoint to verify authorization for specific Content Helper features.
  • Bug Fixes
    • Improved handling and messaging when the API Secret is missing or authorization fails.
  • Chores
    • Updated configuration to reflect minor changes in type coverage requirements.
  • Style
    • Added styling for Content Helper admin messages to improve readability.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 19, 2025

Warning

Rate limit exceeded

@acicovic has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 50 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between d9d1fe9 and d89e6c3.

📒 Files selected for processing (2)
  • src/content-helper/common/providers/check-auth-provider.ts (1 hunks)
  • src/js/admin-settings.ts (2 hunks)
📝 Walkthrough

Walkthrough

A new authorization check feature for the Content Helper Suggestions API was introduced. This includes backend PHP endpoints for checking authorization, a new TypeScript provider for frontend requests, and UI logic to display status messages based on authorization. Minor configuration and controller changes were made to support the new endpoint and service methods.

Changes

File(s) Change Summary
phpstan.neon Lowered type_coverage > return_type from 88 to 87.7.
src/content-helper/common/providers/check-auth-provider.ts Added a singleton provider class with methods and interfaces for checking Content Helper authorization via API.
src/js/admin-settings.ts Added async function to display Content Helper section messages based on authorization responses; invoked on DOMContentLoaded.
src/rest-api/content-helper/class-content-helper-controller.php Modified init() to register the new Endpoint_Check_Auth as the first endpoint.
src/rest-api/content-helper/class-endpoint-check-auth.php Introduced Endpoint_Check_Auth class implementing a /check-auth REST API endpoint for authorization checks.
src/services/suggestions-api/class-suggestions-api-service.php Registered the new endpoint class and added get_check_auth() method to call it.
src/services/suggestions-api/endpoints/class-endpoint-check-auth.php Added Endpoint_Check_Auth class for Suggestions API, handling remote /check-auth requests and responses.
tests/Integration/RestAPI/ContentHelper/ContentHelperControllerTest.php Updated test to assert registration of new Endpoint_Check_Auth endpoint and endpoint count incremented from 4 to 5.
src/UI/class-settings-page.php Fixed asset URL concatenation by removing extra slash and replaced CSS dependencies argument with empty array in enqueue method.
src/css/admin-settings.scss Added CSS rules for .content-helper-message to style top margin and paragraph padding inside the Content Helper section.

Sequence Diagram(s)

sequenceDiagram
    participant AdminUI
    participant CheckAuthProvider (TS)
    participant REST API (WP)
    participant Endpoint_Check_Auth (PHP)
    participant Suggestions_API_Service
    participant RemoteSuggestionsAPI

    AdminUI->>CheckAuthProvider (TS): getAuthorizationResponse({auth_scope})
    CheckAuthProvider (TS)->>REST API (WP): POST /wp-parsely/v2/content-helper/check-auth?auth_scope=...
    REST API (WP)->>Endpoint_Check_Auth (PHP): get_check_auth(request)
    Endpoint_Check_Auth (PHP)->>Suggestions_API_Service: get_check_auth(['auth_scope' => ...])
    Suggestions_API_Service->>Endpoint_Check_Auth (Endpoint): get_check_auth_result(['auth_scope' => ...])
    Endpoint_Check_Auth (Endpoint)->>RemoteSuggestionsAPI: GET /check-auth?auth_scope=...
    RemoteSuggestionsAPI-->>Endpoint_Check_Auth (Endpoint): {code, message}
    Endpoint_Check_Auth (Endpoint)-->>Suggestions_API_Service: {code, message}
    Suggestions_API_Service-->>Endpoint_Check_Auth (PHP): {code, message}
    Endpoint_Check_Auth (PHP)-->>REST API (WP): REST response {code, message}
    REST API (WP)-->>CheckAuthProvider (TS): {code, message}
    CheckAuthProvider (TS)-->>AdminUI: {code, message}
Loading
sequenceDiagram
    participant AdminUI
    participant CheckAuthProvider (TS)

    AdminUI->>CheckAuthProvider (TS): getAuthorizationResponse('suggestions_api')
    AdminUI->>CheckAuthProvider (TS): getAuthorizationResponse('traffic_boost')
    Note right of AdminUI: Both requests run concurrently
    CheckAuthProvider (TS)-->>AdminUI: {code, message} for each scope
    AdminUI->>AdminUI: Display message in UI based on responses
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@acicovic acicovic marked this pull request as ready for review May 19, 2025 18:56
@acicovic acicovic requested a review from a team as a code owner May 19, 2025 18:56
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (9)
src/services/suggestions-api/class-suggestions-api-service.php (1)

101-116: New get_check_auth method follows service class patterns.

The method implementation and documentation follow the established patterns of the service class. Consider adding a PHPStan import-type annotation for the options parameter to improve type safety, similar to other methods in this class.

 * @since 3.19.0
 *
+ * @phpstan-import-type Endpoint_Check_Auth_Options from Endpoints\Endpoint_Check_Auth
 * @param array<mixed> $options The options to pass to the API request.
src/js/admin-settings.ts (4)

1-14: Add @SInCE tags to imports section.

According to WordPress coding standards and the project guidelines, every JSDoc comment should include a @SInCE tag indicating the version when the code was added.

 /**
  * WordPress dependencies
+ *
+ * @since 3.19.0
  */
 import { __ } from '@wordpress/i18n';

 /**
  * Internal dependencies
+ *
+ * @since 3.19.0
  */
 import {
 	ContentHelperError,
 	ContentHelperErrorCode,
 } from '../content-helper/common/content-helper-error';
 import { CheckAuthProvider } from '../content-helper/common/providers/check-auth-provider';

253-267: Simplify concurrent API requests with more descriptive variable names.

The Promise.all implementation is correct, but the variable naming could be improved for better readability. Also, consider adding error handling specifically for network failures.

 	try {
 		const [ apiAuth, trafficBoostAuth ] = await Promise.all( [
 			CheckAuthProvider.getInstance().getAuthorizationResponse(
-				{ auth_scope: 'suggestions_api' }
+				{ auth_scope: 'suggestions_api' } // Main API authorization
 			),
 			CheckAuthProvider.getInstance().getAuthorizationResponse(
-				{ auth_scope: 'traffic_boost' }
+				{ auth_scope: 'traffic_boost' } // Traffic Boost feature authorization
 			),
 		] );

 		authResponse = {
-			api: apiAuth,
-			traffic_boost: trafficBoostAuth,
+			api: apiAuth, // Main Suggestions API authorization result
+			traffic_boost: trafficBoostAuth, // Traffic Boost feature authorization result
 		};

268-274: Add specific handling for network errors.

The error handling could be improved by adding specific cases for network errors, which would provide more helpful feedback to users.

 	} catch ( err: unknown ) {
 		console.error( err ); // eslint-disable-line no-console
 		if ( err instanceof ContentHelperError ) {
 			if ( ContentHelperErrorCode.PluginSettingsApiSecretNotSet === err.code ) {
 				message = __( '<p>All Content Helper AI functionality is disabled because An API Secret has not been set.</p>', 'wp-parsely' );
 			}
+		} else if (err instanceof Error) {
+			// Handle network errors or other unexpected issues
+			message = __( '<p>Unable to verify Content Helper authorization status due to a network error. Please refresh the page to try again.</p>', 'wp-parsely' );
 		}

271-271: Fix grammatical error in error message.

There's a grammatical error in the API Secret not set message - "because An API Secret" should be "because an API Secret".

-				message = __( '<p>All Content Helper AI functionality is disabled because An API Secret has not been set.</p>', 'wp-parsely' );
+				message = __( '<p>All Content Helper AI functionality is disabled because an API Secret has not been set.</p>', 'wp-parsely' );
src/rest-api/content-helper/class-endpoint-check-auth.php (2)

72-94: Verify route registration parameters.

The route registration parameters appear correct, but there's a potential improvement in documentation clarity.

The route comment on line 79-81 describes the endpoint's purpose, but it would be more explicit to include that this endpoint expects a POST request with a required 'auth_scope' parameter. Also, consider mentioning the expected values for 'auth_scope' in the parameter description.

-				'auth_scope' => array(
-					'description' => __( 'The scope for which to authorize.', 'wp-parsely' ),
-					'type'        => 'string',
-					'required'    => true,
-				),
+				'auth_scope' => array(
+					'description' => __( 'The scope for which to authorize (e.g., "suggestions_api" or "traffic_boost").', 'wp-parsely' ),
+					'type'        => 'string',
+					'required'    => true,
+				),

108-119: Ensure error handling is comprehensive.

Your error handling approach is correct by directly returning WP_Error objects from the service. However, consider adding more specific error handling for different scenarios.

Consider enhancing the error handling by checking for specific error codes or messages from the suggestions API service and augmenting them with more user-friendly explanations. This would help frontend developers better understand and communicate errors to users.

 	public function get_check_auth( WP_REST_Request $request ) {
 		$auth_scope = $request->get_param( 'auth_scope' );
 
 		$response = $this->suggestions_api->get_check_auth(
 			array( 'auth_scope' => $auth_scope )
 		);
 
 		if ( is_wp_error( $response ) ) {
+			// Add more context to common error scenarios
+			$error_code = $response->get_error_code();
+			if ( 'parsely_api_key_missing' === $error_code ) {
+				$response->add_data( array( 'status' => 400 ) );
+			} elseif ( 'parsely_api_request_failed' === $error_code ) {
+				$response->add_data( array( 'status' => 502 ) );
+			}
 			return $response;
 		}
 
 		return new WP_REST_Response( array( 'data' => $response ), 200 );
 	}
src/content-helper/common/providers/check-auth-provider.ts (1)

16-24: Correct JSDoc comment description.

There's an issue with the JSDoc comment description for AuthResponse.

The comment description for AuthResponse incorrectly states it's for "Authorization request parameters" when it should be describing an authorization response.

- * Type definition for the Authorization request parameters.
+ * Type definition for the Authorization response.
src/services/suggestions-api/endpoints/class-endpoint-check-auth.php (1)

93-103: Consider adding response validation.

The call method is a simple wrapper around get_check_auth_result, but it might benefit from additional validation of the input arguments.

Consider validating the auth_scope parameter to ensure it matches expected values:

 public function call( array $args = array() ) {
+	// Validate auth_scope if present
+	if ( isset( $args['auth_scope'] ) ) {
+		$valid_scopes = array( 'suggestions_api', 'traffic_boost' );
+		if ( ! in_array( $args['auth_scope'], $valid_scopes, true ) ) {
+			return new WP_Error(
+				'parsely_invalid_auth_scope',
+				sprintf(
+					/* translators: %s is the invalid scope value */
+					__( 'Invalid auth_scope value: %s. Expected one of: suggestions_api, traffic_boost.', 'wp-parsely' ),
+					$args['auth_scope']
+				)
+			);
+		}
+	}
+
 	return $this->get_check_auth_result( $args );
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 9a9dda3 and 3817a52.

⛔ Files ignored due to path filters (2)
  • build/admin-settings.asset.php is excluded by !build/**
  • build/admin-settings.js is excluded by !build/**
📒 Files selected for processing (7)
  • phpstan.neon (1 hunks)
  • src/content-helper/common/providers/check-auth-provider.ts (1 hunks)
  • src/js/admin-settings.ts (2 hunks)
  • src/rest-api/content-helper/class-content-helper-controller.php (1 hunks)
  • src/rest-api/content-helper/class-endpoint-check-auth.php (1 hunks)
  • src/services/suggestions-api/class-suggestions-api-service.php (2 hunks)
  • src/services/suggestions-api/endpoints/class-endpoint-check-auth.php (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.{html,php}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the HTML and PHP code to ensure it is well-structured and adheres ...

**/*.{html,php}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the HTML and PHP code to ensure it is well-structured and adheres to best practices.
  • Ensure the code follows WordPress coding standards and is well-documented.
  • Confirm the code is secure and free from vulnerabilities.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Verify code compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • src/rest-api/content-helper/class-content-helper-controller.php
  • src/services/suggestions-api/class-suggestions-api-service.php
  • src/rest-api/content-helper/class-endpoint-check-auth.php
  • src/services/suggestions-api/endpoints/class-endpoint-check-auth.php
`**/*.{js,ts,tsx,jsx}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the code to ensure it is well-structured and adheres to best ...

**/*.{js,ts,tsx,jsx}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the code to ensure it is well-structured and adheres to best practices.
  • Verify compliance with WordPress coding standards.
  • Ensure the code is well-documented.
  • Check for security vulnerabilities and confirm the code is secure.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate JSDoc comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Confirm every JSDoc comment includes a @SInCE tag indicating the next version of the plugin to include the code.
  • Guarantee compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • src/js/admin-settings.ts
  • src/content-helper/common/providers/check-auth-provider.ts
🪛 Biome (1.9.4)
src/content-helper/common/providers/check-auth-provider.ts

[error] 42-42: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 43-43: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 46-46: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: E2E against WordPress latest
🔇 Additional comments (11)
phpstan.neon (1)

16-16: Change to type coverage metric looks reasonable.

The configuration update reducing return_type coverage from 88 to 87.7 aligns with the new code being added in this PR. This minor adjustment accommodates the introduction of new functionality while maintaining high standards for type safety.

src/rest-api/content-helper/class-content-helper-controller.php (1)

41-41: New authorization check endpoint registered correctly.

The Endpoint_Check_Auth addition follows the established pattern for registering endpoints in the Content Helper API. This enables the authentication checks for the Suggestions API and Traffic Boost functionality.

src/services/suggestions-api/class-suggestions-api-service.php (1)

49-49: Endpoint registration follows established pattern.

The Endpoint_Check_Auth registration is properly added to the endpoints array, following the existing pattern in this service class.

src/js/admin-settings.ts (1)

16-16: Authorization check function called correctly on DOM load.

The function call to displayContentHelperSectionMessages() is properly placed in the DOMContentLoaded event listener to ensure Content Helper authorization messages are displayed when the page loads.

src/rest-api/content-helper/class-endpoint-check-auth.php (3)

1-8: Documentation is well-formatted.

The file header documentation follows WordPress coding standards with proper package annotation and version information.


20-27: Class documentation is complete and follows standards.

The class documentation clearly explains the purpose of this endpoint - checking a Site ID's authorization to use the Suggestions API and its features.


45-48: Constructor correctly sets up dependencies.

The constructor properly initializes the parent class and sets up the Suggestions API dependency through the controller. This follows good dependency injection practices.

src/content-helper/common/providers/check-auth-provider.ts (1)

7-14: Type definitions look good.

The interface definition for AuthRequestParams is well-structured with appropriate typing for the auth_scope property.

src/services/suggestions-api/endpoints/class-endpoint-check-auth.php (3)

1-22: Documentation follows WordPress standards.

The file header and PHPDoc comment for the class follow WordPress coding standards with appropriate @since tags and descriptions.


23-33: Endpoint implementation looks good.

The get_endpoint() method correctly returns the API endpoint path.


35-50: Method implements proper error handling.

The get_check_auth_result method correctly returns either the API response or a WP_Error object, allowing callers to handle error cases appropriately.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
tests/Integration/RestAPI/ContentHelper/ContentHelperControllerTest.php (1)

77-97: Update PHPDoc with new @uses tag.

The PHPDoc for test_init_registers_endpoints should include @uses tags for the Endpoint_Check_Auth class methods since they're now being tested. This would maintain consistency with the existing documentation pattern.

 * @uses \Parsely\REST_API\Base_Endpoint::__construct
 * @uses \Parsely\REST_API\Base_Endpoint::init
+* @uses \Parsely\REST_API\Content_Helper\Endpoint_Check_Auth::__construct
+* @uses \Parsely\REST_API\Content_Helper\Endpoint_Check_Auth::get_endpoint_name
 * @uses \Parsely\REST_API\Content_Helper\Endpoint_Excerpt_Generator::__construct
 * @uses \Parsely\REST_API\Content_Helper\Endpoint_Excerpt_Generator::get_endpoint_name
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 3817a52 and 395053e.

📒 Files selected for processing (1)
  • tests/Integration/RestAPI/ContentHelper/ContentHelperControllerTest.php (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{html,php}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the HTML and PHP code to ensure it is well-structured and adheres ...

**/*.{html,php}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the HTML and PHP code to ensure it is well-structured and adheres to best practices.
  • Ensure the code follows WordPress coding standards and is well-documented.
  • Confirm the code is secure and free from vulnerabilities.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Verify code compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • tests/Integration/RestAPI/ContentHelper/ContentHelperControllerTest.php
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: E2E against WordPress latest
  • GitHub Check: build
🔇 Additional comments (3)
tests/Integration/RestAPI/ContentHelper/ContentHelperControllerTest.php (3)

15-15: Import added correctly.

The import for the new Endpoint_Check_Auth class follows WordPress coding standards and is properly placed in alphabetical order with other endpoint imports.


102-102: Test assertion count updated correctly.

The assertion count has been properly updated from 4 to 5 to reflect the addition of the new endpoint.


104-104: New endpoint assertion added appropriately.

The assertion for the new Endpoint_Check_Auth endpoint is correctly implemented, following the same pattern as the existing endpoint assertions.

@alecgeatches
Copy link
Contributor

@acicovic I did not complete this PR today, but I made a few steps to get it in better shape:

  1. Fixed tests (except SonarCloud, which we can probably ignore)

  2. Fixed the CSS issue here.

  3. Spent some time testing and styling the error messages we show if CH/TB are disabled:

    Content helper disabled:

    Screenshot 2025-05-19 at 4 22 55 PM


    TB disabled:

    Screenshot 2025-05-19 at 4 21 31 PM

    These still might need more work, but they should be closer.

@acicovic acicovic added this to the 3.19.0 milestone May 20, 2025
@acicovic acicovic added the Changelog: Added PR to be added under the changelog's "Added" section label May 20, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/content-helper/common/providers/check-auth-provider.ts (1)

43-47: Using 'this' in static methods is flagged by linters.

Static analysis flagged using this in a static context, which can be confusing. However, as noted in previous reviews, this pattern is consistently used across the codebase for singleton implementations.

🧰 Tools
🪛 Biome (1.9.4)

[error] 43-43: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 44-44: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 47-47: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

🧹 Nitpick comments (4)
src/content-helper/common/providers/check-auth-provider.ts (4)

17-21: Fix incorrect JSDoc comment description.

The JSDoc comment incorrectly states "Type definition for the Authorization request parameters" when it's actually describing the AuthResponse interface for the response.

/**
- * Type definition for the Authorization request parameters.
+ * Type definition for the Authorization response.
 *
 * @since 3.19.0
 */

22-25: Consider documenting response codes and their meanings.

The AuthResponse interface defines a code property but doesn't document what different code values mean. Adding this documentation would help consumers understand how to interpret the responses.

export interface AuthResponse {
	code: number;
	message: string;
+	/**
+	 * Response codes:
+	 * 200 - Authorized
+	 * 401 - Not authenticated
+	 * 403 - Not authorized
+	 * 500 - Server error
+	 */
}

50-53: Improve JSDoc description accuracy.

The method description mentions both "Suggestions API" and "Suggestions API feature" which seems redundant or confusing.

/**
- * Returns whether the Site ID is authorized to use the Suggestions API or
- * Suggestions API feature.
+ * Returns whether the Site ID is authorized to use the Suggestions API or
+ * Traffic Boost feature.
 *

61-83: Provide better default response and add retry handling.

The method initializes a default response with a code of 0, which isn't a standard HTTP status code. Consider using a more meaningful default value and adding configuration for retry attempts on failure.

public async getAuthorizationResponse( args: AuthRequestParams ): Promise<AuthResponse> {
-	let response: AuthResponse = { code: 0, message: '' };
+	let response: AuthResponse = { code: 500, message: 'Request not completed' };

	try {
		response = await this.fetch<AuthResponse>( {
			method: 'POST',
			path: addQueryArgs(
				'/wp-parsely/v2/content-helper/check-auth', {
					...args,
				} ),
+			retryAttempts: 2, // Add retry configuration if supported by BaseProvider
		} );
	} catch ( error: unknown ) {
		if ( error instanceof ContentHelperError ) {
			throw error;
		}

		if ( error instanceof Error ) {
			throw new ContentHelperError(
				error.message,
				ContentHelperErrorCode.UnknownError
			);
		}
+		
+		// Handle non-Error objects
+		throw new ContentHelperError(
+			'Unknown error occurred',
+			ContentHelperErrorCode.UnknownError
+		);
	}

	return response;
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 0b0720b and d9d1fe9.

⛔ Files ignored due to path filters (2)
  • build/admin-settings.asset.php is excluded by !build/**
  • build/admin-settings.js is excluded by !build/**
📒 Files selected for processing (3)
  • src/content-helper/common/providers/check-auth-provider.ts (1 hunks)
  • src/js/admin-settings.ts (2 hunks)
  • src/services/suggestions-api/endpoints/class-endpoint-check-auth.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/services/suggestions-api/endpoints/class-endpoint-check-auth.php
  • src/js/admin-settings.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{js,ts,tsx,jsx}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the code to ensure it is well-structured and adheres to best ...

**/*.{js,ts,tsx,jsx}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the code to ensure it is well-structured and adheres to best practices.
  • Verify compliance with WordPress coding standards.
  • Ensure the code is well-documented.
  • Check for security vulnerabilities and confirm the code is secure.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate JSDoc comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Confirm every JSDoc comment includes a @SInCE tag indicating the next version of the plugin to include the code.
  • Guarantee compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • src/content-helper/common/providers/check-auth-provider.ts
🧬 Code Graph Analysis (1)
src/content-helper/common/providers/check-auth-provider.ts (1)
src/content-helper/common/content-helper-error.tsx (1)
  • ContentHelperError (56-227)
🪛 Biome (1.9.4)
src/content-helper/common/providers/check-auth-provider.ts

[error] 43-43: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 44-44: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 47-47: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

🔇 Additional comments (1)
src/content-helper/common/providers/check-auth-provider.ts (1)

8-25: Good interface design and documentation.

The interfaces are well-defined with clear type constraints. The auth_scope parameter is properly restricted to specific string literals, making the API more robust and type-safe.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/content-helper/common/providers/check-auth-provider.ts (2)

17-21: Fix incorrect JSDoc description.

The JSDoc comment incorrectly describes this as "Type definition for the Authorization request parameters" when it's actually defining the response interface.

/**
- * Type definition for the Authorization request parameters.
+ * Type definition for the Authorization response.
 *
 *
 * @since 3.19.0
 */

50-53: Fix inaccurate method description.

The JSDoc comment mentions "Returns whether the Site ID is authorized" but it actually returns a response object with a code and message, not just a boolean.

/**
- * Returns whether the Site ID is authorized to use the Suggestions API or
- * Suggestions API feature.
+ * Returns authorization status information for the Site ID to use the Suggestions API or
+ * Traffic Boost feature.
 *
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 0b0720b and d9d1fe9.

⛔ Files ignored due to path filters (2)
  • build/admin-settings.asset.php is excluded by !build/**
  • build/admin-settings.js is excluded by !build/**
📒 Files selected for processing (3)
  • src/content-helper/common/providers/check-auth-provider.ts (1 hunks)
  • src/js/admin-settings.ts (2 hunks)
  • src/services/suggestions-api/endpoints/class-endpoint-check-auth.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/js/admin-settings.ts
  • src/services/suggestions-api/endpoints/class-endpoint-check-auth.php
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{js,ts,tsx,jsx}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the code to ensure it is well-structured and adheres to best ...

**/*.{js,ts,tsx,jsx}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the code to ensure it is well-structured and adheres to best practices.
  • Verify compliance with WordPress coding standards.
  • Ensure the code is well-documented.
  • Check for security vulnerabilities and confirm the code is secure.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate JSDoc comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Confirm every JSDoc comment includes a @SInCE tag indicating the next version of the plugin to include the code.
  • Guarantee compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • src/content-helper/common/providers/check-auth-provider.ts
🧬 Code Graph Analysis (1)
src/content-helper/common/providers/check-auth-provider.ts (1)
src/content-helper/common/content-helper-error.tsx (1)
  • ContentHelperError (56-227)
🪛 Biome (1.9.4)
src/content-helper/common/providers/check-auth-provider.ts

[error] 43-43: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 44-44: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 47-47: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

🔇 Additional comments (3)
src/content-helper/common/providers/check-auth-provider.ts (3)

42-48: Consider following TypeScript best practices while respecting codebase conventions.

Using this in static methods can be confusing and is flagged by static analysis. However, I see from previous comments that this pattern is consistently used throughout your codebase, so maintaining consistency is reasonable.

🧰 Tools
🪛 Biome (1.9.4)

[error] 43-43: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 44-44: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 47-47: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


60-85: Good implementation of error handling.

The method properly initializes a default response, uses try-catch for error handling, and appropriately handles different error types. The implementation follows best practices by:

  1. Initializing a default response object
  2. Using async/await with proper error handling
  3. Preserving ContentHelperError instances
  4. Properly wrapping other errors

1-87: Well-structured provider implementation with good TypeScript types.

The overall implementation is well-structured with:

  • Clear type definitions using TypeScript interfaces
  • Good separation of concerns
  • Proper singleton pattern implementation
  • Consistent error handling

This provider will cleanly integrate with the WordPress REST API for checking authorization statuses.

🧰 Tools
🪛 Biome (1.9.4)

[error] 43-43: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 44-44: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 47-47: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

@acicovic
Copy link
Collaborator Author

@alecgeatches: after your changes and myself addressing some CodeRabbit feedback and a self-review, this looks good enough to me. The SonarCloud complaint is about code duplication and can be ignored.

I wouldn't mind a post-merge review, although I will be merging this now with the v3.19 release being today.

@acicovic acicovic merged commit f244a0a into add/traffic-boost May 20, 2025
38 of 39 checks passed
@acicovic acicovic deleted the add/content-helper-messages-in-settings-page branch May 20, 2025 09:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Changelog: Added PR to be added under the changelog's "Added" section

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants