Skip to content

refactor(core): extract recommendation data layer into src/sdk/recommendations - #3442

Merged
eduardoformiga merged 3 commits into
devfrom
feat/RR-568-recommendations-sdk
Aug 12, 2026
Merged

eduardoformiga merged 3 commits into
devfrom
feat/RR-568-recommendations-sdk

Conversation

@thiagopereira-vtex

@thiagopereira-vtex thiagopereira-vtex commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

What is the purpose of this pull request?

Extracts the data layer behind RecommendationShelf into a headless SDK module at src/sdk/recommendations, leaving the section as a presentation-only component.

  • vrn.ts, useRecommendations.ts and useRecommendationUserId.ts move out of src/components/sections/RecommendationShelf/ unchanged (Git tracks them as renames).
  • types.ts centralizes ItemContext and RecommendationType. RecommendationShelf.types.ts re-exports both, so existing imports and store customizations keep working.
  • New useRecommendationShelf() hook orchestrates the pieces (user id, product context, campaign gating, fetch) and returns items, isLoading, error, campaign and correlationId.
  • RecommendationShelf.tsx drops ~100 lines and now just consumes the hook.

No behavior change. The campaign rules, the CMS opt-in gate and the error handling are the same code, only relocated. The one cosmetic difference is that the empty-items fallback is now a stable constant instead of a new array per render.

What problem is this solving?

Part of RR-568 (mini cart recommendation shelf). A second surface will render recommendations inside the cart drawer with a different layout but identical campaign rules. Without this extraction, that surface would have to duplicate VRN resolution, the anonymous user id cookie handling and the context-products logic — three places to keep in sync every time a campaign type is added.

This PR is the enabler and ships on its own so the refactor can be reviewed as a pure move, separately from the new feature.

How to test it?

No functional change is expected, so the check is that the existing shelf keeps behaving identically.

Locally on this branch:

  • pnpm vitest run test/sdk/recommendations test/components/RecommendationShelf test/sdk/analytics in packages/core — 43 tests passing across 8 files.
  • pnpm lint and tsc --noEmit clean (no new errors in the touched files).
  • In a store, a configured Recommendation Shelf should render, fetch and track exactly as before.

No workspace link is attached, since this branch has no user-facing change to preview.

Screenshots or example usage

Not applicable — refactor with no visual or behavioral change.

Usage of the extracted hook:

const { items, isLoading, error, campaign, correlationId } =
  useRecommendationShelf({ campaignVrn, enableRecommendations, itemsContext })

How does this PR make you feel? 🔗

Like tidying a drawer before buying more stuff to put in it. (No gif picked.)

Types of changes

  • Chore (non-breaking change which doesn't change any functionalities)
  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Requires change to documentation, which has been updated accordingly.

Summary by CodeRabbit

  • New Features

    • Added a shared recommendations SDK for fetching recommendation products, campaign metadata, and correlation details.
    • Added support for recommendation shelves using product-page or cart context, including cart item deduplication.
    • Added validation for campaign identifiers and recommendation user IDs.
    • Added configuration to enable or disable recommendation fetching.
  • Documentation

    • Updated recommendation shelf documentation with new data-handling and validation references.
  • Tests

    • Expanded coverage for loading, validation, cart and product contexts, disabled fetching, and error handling.

…endations

Move the VRN parsing, anonymous user id and recommendations query out of the
RecommendationShelf section and into a headless SDK module, orchestrated by a
new useRecommendationShelf() hook. The section becomes a presentation-only
component that consumes the hook.

No behavior change: the campaign rules, the CMS opt-in gate and the error
handling are the same code, only relocated.
@thiagopereira-vtex
thiagopereira-vtex requested a review from a team as a code owner August 11, 2026 20:27
@thiagopereira-vtex
thiagopereira-vtex requested review from gabpaladino and lariciamota and removed request for a team August 11, 2026 20:27
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d76be5b2-be94-454a-8c53-8a6254e8431d

📥 Commits

Reviewing files that changed from the base of the PR and between 1c67842 and 8670314.

📒 Files selected for processing (1)
  • packages/core/src/sdk/recommendations/useRecommendationShelf.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/sdk/recommendations/useRecommendationShelf.ts

Walkthrough

Recommendation data handling moved from RecommendationShelf into shared SDK hooks. The SDK now exposes recommendation types, fetching, user ID resolution, shelf orchestration, and VRN utilities. Component integration, documentation, and tests use the new module paths.

Changes

Recommendations SDK migration

Layer / File(s) Summary
Recommendation contracts and data hooks
packages/core/src/sdk/recommendations/types.ts, packages/core/src/sdk/recommendations/useRecommendations.ts, packages/core/src/sdk/recommendations/useRecommendationUserId.ts, packages/core/src/sdk/recommendations/index.ts, packages/core/test/sdk/recommendations/*
The SDK defines recommendation types, executes the GraphQL query, resolves anonymous user IDs, and exports the recommendation APIs and utilities.
Shelf context and request orchestration
packages/core/src/sdk/recommendations/useRecommendationShelf.ts, packages/core/test/sdk/recommendations/useRecommendationShelf.browser.test.tsx
useRecommendationShelf validates campaign and user data, selects PDP or deduplicated cart products, gates requests, and returns recommendation state and metadata.
RecommendationShelf integration
packages/core/src/components/sections/RecommendationShelf/*, packages/core/test/components/RecommendationShelf/RecommendationShelf.browser.test.tsx
RecommendationShelf consumes the shared hook. Its types, mocks, and documentation use the SDK recommendations module.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RecommendationShelf
  participant useRecommendationShelf
  participant useRecommendationUserId
  participant useRecommendations
  RecommendationShelf->>useRecommendationShelf: pass campaign VRN and item context
  useRecommendationShelf->>useRecommendationUserId: resolve anonymous user ID
  useRecommendationShelf->>useRecommendations: fetch campaign recommendations
  useRecommendations-->>useRecommendationShelf: return products and metadata
  useRecommendationShelf-->>RecommendationShelf: return items, state, campaign, and correlation ID
Loading

Possibly related PRs

  • vtex/faststore#3403: Introduced the RecommendationShelf recommendation hooks and types that this PR moves into the shared SDK module.
  • vtex/faststore#3413: Updates RecommendationShelf documentation for the recommendation SDK paths.
  • vtex/faststore#3414: Also modifies RecommendationShelf recommendation fetching and enableRecommendations gating.

Suggested reviewers: lariciamota, gabpaladino

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: moving the recommendation data layer into src/sdk/recommendations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/RR-568-recommendations-sdk

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

Comment @coderabbitai help to get the list of available commands.

@codesandbox-ci

codesandbox-ci Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.tsx (1)

3-3: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Alias composed UI components with the UI prefix.

Rename Carousel and ProductShelf imports to UICarousel and UIProductShelf. Update their JSX references.

As per coding guidelines, “Import from @faststore/ui and alias with UI prefix to avoid local name collisions when composing library components.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.tsx`
at line 3, Alias the Carousel and ProductShelf imports from `@faststore/ui` as
UICarousel and UIProductShelf, then update all corresponding JSX references in
RecommendationShelf to use the aliased names.

Source: Coding guidelines

packages/core/src/sdk/recommendations/useRecommendations.ts (1)

42-48: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the synthetic request variables.

RecommendationInput has required fields, so {} is not a valid request. Pass args directly and declare the variables as RecommendationInput | null. useQuery returns a null key before request execution when doNotRun is true.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/sdk/recommendations/useRecommendations.ts` around lines 42
- 48, Update useRecommendations to pass args directly to useQuery instead of
using the synthetic empty RecommendationInput cast, and change the useQuery
variables type to RecommendationInput | null. Preserve doNotRun: args === null
so the query remains unexecuted with a null key.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/sdk/recommendations/useRecommendationShelf.ts`:
- Line 87: Update the recommendation shelf flow around useRecommendationUserId
to receive the enableRecommendations opt-in state, and make its effect return
before invoking retry or reading the cookie when recommendations are disabled.
Preserve the existing enabled behavior, and add a test verifying disabled
shelves do not read the personalization cookie.

---

Nitpick comments:
In
`@packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.tsx`:
- Line 3: Alias the Carousel and ProductShelf imports from `@faststore/ui` as
UICarousel and UIProductShelf, then update all corresponding JSX references in
RecommendationShelf to use the aliased names.

In `@packages/core/src/sdk/recommendations/useRecommendations.ts`:
- Around line 42-48: Update useRecommendations to pass args directly to useQuery
instead of using the synthetic empty RecommendationInput cast, and change the
useQuery variables type to RecommendationInput | null. Preserve doNotRun: args
=== null so the query remains unexecuted with a null key.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: ef8c7407-54dd-4ec1-9d5e-a8f7c0f3253a

📥 Commits

Reviewing files that changed from the base of the PR and between 74e2d50 and 1c67842.

📒 Files selected for processing (14)
  • packages/core/src/components/sections/RecommendationShelf/README.md
  • packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.tsx
  • packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.types.ts
  • packages/core/src/sdk/recommendations/index.ts
  • packages/core/src/sdk/recommendations/types.ts
  • packages/core/src/sdk/recommendations/useRecommendationShelf.ts
  • packages/core/src/sdk/recommendations/useRecommendationUserId.ts
  • packages/core/src/sdk/recommendations/useRecommendations.ts
  • packages/core/src/sdk/recommendations/vrn.ts
  • packages/core/test/components/RecommendationShelf/RecommendationShelf.browser.test.tsx
  • packages/core/test/sdk/recommendations/useRecommendationShelf.browser.test.tsx
  • packages/core/test/sdk/recommendations/useRecommendationUserId.test.ts
  • packages/core/test/sdk/recommendations/useRecommendations.test.ts
  • packages/core/test/sdk/recommendations/vrn.test.ts

The previous wording claimed no personalization cookie is read when the opt-in
is off. The cookie lookup is not gated (and was not before this refactor), so
describe what actually happens: the campaign is never requested and the
resolved user id goes unused.
@thiagopereira-vtex

Copy link
Copy Markdown
Contributor Author

On the two nitpicks — declining both, since they target pre-existing code that this PR only relocated.

UI prefix on the @faststore/ui imports. The guideline is real (packages/core/AGENTS.md:67), but this file already violated it on dev, where line 4 read import { ProductShelf, Carousel } from '@faststore/ui'. My diff only reordered the two names alphabetically (Biome), and that cosmetic change is what pulled the line into the review. Applying the alias means renaming the JSX references across the component, which is unrelated churn in a move-only PR. Happy to do it as a separate cleanup if the team wants the rule enforced retroactively.

Synthetic {} variables in useRecommendations. The critique is technically right: args ?? ({} as RecommendationInput) is an unsound cast, and the suggested RecommendationInput | null typing would work. But that value is provably never used — useQuery only builds the SWR key when doNotRun is false — and the file currently shows up in this PR as a rename with zero changed lines. Touching it would destroy exactly the property that makes this PR cheap to review: every moved file can be verified as byte-identical to its previous location.

Both are reasonable improvements on their own, just not in a PR whose entire value proposition is being a verifiable pure move.

@pkg-pr-new

pkg-pr-new Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@177a326

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@177a326

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@177a326

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@177a326

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@177a326

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@177a326

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@177a326

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@177a326

commit: 177a326

@eduardoformiga eduardoformiga left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM!

@sonar-workflows

Copy link
Copy Markdown

@eduardoformiga
eduardoformiga merged commit d89c363 into dev Aug 12, 2026
10 checks passed
@eduardoformiga
eduardoformiga deleted the feat/RR-568-recommendations-sdk branch August 12, 2026 15:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants