Repository navigation
feat: Add ActivityFlow data parameters with search-related information - #3105
Conversation
|
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. |
2ee4dc1 to
27cc25b
Compare
| const products = data?.search?.products?.edges ?? [] | ||
| const searchId = data?.search?.searchId | ||
|
|
||
| function buildExtraProductProps( |
There was a problem hiding this comment.
que tal mover essa função para fora do componente ou envolver com useCallback para evitar recriação a cada render?
|
Important Review skippedThis PR was authored by the user configured for CodeRabbit reviews. CodeRabbit does not review PRs authored by this user. It's recommended to use a dedicated user account to post CodeRabbit review feedback. ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
WalkthroughThis pull request introduces a Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/components/product/ProductGrid/ProductGrid.tsx (1)
138-165:⚠️ Potential issue | 🟠 MajorOffset the sliced index before building analytics props.
In this branch,
products.slice(2).map(... idx)restartsidxat 0, so the third card is emitted with the same position as the first one.packages/core/src/ui/ProductGallery/ProductGalleryPage.tsx(Lines 30-46) uses that argument to populatedata-af-product-position, so mobile first-page analytics will duplicate positions after the second item.Suggested fix
{products.slice(2).map(({ node: product }, idx) => ( <UIProductGridItem key={`${product.id}`}> @@ - index={pageSize * page + idx + 1} + index={pageSize * page + idx + 3} taxesConfiguration={taxesConfiguration} sponsoredLabel={sponsoredLabel} - {...buildExtraProductProps(product, idx)} + {...buildExtraProductProps(product, idx + 2)} />🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/components/product/ProductGrid/ProductGrid.tsx` around lines 138 - 165, The sliced map restarts idx at 0 so analytics positions duplicate; offset idx by the slice length (2) before using it for analytics. In ProductGrid.tsx update the mapped index usages: replace index={pageSize * page + idx + 1} with index={pageSize * page + (idx + 2) + 1} (or compute const adjustedIdx = idx + 2 and use adjustedIdx), and pass the adjusted index into buildExtraProductProps (buildExtraProductProps(product, adjustedIdx)) so ProductCard.Component and any analytics props use the correct absolute position; adjust any other uses of idx in this map similarly.
♻️ Duplicate comments (3)
packages/api/src/typeDefs/query.graphql (1)
189-192:⚠️ Potential issue | 🔴 CriticalMake
searchIdnullable unless the resolver can guarantee it.Line 192 advertises a hard GraphQL guarantee, but the VTEX payload models
searchIdas optional andpackages/api/src/platforms/vtex/resolvers/searchResult.tsreturns it verbatim. If it comes back missing, this can turnsearchinto a runtime GraphQL error instead of just omitting analytics metadata.Proposed fix
- searchId: String! + searchId: String🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/api/src/typeDefs/query.graphql` around lines 189 - 192, The GraphQL field searchId is declared non-nullable but the VTEX payload and the resolver platforms/vtex/resolvers/searchResult.ts treat it as optional; update the schema to make searchId nullable (change from String! to String) unless you add a guaranteed fallback in the resolver, or alternatively modify the resolver (in searchResult.ts) to synthesize a stable value for searchId before returning; ensure the schema and the resolver behavior agree so missing VTEX searchId won't cause runtime GraphQL errors.packages/core/src/components/ui/ProductGallery/ProductGalleryPage.tsx (1)
35-45:⚠️ Potential issue | 🟠 MajorFix the first-item position in the analytics payload.
Line 43 keeps
0as-is, so the first product is emitted with position0instead of1. That skews the search analytics ranking for the very first card.Proposed fix
- 'data-af-product-position': index ?? Number(index) + 1, // Product position in Search Analytics starts with 1 + 'data-af-product-position': Number(index ?? 0) + 1, // Product position in Search Analytics starts with 1🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/components/ui/ProductGallery/ProductGalleryPage.tsx` around lines 35 - 45, buildExtraProductProps is emitting a zero-based position because the expression "index ?? Number(index) + 1" returns 0 for the first item; change the logic so you coerce/index-default before adding 1 (e.g., compute position as (index ?? 0) + 1 or Number(index ?? 0) + 1, or guard with typeof index === 'number' ? index + 1 : 1) and assign that value to 'data-af-product-position' in buildExtraProductProps so the first product is reported as position 1; keep other fields (like 'data-af-product-id' and searchId) unchanged.packages/core/src/components/product/ProductGrid/ProductGrid.tsx (1)
62-65:⚠️ Potential issue | 🔴 CriticalDefault
buildExtraProductPropsbefore invoking it.
buildExtraProductPropsis optional in the prop type, but Lines 132, 165, and 201 call it unconditionally. Any existingProductGridusage that doesn't pass this prop will throw during render.Suggested fix
function ProductGrid({ products, page, pageSize, @@ compareLabel, title, searchId, - buildExtraProductProps, + buildExtraProductProps = () => ({}), }: Props) {Also applies to: 82-83, 132-132, 165-165, 201-201
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/components/product/ProductGrid/ProductGrid.tsx` around lines 62 - 65, The prop buildExtraProductProps on ProductGrid is optional but is invoked unguarded in render; update ProductGrid to provide a safe default or guard calls: either default buildExtraProductProps to a no-op function that returns an empty object (e.g., set a defaultProp or fallback in the function/component body) or wrap each invocation (where ProductGrid currently calls buildExtraProductProps) with a conditional check (if (buildExtraProductProps) ...) so calls in render (references to buildExtraProductProps in ProductGrid) never throw when the prop is omitted.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@packages/core/src/components/templates/ProductListingPage/ProductListing.tsx`:
- Line 76: The initialPages object is being seeded with a fabricated empty
searchId which disables analytics attrs; update the initialization of
initialPages (the const initialPages = { search: { ...server?.search, searchId:
'' } }) to preserve the real searchId from the server response (e.g., use
server?.search.searchId or spread server?.search without overriding searchId) or
modify the server-side query to include a valid searchId so you do not set
searchId to an empty string; ensure the symbol initialPages and the
server?.search payload carry the real searchId so analytics data-af-* attributes
remain enabled on the initial render.
---
Outside diff comments:
In `@packages/core/src/components/product/ProductGrid/ProductGrid.tsx`:
- Around line 138-165: The sliced map restarts idx at 0 so analytics positions
duplicate; offset idx by the slice length (2) before using it for analytics. In
ProductGrid.tsx update the mapped index usages: replace index={pageSize * page +
idx + 1} with index={pageSize * page + (idx + 2) + 1} (or compute const
adjustedIdx = idx + 2 and use adjustedIdx), and pass the adjusted index into
buildExtraProductProps (buildExtraProductProps(product, adjustedIdx)) so
ProductCard.Component and any analytics props use the correct absolute position;
adjust any other uses of idx in this map similarly.
---
Duplicate comments:
In `@packages/api/src/typeDefs/query.graphql`:
- Around line 189-192: The GraphQL field searchId is declared non-nullable but
the VTEX payload and the resolver platforms/vtex/resolvers/searchResult.ts treat
it as optional; update the schema to make searchId nullable (change from String!
to String) unless you add a guaranteed fallback in the resolver, or
alternatively modify the resolver (in searchResult.ts) to synthesize a stable
value for searchId before returning; ensure the schema and the resolver behavior
agree so missing VTEX searchId won't cause runtime GraphQL errors.
In `@packages/core/src/components/product/ProductGrid/ProductGrid.tsx`:
- Around line 62-65: The prop buildExtraProductProps on ProductGrid is optional
but is invoked unguarded in render; update ProductGrid to provide a safe default
or guard calls: either default buildExtraProductProps to a no-op function that
returns an empty object (e.g., set a defaultProp or fallback in the
function/component body) or wrap each invocation (where ProductGrid currently
calls buildExtraProductProps) with a conditional check (if
(buildExtraProductProps) ...) so calls in render (references to
buildExtraProductProps in ProductGrid) never throw when the prop is omitted.
In `@packages/core/src/components/ui/ProductGallery/ProductGalleryPage.tsx`:
- Around line 35-45: buildExtraProductProps is emitting a zero-based position
because the expression "index ?? Number(index) + 1" returns 0 for the first
item; change the logic so you coerce/index-default before adding 1 (e.g.,
compute position as (index ?? 0) + 1 or Number(index ?? 0) + 1, or guard with
typeof index === 'number' ? index + 1 : 1) and assign that value to
'data-af-product-position' in buildExtraProductProps so the first product is
reported as position 1; keep other fields (like 'data-af-product-id' and
searchId) unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 8127134a-a188-4df9-ba5b-79e7debd780c
⛔ Files ignored due to path filters (3)
packages/api/src/__generated__/schema.tsis excluded by!**/__generated__/**and included bypackages/**packages/core/@generated/gql.tsis excluded by!**/@generated/**,!**/@generated/**and included bypackages/**packages/core/@generated/graphql.tsis excluded by!**/@generated/**,!**/@generated/**and included bypackages/**
📒 Files selected for processing (13)
packages/api/src/platforms/vtex/clients/search/types/ProductSearchResult.tspackages/api/src/platforms/vtex/resolvers/searchResult.tspackages/api/src/typeDefs/query.graphqlpackages/components/src/molecules/SearchProducts/SearchProductItem.tsxpackages/components/src/molecules/SearchProvider/SearchProvider.tsxpackages/components/src/organisms/SearchInput/SearchInput.tsxpackages/core/src/components/product/ProductGrid/ProductGrid.tsxpackages/core/src/components/search/SearchDropdown/SearchDropdown.tsxpackages/core/src/components/search/SearchInput/SearchInput.tsxpackages/core/src/components/templates/ProductListingPage/ProductListing.tsxpackages/core/src/components/ui/ProductGallery/ProductGalleryPage.tsxpackages/core/src/sdk/product/usePageProductsQuery.tspackages/core/src/sdk/search/useSuggestions.ts
There was a problem hiding this comment.
Actionable comments posted: 11
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/core/src/sdk/analytics/platform/vtex/search.ts (2)
131-138:⚠️ Potential issue | 🟠 MajorDon’t drop zero-based positions from click tracking.
Line 131 and Line 178 treat
0as missing, so the first search result / autocomplete suggestion is skipped whenever positions are zero-based. Check fornull/undefinedinstead of truthiness.Suggested fix
- if (productId && position) { + if (productId && position != null) { sendEvent({ type: 'search.click', productId, position, url: url.href, text: url.searchParams.get('q') ?? '<empty>', }) } @@ - ...(event.params.position && { position: event.params.position }), + ...(event.params.position != null + ? { position: event.params.position } + : {}),Also applies to: 174-180
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/sdk/analytics/platform/vtex/search.ts` around lines 131 - 138, The conditional treating position as truthy drops zero (first item); update the checks around the sendEvent calls (the blocks containing "if (productId && position)" and the similar check at the other sendEvent near the autocomplete/click handling) to test for null/undefined instead of truthiness — e.g., use position !== undefined && position !== null (and likewise productId !== undefined && productId !== null or productId != null) so zero-based positions (0) are allowed.
16-19:⚠️ Potential issue | 🟠 MajorReplace the randomUUID fallback with a collision-resistant alternative.
The current
Math.random() * 1e6fallback has only ~20 bits of entropy (~1M possible values), which is too small foranonymous/sessionidentifiers and will cause user/session merging in analytics. Usecrypto.getRandomValues()instead—it has 128-bit entropy and is universally supported since 2015 (predatingcrypto.randomUUIDby ~7 years).Suggested fix
-const randomUUID = () => - typeof crypto.randomUUID === 'function' - ? crypto.randomUUID().replaceAll('-', '') - : (Math.random() * 1e6).toFixed(0) +const randomUUID = () => { + if (typeof crypto.randomUUID === 'function') { + return crypto.randomUUID().replaceAll('-', '') + } + + const bytes = new Uint8Array(16) + crypto.getRandomValues(bytes) + + return Array.from(bytes, (byte) => + byte.toString(16).padStart(2, '0') + ).join('') +}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/sdk/analytics/platform/vtex/search.ts` around lines 16 - 19, Replace the weak Math.random() fallback in the randomUUID function with a collision-resistant implementation using crypto.getRandomValues: when crypto.randomUUID isn't available generate 16 random bytes via crypto.getRandomValues(new Uint8Array(16)) and convert them to a 32-character hex string (no dashes) to provide ~128-bit entropy; update the randomUUID function to use crypto.randomUUID().replaceAll('-', '') if available otherwise build the hex string from the Uint8Array so anonymous/session identifiers are collision-resistant.
🟡 Minor comments (15)
packages/lighthouse/CHANGELOG.md-10-14 (1)
10-14:⚠️ Potential issue | 🟡 MinorAlign the subsection heading depth with markdownlint.
Lines 12 and 30 jump from
#version headings straight to### Features, which triggersMD001on the changed lines. Use## Featureshere, or adjust the version heading depth so section levels only increase by one.Also applies to: 28-32
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/lighthouse/CHANGELOG.md` around lines 10 - 14, The subsection heading depth is too deep compared to the version heading (e.g., the "[3.98.0-dev.0]" version heading) causing markdownlint MD001; update the "### Features" headings to "## Features" (or alternatively adjust the version heading level) so headings only increase by one level, and apply the same fix to the other occurrence around lines referencing the "Features" subsection (the second "### Features" instance).packages/lighthouse/CHANGELOG.md-24-36 (1)
24-36:⚠️ Potential issue | 🟡 MinorRemove the duplicated
3.96.0-dev.22entry.Lines 24-36 repeat the same release heading and note, which makes the changelog ambiguous and triggers the duplicate-heading lint warning. Keep a single
3.96.0-dev.22block here, or replace the second one if it was meant to be a different version.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/lighthouse/CHANGELOG.md` around lines 24 - 36, The changelog contains a duplicated release block titled "3.96.0-dev.22" with the same "**Note:** Version bump only for package `@faststore/lighthouse`"; remove the redundant second "3.96.0-dev.22" block (or replace it if it was intended to be a different version) so there is only a single release heading for that dev version and the duplicate-heading lint warning is resolved.packages/ui/CHANGELOG.md-10-14 (1)
10-14:⚠️ Potential issue | 🟡 MinorNormalize subsection heading levels for markdownlint.
At Line 12 and Line 38,
### Featuresjumps from an h1 release heading to h3. Switching these to## Featureskeeps the hierarchy valid and clearsMD001.Suggested fix
-### Features +## FeaturesAlso applies to: 36-40
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/ui/CHANGELOG.md` around lines 10 - 14, The "Features" subsection headings under the release title "# [3.98.0-dev.0] (2026-02-24)" are using h3 (### Features) which breaks heading hierarchy and triggers MD001; change those "### Features" occurrences (e.g., the one immediately under the release heading and the one around lines ~36-40) to h2 ("## Features") so they are direct children of the release h1 heading and satisfy markdownlint.packages/ui/CHANGELOG.md-32-44 (1)
32-44:⚠️ Potential issue | 🟡 MinorRemove the duplicated
3.96.0-dev.22entry.Line 42 repeats the same version heading already introduced at Line 32, along with the same package-bump note. That makes the changelog ambiguous and also triggers
MD024.Suggested fix
# 3.96.0-dev.22 (2026-01-21) **Note:** Version bump only for package `@faststore/ui` # [3.96.0](https://github.com/vtex/faststore/compare/v3.95.0...v3.96.0) (2025-12-24) ### Features - version 20251223 ([`#3161`](https://github.com/vtex/faststore/issues/3161)) ([ad5e8d1](https://github.com/vtex/faststore/commit/ad5e8d12fe45f1fb8e1134165172bf1c6b2a91e2)) - -# 3.96.0-dev.22 (2026-01-21) - -**Note:** Version bump only for package `@faststore/ui`🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/ui/CHANGELOG.md` around lines 32 - 44, Remove the duplicated "3.96.0-dev.22 (2026-01-21)" changelog block: locate the second occurrence of the heading "3.96.0-dev.22 (2026-01-21)" and the repeated "**Note:** Version bump only for package `@faststore/ui`" and delete that entire duplicate block so only a single entry for 3.96.0-dev.22 remains in CHANGELOG.md; ensure surrounding spacing and headings remain correct after removal.packages/storybook/CHANGELOG.md-32-45 (1)
32-45:⚠️ Potential issue | 🟡 MinorRemove duplicate
3.96.0-dev.22entry.The version
3.96.0-dev.22appears twice (lines 32-35 and lines 42-45) with identical content. Changelogs should have unique version entries.🧹 Proposed fix
# 3.96.0-dev.22 (2026-01-21) **Note:** Version bump only for package `@faststore/storybook` # [3.96.0](https://github.com/vtex/faststore/compare/v3.95.0...v3.96.0) (2025-12-24) ### Features - version 20251223 ([`#3161`](https://github.com/vtex/faststore/issues/3161)) ([ad5e8d1](https://github.com/vtex/faststore/commit/ad5e8d12fe45f1fb8e1134165172bf1c6b2a91e2)) -# 3.96.0-dev.22 (2026-01-21) - -**Note:** Version bump only for package `@faststore/storybook` - # 3.96.0-dev.18 (2025-12-24)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/storybook/CHANGELOG.md` around lines 32 - 45, The CHANGELOG contains a duplicated version block for "3.96.0-dev.22" — remove the redundant second block (the repeated lines starting with "# 3.96.0-dev.22 (2026-01-21)" and its "**Note:** Version bump only for package `@faststore/storybook`") so only one entry for 3.96.0-dev.22 remains, preserving the surrounding changelog order and formatting.packages/core/src/pages/_document.tsx-9-10 (1)
9-10:⚠️ Potential issue | 🟡 MinorTreat blank GTM container IDs as disabled.
typeof gtmContainerId === 'string'is also true for'', so a misconfigured empty ID still enablesdataLayer.pushforwarding. Gate this on a non-empty value instead.🔧 Suggested fix
- const includeGTM = typeof gtmContainerId === 'string' + const includeGTM = + typeof gtmContainerId === 'string' && gtmContainerId.trim() !== ''🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/pages/_document.tsx` around lines 9 - 10, The check for enabling GTM uses typeof gtmContainerId === 'string' which treats an empty string as enabled; change the predicate so includeGTM only becomes true for a non-empty string (e.g., check gtmContainerId && gtmContainerId.trim() !== '' or Boolean(gtmContainerId?.trim())) so blank GTM IDs do not enable dataLayer.push forwarding; update the declaration of includeGTM (and any downstream logic that relies on it) to use the non-empty-string check referencing gtmContainerId and includeGTM.packages/core/src/pages/_document.tsx-41-43 (1)
41-43:⚠️ Potential issue | 🟡 MinorMatch the GTM debug flag by query-param key, not substring.
The current
includes('${GTM_DEBUG_QUERY_STRING}=')check can also match unrelated params likefoo_${GTM_DEBUG_QUERY_STRING}=1, which disables forwarding unexpectedly.🔧 Suggested fix
- forward:[...${JSON.stringify( - forwards - )},!window.location.search.includes('${GTM_DEBUG_QUERY_STRING}=')&&${includeGTM}?'dataLayer.push':null].filter(Boolean) + forward:[...${JSON.stringify( + forwards + )},${includeGTM} && + !new URLSearchParams(window.location.search).has('${GTM_DEBUG_QUERY_STRING}') + ? 'dataLayer.push' + : null].filter(Boolean)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/pages/_document.tsx` around lines 41 - 43, The GTM debug check uses window.location.search.includes('${GTM_DEBUG_QUERY_STRING}=') which can match substrings of other param names; update the condition in the forward array to check the query key explicitly (e.g. use URLSearchParams on window.location.search and call .has('${GTM_DEBUG_QUERY_STRING}') instead of .includes) so the forwarding logic that references includeGTM and 'dataLayer.push' only triggers when the exact GTM_DEBUG_QUERY_STRING key is present.packages/core/src/pages/api/graphql.ts-60-69 (1)
60-69:⚠️ Potential issue | 🟡 MinorUse exact matching for bare allowlist entries.
Line 69 makes
localhostbehave like a suffix, so hosts likemylocalhostwould pass the guard. That broadens cookie rewriting beyond the hosts listed inALLOWED_HOST_SUFFIXES.🔧 Suggested guard
const isAllowedHost = ({ host, allowList, }: { host: string allowList: string[] }) => { const normalizedHost = host.toLowerCase() - return allowList.some((suffix) => normalizedHost.endsWith(suffix)) + return allowList.some((suffix) => + suffix.startsWith('.') + ? normalizedHost.endsWith(suffix) + : normalizedHost === suffix + ) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/pages/api/graphql.ts` around lines 60 - 69, isAllowedHost currently treats every allowList entry as a suffix which makes entries like "localhost" match "mylocalhost"; update isAllowedHost so entries that are bare names require exact match while entries intended as suffixes (e.g., prefixed with a dot) perform a suffix check. Concretely, modify the allowList.some callback in isAllowedHost to: normalize the suffix, if the suffix startsWith('.') then return normalizedHost.endsWith(suffix) else return normalizedHost === suffix (or optionally allow normalizedHost === suffix || normalizedHost.endsWith('.' + suffix) if you want subdomains to match); keep using the same symbols host, allowList, normalizedHost and the isAllowedHost function name to locate the change.packages/sdk/CHANGELOG.md-24-24 (1)
24-24:⚠️ Potential issue | 🟡 MinorDuplicate changelog entry for version 3.96.0-dev.22.
The version
3.96.0-dev.22appears twice (lines 24 and 34). This is likely a merge artifact from the auto-generated changelog. Consider removing one of the duplicate entries.Also applies to: 34-34
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/sdk/CHANGELOG.md` at line 24, Remove the duplicated changelog header for version "3.96.0-dev.22" so the changelog contains a single entry for that version; locate the two identical headers ("# 3.96.0-dev.22 (2026-01-21)") in CHANGELOG.md and delete the redundant one (ensure you preserve the full, non-duplicated changelog body so only the extra header/section is removed).packages/components/CHANGELOG.md-24-26 (1)
24-26:⚠️ Potential issue | 🟡 MinorDuplicate changelog entry for version 3.96.0-dev.22.
Lines 24-26 and 34-36 both contain duplicate entries for
3.96.0-dev.22. Consider consolidating.Also applies to: 34-36
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/components/CHANGELOG.md` around lines 24 - 26, There are duplicate changelog entries for the same version string "3.96.0-dev.22"; open the CHANGELOG.md, locate both occurrences of the header "3.96.0-dev.22 (2026-01-21)" and consolidate them into a single entry by removing the redundant copy while preserving the combined content (e.g., the "**Note:** Version bump only for package `@faststore/components`") so the changelog contains only one canonical block for that version.packages/api/CHANGELOG.md-24-26 (1)
24-26:⚠️ Potential issue | 🟡 MinorDuplicate changelog entry for version 3.96.0-dev.22.
Lines 24-26 and 66-70 both contain entries for
3.96.0-dev.22. This appears to be an accidental duplication that should be consolidated.Also applies to: 66-70
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/api/CHANGELOG.md` around lines 24 - 26, The changelog contains a duplicated entry for the version "3.96.0-dev.22"; locate both sections titled or referencing "3.96.0-dev.22" and remove the redundant copy so only one consolidated entry remains (merge any differing notes from both into the single kept entry), and ensure the remaining entry stays in the correct chronological order under the releases list.packages/graphql-utils/CHANGELOG.md-24-26 (1)
24-26:⚠️ Potential issue | 🟡 MinorDuplicate changelog entry for version 3.96.0-dev.22.
Lines 24-26 and 34-36 both contain entries for
3.96.0-dev.22. This duplication should be cleaned up.Also applies to: 34-36
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/graphql-utils/CHANGELOG.md` around lines 24 - 26, Remove the duplicate changelog entry for version "3.96.0-dev.22" so only a single entry remains; find both blocks labeled "3.96.0-dev.22" in CHANGELOG.md and delete the redundant one (ensure you keep the most complete/accurate block if they differ), leaving the rest of the changelog intact and preserving formatting/ordering for subsequent versions.packages/cli/CHANGELOG.md-66-122 (1)
66-122:⚠️ Potential issue | 🟡 MinorRemove the duplicated release entries.
This block repeats versions that already appear above, which creates duplicate headings and breaks markdownlint (
MD024, plus the surrounding heading-structure warnings). Keep a single entry per version before publishing the changelog.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/CHANGELOG.md` around lines 66 - 122, The CHANGELOG contains duplicated release headings (e.g., "3.96.0-dev.22", "3.96.0-dev.21", "3.96.0-dev.20", "3.96.0-dev.19") repeated later in the file; remove the duplicate blocks so each version heading appears exactly once, keeping the first (or canonical) occurrence and deleting the repeated subsequent entries, then verify the heading order/structure is consistent to satisfy markdownlint (MD024) before committing.packages/core/CHANGELOG.md-82-160 (1)
82-160:⚠️ Potential issue | 🟡 MinorDeduplicate the repeated version blocks.
This hunk reintroduces
3.97.0-dev.5through3.96.0-dev.19later in the file. The duplicate headings already show up in markdownlint output and make the release history ambiguous.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/CHANGELOG.md` around lines 82 - 160, The CHANGELOG contains duplicated release blocks (e.g., headings "3.97.0-dev.5" through "3.96.0-dev.19") that reappear later in the file; remove the repeated blocks so each release heading appears only once and the history remains chronological. Locate the duplicated headings (e.g., "3.97.0-dev.5", "3.97.0-dev.4", "3.97.0-dev.3", "3.97.0-dev.2", "3.97.0-dev.1", "3.97.0-dev.0", "3.96.4-dev.0", "3.96.0-dev.22", "3.96.0-dev.21", "3.96.0-dev.20", "3.96.0-dev.19") and delete the later repeated blocks, keeping the intended single authoritative entries; after editing, ensure markdown is valid and run markdownlint to confirm duplicates are resolved.packages/core/CHANGELOG.md-459-459 (1)
459-459:⚠️ Potential issue | 🟡 MinorRestore the full release-note titles.
These entries now end in
……, which drops the issue context and makes the changelog harder to search or reference.Also applies to: 465-465, 643-643
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/CHANGELOG.md` at line 459, Several changelog entries have their release-note titles truncated with trailing ellipses (e.g., the entry containing "OrganizationDrawer……" and the commit 6e73b8e); find each truncated title (also the similar entries referenced by the reviewer) and replace the ellipses with the full release-note title text from the original commit message or PR title so the issue context and links remain searchable; update the lines containing the truncated strings (search for "……" and for the exact fragment "OrganizationDrawer……") and restore the complete titles for those entries, preserving the associated PR/commit links and formatting.
🧹 Nitpick comments (13)
packages/core/src/pages/api/preview.ts (1)
42-42: Consider narrowing the type instead of casting.The type assertion
previewData as PreviewDataworks, but ifPreviewDatais a subset ofRecord<string, string>, you could refine the function signature to acceptPreviewDatadirectly. If that's not feasible due to the caller's constraints, this cast is acceptable sinceisBranchPreviewis a type guard.💡 Alternative: Update function signature
If the caller can provide properly typed
PreviewData:const setPreviewAndRedirect = ( res: NextApiResponse, - previewData: Record<string, string>, + previewData: PreviewData, redirectPath: string ) => { ... - if (!isBranchPreview(previewData as PreviewData)) { + if (!isBranchPreview(previewData)) {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/pages/api/preview.ts` at line 42, The code is using a type assertion previewData as PreviewData when calling isBranchPreview; instead, narrow the variable's type so the guard can operate without a cast: update the handler or its caller to declare previewData with the PreviewData type (or change the function signature that provides previewData), then call isBranchPreview(previewData) directly; if changing the upstream type isn't possible, leave the cast but prefer adding a local type-narrowing check (e.g., validate required keys) before calling isBranchPreview to avoid the assertion.packages/api/src/platforms/vtex/clients/commerce/index.ts (1)
222-251: Clean implementation for dual-purpose orderForm endpoint.The conditional logic correctly handles both scenarios:
- With ID: Fetches/refreshes existing order form with
refreshOutdatedDataparam, no body- Without ID: Creates new order form with empty body
'{}'The flat conditionals using ternaries keep this readable. One minor edge case to consider: an empty string
''foridis falsy and would trigger the "create new" path. If callers might accidentally pass'', you could add explicit validation.💡 Optional: Explicit empty string guard
orderForm: ({ id, refreshOutdatedData = true, channel = ctx.storage.channel, }: { id?: string refreshOutdatedData?: boolean channel?: Required<Channel> }): Promise<OrderForm> => { + const hasId = Boolean(id?.trim()) const { salesChannel } = channel const headers: HeadersInit = withCookie({ 'content-type': 'application/json', 'X-FORWARDED-HOST': forwardedHost, }) const params = new URLSearchParams({ sc: salesChannel }) - if (id) { + if (hasId) { params.set('refreshOutdatedData', refreshOutdatedData.toString()) } - const url = `${base}/api/checkout/pub/orderForm${id ? `/${id}` : ''}?${params.toString()}` + const url = `${base}/api/checkout/pub/orderForm${hasId ? `/${id}` : ''}?${params.toString()}` return fetchAPI( url, { ...BASE_INIT, headers, - ...(id ? {} : { body: '{}' }), + ...(hasId ? {} : { body: '{}' }), }, { storeCookies } ) },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/api/src/platforms/vtex/clients/commerce/index.ts` around lines 222 - 251, The orderForm function treats a falsy id (e.g., empty string '') as "no id" which incorrectly routes to the create-new path; add an explicit guard so only undefined or null are considered "no id". Update the checks around id usage in orderForm (used when building params, url string `${id ? `/${id}` : ''}`, and the conditional body `(id ? {} : { body: '{}' })`) to first normalize/validate id (e.g., treat '' as invalid) or check for id !== undefined && id !== null before branching, ensuring empty strings do not trigger the create-new behavior.packages/api/src/typeDefs/userOrder.graphql (1)
813-819: FieldToBeSpentshould use camelCase (toBeSpent).GraphQL convention is camelCase for field names. This field breaks consistency with the rest of the schema.
Proposed fix
type UserOrderBudgetAllocation { id: String linkedEntity: UserOrderBudgetAllocationLinkedEntity balance: UserOrderBudgetBalance reservations: JSONObject - ToBeSpent: Float + toBeSpent: Float }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/api/src/typeDefs/userOrder.graphql` around lines 813 - 819, Rename the GraphQL field on type UserOrderBudgetAllocation from ToBeSpent to camelCase toBeSpent; update the schema definition (type UserOrderBudgetAllocation) to replace the ToBeSpent field name and then search for and update any resolvers, fragments, queries, mutations, and TypeScript types that reference UserOrderBudgetAllocation.ToBeSpent to use toBeSpent so the server and clients remain consistent.packages/api/src/platforms/vtex/resolvers/validateSession.ts (1)
23-30: Good null safety improvement, but consider validating array contents.The check for
address.geoCoordinatesbeing truthy handles the undefined/null case well. However, an empty array[]or an array with fewer than 2 elements would pass this check but produce{ latitude: undefined, longitude: undefined }. This object then passes the!!geoCoordinatescheck at line 85, potentially sendingundefined,undefinedto the session API.♻️ Suggested fix to validate coordinate values
- const geoCoordinates = address.geoCoordinates - ? { - latitude: address.geoCoordinates[1], - longitude: address.geoCoordinates[0], - } - : null + const [longitude, latitude] = address.geoCoordinates ?? [] + const geoCoordinates = + longitude != null && latitude != null + ? { latitude, longitude } + : null🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/api/src/platforms/vtex/resolvers/validateSession.ts` around lines 23 - 30, The geoCoordinates creation in validateSession.ts can produce {latitude: undefined, longitude: undefined} for empty or short arrays; update the logic that builds geoCoordinates (used in the function returning { city, geoCoordinates }) to only set geoCoordinates when address.geoCoordinates is an array with length >= 2 and both entries are finite numbers (e.g., Number.isFinite(+address.geoCoordinates[1]) and Number.isFinite(+address.geoCoordinates[0])); convert/parse the values to numbers before assigning latitude and longitude and otherwise set geoCoordinates to null so downstream checks like !!geoCoordinates never pass undefined values to the session API.packages/api/src/platforms/vtex/resolvers/validateCart.ts (2)
463-471: Good early-exit optimization, but note the duplicate call.The early return when no changes exist is a solid optimization. However,
shouldUpdateShippingDatais called here (line 465) and again insideupdateOrderFormShippingData(line 281). Consider passing theupdateShippingresult to avoid recomputation:♻️ Optional: Pass updateShipping result to avoid duplicate computation
-const updateOrderFormShippingData = async ( +const updateOrderFormShippingData = async ( orderForm: OrderForm, session: Maybe<IStoreSession> | undefined, - { clients: { commerce } }: Context + { clients: { commerce } }: Context, + precomputedUpdateShipping?: { updateShipping: boolean; addressChanged: boolean } ) => { if (!session) { return orderForm } - const { updateShipping, addressChanged } = shouldUpdateShippingData( + const { updateShipping, addressChanged } = precomputedUpdateShipping ?? shouldUpdateShippingData( orderForm, session )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/api/src/platforms/vtex/resolvers/validateCart.ts` around lines 463 - 471, The code calls shouldUpdateShippingData twice (once here to get updateShipping and again inside updateOrderFormShippingData), so compute shouldUpdateShippingData once and pass its result into the later call to avoid duplicate work: keep the current extraction of updateShipping from shouldUpdateShippingData(session ? shouldUpdateShippingData(orderForm, session) : { updateShipping: false }), then modify the invocation of updateOrderFormShippingData to accept an optional updateShipping boolean (or add an overload/parameter) and pass the computed updateShipping into updateOrderFormShippingData instead of having that function recompute it internally.
496-517: RedundantPromise.resolvewrapper.
updatedOrderFormis already resolved from theawaitin both branches (lines 478-486 and 489-493). ThePromise.resolve()wrap is unnecessary.♻️ Remove redundant Promise.resolve
- // Continue with marketingData and etag updates - updatedOrderForm = await Promise.resolve(updatedOrderForm) - // update marketingData - .then((form: OrderForm) => { + // Continue with marketingData and etag updates + // update marketingData + if (session?.marketingData) { + const updatedMarketingData = { + ...updatedOrderForm.marketingData, + ...session.marketingData, + } + updatedOrderForm = await commerce.checkout.marketingData({ + id: orderForm.orderFormId, + marketingData: updatedMarketingData, + }) + } + + // update orderForm etag so we know last time we touched this orderForm + updatedOrderForm = joinItems( + await setOrderFormEtag(updatedOrderForm, commerce, sessionJwt) + )Alternatively, keep the
.then()chain but start directly:- updatedOrderForm = await Promise.resolve(updatedOrderForm) + updatedOrderForm = await (async () => updatedOrderForm)()Or simply inline:
- // Continue with marketingData and etag updates - updatedOrderForm = await Promise.resolve(updatedOrderForm) - // update marketingData - .then((form: OrderForm) => { + // Continue with marketingData and etag updates + let formToUpdate: OrderForm = updatedOrderForm + + // update marketingData + formToUpdate = await (async (form: OrderForm) => { if (session?.marketingData) { const updatedMarketingData = { ...form.marketingData, ...session.marketingData, } - return commerce.checkout.marketingData({ id: orderForm.orderFormId, marketingData: updatedMarketingData, }) } - return form - }) - // update orderForm etag so we know last time we touched this orderForm - .then((form: OrderForm) => setOrderFormEtag(form, commerce, sessionJwt)) - .then(joinItems) + })(formToUpdate) + + // update orderForm etag so we know last time we touched this orderForm + updatedOrderForm = joinItems(await setOrderFormEtag(formToUpdate, commerce, sessionJwt))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/api/src/platforms/vtex/resolvers/validateCart.ts` around lines 496 - 517, The Promise.resolve wrapper around updatedOrderForm is redundant because updatedOrderForm is already resolved; remove Promise.resolve and either chain directly off updatedOrderForm or, clearer, perform the steps sequentially: take updatedOrderForm into a local variable (e.g., form), if session?.marketingData call commerce.checkout.marketingData with id: orderForm.orderFormId and constructed updatedMarketingData, then pass the returned/updated form into setOrderFormEtag(form, commerce, sessionJwt), and finally call joinItems on the resulting form (references: updatedOrderForm, session.marketingData, commerce.checkout.marketingData, setOrderFormEtag, joinItems).packages/storybook/CHANGELOG.md (1)
10-15: Optional: Consider using H2 for feature sections.The markdown linter flags heading increments from H1 (version) to H3 (Features) which skips H2. While this is a common pattern in auto-generated changelogs, using H2 for section headers would be more semantically correct.
📝 Example adjustment
# [3.98.0-dev.0](https://github.com/vtex/faststore/compare/v3.97.0-dev.6...v3.98.0-dev.0) (2026-02-24) -### Features +## Features - release version 20260224 ([`#3225`](https://github.com/vtex/faststore/issues/3225)) ([7a52516](https://github.com/vtex/faststore/commit/7a5251677a8f67066a2e060191b896ae6d0b0d9a))Also applies to: 36-41
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/storybook/CHANGELOG.md` around lines 10 - 15, The changelog jumps from the H1 version heading to H3 section headers; update the section headings (e.g., the "### Features" header shown in CHANGELOG.md) to use H2 ("## Features") so headings are semantically incremental, and apply the same change to the other section headers referenced (lines ~36-41) to consistently use H2 for top-level changelog sections.packages/core/src/pages/api/graphql.ts (1)
75-101: Add focused coverage for the normalization matrix.This helper now carries the contract for
localhost,.localhost,.vtex.app, and already-compatible parent domains. A small parameterized test aroundnormalizeSetCookieDomain()would make auth-cookie regressions much easier to catch.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/pages/api/graphql.ts` around lines 75 - 101, Add parameterized unit tests for normalizeSetCookieDomain to cover the normalization matrix (localhost, .localhost, .vtex.app and already-compatible parent domains) so auth-cookie regressions are caught early; write tests that call normalizeSetCookieDomain (importing MATCH_DOMAIN_REGEXP, getRequestHostname, ALLOWED_HOST_SUFFIXES, shouldReplaceCookieDomain if needed to construct scenarios) with mocked NextApiRequest hostnames and setCookie strings containing domains, asserting that: when host is allowed and shouldReplaceCookieDomain returns true the returned cookie has domain replaced with the host, and in all other cases the original setCookie is returned unchanged; include separate cases for exact "localhost", ".localhost", a vtex.app subdomain, and a parent-compatible domain to validate both replacement and no-op paths.packages/storybook/package.json (1)
24-28: Minor formatting artifact in volta config.There's an empty line between
nodeandpnpmin the volta configuration. This doesn't affect functionality but could be cleaned up for consistency.🧹 Proposed cleanup
"volta": { "node": "18.19.0", - "pnpm": "9.15.1" },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/storybook/package.json` around lines 24 - 28, Remove the stray blank line inside the "volta" object in package.json so the "node": "18.19.0" and "pnpm": "9.15.1" entries are adjacent; locate the "volta" object and reformat it to a compact, consistent key/value listing (ensure keys "node" and "pnpm" remain unchanged).packages/core/src/components/ThirdPartyScripts/GoogleTagManager.tsx (1)
13-26: RenameuseSnippetto avoid hook naming confusion.The
useprefix is conventionally reserved for React hooks. Since this is a regular function returning a string, consider renaming it togetSnippetorcreateSnippetto avoid confusion.♻️ Suggested rename
-const useSnippet = (opts: Props & { partytownScript: boolean }) => { +const createSnippet = (opts: Props & { partytownScript: boolean }) => {Then update the calls on lines 50 and 60 accordingly.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/components/ThirdPartyScripts/GoogleTagManager.tsx` around lines 13 - 26, Rename the function useSnippet to a non-hook name (e.g., getSnippet or createSnippet) to avoid React hook naming confusion: change the function declaration const useSnippet = (...) => { ... } to const getSnippet = (...) => { ... } (or createSnippet) and update every call site that invokes useSnippet (including the two call sites in this file that currently call useSnippet) to use the new name; also update any exported identifier or type references that reference useSnippet so all usages match the new function name.packages/core/src/sdk/cart/redirectToCheckout.ts (1)
3-15: Simplify conditional logic and handle existing query params.The nested if/else can be flattened—lines 9 and 13 are identical. Also, if
checkoutUrlalready contains query parameters, appending?orderFormId=would produce an invalid URL.♻️ Proposed refactor
export const redirectToCheckout = (orderFormId?: string) => { const isDevEnv = window.location.host.includes('.vtex.app') || window.location.host.includes('localhost') - if (!isDevEnv) { - window.location.href = `${storeConfig.checkoutUrl}` - } else if (orderFormId) { - window.location.href = `${storeConfig.checkoutUrl}?orderFormId=${orderFormId}` - } else { - window.location.href = `${storeConfig.checkoutUrl}` + const baseUrl = storeConfig.checkoutUrl + if (isDevEnv && orderFormId) { + const separator = baseUrl.includes('?') ? '&' : '?' + window.location.href = `${baseUrl}${separator}orderFormId=${orderFormId}` + } else { + window.location.href = baseUrl } }As per coding guidelines: "Prefer flat conditionals over nested ifs: combine conditions with && or use early returns to avoid deep nesting and improve readability."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/sdk/cart/redirectToCheckout.ts` around lines 3 - 15, The redirectToCheckout function has duplicated branches and incorrectly appends ?orderFormId= when storeConfig.checkoutUrl may already contain query params; refactor redirectToCheckout to use flat conditionals (early return when not dev) and build the final URL by parsing storeConfig.checkoutUrl (use the URL constructor or check for '?' to choose '?' vs '&') before appending orderFormId only when provided; update references to window.location.host, storeConfig.checkoutUrl and orderFormId in redirectToCheckout accordingly.packages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountBudgetsCard/index.ts (1)
1-1: Consider exporting the props type for better API documentation.MyAccountBudgetsCardProps exists in the component file. While not a widespread pattern in this directory, exporting props types (as MyAccountReorderButton does) makes the API clearer for consumers and follows TypeScript best practices for public components.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountBudgetsCard/index.ts` at line 1, The index currently re-exports the component only; export the component's props type as well by adding a type export for MyAccountBudgetsCardProps alongside the default export so consumers can import the props type (e.g., export { default } from './MyAccountBudgetsCard' and also export type { MyAccountBudgetsCardProps } from './MyAccountBudgetsCard'); ensure the exported symbol name exactly matches MyAccountBudgetsCardProps.packages/core/test/utils/clearCookies.test.ts (1)
22-43: Add a subdomain regression case here.This suite never exercises
www.example.com/store.example.com, so it won't catch the common case where logout also needs an expiration attempt for.example.com.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/test/utils/clearCookies.test.ts` around lines 22 - 43, Add a regression test for subdomains to ensure getCookieDomains handles hostnames like "www.example.com" (and similar "store.example.com") by returning undefined, the exact hostname, and the parent-dot domain; specifically add an it block that calls getCookieDomains('www.example.com') and asserts it equals [undefined, 'www.example.com', '.example.com'] so logout will also attempt expiration on the base ".example.com".
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 5172ed5c-b186-448a-94e1-de6eba1df6c5
⛔ Files ignored due to path filters (7)
.coderabbit.yamlis excluded by none and included by noneCHANGELOG.mdis excluded by none and included by nonelerna.jsonis excluded by none and included by nonepackages/api/src/__generated__/schema.tsis excluded by!**/__generated__/**and included bypackages/**packages/core/@generated/gql.tsis excluded by!**/@generated/**,!**/@generated/**and included bypackages/**packages/core/@generated/graphql.tsis excluded by!**/@generated/**,!**/@generated/**and included bypackages/**pnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (63)
packages/api/CHANGELOG.mdpackages/api/package.jsonpackages/api/src/platforms/vtex/clients/commerce/index.tspackages/api/src/platforms/vtex/clients/commerce/types/Address.tspackages/api/src/platforms/vtex/clients/search/types/ProductSearchResult.tspackages/api/src/platforms/vtex/resolvers/product.tspackages/api/src/platforms/vtex/resolvers/query.tspackages/api/src/platforms/vtex/resolvers/validateCart.tspackages/api/src/platforms/vtex/resolvers/validateSession.tspackages/api/src/typeDefs/product.graphqlpackages/api/src/typeDefs/userOrder.graphqlpackages/api/test/integration/mutations.test.tspackages/api/test/mocks/ValidateCartMutation.tspackages/cli/CHANGELOG.mdpackages/cli/README.mdpackages/cli/package.jsonpackages/components/CHANGELOG.mdpackages/components/package.jsonpackages/core/CHANGELOG.mdpackages/core/cms/faststore/pages/cms_content_type__landingpage.jsoncpackages/core/discovery.config.default.jspackages/core/package.jsonpackages/core/src/Layout.tsxpackages/core/src/components/ThirdPartyScripts/GoogleTagManager.tsxpackages/core/src/components/ThirdPartyScripts/ThirdPartyScripts.tsxpackages/core/src/components/ThirdPartyScripts/vtex.tsxpackages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/OrganizationDrawer.tsxpackages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountBudgetsCard/MyAccountBudgetsCard.tsxpackages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountBudgetsCard/index.tspackages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountBudgetsCard/styles.scsspackages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountOrderActions/MyAccountOrderActions.tsxpackages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountOrderActions/styles.scsspackages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountOrderDetails.tsxpackages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountReorderButton/MyAccountReorderButton.tsxpackages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountReorderButton/index.tspackages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountReorderButton/styles.scsspackages/core/src/components/account/orders/MyAccountOrderDetails/section.module.scsspackages/core/src/components/search/Filter/FilterSlider.tsxpackages/core/src/constants.tspackages/core/src/pages/[slug]/p.tsxpackages/core/src/pages/_document.tsxpackages/core/src/pages/api/fs/logout.tspackages/core/src/pages/api/graphql.tspackages/core/src/pages/api/preview.tspackages/core/src/pages/pvt/account/orders/[id].tsxpackages/core/src/sdk/account/useReorder.tspackages/core/src/sdk/analytics/hooks/usePageViewEvent.tspackages/core/src/sdk/analytics/platform/vtex/search.tspackages/core/src/sdk/cart/redirectToCheckout.tspackages/core/src/sdk/cart/useCheckoutButton.tspackages/core/src/sdk/error/ReorderError/ReorderError.tspackages/core/src/utils/clearCookies.tspackages/core/test/utils/clearCookies.test.tspackages/graphql-utils/CHANGELOG.mdpackages/graphql-utils/package.jsonpackages/lighthouse/CHANGELOG.mdpackages/lighthouse/package.jsonpackages/sdk/CHANGELOG.mdpackages/sdk/package.jsonpackages/storybook/CHANGELOG.mdpackages/storybook/package.jsonpackages/ui/CHANGELOG.mdpackages/ui/package.json
✅ Files skipped from review due to trivial changes (2)
- packages/graphql-utils/package.json
- packages/lighthouse/package.json
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/api/src/platforms/vtex/clients/search/types/ProductSearchResult.ts
| """ | ||
| Manufacturer Part Number. Identifies the product to its manufacturer. | ||
| """ | ||
| mpn: String! |
There was a problem hiding this comment.
mpn should be nullable in the schema.
manufacturerCode is optional upstream, and the resolver currently compensates by returning ''. That hides missing data from clients and pushes empty mpn values into structured data. Make the field nullable and return null when the source value is absent.
Suggested contract change
- mpn: String!
+ mpn: String// packages/api/src/platforms/vtex/resolvers/product.ts
mpn: ({ isVariantOf: { manufacturerCode } }) => manufacturerCode ?? nullAs per coding guidelines, packages/api/src/**: TypeDefs should follow GraphQL best practices.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| """ | |
| Manufacturer Part Number. Identifies the product to its manufacturer. | |
| """ | |
| mpn: String! | |
| """ | |
| Manufacturer Part Number. Identifies the product to its manufacturer. | |
| """ | |
| mpn: String |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/api/src/typeDefs/product.graphql` around lines 49 - 52, Update the
GraphQL product type and resolver so mpn is nullable and returns null when
missing: change the mpn field in product.graphql from String! to String, and
update the resolver function mpn in
packages/api/src/platforms/vtex/resolvers/product.ts (the mpn resolver that
reads isVariantOf.manufacturerCode) to return manufacturerCode ?? null instead
of returning an empty string.
| "slug": { | ||
| "widget": { | ||
| "ui:widget": "slug" | ||
| }, | ||
| "type": "string" | ||
| }, |
There was a problem hiding this comment.
Avoid introducing a second editable slug source of truth.
This new root-level slug now coexists with seo.slug, which is still editable and required. Those values can drift, so page identity/routing may use one slug while SEO metadata/canonical uses another. Please keep a single editable slug and derive the other value from it.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/cms/faststore/pages/cms_content_type__landingpage.jsonc` around
lines 8 - 13, The root-level "slug" field introduces a second editable source of
truth alongside "seo.slug"; remove the editable root-level "slug" definition
(the object with "widget" / "ui:widget": "slug" and "type": "string") so only
one editable slug remains, and instead derive or populate "seo.slug" from that
single slug (make "seo.slug" the canonical editable field and ensure any
root-level references use/compute from "seo.slug" rather than adding a separate
editable "slug").
| // Clear HttpOnly cookies via API endpoint (server-side) | ||
| try { | ||
| await fetch('/api/fs/logout', { | ||
| method: 'POST', | ||
| credentials: 'include', | ||
| }) | ||
| } catch { | ||
| // Continue even if API call fails | ||
| } |
There was a problem hiding this comment.
Bound the logout cleanup request with a timeout.
This await fetch('/api/fs/logout') runs before the final redirect. If the request stalls, logout can hang indefinitely and never reach the VTEX logout URL. Since the cleanup is best-effort, abort it after a short timeout and continue.
Suggested fix
try {
- await fetch('/api/fs/logout', {
- method: 'POST',
- credentials: 'include',
- })
+ const controller = new AbortController()
+ const timeoutId = window.setTimeout(() => controller.abort(), 3000)
+
+ try {
+ await fetch('/api/fs/logout', {
+ method: 'POST',
+ credentials: 'include',
+ signal: controller.signal,
+ })
+ } finally {
+ window.clearTimeout(timeoutId)
+ }
} catch {
// Continue even if API call fails
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@packages/core/src/components/account/MyAccountDrawer/OrganizationDrawer/OrganizationDrawer.tsx`
around lines 107 - 115, The logout cleanup fetch can hang; wrap the
fetch('/api/fs/logout', { method: 'POST', credentials: 'include' }) in an
AbortController with a short timeout (e.g. ~2000ms): create an AbortController,
start a setTimeout to call controller.abort() after the timeout, pass
controller.signal to fetch, and clear the timer once fetch resolves; keep the
existing try/catch but ensure abort and other errors are swallowed so the code
in OrganizationDrawer (the logout handler where the fetch is called) proceeds to
the VTEX redirect regardless of cleanup success.
| return ( | ||
| <MyAccountCard title="Budgets" data-fs-order-budgets-card> | ||
| <div data-fs-budgets-table> | ||
| <div data-fs-budgets-table-header> | ||
| <div data-fs-budgets-header-name>Name</div> | ||
| <div data-fs-budgets-header-available>Available</div> | ||
| <div data-fs-budgets-header-to-be-spent>To be spent</div> | ||
| <div data-fs-budgets-header-remaining>Remaining</div> | ||
| </div> | ||
| <div data-fs-budgets-table-body> | ||
| {budgetRows.map( | ||
| ( | ||
| { budget, allocationIds, toBeSpent, remaining, available }, | ||
| index | ||
| ) => { | ||
| const budgetName = budget.name || '' | ||
| const allocationsList = allocationIds || '' | ||
|
|
||
| return ( | ||
| <div data-fs-budgets-row key={budget.id || index}> | ||
| <div data-fs-budgets-name> | ||
| <div data-fs-budgets-name-primary>{budgetName}</div> | ||
| <div data-fs-budgets-name-secondary title={allocationsList}> | ||
| {allocationsList} | ||
| </div> | ||
| </div> | ||
| <div data-fs-budgets-available> | ||
| {Number.isFinite(available) | ||
| ? formatPrice(available, currencyCode) | ||
| : '—'} | ||
| </div> | ||
| <div data-fs-budgets-to-be-spent> | ||
| {toBeSpent !== 0 | ||
| ? formatPrice(toBeSpent, currencyCode) | ||
| : formatPrice(0, currencyCode)} | ||
| </div> | ||
| <div data-fs-budgets-remaining> | ||
| <strong>{formatPrice(remaining, currencyCode)}</strong> | ||
| </div> | ||
| </div> | ||
| ) | ||
| } | ||
| )} | ||
| </div> | ||
| </div> | ||
| </MyAccountCard> |
There was a problem hiding this comment.
Use semantic table markup for this data.
This is tabular budget data, but it is rendered entirely with <div>s, so screen readers lose the header-to-cell relationship. Please switch this structure to <table>, <thead>, <tbody>, <th>, and <td> (or equivalent ARIA table roles if markup is constrained).
As per coding guidelines, packages/**/src/components/**: Use semantic HTML and proper ARIA labels for accessibility.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@packages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountBudgetsCard/MyAccountBudgetsCard.tsx`
around lines 70 - 115, The Budgets card (MyAccountBudgetsCard) is rendering
tabular data with divs; change the markup to a semantic table: replace the outer
wrapper under MyAccountCard with a <table> containing <thead> (use <th> for
"Name", "Available", "To be spent", "Remaining" and set scope="col"), and
<tbody> where each budgetRows map renders a <tr> keyed by budget.id || index and
cells as <td> (keep budgetName, allocationsList, formatPrice(…), currencyCode
and the logic for available/toBeSpent/remaining unchanged). Ensure the
allocations secondary text remains a visible cell with title={allocationsList}
for tooltip, and if you cannot use actual table tags, apply appropriate ARIA
roles (role="table", role="rowgroup", role="columnheader" on headers,
role="row"/role="cell" on rows/cells) and include scope or aria-labels so screen
readers can associate headers with cells.
| const { reorder } = useReorder() | ||
|
|
There was a problem hiding this comment.
Guard against repeated reorder clicks.
This component ignores the hook's loading state, so users can trigger multiple reorder requests before the first one finishes. Because reorder writes into the current cart, duplicate clicks can append the same items more than once.
Suggested change
- const { reorder } = useReorder()
+ const { reorder, loading: reordering } = useReorder()
@@
- const handleReorder = () => {
- reorder(order)
+ const handleReorder = async () => {
+ if (reordering) return
+
+ await reorder(order)
}Also applies to: 64-83
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@packages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountOrderActions/MyAccountOrderActions.tsx`
around lines 34 - 35, The reorder flow currently calls the reorder function from
useReorder without checking its in-progress state, allowing duplicate clicks to
append items multiple times; update MyAccountOrderActions to read and respect
the hook's loading/inProgress flag (e.g., const { reorder, loading } =
useReorder() or similar) and short-circuit/disable the reorder action when
loading is true (both where reorder is invoked and in the UI button handlers),
ensuring repeated clicks are ignored until the first reorder resolves.
| if (discoveryConfig.experimental?.refreshToken && cookies.vid_rt) { | ||
| for (const domain of domains) { | ||
| const clearedCookie = expireCookieServer({ | ||
| name: 'vid_rt', | ||
| path: '/api/vtexid/refreshtoken/webstore', | ||
| domain, | ||
| }) | ||
| clearedCookies.push(clearedCookie) | ||
| } | ||
| } |
There was a problem hiding this comment.
The vid_rt check can never pass on this route.
vid_rt is scoped to /api/vtexid/refreshtoken/webstore, so the browser will not send it on requests to /api/fs/logout. The cookies.vid_rt guard therefore keeps this block from emitting the expiration header, leaving the refresh-token cookie behind on logout. Expiring a missing cookie is idempotent, so this should run whenever refreshToken is enabled.
Suggested fix
- if (discoveryConfig.experimental?.refreshToken && cookies.vid_rt) {
+ if (discoveryConfig.experimental?.refreshToken) {
for (const domain of domains) {
const clearedCookie = expireCookieServer({
name: 'vid_rt',
path: '/api/vtexid/refreshtoken/webstore',
domain,📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (discoveryConfig.experimental?.refreshToken && cookies.vid_rt) { | |
| for (const domain of domains) { | |
| const clearedCookie = expireCookieServer({ | |
| name: 'vid_rt', | |
| path: '/api/vtexid/refreshtoken/webstore', | |
| domain, | |
| }) | |
| clearedCookies.push(clearedCookie) | |
| } | |
| } | |
| if (discoveryConfig.experimental?.refreshToken) { | |
| for (const domain of domains) { | |
| const clearedCookie = expireCookieServer({ | |
| name: 'vid_rt', | |
| path: '/api/vtexid/refreshtoken/webstore', | |
| domain, | |
| }) | |
| clearedCookies.push(clearedCookie) | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/src/pages/api/fs/logout.ts` around lines 35 - 44, The logout
handler's block that clears the vid_rt cookie is gated by cookies.vid_rt, but
vid_rt is scoped to /api/vtexid/refreshtoken/webstore and won't be sent on
/api/fs/logout, so the guard prevents emitting expiration headers; remove the
cookies.vid_rt check and always iterate domains to call expireCookieServer({
name: 'vid_rt', path: '/api/vtexid/refreshtoken/webstore', domain }) and push
results into clearedCookies when discoveryConfig.experimental?.refreshToken is
true (leave discoveryConfig.experimental?.refreshToken as the only guard), using
the existing domains and expireCookieServer/clearedCookies symbols.
| const shouldReplaceCookieDomain = ({ | ||
| cookieDomain, | ||
| host, | ||
| }: { | ||
| cookieDomain: string | ||
| host: string | ||
| }) => { | ||
| const normalizedDomain = cookieDomain.replace(/^\./, '').toLowerCase() | ||
| const normalizedHost = host.toLowerCase() | ||
|
|
||
| return normalizedDomain !== normalizedHost | ||
| } |
There was a problem hiding this comment.
Don't narrow cookie scope when the current domain already matches.
Line 54 rewrites any non-exact match. For example, Domain=.vtex.app already applies to shop.vtex.app, but this predicate still forces a rewrite to shop.vtex.app. That changes cookie scope even though no normalization is needed, which can break flows that rely on sibling subdomains sharing the same cookie.
🔧 Suggested predicate
const shouldReplaceCookieDomain = ({
cookieDomain,
host,
}: {
cookieDomain: string
host: string
}) => {
const normalizedDomain = cookieDomain.replace(/^\./, '').toLowerCase()
const normalizedHost = host.toLowerCase()
- return normalizedDomain !== normalizedHost
+ return (
+ normalizedDomain !== normalizedHost &&
+ !normalizedHost.endsWith(`.${normalizedDomain}`)
+ )
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const shouldReplaceCookieDomain = ({ | |
| cookieDomain, | |
| host, | |
| }: { | |
| cookieDomain: string | |
| host: string | |
| }) => { | |
| const normalizedDomain = cookieDomain.replace(/^\./, '').toLowerCase() | |
| const normalizedHost = host.toLowerCase() | |
| return normalizedDomain !== normalizedHost | |
| } | |
| const shouldReplaceCookieDomain = ({ | |
| cookieDomain, | |
| host, | |
| }: { | |
| cookieDomain: string | |
| host: string | |
| }) => { | |
| const normalizedDomain = cookieDomain.replace(/^\./, '').toLowerCase() | |
| const normalizedHost = host.toLowerCase() | |
| return ( | |
| normalizedDomain !== normalizedHost && | |
| !normalizedHost.endsWith(`.${normalizedDomain}`) | |
| ) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/src/pages/api/graphql.ts` around lines 44 - 55, The predicate
in shouldReplaceCookieDomain currently returns true whenever the normalized
cookie domain differs from the host, which wrongly narrows cookies like
Domain=.vtex.app for host shop.vtex.app; change the logic to only replace when
the cookie domain is neither equal to the host nor already a parent domain of
the host. In shouldReplaceCookieDomain (variables cookieDomain, host,
normalizedDomain, normalizedHost) update the return to false when normalizedHost
=== normalizedDomain or normalizedHost.endsWith('.' + normalizedDomain), and
return true otherwise (i.e., only replace when the cookie domain is not equal
and not a parent domain).
| } catch (err) { | ||
| setError(err instanceof Error ? err : new ReorderError('Unknown error')) | ||
| console.error('Error reordering:', err) |
There was a problem hiding this comment.
Don't swallow reorder failures.
This catch block only updates local state, so await reorder(order) still resolves on failure. Callers cannot prevent follow-up UI from running after an error—for example, MyAccountReorderButton will still call onClick after a failed reorder. Re-throw here, or return an explicit success/error result from the hook.
Suggested change
} catch (err) {
- setError(err instanceof Error ? err : new ReorderError('Unknown error'))
- console.error('Error reordering:', err)
+ const error =
+ err instanceof Error ? err : new ReorderError('Unknown error')
+
+ setError(error)
+ console.error('Error reordering:', err)
+ throw error
} finally {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| } catch (err) { | |
| setError(err instanceof Error ? err : new ReorderError('Unknown error')) | |
| console.error('Error reordering:', err) | |
| } catch (err) { | |
| const error = | |
| err instanceof Error ? err : new ReorderError('Unknown error') | |
| setError(error) | |
| console.error('Error reordering:', err) | |
| throw error | |
| } finally { |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/src/sdk/account/useReorder.ts` around lines 135 - 137, The
catch in useReorder.ts currently only calls setError and logs the error (using
ReorderError) which causes await reorder(order) to resolve on failure; update
the catch block in the reorder function to re-throw the caught error (or throw
the new ReorderError) after calling setError and console.error so callers (e.g.,
MyAccountReorderButton) can await and react to failures instead of proceeding as
if successful. Ensure you reference the same error object when re-throwing so
upstream code receives the original error.
| export default class ReorderError extends Error { | ||
| constructor(message: string) { | ||
| super(message) | ||
| this.name = 'ReorderError' | ||
| } | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check TypeScript target in tsconfig files
fd -e json "tsconfig" --exec grep -l "target" {} \; | xargs -I{} sh -c 'echo "=== {} ===" && grep -A1 -B1 "target" {}'Repository: vtex/faststore
Length of output: 286
🏁 Script executed:
# Find other error classes in the SDK
fd "Error\.ts" packages/core/src/sdk/error/Repository: vtex/faststore
Length of output: 347
🏁 Script executed:
# Check if instanceof is used with error classes in the codebase
rg "instanceof.*Error" packages/core/src/ -A 2 -B 2Repository: vtex/faststore
Length of output: 2689
🏁 Script executed:
# Check implementations of other error classes
for file in packages/core/src/sdk/error/*/; do
echo "=== $file ==="
cat "$(ls "$file"*.ts 2>/dev/null | head -1)"
doneRepository: vtex/faststore
Length of output: 1711
🏁 Script executed:
# Check the exact instanceof usage with ReorderError
cat -n packages/core/src/sdk/account/useReorder.ts | grep -A 5 -B 5 "ReorderError"Repository: vtex/faststore
Length of output: 2506
Add prototype chain fix for ES5 compatibility with instanceof checks.
The codebase targets ES5 (packages/core/tsconfig.json), and error classes are used with instanceof checks throughout the SDK (e.g., MissingContentError in service.ts and templates). Without the prototype fix, these checks may fail at runtime.
♻️ Recommended fix
export default class ReorderError extends Error {
constructor(message: string) {
super(message)
this.name = 'ReorderError'
+ Object.setPrototypeOf(this, ReorderError.prototype)
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export default class ReorderError extends Error { | |
| constructor(message: string) { | |
| super(message) | |
| this.name = 'ReorderError' | |
| } | |
| } | |
| export default class ReorderError extends Error { | |
| constructor(message: string) { | |
| super(message) | |
| this.name = 'ReorderError' | |
| Object.setPrototypeOf(this, ReorderError.prototype) | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/src/sdk/error/ReorderError/ReorderError.ts` around lines 1 - 6,
The custom Error subclass ReorderError lacks the ES5 prototype-chain fix, which
can break instanceof checks; inside the ReorderError constructor (after calling
super(message)), restore the prototype chain by setting
Object.setPrototypeOf(this, ReorderError.prototype) (or
Object.setPrototypeOf(this, new.target.prototype) for generic subclassing) so
instances correctly pass instanceof ReorderError under the ES5 target and
maintain the existing this.name assignment.
| export const getCookieDomains = ( | ||
| hostname: string | ||
| ): Array<string | undefined> => [ | ||
| undefined, // host-only cookie | ||
| hostname, | ||
| hostname.startsWith('.') ? hostname : `.${hostname}`, | ||
| ] |
There was a problem hiding this comment.
getCookieDomains misses parent-domain cookies.
On www.example.com this only tries www.example.com and .www.example.com; it never tries .example.com. Both logout paths then fail to expire cookies scoped to the registrable domain, which is a common setup for VTEX auth/search cookies. Please walk the parent-domain chain here (deduped), or use a public-suffix-aware helper before generating the expiration attempts.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/src/utils/clearCookies.ts` around lines 49 - 55,
getCookieDomains currently returns only host-only, the exact hostname and a
dot-prefixed hostname, missing parent registrable domains (e.g., .example.com).
Update getCookieDomains to walk the parent-domain chain (deduped) from the full
hostname up to the registrable domain: start with undefined (host-only), then
include the exact hostname, then for each parent domain remove the left-most
label and add both plain and dot-prefixed variants as appropriate (or just the
dot-prefixed for expiry attempts), ensuring duplicates are removed. Preferably
use a public-suffix-aware helper (publicsuffix or tldts) to stop at the
effective TLD+1, or if not available, split hostname labels and iterate
conservatively; reference the function name getCookieDomains and ensure returned
array order remains suitable for cookie-expiration attempts.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/core/src/components/ui/ProductGallery/ProductGalleryPage.tsx`:
- Around line 21-33: buildExtraProductProps is being passed raw to ProductGrid
but requires a third parameter searchId, causing data-af-search-id to be
undefined; fix by passing a bound/curried version that injects the current
searchId before giving it to ProductGrid (e.g. wrap with an arrow or use .bind
to produce a function like (product, index) => buildExtraProductProps(product,
index, searchId)), and update both places where the helper is handed off (the
ProductGrid prop and the other occurrence noted around lines 65-66) so every
product-level attribute includes the correct searchId.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ba61effc-3586-48fb-ad55-003e896c2e84
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (3)
packages/api/src/platforms/vtex/clients/search/types/ProductSearchResult.tspackages/core/src/components/product/ProductGrid/ProductGrid.tsxpackages/core/src/components/ui/ProductGallery/ProductGalleryPage.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/api/src/platforms/vtex/clients/search/types/ProductSearchResult.ts
- packages/core/src/components/product/ProductGrid/ProductGrid.tsx
| function buildExtraProductProps( | ||
| product: Record<string, string>, | ||
| index: number, | ||
| searchId: string | ||
| ) { | ||
| return { | ||
| 'data-af-element': 'search-result', | ||
| 'data-af-onclick': product && !!product.productId, | ||
| 'data-af-search-id': searchId, | ||
| 'data-af-product-position': Number(index ?? 0) + 1, // Product position in Search Analytics starts with 1 | ||
| 'data-af-product-id': product && product.productId, | ||
| } | ||
| } |
There was a problem hiding this comment.
Bind searchId before passing the helper to ProductGrid.
Right now the raw buildExtraProductProps reference is passed through, but this helper needs searchId as a third argument. That leaves data-af-search-id undefined on the product-level attributes, which breaks the analytics payload this PR is adding.
Proposed fix
function buildExtraProductProps(
- product: Record<string, string>,
- index: number,
+ product: Record<string, string> | undefined,
+ index: number | undefined,
searchId: string
) {
return {
'data-af-element': 'search-result',
- 'data-af-onclick': product && !!product.productId,
+ 'data-af-onclick': Boolean(product?.productId),
'data-af-search-id': searchId,
'data-af-product-position': Number(index ?? 0) + 1, // Product position in Search Analytics starts with 1
- 'data-af-product-id': product && product.productId,
+ 'data-af-product-id': product?.productId,
}
}
@@
- buildExtraProductProps={searchId && buildExtraProductProps}
+ buildExtraProductProps={
+ searchId
+ ? (product, index) => buildExtraProductProps(product, index, searchId)
+ : undefined
+ }Also applies to: 65-66
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/src/components/ui/ProductGallery/ProductGalleryPage.tsx` around
lines 21 - 33, buildExtraProductProps is being passed raw to ProductGrid but
requires a third parameter searchId, causing data-af-search-id to be undefined;
fix by passing a bound/curried version that injects the current searchId before
giving it to ProductGrid (e.g. wrap with an arrow or use .bind to produce a
function like (product, index) => buildExtraProductProps(product, index,
searchId)), and update both places where the helper is handed off (the
ProductGrid prop and the other occurrence noted around lines 65-66) so every
product-level attribute includes the correct searchId.
…hanced search analytics
…rface and update buildExtraProductProps to include searchId parameter
048ea3d to
ad6ac3d
Compare
What's the purpose of this pull request?
This PR adds Activity Flow data parameters containing search-related information to be used in Search Analytics.
How it works?
It retrieves the searchId from search requests and includes it as data-af attributes in the rendered elements.
There’s no impact on the UI or existing functionality — the change only introduces new tracking parameters.
How to test it?
Starters Deploy Preview
References
Checklist
You may erase this after checking them all 😉
PR Title and Commit Messages
feat,fix,chore,docs,style,refactor,ciandtestPR Description
breaking change,bug,contributing,performance,documentation..Dependencies
pnpm-lock.yamlfile when there were changes to the packagesDocumentation
@Mariana-Caetanoto review and update (Or submit a doc request)Summary by CodeRabbit
New Features
Documentation
Chores