Repository navigation
feat: CMS-driven custom My Account pages - #3411
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (2)
WalkthroughAdds CMS-driven My Account route metadata, authenticated server-side rendering, page templates, route parsing, and CLI generation. CMS pages support hybrid customization components, route validation, native-page precedence, and legacy-generation skipping. ChangesMy Account CMS pages
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant createNextJsPages
participant readMyAccountCmsRoutes
participant myAccountCmsPageTemplate
participant LegacyPages
createNextJsPages->>readMyAccountCmsRoutes: Read navigation.ts
readMyAccountCmsRoutes-->>createNextJsPages: Return CMS routes
createNextJsPages->>myAccountCmsPageTemplate: Create page source
myAccountCmsPageTemplate-->>createNextJsPages: Return generated module
createNextJsPages->>LegacyPages: Generate remaining legacy pages
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
|
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. |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/cli/src/utils/createNextjsPages.test.ts`:
- Around line 31-53: Update packages/cli/src/utils/createNextjsPages.test.ts
lines 31-53 and its filesystem-dependent tests to mock node:fs (or use an
injectable filesystem adapter), replacing real temp-directory creation and file
I/O while preserving each test’s existing behavior. Also update
packages/cli/src/utils/readMyAccountCmsRoutes.test.ts lines 44-56 so the
unparseable-input test mocks filesystem access instead of writing and deleting a
real temporary file; both suites must avoid disk access.
In `@packages/core/src/experimental/myAccountCmsServerSideProps.ts`:
- Around line 85-91: Update the `!isFaststoreMyAccountEnabled` branch in
`myAccountCmsServerSideProps` to narrow or validate `redirect` before returning
`{ redirect }`, ensuring `GetServerSideProps` never receives a null redirect;
alternatively, change `getMyAccountRedirect` to return a discriminated union
that guarantees a non-null redirect for this branch.
🪄 Autofix (Beta)
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
Run ID: 7316e5a1-9b42-42e3-9f46-8ddc439073b1
📒 Files selected for processing (15)
packages/cli/src/utils/__fixtures__/myAccount/navigation-collision.tspackages/cli/src/utils/__fixtures__/myAccount/navigation-legacy-only.tspackages/cli/src/utils/__fixtures__/myAccount/navigation-with-cms.tspackages/cli/src/utils/createNextjsPages.test.tspackages/cli/src/utils/createNextjsPages.tspackages/cli/src/utils/readMyAccountCmsRoutes.test.tspackages/cli/src/utils/readMyAccountCmsRoutes.tspackages/cli/src/utils/templates/myAccountCmsPage.test.tspackages/cli/src/utils/templates/myAccountCmsPage.tspackages/core/src/experimental/myAccountCmsServerSideProps.tspackages/core/src/sdk/account/getMyAccountRoutes.tspackages/core/src/server/cms/myAccountDefaultSections.tspackages/core/test/experimental/myAccountCmsServerSideProps.test.tspackages/core/test/sdk/account/getMyAccountRoutes.test.tspackages/core/test/server/cms/myAccountDefaultSections.test.ts
renatomaurovtex
left a comment
There was a problem hiding this comment.
Reviewed the full diff (cli + core) and cross-checked the integration points on the head branch (fetchMyAccountPageContent, native myAccountServerSideProps, ACCOUNT_COMPONENTS, RenderSectionsBase, Layout). The design is solid: the SSR factory mirrors the native guards exactly (login redirect, 403+from, My Account toggle, locale validation), ACCOUNT_COMPONENTS already merges GLOBAL + PLUGINS + CUSTOM components so store sections resolve on custom pages, CMS fetch fails open to empty sections, and the CLI enforces the /pvt/account prefix and native-page precedence. Test coverage on both packages is good. Findings below are hardening-level — no blockers.
packages/cli/src/utils/readMyAccountCmsRoutes.ts
🟡 [bug/edge case] Block comments are not stripped — commented-out routes still generate pages
Only // line comments are removed. A route entry disabled with /* ... */ inside the routes: [...] array still matches the object-literal regex, so the CLI generates a page for a route the developer thinks is off:
routes: [
/* { route: '/pvt/account/old', title: 'Old', contentType: 'myAccountOld' }, */
]- // Strip line comments to avoid false matches inside comments.
- const withoutLineComments = sourceText.replace(/^\s*\/\/.*$/gm, '')
+ // Strip block and line comments to avoid false matches inside comments.
+ const withoutLineComments = sourceText
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/^\s*\/\/.*$/gm, '')Related, lower priority: routes\s*:\s*\[([\s\S]*?)\] stops at the first ], so if a route entry ever grows an array-valued prop, every entry after it is silently dropped (no warning, unlike the documented dynamic-entry case). Fine for today's Route shape — maybe leave a comment on the regex so the next person extending Route knows. ⚡
🟡 [robustness] Validate contentType/route before interpolating them into generated source
myAccountCmsPageTemplate splices these strings raw between single quotes (myAccountCmsServerSideProps('${contentType}', '${routePath}')). A stray ' in navigation.ts (typo, smart quote) produces a syntactically broken generated page and a cryptic Next.js build error far from the cause. Since this is store-authored input parsed by regex, a cheap allowlist here keeps garbage out of codegen: ⚡
const contentType = readStringProp(literal, 'contentType')
if (!contentType) {
continue
}
+
+ if (!/^[A-Za-z0-9_-]+$/.test(contentType)) {
+ logger.warn(
+ `[my-account-cms] Skipping route with invalid contentType "${contentType}" in ${navigationFilePath}`
+ )
+ continue
+ }packages/core/src/server/cms/myAccountDefaultSections.ts
🟡 [bug/edge case] Prototype keys crash the lookup now that contentType is an open string
DEFAULT_SECTION_KEYS[contentType as NativeMyAccountContentType] with a store-controlled string means contentType: 'toString' (or any Object.prototype key) returns a function — the ?? [] never kicks in and .map throws, turning a bad nav entry into an SSR 500. Absurd input, one-line guard: ⚡
- return (
- DEFAULT_SECTION_KEYS[contentType as NativeMyAccountContentType] ?? []
- ).map((key) => ({
+ return (
+ (Object.hasOwn(DEFAULT_SECTION_KEYS, contentType)
+ ? DEFAULT_SECTION_KEYS[contentType as NativeMyAccountContentType]
+ : []) ?? []
+ ).map((key) => ({The NativeMyAccountContentType | (string & {}) split itself is a nice touch — autocomplete preserved, no breaking change.
packages/cli/src/utils/createNextjsPages.ts
💬 The if (items.length === 0) return true early-return is a no-op — [].every() already returns true. Harmless; keep it only if you want the "Mode A only" intent documented, otherwise drop.
💬 Shadowed-param rename (basePath → pagesBase) inside allPagesAreAllowed is a good catch.
packages/cli/src/utils/readMyAccountCmsRoutes.test.ts
💬 The trailing top-level afterEach(() => { /* no-op placeholder for symmetry */ }) is dead code — remove it.
packages/core/src/experimental/myAccountCmsServerSideProps.ts
💬 A typo'd or never-published contentType renders an empty page body with only a server-side console.warn — hard for a merchant to self-diagnose. A follow-up dev-mode hint (or a note in the docs/quickstart) would help. Not blocking.
💬 This factory duplicates ~80 lines of guard logic from myAccountServerSideProps, and the two have already drifted slightly (this one optional-chains account.data?.accountProfile?.name ?? ''; native dereferences unguarded — yours is the better behavior). Consider extracting a shared guard helper later so fixes land in both.
Verdict: Approved with comments
Blocking (🔴/🟠):
- None.
Non-blocking (🟡/💬):
- Strip block comments in
readMyAccountCmsRoutes(commented-out routes still generate pages). - Allowlist-validate
contentTypebefore code generation. Object.hasOwnguard ingetDefaultMyAccountSections(prototype-key SSR crash).- Dead code: redundant empty-dir early return; stray top-level
afterEachin test. - Follow-ups: dev-visible signal for unpublished/typo'd content-types; extract shared SSR guard to prevent drift.
Checks to confirm before merge: pnpm lint · build · pnpm turbo run test --filter=@faststore/cli --filter=@faststore/core · pnpm size (touches core). SonarQube red is the usual new-code gate; UI Tests (Chromatic) still pending.
eduardoformiga
left a comment
There was a problem hiding this comment.
do you happen to test it in any store/account? I can't see the content types in the b2bfaststoredev.
Also would be good to ask the education team to create docs about the behaviour and all the possibilities/priorities etc.
| expect(content).not.toContain('myAccountCmsServerSideProps') | ||
| }) | ||
|
|
||
| it('skips CMS generation when the route collides with a native page', () => { |
0d6405c to
b70bae1
Compare
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/cli/src/utils/createNextjsPages.ts (1)
165-169: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winEnforce route-segment boundaries during CMS validation.
startsWith('/pvt/account')also accepts routes such as/pvt/accounting, so invalid CMS routes can be generated outside/pvt/account. Change the helper to allow only the exact prefix or descendants:Proposed fix
- return ALLOWED_PREFIX_PAGES.some((prefix) => file.startsWith(prefix)) + return ALLOWED_PREFIX_PAGES.some( + (prefix) => file === prefix || file.startsWith(`${prefix}/`) + )Add a regression test covering
/pvt/accounting.🤖 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/cli/src/utils/createNextjsPages.ts` around lines 165 - 169, Update isAllowedPrefixPage, used by the CMS route validation around normalizedRoute, to require each allowed prefix to match exactly or be followed by a route-segment boundary such as “/”, rather than relying on startsWith alone. Preserve descendant routes while rejecting `/pvt/accounting`, and add a regression test covering that invalid route.
🤖 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.
Outside diff comments:
In `@packages/cli/src/utils/createNextjsPages.ts`:
- Around line 165-169: Update isAllowedPrefixPage, used by the CMS route
validation around normalizedRoute, to require each allowed prefix to match
exactly or be followed by a route-segment boundary such as “/”, rather than
relying on startsWith alone. Preserve descendant routes while rejecting
`/pvt/accounting`, and add a regression test covering that invalid route.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 24c8baee-1f8b-45bf-a1b5-f9c46d5e4228
📒 Files selected for processing (3)
packages/cli/src/utils/createNextjsPages.tspackages/cli/src/utils/readMyAccountCmsRoutes.tspackages/core/src/experimental/myAccountCmsServerSideProps.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/core/src/experimental/myAccountCmsServerSideProps.ts
`/pvt/accounting` was accepted as a `/pvt/account` descendant, so CMS pages could be generated outside the allowed prefix.
Guarantees a non-null `redirect` for callers that guard on `isFaststoreMyAccountEnabled` instead of typing it as nullable.
|
Addressed the outside-diff finding from the last CodeRabbit review ( The nullable-redirect finding is answered in its thread (fixed via a discriminated union in |
…My Account (#3464) Fixes the broken Order Details page reported in [SFS-3325](https://vtex-dev.atlassian.net/browse/SFS-3325) (High). [Jira on-call](https://vtex-dev.atlassian.net/browse/SO-667) ## Summary The CMS-driven migration ([#3354](#3354), first released in **v4.4.0**) broke several things at once on `/pvt/account/orders/[id]`. **Grid placement targeted the wrong element.** `[data-fs-order-details-content]` gave full width to its blocks via rules on the cards, which worked while `OrderDetails.tsx` mounted them as direct grid children. Every card now sits inside a `<Section>` wrapper — the real grid item — so `grid-column` on the nested card is inert. Status, budgets and the delivery accordions collapsed to one column, and the header, itself a section now, took a grid cell and overlapped the status card. The placement contract moves to the section wrapper. Attribute selectors (`[class~="section-account-order-status"]`) are required rather than plain classes: this is a CSS module, so a class selector would be hashed and never match the global class emitted by `Section.tsx`, and stylelint here does not support `:global()`. **The delivery section holds two blocks the design treats as independent** — the compact recipient card and the full-width option list. Its wrapper becomes `display: contents` so both are grid items again, without splitting the section (which would be a CMS contract change, and therefore not backportable as a patch). **The default section order never matched the design.** `DEFAULT_SECTION_KEYS.myAccountOrderDetails` was written wholesale in #3354 and never revised; it does not match the render order of the component it replaced. The broken CSS was hiding it. Reordered to mirror `@deprecated OrderDetails.tsx`. **Sections were lazy-loaded behind 823px placeholders.** `RenderSectionsBase` runs every section through `ViewportObserver`; the account pages pass no `isInteractive` and no account section sets `skipLazyLoadingSection`, so all eight order-details sections rendered as placeholders. Since `ViewportObserver` starts with `isVisible = false`, this reached the SSR HTML too — the served markup carried placeholders and real content only appeared after hydration. New `skipLazyLoading` prop, set on every account page (eight call sites, including the Cards page that landed on `dev` while this branch was open). Side effect worth noting: content now ships in the SSR HTML, which should improve LCP and removes a CLS source (each 823px placeholder collapsing to the real card height). **The page crashed before rendering on stores with no CMS content.** Surfaced while testing this fix. `extractOrderStatusLabelsFromSections` returns `undefined` when no section carries order-status labels — exactly the case for default sections, which are created with empty data — and `getServerSideProps` cannot serialize `undefined`. Pre-existing since the migration and independent of the layout work, but it blocks verifying it: the default-sections store is the very shape the layout fix has to be checked against. Note that [#3417](#3417) targeted this class of failure ("missing CMS content") and left this path. **Two grid rules never matched anything.** `[data-fs-buying-policy-alert]` and `[data-fs-pending-policies-alert]` were scoped to `[data-fs-order-details-content]`, but `BuyingPolicyAlert` only renders inside `OrderDetailsHeader`, which in the deprecated component sits *outside* `<main>`. Removed. ## Tests 12 tests, all passing. - `test/server/cms/myAccountDefaultSections.test.ts` — pins the default order and asserts the key set is unchanged (reorder only, nothing added or removed). - `test/components/cms/RenderSections.browser.test.tsx` — immediate render, coverage of store-authored sections, content present in the SSR HTML via `renderToString`, and a regression guard proving lazy loading still works without the flag. Biome, stylelint and SonarQube are clean. ## Assumptions - **`403.tsx` and `404.tsx` also get `skipLazyLoading`.** The binding rule is "no My Account section goes through `ViewportObserver`", so it applies to every page under `/pvt/account`, not only the five content pages. ## Deviations - **The delivery accordions sit right after the compact delivery card**, whereas the deprecated component rendered them after the summary. They are siblings inside one section, so this is unavoidable without splitting `AccountOrderDelivery` into two CMS sections. Deliberately accepted to keep this PR free of CMS contract changes and backportable as a patch. - **`display: contents` is not scoped to the grid breakpoint**, so mobile changes too. Below `>=notebook` the container is a flex column with a gap; today the delivery wrapper is a block box and neither child carries a margin of its own, so the recipient card and the accordions stack flush against each other, unlike every other pair of blocks. Unscoped, they become sibling flex items and pick up the container gap. Scoping the rule would preserve the flush stacking. Discussed [here](#3464 (comment)). ## Not verified here The visual acceptance criteria — column widths, header overlap, the un-clipped status timeline, and the mobile spacing change above — need a layout engine, and the `browser` vitest project is jsdom. They require the store running. Also still open: the header now inherits the grid `gap` on top of its own `padding`, so its vertical spacing should be checked against the design. ## Follow-ups - **Backport as a patch.** The bug affects every store on **v4.4.0+** with `enableFaststoreMyAccount: true` — not 4.5.0+ as the Jira states (#3411 merged three hours *after* the bug was reported; the culprit is #3354). The reported stores are `b2bfaststoredev` and `usb2bstore`; their versions still need to be established. - [SFS-3345](https://vtex-dev.atlassian.net/browse/SFS-3345) — remove the deprecated `OrderDetails.tsx` and the two remaining orphan card rules (status, budgets). Kept out of this PR because deleting an importable surface does not belong in a patch. The SCSS carries a comment block mapping which rules are live for the CMS render, which one is live via `display: contents`, and which serve only the deprecated component. - The layout contract is now coupled by string to the `section-account-order-*` class names, and nothing enforces that coupling — renaming a wrapper class would silently break the grid. Consistent with how `data-fs-*` selectors work across the repo, so left as is rather than adding a bespoke guard here. - `cms/faststore/my-account/README.md` still has an empty "How a merchant enables My Account in their CMS" heading. Its schema counts were stale (14/6 vs 15/7 after the Cards schemas) and are fixed here. - 3 pre-existing test failures on `dev` (`cookieCacheBusting.test.ts`, `graphql.test.ts`) are unrelated to this change — they reproduce on a clean checkout. ## Spec The spec driving this change lives at `specs/order-details-layout-fix.md` and is intentionally **not committed** (`specs` is gitignored in this repo). It is available on request; every decision above is summarised here. 🤖 Generated with [Claude Code](https://claude.com/claude-code) [SFS-3325]: https://vtex-dev.atlassian.net/browse/SFS-3325?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ [SFS-3345]: https://vtex-dev.atlassian.net/browse/SFS-3345?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Summary by CodeRabbit - **New Features** - My Account pages now display content sections immediately, improving first-load visibility. - Order details use an updated layout and section order for clearer information presentation. - **Bug Fixes** - Improved handling of missing order status labels. - Preserved full-width delivery option presentation within order details. - **Documentation** - Updated My Account content schema documentation and section guidance. - **Tests** - Added coverage for immediate section rendering and order-details section ordering. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 5 <[email protected]>

What's the purpose of this pull request?
After the My Account CMS migration, new account pages created by a store were still code-only — merchants could not author/edit them in CMS Admin. This PR closes that gap (SFS-3250): stores can declare a My Account route bound to a CMS content-type and render it SSR like native pages.
How it works?
contentTypeonRouteinnavigation.ts(no separatesourceflag).contentType+ no.tsx→ body 100% from CMS (CLI generates the page).contentType+.tsx→ CMS sections + code body (+ optional before/after).contentType→ legacy code-only wrap (unchanged).MyAccountContentType; newmyAccountCmsServerSideProps(same auth as native pages).navigation.ts, generates pages viamyAccountCmsPageTemplate; skips native collisions and routes outside/pvt/account.How to test it?
@faststore/coreand@faststore/cli(CMS SSR, routes, page generation).contentTypeon a route, add content-type undercms/faststore/pages/,cms-sync, publish sections in Admin, open the route logged in.contentTypeand existing before/after still work.specs/007-myaccount-cms-custom-pages/quickstart.md.References
specs/007-myaccount-cms-custom-pages/Summary by CodeRabbit
New Features
/pvt/accountusing an optional content type.Tests