diff --git a/.changeset/sync-makeswift-1-14-0.md b/.changeset/sync-makeswift-1-14-0.md new file mode 100644 index 0000000000..d24255aad5 --- /dev/null +++ b/.changeset/sync-makeswift-1-14-0.md @@ -0,0 +1,5 @@ +--- +"@bigcommerce/catalyst-b2b-makeswift": minor +--- + +Pulls in changes from the `@bigcommerce/catalyst-makeswift@1.14.0` release. For more information, see the [changelog entry](https://github.com/bigcommerce/catalyst/blob/f85777b06a95de022eb5f03ced3a78a93bcdceaa/core/CHANGELOG.md#1140). diff --git a/.github/workflows/native-hosting.yml b/.github/workflows/native-hosting.yml index 61038e24f1..1f2f30fc20 100644 --- a/.github/workflows/native-hosting.yml +++ b/.github/workflows/native-hosting.yml @@ -35,17 +35,10 @@ jobs: # Keep the adapter version in sync with OPENNEXT_CLOUDFLARE_VERSION in # packages/catalyst/src/cli/lib/commerce-hosting.ts - - name: Install Catalyst CLI - run: pnpm add @bigcommerce/catalyst@alpha @opennextjs/cloudflare@1.20.6 + - name: Install OpenNext adapter + run: pnpm add @opennextjs/cloudflare@1.20.15 working-directory: core - - name: Convert proxy.ts to middleware.ts - working-directory: core - run: | - mv proxy.ts middleware.ts - sed -i 's/export const proxy/export const middleware/' middleware.ts - sed -i "s/export const config = {/export const config = {\n runtime: 'experimental-edge',/" middleware.ts - - name: Build monorepo packages run: pnpm --filter "./packages/*" build @@ -57,8 +50,9 @@ jobs: BIGCOMMERCE_STOREFRONT_TOKEN: ${{ secrets.NATIVE_HOSTING_BIGCOMMERCE_STOREFRONT_TOKEN }} BIGCOMMERCE_CHANNEL_ID: ${{ vars.NATIVE_HOSTING_BIGCOMMERCE_CHANNEL_ID }} + # The CLI built from this commit, so its project checks match this core. - name: Build - run: pnpm exec catalyst build + run: node ../packages/catalyst/dist/cli.js build working-directory: core env: # CLI env vars @@ -71,7 +65,7 @@ jobs: - name: Deploy run: | - pnpm exec catalyst deploy --prebuilt \ + node ../packages/catalyst/dist/cli.js deploy --prebuilt \ --secret BIGCOMMERCE_STORE_HASH=${{ vars.NATIVE_HOSTING_BIGCOMMERCE_STORE_HASH }} \ --secret BIGCOMMERCE_STOREFRONT_TOKEN=${{ secrets.NATIVE_HOSTING_BIGCOMMERCE_STOREFRONT_TOKEN }} \ --secret BIGCOMMERCE_CHANNEL_ID=${{ vars.NATIVE_HOSTING_BIGCOMMERCE_CHANNEL_ID }} \ diff --git a/core/.agents/skills/verify-catalyst/SKILL.md b/core/.agents/skills/verify-catalyst/SKILL.md new file mode 100644 index 0000000000..ebdbfef87c --- /dev/null +++ b/core/.agents/skills/verify-catalyst/SKILL.md @@ -0,0 +1,189 @@ +--- +name: verify-catalyst +description: Drive a Catalyst storefront in a real browser to prove a UI change works, and attach screenshot and video evidence to the pull request. Use when you change anything a shopper can see or do (pages, components, forms, cart, account, search), when asked to "verify", "show it working", "screenshot this", or "add evidence to the PR", and before marking a UI pull request ready for review. Works in the Catalyst monorepo and in any project created with `create catalyst` or forked from it. +license: MIT +compatibility: Requires Node.js 24+, the storefront's installed dependencies (including @playwright/test), and a BigCommerce store configured in .env.local. git and GitHub CLI 2.99.0+ (for `--attach`) are needed only to publish evidence; ffmpeg is optional (GIF/MP4). Runs on macOS, Linux, Windows, and WSL. +metadata: + adapted-from: https://github.com/cursor/plugins/tree/main/pstack/skills/create-verification-skill +--- + +# Verify a Catalyst storefront + +Prove a change by driving the real storefront the way a shopper would, then hand the reviewer the evidence: a recording, step screenshots, and a Playwright trace. Unit tests and type checks do not count as proof of UI behavior. + +Everything goes through one helper, run from the **storefront directory** (the folder with `next.config.ts`): + +- Catalyst monorepo: `core/` +- A project created with `create catalyst`, or a fork of one: the repository root + +```sh +node .agents/skills/verify-catalyst/scripts/verify.mjs +``` + +The helper is plain Node, so the same command works in bash, zsh, PowerShell, and cmd. Below, `verify` stands for that whole command. + +## Rules + +- **Exercise the real user path.** Click, type, and navigate as a shopper. Do not call server actions, set cookies, or hit internal routes to fake a state. +- **Capture the action and the result,** not only the final screen. A step's screenshot is taken _after_ its action, so name steps by what they prove. +- **Never hardcode store data.** Each store has its own catalog, categories, and settings. Discover product URLs, category names, and countries from the running store (`verify explore`), or read them from `.env.test.local` (`DEFAULT_PRODUCT_ID`, `TEST_CUSTOMER_EMAIL`, …). +- **Read-only by default.** The storefront talks to a live BigCommerce store. Do not submit orders, register customers, or write reviews unless the store is a sandbox and the change requires it. Stop before the final submit button when the visible result is enough. Treat `TESTS_READ_ONLY=true` in `.env.test.local` as a hard stop. +- **Never weaken a journey to make it pass.** If the store lacks a precondition (no product with variants, no country without states), report the run as blocked and name the missing data. +- **Never drive or stop a server you did not start.** Point `--url` at a developer's own server only when asked to. +- **Synthetic data only.** Everything you type into a form ends up in the recording. Use obviously fake values (`Test Shopper`, `test@example.com`, a made-up street address, `555` phone numbers) and never the developer's own name, email, address, or payment details. Credentials come only from `.env.test.local`. Look at the step screenshots before publishing; if one shows something that should not leave the machine, do not publish it. +- **Evidence is not secret-free by default.** Screenshots show the store's real catalog and prices. `publish` chooses where uploads go based on your access and the repository's visibility; see _Publish_. Evidence only ever goes to the repository that owns the PR, so a private storefront's PR never posts to a public repository. + +## 1. Doctor + +```sh +verify doctor +``` + +This read-only check covers Node, dependencies, `.env.local` keys (names only, never values), Makeswift config, Chromium, ffmpeg, the GitHub CLI, and whether the target URL serves Catalyst (``). Fix every `FAIL` before going on, and run it again whenever something looks wrong. + +Common fixes: + +| FAIL | Fix | +| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | +| `.env.local missing` in a git worktree | Worktrees do not copy gitignored files. Copy `.env.local` (and `.env.test.local`, if present) from the main checkout path the doctor prints. | +| `.env.local missing` elsewhere | Copy `.env.example` and fill it in, or use the Catalyst CLI to link a store. | +| `chromium missing` | `npx playwright install chromium`. On a fresh Linux box or in CI, use `npx playwright install --with-deps chromium`. | +| `dependencies` | `pnpm install` (the monorepo and new projects use pnpm). | + +`WARN` lines are optional capabilities: ffmpeg gives GIF/MP4 output, `gh` 2.99.0+ posts evidence straight to the PR, and a test customer enables signed-in journeys. + +## 2. Launch + +```sh +verify launch # next dev on port 3100 +verify launch --prod # next build + next start, closer to production; slower +verify launch --port 3200 +``` + +`launch` builds `@bigcommerce/catalyst-client` when the monorepo needs it, regenerates GraphQL types, and starts Next.js detached with its log at `.verification/server.log`. It returns once the home page serves a Catalyst page; the first dev compile can take a few minutes. It refuses a busy port instead of attaching to someone else's server. + +A developer who already runs `pnpm dev` can skip `launch` and pass `--url http://localhost:3000` to the other commands. Next.js allows only one `next dev` per directory, so if `launch` reports the server exiting at startup, check for an existing dev server and use `--url` instead. + +## 3. Find stable handles + +```sh +verify explore / # whole page +verify explore /register --selector main +verify explore "/search?term=shirt" --device mobile --screenshot tmp.png +``` + +`explore` prints the page's ARIA snapshot. Build locators from roles and accessible names (`page.getByRole('button', { name: 'Add to cart' })`). Avoid CSS classes, which are Tailwind utilities and change freely, and avoid DOM position. + +Before writing a journey, read the matching feature file in [`features/`](features/README.md). It lists entry points, known handles, and gotchas for each area of the storefront. + +## 4. Write a journey + +A journey is a small ES module. Keep throwaway journeys in `.verification/journeys/`, which is gitignored: + +```js +// .verification/journeys/state-field.mjs +export const meta = { title: 'Register: State/Province follows country', feature: 'account' }; + +export default async function journey({ page, step, expect }) { + await step('Open the registration form', async () => { + await page.goto('/register'); + await expect(page.getByRole('heading', { level: 1 })).toBeVisible(); + }); + + await step('Country without states hides State/Province', async () => { + // ...interact, then assert what the shopper sees. Match by label: the field can be a + // textbox or a dropdown, and a role-based "absent" check would pass on the wrong one. + await expect(page.getByLabel('State/Province', { exact: true })).toHaveCount(0); + }); +} +``` + +The journey receives: + +- `page`, `context`: Playwright objects with `baseURL` set, so `page.goto('/cart')` works. +- `step(label, fn, { fullPage })`: runs `fn`, waits for the network to settle, then screenshots. If `fn` throws, it saves a `-FAILED` screenshot and the run fails. +- `expect`: Playwright's auto-waiting assertions. Assert inside every step; a screenshot with no assertion proves nothing. +- `env`: values from `.env.test.local`, such as test customer credentials. + +## 5. Capture + +```sh +verify capture .verification/journeys/state-field.mjs +verify capture .verification/journeys/state-field.mjs --device mobile +``` + +Each run writes `.verification/runs/--/` containing: + +- `video.webm`, plus `video.mp4` and `video.gif` when ffmpeg is installed +- `NN-.png` for every step +- `trace.zip` (open it with `npx playwright show-trace trace.zip`) +- `manifest.json` (git SHA, dirty flag, OS, viewport, step results, console errors, same-origin 4xx/5xx responses) +- `summary.md` + +`git.dirtyFiles` lists uncommitted tracked files, and the evidence names them. `next dev` rewrites `AGENTS.md` on start, so that entry alone does not mean untested code. + +Exit code 0 means every step passed. Read `manifest.json` → `consoleErrors` even when the run passes; a new hydration error is a finding. + +**Responsive changes:** capture both `--device desktop` and `--device mobile`. +**Before/after:** for a visual change, capture the base branch too. Run `git worktree add ../catalyst-base origin/`, install dependencies, copy `.env.local`, then `verify launch --port 3101`. Capture with `--label before --url http://localhost:3101` there, and with `--label after` on your branch. Stop the base server from the base worktree. + +## 6. Publish to the pull request + +Evidence belongs on the PR, posted from the CLI. Use **GitHub CLI 2.99.0 or newer**. That release added `--attach` to `gh pr create`, `gh pr edit`, and `gh pr comment`, which upload images and videos as native GitHub attachments: MP4s play inline and access follows the repository. Check with `gh --version`. Upgrade with `brew upgrade gh` (macOS), `winget upgrade --id GitHub.cli` (Windows), or your Linux package manager / [the releases page](https://github.com/cli/cli/releases), then run `gh auth login`. `verify doctor` warns when `gh` is missing, too old, or signed out. + +```sh +verify publish # latest run → new comment on this branch's PR +verify publish # several runs in one comment +verify publish --pr 123 --into body # into the PR body instead of a comment +verify publish --dry-run # write the markdown and print the gh command only +``` + +`publish` writes the evidence markdown (recording, step table, screenshots, console errors), then posts it with `gh`. Images are sized by orientation: landscape captures stack at 720px, portrait (mobile) captures sit side by side as a filmstrip, and GIFs are rendered to fit within 800×600 and start at the first page load rather than on a blank frame. The PR defaults to the current branch's (`gh pr view`); pass `--pr ` otherwise. With `--into body`, it replaces a `` marker if the body has one (put it under **Testing**), or else appends a section. + +GitHub only accepts `--attach` uploads from accounts with **write access** to the PR's repository. `--to auto` (the default) checks that and picks the route: + +| Situation | Route | Result | +| ------------------------------------------------------------------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Write access, `gh` ≥ 2.99.0 | `attach` | Native attachments on the PR; video plays inline. Traces stay local (not a media type). | +| No write access (fork contribution to a **confirmed public** repo), or `gh` < 2.99.0 | `gist` | Files go to a secret gist you own; the markdown, posted by `gh`, embeds the GIF and links the MP4 and trace. | +| Same, but the repository is private | `branch` | Files go to an orphan `verification-evidence/` on `--remote` (default `origin`; use your fork) so GitHub's access control applies. The PR diff is untouched. | +| `gh` missing or signed out, or the repository's visibility is unknown | `manual` | Prints the files to drag into a PR comment on github.com, which hosts them and plays MP4 inline. | + +Force a route with `--to attach|gist|branch|manual`. Secret gists are unlisted but readable by anyone with the link, so `auto` picks `gist` only when GitHub confirms the repository is public. If it cannot read the visibility, it falls back to `manual` rather than guess; pass `--to gist` yourself if you know the repository is public. Never use `gist` for a private storefront's evidence. + +**By hand.** The `attach` route is plain `gh`, so a person can do the same thing without the helper. Run it from the directory that holds the files. `gh` rewrites any `![alt](./path)` reference in the body that matches an `--attach` path to the uploaded URL, and appends files the body does not reference: + +```sh +gh pr comment 123 --body-file evidence.md --attach ./video.mp4 --attach './03-result.png#State/Province hidden' +``` + +The limit is 50 files per command. If some uploads fail, `gh` still posts the rest and exits non-zero. + +## 7. Clean up + +```sh +verify stop +``` + +This stops only the server that `launch` started, using its recorded PID: process group on macOS and Linux, `taskkill /T` on Windows. It never removes `.verification/runs/`; evidence must outlive the server. Delete old runs by hand when you no longer need them. Run `stop` after failed attempts too, so you do not strand ports. + +## Reporting + +End with a short report containing: + +- Which feature and entry points were driven, and on which devices. +- Pass or fail per step, linked to the evidence (`pr-evidence.md` or the run directory). +- Anything skipped or blocked, with the missing precondition. Never report a skipped entry point as verified through a different path. +- Any console errors or failed requests recorded during the run. + +## Platform notes + +- **Windows:** use the same commands in PowerShell or cmd, with forward slashes in paths. The helper spawns Node directly, so it needs no bash and no `.cmd` shims. Install ffmpeg with `winget install Gyan.FFmpeg`. +- **WSL:** run everything inside WSL, including Node, the browser, and the git checkout. Do not mix a Windows Node with a WSL checkout. +- **Linux/CI (headless):** run `npx playwright install --with-deps chromium` once. No display is needed. +- **macOS:** install ffmpeg with `brew install ffmpeg`. +- **Watching the browser:** set `VERIFY_HEADED=1` (`$env:VERIFY_HEADED=1` in PowerShell). + +## Keep the feature map honest + +[`features/`](features/README.md) is the maintained recipe book. When a verification run teaches you something, update the matching file in the same PR: a new entry point, a handle that changed, or a gotcha that cost time. Add a new file when you verify an area that has none. diff --git a/core/.agents/skills/verify-catalyst/features/README.md b/core/.agents/skills/verify-catalyst/features/README.md new file mode 100644 index 0000000000..fb4a3c6ba0 --- /dev/null +++ b/core/.agents/skills/verify-catalyst/features/README.md @@ -0,0 +1,36 @@ +# Catalyst verification map + +This directory is the maintained source for verifying shopper-facing behavior. Read this index before driving the storefront, then use the matching feature file as the recipe. Handles below come from the stock Catalyst UI (`vibes/soul`) with English messages. If your storefront has a customized UI or another default locale, run `verify explore` and update the files. + +## Baseline preconditions + +- Run `verify doctor` with no `FAIL`, against a server you started with `verify launch` (or one you were explicitly given via `--url`). +- The store has at least one visible, purchasable product. Find one with the search popup or a category page. Do not assume a product URL, because catalogs differ per store. +- Signed-in journeys need `TEST_CUSTOMER_EMAIL` and `TEST_CUSTOMER_PASSWORD` in `.env.test.local`. Journeys receive these as `env`. +- Cookie consent: if the store enables a consent banner, it can cover the bottom of the page. Accept or dismiss it in the first step and capture that step. + +## Driving conventions + +- Navigate with `page.goto('/path')`; the base URL is set for you. With the default locale, paths have no locale prefix (`/cart`, not `/en/cart`). +- Locate by role and accessible name. Tailwind class names are not stable handles. +- Wait for UI state with `expect(...)` assertions, never fixed sleeps. Server actions and streamed (Suspense) sections finish after `load`. +- One `step` per shopper action, named by what it proves. +- Every mutation (cart, wishlist, account) touches the live store. Prefer flows that are reversible, and restore state at the end: remove the cart line you added. + +## Proof and skip reporting + +- UI proof is the step screenshot plus an `expect` on the visible result. For mutations, add a second, read-only view, such as reloading `/cart` after adding a line. +- Responsive or layout changes need captures at both `--device desktop` and `--device mobile`. +- Report an unreachable path with the attempted action and the unmet precondition (for example "store has no country without states"). +- Do not report a skipped entry point as verified through a different path. + +## Feature entry contract + +Each feature file starts with an H1 title and one paragraph describing the user-visible behavior. It then uses exactly four H2 sections, in order: `Sub-features`, `How to get to it (user POV)`, `Driving it with verify.mjs` (starting with `Preconditions:`), and `Gotchas`. Keep implementation details out; name only user paths, stable handles, required state, and observable proof. + +## Features + +- [Search](./search.md) covers the header search popup, the search results page, and empty results. +- [Product detail page](./product-detail.md) covers the gallery, quantity, add to cart, and the added-to-cart toast. +- [Cart](./cart.md) covers line items, quantity changes, removal, the summary, and the checkout handoff. +- [Account](./account.md) covers log in, registration (including State/Province rules), and the signed-in account area. diff --git a/core/.agents/skills/verify-catalyst/features/account.md b/core/.agents/skills/verify-catalyst/features/account.md new file mode 100644 index 0000000000..135943f051 --- /dev/null +++ b/core/.agents/skills/verify-catalyst/features/account.md @@ -0,0 +1,39 @@ +# Account + +Shoppers log in, register a new account through a form driven by the store's customer and address fields, and manage their orders, addresses, wishlists, and settings once signed in. + +## Sub-features + +- `account-login` logs in with email and password and lands in the account area. +- `account-register` renders the store-configured registration form and creates a customer. +- `account-register-state` shows State/Province only when the selected country has states. +- `account-forgot-password` requests a reset email. +- `account-area` covers orders, addresses, wishlists, and settings for signed-in shoppers. + +## How to get to it (user POV) + +- Choose the `Profile` link in the header. Signed-out shoppers land on `/login`. +- On `/login`, choose `Create account` to reach `/register`. +- Visit `/login`, `/register`, or `/account/orders` directly. Signed-out shoppers are redirected to log in. + +## Driving it with verify.mjs + +Preconditions: + +- Log-in and account-area journeys need `env.TEST_CUSTOMER_EMAIL` and `env.TEST_CUSTOMER_PASSWORD` from `.env.test.local`. +- Registration journeys stay read-only: fill in the form and assert the visible behavior, but do not choose `Create account` unless the store is a sandbox. +- Fill registration and address forms with synthetic values only (`Test Shopper`, `test@example.com`, a made-up address). The recording captures every keystroke, so never type the developer's own details. + +- **Log in.** `page.goto('/login')`, fill `textbox` `Email` and `textbox` `Password`, then choose `button` `Log in`. The URL moves under `/account`. +- **Registration form.** `page.goto('/register')`. The `heading` level 1 reads `New account`, followed by text fields (`First Name`, `Last Name`, `Email Address`, `Password`, `Confirm Password`, address fields) and a `combobox` `Country`. +- **Choose a country.** Choose the `combobox` `Country`, then the `option` by name, for example `page.getByRole('option', { name: 'United States' })`. The list is long; typing the first letters narrows it. +- **State/Province follows the country.** With a country that has states, the `State/Province` field is present. With a country that has none, the field is absent: assert `toHaveCount(0)` on `page.getByLabel('State/Province', { exact: true })`. Switching back brings it back. Confirm the switch landed first (`expect(country).toContainText('Algeria')`) so an absent field is not a race. The field sits beside `Country`, so the step screenshot (scrolled to the focused combobox) shows both. +- **Validation.** Choose `Create account` with empty required fields. Inline errors appear and no request leaves the form. This is safe because nothing is submitted. + +## Gotchas + +- Countries without states come from the store's own country data. Algeria (`DZ`) has none in BigCommerce defaults, but a store can add states to any country, so confirm visually before asserting. +- With no country chosen, the field shows as a text input labeled `State/Province`; for countries with states it can render as a dropdown. Match it by label, not by role. +- Registration fields are configurable per store (extra customer and address fields, required flags). Never assume the stock field list. +- reCAPTCHA, when enabled on the store, blocks automated submission. Verify up to the submit button. +- Logging in sets a session cookie for the rest of the journey's context; log-out lives at `/logout`. diff --git a/core/.agents/skills/verify-catalyst/features/cart.md b/core/.agents/skills/verify-catalyst/features/cart.md new file mode 100644 index 0000000000..4f74cd6723 --- /dev/null +++ b/core/.agents/skills/verify-catalyst/features/cart.md @@ -0,0 +1,39 @@ +# Cart + +The cart lists line items with quantity controls and removal, a summary with subtotal, tax, shipping estimate, coupon code, and total, and hands off to BigCommerce checkout. + +## Sub-features + +- `cart-empty` shows the empty state with `Continue shopping`. +- `cart-lines` lists each item with price, quantity controls, and `Remove item`. +- `cart-quantity` updates totals when quantity changes; rapid clicks coalesce. +- `cart-shipping` estimates shipping from the summary's `Shipping` → `Add` form. +- `cart-coupon` applies a coupon code. +- `cart-checkout` sends the shopper to checkout via `Proceed to checkout`. + +## How to get to it (user POV) + +- Choose the `Cart` link in the header. +- Choose `your cart` in the toast after adding a product. +- Visit `/cart`. + +## Driving it with verify.mjs + +Preconditions: + +- For anything except the empty state: add a product first, through the PDP flow in [product-detail.md](./product-detail.md). Do not seed the cart another way. + +- **Empty state.** On a fresh context, `page.goto('/cart')`. The `heading` level 1 reads `Your cart is empty.` and a `link` `Continue shopping` points to the catalog. +- **Line items.** After adding a product, `page.goto('/cart')`. The `main` region contains a `list` whose `listitem` shows the product name and price. The level 1 `heading` reads `Cart` followed by the item count. +- **Quantity.** Choose `button` `Increase quantity` inside the line. The quantity text and the `Subtotal` and `Total` definitions in the summary update. +- **Remove.** Choose `button` `Remove item`. The line disappears; with no lines left, the empty state returns. +- **Coupon.** Fill `textbox` `Coupon code` and choose `Apply`. A valid code shows a discount line; an invalid code shows a field error. +- **Checkout handoff.** Choose `button` `Proceed to checkout`. The browser leaves Catalyst for the store's checkout domain. Stop the journey once the URL changes; checkout is not Catalyst UI. + +## Gotchas + +- The decrease button's accessible name is `Decrease count`, while the PDP uses `Decrease quantity`. Increase is `Increase quantity` in both places. +- `Decrease count` is disabled at quantity 1; use `Remove item` instead. +- Each browser context has its own cart cookie. Carts are per channel, so multi-channel storefronts keep a separate cart per channel. +- Checkout runs on BigCommerce. Cross-origin preflight can fail under headless Chromium on some stores; record that as a boundary, not as a Catalyst failure. +- Restore state: remove lines you added so later runs start from an empty cart. diff --git a/core/.agents/skills/verify-catalyst/features/product-detail.md b/core/.agents/skills/verify-catalyst/features/product-detail.md new file mode 100644 index 0000000000..24f136f940 --- /dev/null +++ b/core/.agents/skills/verify-catalyst/features/product-detail.md @@ -0,0 +1,38 @@ +# Product detail page + +The product detail page (PDP) shows a product's gallery, price, options, quantity, add to cart, wishlist, description, specifications, related products, and reviews. + +## Sub-features + +- `pdp-gallery` swaps the main image from the thumbnail buttons, and follows variant images when options change. +- `pdp-options` selects variant options (swatches, radios, dropdowns, date pickers) and updates the price and stock. +- `pdp-quantity` changes quantity within stock limits. +- `pdp-add-to-cart` adds the configured item and confirms it with a toast. +- `pdp-wishlist` adds to a wish list (signed-in shoppers). +- `pdp-reviews` shows reviews and the `Write a review` form. + +## How to get to it (user POV) + +- Choose a product card on a category page, the home page, or search results. +- Visit the product's SEO URL directly (`/`). The `with-routes` proxy resolves it, so the path is not `/product/`. + +## Driving it with verify.mjs + +Preconditions: + +- A product URL discovered from the running store, for example via the search popup or a category page. For options or variant work, use a product with variants (`DEFAULT_COMPLEX_PRODUCT_ID` in `.env.test.local` names one when it is set). + +- **Land on the PDP.** `page.goto(productPath)`. The `heading` level 1 is the product name. +- **Gallery.** Choose `button` `View image number 2`. The main image changes. +- **Quantity.** Use `button` `Increase quantity` and `Decrease quantity`. The `spinbutton` `Quantity` reflects the value. +- **Add to cart.** `page.getByRole('button', { name: 'Add to cart' }).click()`. An `alert` in the `Notifications` region reads `1 item added to your cart` with a `link` `your cart`. Prove the side effect with a read-only second view: `page.goto('/cart')` lists the product. +- **Wishlist.** `button` `Add to wish list` redirects signed-out shoppers to log in. +- **Reviews.** `button` `Scroll to reviews` jumps to the `heading` `Reviews `. + +## Gotchas + +- Products with required options keep `Add to cart` disabled, or show field errors, until the options are chosen. +- Out-of-stock and backorder settings change the button label and messaging per store. Read them from the page; do not assume them. +- Adding to cart mutates the live cart. Remove the line on `/cart` at the end of the journey. +- Related products and reviews stream in after the main content. Assert them with `expect`, which waits. +- The toast disappears after a few seconds. Assert it right after the click, in the same step. diff --git a/core/.agents/skills/verify-catalyst/features/search.md b/core/.agents/skills/verify-catalyst/features/search.md new file mode 100644 index 0000000000..35a28fff85 --- /dev/null +++ b/core/.agents/skills/verify-catalyst/features/search.md @@ -0,0 +1,34 @@ +# Search + +Shoppers search the catalog from a popup in the header, which shows live category and product suggestions, or from the full search results page with sorting, filters, and pagination. + +## Sub-features + +- `search-popup` opens the header popup and shows suggestions as the shopper types. +- `search-submit` submits the query and lands on the results page. +- `search-results` lists matching products with sort and filters. +- `search-empty` shows the empty state for a query with no matches. + +## How to get to it (user POV) + +- Choose the search icon in the header (button `Open search popup`). +- Visit `/search?term=` directly, for example from a shared link. + +## Driving it with verify.mjs + +Preconditions: + +- At least one product name in the store contains your query. Pick the query by first exploring a category page. + +- **Open popup.** `page.getByRole('button', { name: 'Open search popup' }).click()`. A `dialog` appears containing a `textbox` whose placeholder reads `Search products, categories, brands...` (store settings can change it). +- **Live suggestions.** `page.getByRole('dialog').getByRole('textbox').fill(query)`. Wait for `page.getByRole('dialog').getByRole('region', { name: 'Products' })` to be visible; each suggestion is an `article` with a `link` named after the product. A `Categories` region may also appear. +- **Submit.** Press `Enter` in the textbox or choose the `Search` button in the dialog. The URL contains `/search?term=` and the `heading` level 1 reads `Search results for ""`. +- **Results page.** Products are `article` elements with a product `link`. Sorting uses `combobox` `Sort by:`; filters live in the `complementary` region headed `Filters`. +- **Empty state.** Search for a nonsense term (`zzqxv`). Assert that the result count is `0` and that no product `article` is rendered. + +## Gotchas + +- The popup's input is a `textbox`, not a `searchbox`. `getByRole('searchbox')` times out. +- Suggestions are debounced. Wait for the `Products` region, not a timeout. +- On mobile, the header collapses into a menu, but the `Open search popup` button stays visible. +- The search placeholder text comes from store settings, so locate the input by role inside the dialog, not by placeholder. diff --git a/core/.agents/skills/verify-catalyst/scripts/verify.mjs b/core/.agents/skills/verify-catalyst/scripts/verify.mjs new file mode 100644 index 0000000000..f8e6fef376 --- /dev/null +++ b/core/.agents/skills/verify-catalyst/scripts/verify.mjs @@ -0,0 +1,1364 @@ +#!/usr/bin/env node +// Verification helper for Catalyst storefronts. See ../SKILL.md for how to use it. +// +// Pure Node (no shell scripts) so the same commands work on macOS, Linux, and Windows. +// It resolves Playwright and Next.js from the storefront's own node_modules, so it works +// both in the Catalyst monorepo (`core/`) and in standalone projects created with +// `create catalyst`, where the storefront is the repository root. + +import { spawn, spawnSync } from 'node:child_process'; +import { + closeSync, + copyFileSync, + existsSync, + mkdirSync, + mkdtempSync, + openSync, + readdirSync, + readFileSync, + renameSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { createRequire } from 'node:module'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { basename, dirname, extname, join, relative, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { parseArgs } from 'node:util'; + +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)); +const APP_DIR = resolve(SCRIPT_DIR, '../../../..'); +const EVIDENCE_DIR = join(APP_DIR, '.verification'); +const STATE_FILE = join(EVIDENCE_DIR, 'server.json'); +const IS_WINDOWS = process.platform === 'win32'; +const DEFAULT_PORT = 3100; +const READY_TIMEOUT_MS = 6 * 60 * 1000; +const REQUIRED_ENV = [ + 'BIGCOMMERCE_STORE_HASH', + 'BIGCOMMERCE_STOREFRONT_TOKEN', + 'BIGCOMMERCE_CHANNEL_ID', + 'AUTH_SECRET', +]; +const VIEWPORTS = { + desktop: { viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 }, + tablet: { viewport: { width: 834, height: 1112 }, deviceScaleFactor: 1, hasTouch: true }, + mobile: { + viewport: { width: 390, height: 844 }, + deviceScaleFactor: 2, + isMobile: true, + hasTouch: true, + }, +}; + +// --------------------------------------------------------------------------------------------- +// Small utilities + +const requireFromApp = createRequire(join(APP_DIR, 'package.json')); + +function fail(message) { + console.error(`\n✖ ${message}`); + process.exit(1); +} + +function run(cmd, args, opts = {}) { + // `.cmd` shims (pnpm, npm, npx) need a shell on Windows; real executables (git, gh, ffmpeg) do not. + const result = spawnSync(cmd, args, { + cwd: APP_DIR, + encoding: 'utf8', + shell: IS_WINDOWS && opts.shim === true, + ...opts, + }); + + return { + ok: result.status === 0, + status: result.status, + stdout: (result.stdout ?? '').trim(), + stderr: (result.stderr ?? '').trim(), + error: result.error, + }; +} + +// ffmpeg only understands `-version`; git and gh accept it too. +function has(cmd) { + return run(cmd, ['-version']).ok || run(cmd, ['--version']).ok; +} + +function slugify(value) { + return ( + value + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 60) || 'run' + ); +} + +function timestamp() { + return new Date().toISOString().replace(/[:T]/g, '-').replace(/\..+$/, ''); +} + +function parseEnvFile(file) { + if (!existsSync(file)) return {}; + + const env = {}; + + for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) { + const match = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/); + + if (!match) continue; + + let value = match[2]; + + if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1); + else value = value.replace(/\s+#.*$/, ''); + + env[match[1]] = value; + } + + return env; +} + +function readState() { + if (!existsSync(STATE_FILE)) return null; + + try { + return JSON.parse(readFileSync(STATE_FILE, 'utf8')); + } catch { + return null; + } +} + +function isAlive(pid) { + try { + process.kill(pid, 0); + + return true; + } catch (error) { + return error.code === 'EPERM'; + } +} + +function portIsFree(port) { + return new Promise((done) => { + const server = createServer(); + + server.once('error', () => done(false)); + server.once('listening', () => server.close(() => done(true))); + server.listen(port); + }); +} + +function layout() { + const parent = dirname(APP_DIR); + const monorepo = + existsSync(join(parent, 'pnpm-workspace.yaml')) && + existsSync(join(parent, 'packages', 'client')); + + return { monorepo, repoRoot: monorepo ? parent : APP_DIR }; +} + +function git(args, opts = {}) { + return run('git', args, opts); +} + +function gitInfo() { + const sha = git(['rev-parse', 'HEAD']).stdout; + const branch = git(['rev-parse', '--abbrev-ref', 'HEAD']).stdout; + // `next dev` rewrites agent docs (AGENTS.md) on startup; list changed files so a reviewer can + // tell that apart from untested code. + const dirtyFiles = git(['diff', '--name-only', 'HEAD']).stdout.split(/\r?\n/).filter(Boolean); + + return { sha, branch, dirty: dirtyFiles.length > 0, dirtyFiles }; +} + +// The first entry of `git worktree list` is the main checkout. Worktrees do not inherit +// gitignored files such as `.env.local`, so this is where to copy them from. +function mainCheckoutAppDir() { + const list = git(['worktree', 'list', '--porcelain']); + + if (!list.ok) return null; + + const mainRoot = list.stdout.split(/\r?\n/)[0]?.replace(/^worktree /, ''); + const { repoRoot } = layout(); + + if (!mainRoot || resolve(mainRoot) === resolve(repoRoot)) return null; + + return join(mainRoot, relative(repoRoot, APP_DIR)); +} + +function resolveBaseURL(values) { + if (values.url) return values.url.replace(/\/$/, ''); + + const state = readState(); + + if (state && isAlive(state.pid)) return state.url; + + return null; +} + +async function probe(url) { + try { + const response = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(60_000) }); + const html = await response.text(); + const meta = (name) => + html.match(new RegExp(`]+name="${name}"[^>]+content="([^"]*)"`))?.[1] ?? null; + + return { + ok: response.ok, + status: response.status, + catalyst: meta('platform') === 'bigcommerce.catalyst', + channelId: meta('channel_id'), + }; + } catch (error) { + return { ok: false, status: 0, error: error.message }; + } +} + +function loadPlaywright() { + try { + return requireFromApp('@playwright/test'); + } catch { + return null; + } +} + +// --------------------------------------------------------------------------------------------- +// doctor: read-only "is this instance worth driving?" + +async function doctor(values) { + const rows = []; + const add = (level, check, detail) => rows.push({ level, check, detail }); + const { monorepo } = layout(); + const pkg = JSON.parse(readFileSync(join(APP_DIR, 'package.json'), 'utf8')); + + add( + 'PASS', + 'storefront', + `${pkg.name}@${pkg.version} at ${APP_DIR} (${monorepo ? 'monorepo' : 'standalone project'})`, + ); + + const wantedNode = pkg.engines?.node?.match(/(\d+)/)?.[1]; + const haveNode = Number(process.versions.node.split('.')[0]); + + add( + wantedNode && haveNode < Number(wantedNode) ? 'FAIL' : 'PASS', + 'node', + `v${process.versions.node}${wantedNode ? ` (needs >=${wantedNode})` : ''}`, + ); + + add( + existsSync(join(APP_DIR, 'node_modules', 'next')) ? 'PASS' : 'FAIL', + 'dependencies', + existsSync(join(APP_DIR, 'node_modules', 'next')) ? 'installed' : 'run `pnpm install` first', + ); + + if (monorepo) { + const clientDist = join(dirname(APP_DIR), 'packages', 'client', 'dist'); + + add( + existsSync(clientDist) ? 'PASS' : 'WARN', + 'catalyst-client build', + existsSync(clientDist) + ? 'packages/client/dist present' + : '`launch` will build it (pnpm --filter @bigcommerce/catalyst-client build)', + ); + } + + const envFile = join(APP_DIR, '.env.local'); + + if (!existsSync(envFile)) { + const main = mainCheckoutAppDir(); + const hint = + main && existsSync(join(main, '.env.local')) + ? `this is a git worktree; copy it from the main checkout: ${join(main, '.env.local')}` + : 'create it from .env.example (or run `catalyst project link` / the Catalyst CLI)'; + + add('FAIL', '.env.local', `missing — ${hint}`); + } else { + const env = { ...parseEnvFile(envFile), ...process.env }; + const missing = REQUIRED_ENV.filter((key) => !env[key]); + + add( + missing.length ? 'FAIL' : 'PASS', + '.env.local', + missing.length ? `empty: ${missing.join(', ')}` : 'required keys set (values not shown)', + ); + + if (pkg.dependencies?.['@makeswift/runtime'] && !env.MAKESWIFT_SITE_API_KEY) { + add('FAIL', 'makeswift', 'MAKESWIFT_SITE_API_KEY is empty (this storefront uses Makeswift)'); + } + + const testEnv = parseEnvFile(join(APP_DIR, '.env.test.local')); + + add( + testEnv.TEST_CUSTOMER_EMAIL ? 'PASS' : 'WARN', + 'test customer', + testEnv.TEST_CUSTOMER_EMAIL + ? '.env.test.local has TEST_CUSTOMER_EMAIL' + : 'no .env.test.local TEST_CUSTOMER_* — signed-in journeys unavailable', + ); + } + + const playwright = loadPlaywright(); + + if (!playwright) { + add( + 'FAIL', + 'playwright', + '@playwright/test not resolvable from the storefront — `pnpm add -D @playwright/test`', + ); + } else { + const exe = playwright.chromium.executablePath(); + + add( + existsSync(exe) ? 'PASS' : 'FAIL', + 'chromium', + existsSync(exe) + ? 'installed' + : `missing — run \`npx playwright install chromium\`${process.platform === 'linux' ? ' (add --with-deps on a fresh Linux box)' : ''}`, + ); + } + + add( + has('ffmpeg') ? 'PASS' : 'WARN', + 'ffmpeg', + has('ffmpeg') ? 'available (GIF/MP4 from video)' : `optional, for GIF/MP4: ${ffmpegHint()}`, + ); + + const gh = has('gh') ? ghVersion() : null; + const ghAuthed = gh && run('gh', ['auth', 'status']).ok; + const ghMin = GH_ATTACH_MIN.join('.'); + + if (!gh) { + add('WARN', 'gh', `not installed — install GitHub CLI ${ghMin}+ to upload evidence to PRs`); + } else if (!supportsAttach(gh)) { + add( + 'WARN', + 'gh', + `${gh.join('.')} is too old for \`--attach\` — upgrade to ${ghMin}+ (${ghUpgradeHint()})`, + ); + } else if (!ghAuthed) { + add('WARN', 'gh', `${gh.join('.')} installed but not authenticated — run \`gh auth login\``); + } else { + add('PASS', 'gh', `${gh.join('.')} authenticated (publish uploads straight to the PR)`); + } + + const state = readState(); + + if (state) { + const alive = isAlive(state.pid); + + add( + alive ? 'PASS' : 'WARN', + 'launched server', + alive + ? `pid ${state.pid} on ${state.url} (${state.mode})` + : `stale state for pid ${state.pid} — run \`stop\``, + ); + } + + const url = resolveBaseURL(values); + + if (url) { + const result = await probe(url); + + if (!result.ok) + add('FAIL', 'target', `${url} not responding (${result.status || result.error})`); + else if (!result.catalyst) + add( + 'FAIL', + 'target', + `${url} responded but is not a Catalyst storefront (no platform meta tag)`, + ); + else add('PASS', 'target', `${url} is Catalyst (channel ${result.channelId ?? '?'})`); + } else { + add('WARN', 'target', 'no server — run `launch`, or pass --url for one you started yourself'); + } + + const width = Math.max(...rows.map((row) => row.check.length)); + + for (const row of rows) { + console.log(`${row.level.padEnd(4)} ${row.check.padEnd(width)} ${row.detail}`); + } + + if (rows.some((row) => row.level === 'FAIL')) process.exitCode = 1; +} + +function ghUpgradeHint() { + if (process.platform === 'darwin') return '`brew upgrade gh`'; + if (IS_WINDOWS) return '`winget upgrade --id GitHub.cli`'; + + return 'your package manager, or https://github.com/cli/cli/releases'; +} + +function ffmpegHint() { + if (process.platform === 'darwin') return '`brew install ffmpeg`'; + if (IS_WINDOWS) return '`winget install Gyan.FFmpeg`'; + + return '`sudo apt-get install ffmpeg` (or your distro equivalent)'; +} + +// --------------------------------------------------------------------------------------------- +// launch / stop + +async function launch(values) { + const existing = readState(); + + if (existing && isAlive(existing.pid)) { + console.log( + `Already running: pid ${existing.pid} at ${existing.url} (run \`stop\` first to relaunch)`, + ); + + return; + } + + if (!existsSync(join(APP_DIR, '.env.local'))) + fail('.env.local is missing — run `doctor` for the fix.'); + + const port = Number(values.port ?? DEFAULT_PORT); + + if (!(await portIsFree(port))) { + fail( + `Port ${port} is in use. Pick another with --port, or drive the server already there with --url http://localhost:${port}.`, + ); + } + + const { monorepo } = layout(); + + if (monorepo && !existsSync(join(dirname(APP_DIR), 'packages', 'client', 'dist'))) { + console.log('Building @bigcommerce/catalyst-client (monorepo only)…'); + + const build = run('pnpm', ['--filter', '@bigcommerce/catalyst-client', 'build'], { + cwd: dirname(APP_DIR), + shim: true, + stdio: 'inherit', + }); + + if (!build.ok) fail('catalyst-client build failed.'); + } + + mkdirSync(EVIDENCE_DIR, { recursive: true }); + + const logFile = join(EVIDENCE_DIR, 'server.log'); + const node = process.execPath; + const envArgs = ['--env-file-if-exists=.env.local']; + + if (existsSync(join(APP_DIR, 'scripts', 'generate.cjs'))) { + console.log('Generating GraphQL types (scripts/generate.cjs)…'); + + const generate = run(node, [...envArgs, 'scripts/generate.cjs'], { stdio: 'inherit' }); + + if (!generate.ok) + fail('GraphQL generation failed — check the store credentials in .env.local.'); + } + + const nextBin = requireFromApp.resolve('next/dist/bin/next'); + const mode = values.prod ? 'prod' : 'dev'; + + if (mode === 'prod') { + console.log('Building production bundle (next build)…'); + + const build = run(node, [nextBin, 'build'], { stdio: 'inherit' }); + + if (!build.ok) fail('next build failed.'); + } + + const out = openSync(logFile, 'w'); + const child = spawn(node, [nextBin, mode === 'prod' ? 'start' : 'dev', '--port', String(port)], { + cwd: APP_DIR, + detached: true, + windowsHide: true, + stdio: ['ignore', out, out], + env: { ...process.env, NEXT_TELEMETRY_DISABLED: '1', PORT: String(port) }, + }); + + child.unref(); + closeSync(out); + + const url = `http://localhost:${port}`; + + writeFileSync( + STATE_FILE, + JSON.stringify( + { pid: child.pid, port, url, mode, logFile, startedAt: new Date().toISOString() }, + null, + 2, + ), + ); + + console.log(`Started next ${mode} (pid ${child.pid}); log: ${logFile}`); + console.log( + `Waiting for ${url} to serve a Catalyst page (first dev compile can take a few minutes)…`, + ); + + const deadline = Date.now() + READY_TIMEOUT_MS; + + while (Date.now() < deadline) { + if (!isAlive(child.pid)) { + const tail = readFileSync(logFile, 'utf8').split(/\r?\n/).slice(-30).join('\n'); + + rmSync(STATE_FILE, { force: true }); + fail(`Server exited during startup. Last log lines:\n${tail}`); + } + + const result = await probe(url); + + if (result.ok && result.catalyst) { + console.log(`\n✔ Ready: ${url} (channel ${result.channelId ?? '?'})`); + + return; + } + + await new Promise((done) => setTimeout(done, 3000)); + } + + fail(`Timed out waiting for ${url}. Inspect ${logFile}, then run \`stop\`.`); +} + +function killTree(pid) { + if (IS_WINDOWS) { + run('taskkill', ['/pid', String(pid), '/T', '/F']); + + return; + } + + try { + // `launch` starts the server as a process-group leader, so this reaches its children too. + process.kill(-pid, 'SIGTERM'); + } catch { + try { + process.kill(pid, 'SIGTERM'); + } catch { + // already gone + } + } +} + +async function stop() { + const state = readState(); + + if (!state) { + console.log( + 'Nothing to stop: no server was launched by this skill. (It never stops servers it did not start.)', + ); + + return; + } + + if (isAlive(state.pid)) { + killTree(state.pid); + + for (let i = 0; i < 20 && isAlive(state.pid); i++) { + await new Promise((done) => setTimeout(done, 250)); + } + + if (isAlive(state.pid) && !IS_WINDOWS) process.kill(-state.pid, 'SIGKILL'); + } + + rmSync(STATE_FILE, { force: true }); + console.log( + `Stopped pid ${state.pid} (${state.url}). Evidence in ${EVIDENCE_DIR} was left in place.`, + ); +} + +// --------------------------------------------------------------------------------------------- +// Browser helpers shared by explore and capture + +// Hide the Next.js dev-mode indicator so it does not appear in evidence. +const HIDE_DEV_OVERLAY = ` + addEventListener('DOMContentLoaded', () => { + const style = document.createElement('style'); + style.textContent = 'nextjs-portal { display: none !important; }'; + document.head.appendChild(style); + }); +`; + +async function openBrowser(playwright, device, extra = {}) { + const browser = await playwright.chromium.launch({ headless: !process.env.VERIFY_HEADED }); + const context = await browser.newContext({ ...VIEWPORTS[device], ...extra }); + + await context.addInitScript(HIDE_DEV_OVERLAY); + + return { browser, context }; +} + +function requireBaseURL(values) { + const url = resolveBaseURL(values); + + if (!url) fail('No target server. Run `launch` first, or pass --url.'); + + return url; +} + +// explore: print the ARIA snapshot of a page so stable handles can be chosen. +async function explore(values, positionals) { + const playwright = + loadPlaywright() ?? fail('@playwright/test is not installed in the storefront.'); + const baseURL = requireBaseURL(values); + const device = values.device ?? 'desktop'; + const target = new URL(positionals[0] ?? '/', `${baseURL}/`).toString(); + const { browser, context } = await openBrowser(playwright, device); + + try { + const page = await context.newPage(); + + await page.goto(target, { waitUntil: 'networkidle', timeout: 120_000 }).catch(() => undefined); + console.log(`# ${page.url()} — ${await page.title()}\n`); + console.log( + await page + .locator(values.selector ?? 'body') + .first() + .ariaSnapshot(), + ); + + if (values.screenshot) { + await page.screenshot({ path: values.screenshot, fullPage: true }); + console.log(`\nScreenshot: ${resolve(values.screenshot)}`); + } + } finally { + await browser.close(); + } +} + +// --------------------------------------------------------------------------------------------- +// capture: run a journey and keep the evidence + +async function capture(values, positionals) { + const journeyPath = positionals[0] + ? resolve(positionals[0]) + : fail('Usage: capture '); + + if (!existsSync(journeyPath)) fail(`Journey not found: ${journeyPath}`); + + const playwright = + loadPlaywright() ?? fail('@playwright/test is not installed in the storefront.'); + const baseURL = requireBaseURL(values); + const health = await probe(baseURL); + + if (!health.ok || !health.catalyst) fail(`${baseURL} is not serving Catalyst — run \`doctor\`.`); + + const journey = await import(pathToFileURL(journeyPath).href); + const meta = journey.meta ?? {}; + const device = values.device ?? meta.device ?? 'desktop'; + + if (!VIEWPORTS[device]) + fail(`Unknown device "${device}" (use ${Object.keys(VIEWPORTS).join(', ')}).`); + + const name = slugify(values.name ?? meta.name ?? basename(journeyPath, extname(journeyPath))); + const label = values.label ? `-${slugify(values.label)}` : ''; + const runId = `${timestamp()}-${name}${label}-${device}`; + const runDir = join(EVIDENCE_DIR, 'runs', runId); + const videoTmp = join(runDir, '.video'); + + mkdirSync(videoTmp, { recursive: true }); + copyFileSync(journeyPath, join(runDir, 'journey.mjs')); + + const { browser, context } = await openBrowser(playwright, device, { + baseURL, + recordVideo: { dir: videoTmp, size: VIEWPORTS[device].viewport }, + }); + + await context.tracing.start({ screenshots: true, snapshots: true }); + + const page = await context.newPage(); + // Recording starts on about:blank; note when the first page has loaded so the MP4 and GIF can + // skip the blank lead-in (otherwise their first frame, GitHub's poster, is pure white). + const recordingStarted = Date.now(); + let firstLoad = null; + + page.once('load', () => { + firstLoad = Date.now(); + }); + + const consoleErrors = []; + const failedRequests = []; + const steps = []; + const origin = new URL(baseURL).origin; + + page.on( + 'console', + (msg) => msg.type() === 'error' && consoleErrors.push(msg.text().slice(0, 500)), + ); + page.on('pageerror', (error) => consoleErrors.push(`pageerror: ${error.message.slice(0, 500)}`)); + page.on('response', (response) => { + if (response.status() >= 400 && response.url().startsWith(origin)) { + failedRequests.push(`${response.status()} ${response.request().method()} ${response.url()}`); + } + }); + + const step = async (stepLabel, action, opts = {}) => { + const n = String(steps.length + 1).padStart(2, '0'); + const file = `${n}-${slugify(stepLabel)}.png`; + const record = { n: steps.length + 1, label: stepLabel, status: 'passed', screenshot: file }; + + steps.push(record); + console.log(` ${n}. ${stepLabel}`); + + try { + if (action) await action(); + await page.waitForLoadState('networkidle', { timeout: 10_000 }).catch(() => undefined); + } catch (error) { + record.status = 'failed'; + record.error = error.message.split('\n').slice(0, 6).join('\n'); + record.screenshot = file.replace(/\.png$/, '-FAILED.png'); + } finally { + record.url = page.url(); + await page + .screenshot({ path: join(runDir, record.screenshot), fullPage: opts.fullPage === true }) + .catch(() => undefined); + } + + if (record.status === 'failed') { + const error = new Error(`Step "${stepLabel}" failed: ${record.error}`); + + error.stepFailure = true; + throw error; + } + }; + + const started = Date.now(); + let status = 'passed'; + let failure = null; + + console.log(`Capturing "${meta.title ?? name}" on ${baseURL} (${device})`); + + try { + await journey.default({ + page, + context, + baseURL, + step, + expect: playwright.expect, + env: { ...parseEnvFile(join(APP_DIR, '.env.test.local')) }, + }); + } catch (error) { + status = 'failed'; + failure = error.stepFailure ? error.message : error.stack; + } + + await context.tracing.stop({ path: join(runDir, 'trace.zip') }); + + const video = page.video(); + + await context.close(); + await browser.close(); + + const files = []; + + if (video) { + renameSync(await video.path(), join(runDir, 'video.webm')); + files.push('video.webm'); + + if (has('ffmpeg')) { + const input = join(runDir, 'video.webm'); + const skip = firstLoad ? ((firstLoad - recordingStarted) / 1000).toFixed(2) : '0'; + const mp4 = run('ffmpeg', [ + '-y', + '-loglevel', + 'error', + '-i', + input, + '-ss', + skip, + '-c:v', + 'libx264', + '-pix_fmt', + 'yuv420p', + '-movflags', + '+faststart', + join(runDir, 'video.mp4'), + ]); + const gif = run('ffmpeg', [ + '-y', + '-loglevel', + 'error', + '-i', + input, + '-ss', + skip, + '-vf', + // Fit inside 800×600 so portrait (mobile) recordings stay a reasonable size. + 'fps=8,scale=800:600:force_original_aspect_ratio=decrease:flags=lanczos,split[a][b];[a]palettegen[p];[b][p]paletteuse', + join(runDir, 'video.gif'), + ]); + + if (mp4.ok) files.push('video.mp4'); + if (gif.ok) files.push('video.gif'); + } + } + + rmSync(videoTmp, { recursive: true, force: true }); + + const manifest = { + runId, + title: meta.title ?? name, + feature: meta.feature ?? null, + label: values.label ?? null, + status, + failure, + baseURL, + device, + viewport: VIEWPORTS[device].viewport, + git: gitInfo(), + platform: `${process.platform}-${process.arch}`, + startedAt: new Date(started).toISOString(), + durationMs: Date.now() - started, + steps, + consoleErrors, + failedRequests, + files: [...files, 'trace.zip', 'journey.mjs'], + }; + + writeFileSync(join(runDir, 'manifest.json'), JSON.stringify(manifest, null, 2)); + writeFileSync( + join(runDir, 'summary.md'), + renderMarkdown(manifest, (file) => file), + ); + + console.log( + `\n${status === 'passed' ? '✔' : '✖'} ${status.toUpperCase()} — evidence in ${runDir}`, + ); + if (failure) console.log(`\n${failure}`); + if (consoleErrors.length) + console.log(`\n⚠ ${consoleErrors.length} console error(s) recorded in manifest.json`); + if (status !== 'passed') process.exitCode = 1; +} + +// Display widths for the PR. GitHub scales images to the comment column (~880px), which blows a +// portrait (mobile) capture up to several screens tall, so size by orientation instead. +const DISPLAY = { + landscape: { recording: 720, screenshot: 720 }, + portrait: { recording: 280, screenshot: 180 }, +}; + +function img(src, alt, width) { + return `${alt.replace(/`; +} + +function renderMarkdown(manifest, urlFor, { attach = false } = {}) { + const lines = []; + const icon = manifest.status === 'passed' ? '✅' : '❌'; + const sha = manifest.git.sha ? manifest.git.sha.slice(0, 10) : 'unknown'; + const { width, height } = manifest.viewport; + const portrait = height > width; + const size = DISPLAY[portrait ? 'portrait' : 'landscape']; + + const tags = [manifest.device, manifest.label].filter(Boolean).join(', '); + const dirtyFiles = manifest.git.dirtyFiles ?? []; + const dirtyNote = dirtyFiles.length + ? ` + uncommitted changes to ${dirtyFiles + .slice(0, 3) + .map((file) => `\`${file}\``) + .join(', ')}${dirtyFiles.length > 3 ? ` and ${dirtyFiles.length - 3} more` : ''}` + : ''; + + lines.push(`### ${icon} ${manifest.title} (${tags})`); + lines.push(''); + lines.push( + `\`${sha}\`${dirtyNote} · ${manifest.device} ${width}×${height} · ${manifest.platform} · ${(manifest.durationMs / 1000).toFixed(1)}s`, + ); + lines.push(''); + + if (manifest.failure) lines.push('```', manifest.failure, '```', ''); + + const videoFile = manifest.files.includes('video.mp4') ? 'video.mp4' : 'video.webm'; + + if (attach) { + // A bare attachment URL on its own line renders as GitHub's video player. + if (manifest.files.includes(videoFile)) lines.push(urlFor(videoFile), ''); + } else { + if (manifest.files.includes('video.gif')) { + lines.push(img(urlFor('video.gif'), 'Recording', size.recording), ''); + } + + if (manifest.files.includes(videoFile)) { + lines.push( + `🎥 [Full recording (${videoFile.split('.')[1]})](${urlFor(videoFile)}) · 🔍 [Playwright trace](${urlFor('trace.zip')}) (\`npx playwright show-trace trace.zip\`)`, + '', + ); + } + } + + lines.push('| # | Step | Result |', '|---|---|---|'); + + for (const s of manifest.steps) { + lines.push( + `| ${s.n} | ${s.label} | ${s.status === 'passed' ? '✅' : `❌ ${s.error?.split('\n')[0] ?? ''}`} |`, + ); + } + + lines.push(''); + lines.push('
Screenshots', ''); + + if (portrait) { + // Narrow captures read best side by side, as a filmstrip. + lines.push( + `| ${manifest.steps.map((s) => `${s.n}. ${s.label}`).join(' | ')} |`, + `|${manifest.steps.map(() => '---').join('|')}|`, + `| ${manifest.steps.map((s) => img(urlFor(s.screenshot), s.label, size.screenshot)).join(' | ')} |`, + '', + ); + } else { + for (const s of manifest.steps) { + lines.push( + `**${s.n}. ${s.label}**`, + '', + img(urlFor(s.screenshot), s.label, size.screenshot), + '', + ); + } + } + + lines.push('
', ''); + + if (manifest.consoleErrors.length || manifest.failedRequests.length) { + lines.push('
Console errors / failed requests', '', '```'); + lines.push(...manifest.consoleErrors, ...manifest.failedRequests); + lines.push('```', '
', ''); + } + + return lines.join('\n'); +} + +// --------------------------------------------------------------------------------------------- +// publish: upload a run's evidence and write PR-ready markdown + +// `gh` 2.99.0 added `--attach` to `gh pr create|edit|comment`, which uploads images and videos as +// native GitHub attachments: videos play inline and access follows the repository. GitHub only +// accepts attachments from accounts with write access to the repository, so contributors +// opening a PR from a fork upload elsewhere and post the markdown instead. +const GH_ATTACH_MIN = [2, 99, 0]; +const ATTACH_LIMIT = 50; +const EVIDENCE_MARKER = ''; +const UPLOAD_START = ''; +const UPLOAD_END = ''; + +function ghVersion() { + const match = run('gh', ['--version']).stdout.match(/gh version (\d+)\.(\d+)\.(\d+)/); + + return match ? match.slice(1, 4).map(Number) : null; +} + +function supportsAttach(version) { + if (!version) return false; + + for (let i = 0; i < 3; i++) { + if (version[i] !== GH_ATTACH_MIN[i]) return version[i] > GH_ATTACH_MIN[i]; + } + + return true; +} + +function resolvePr(values) { + const view = run('gh', [ + 'pr', + 'view', + ...(values.pr ? [values.pr] : []), + '--json', + 'url', + '--jq', + '.url', + ]); + + return view.ok ? view.stdout : (values.pr ?? null); +} + +function prRepo(prUrl) { + const match = prUrl?.match(/github\.com\/([^/]+)\/([^/]+)\/pull\/\d+/); + + return match ? { owner: match[1], repo: match[2] } : null; +} + +function repoAccess({ owner, repo }) { + const view = run('gh', [ + 'repo', + 'view', + `${owner}/${repo}`, + '--json', + 'visibility,viewerPermission', + ]); + + return view.ok ? JSON.parse(view.stdout) : {}; +} + +function githubSlug(remote) { + const url = git(['remote', 'get-url', remote]).stdout; + const match = url.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?$/); + + return match ? { owner: match[1], repo: match[2] } : null; +} + +function latestRunDir() { + const runsDir = join(EVIDENCE_DIR, 'runs'); + + if (!existsSync(runsDir)) return null; + + const runs = readdirSync(runsDir) + .map((entry) => join(runsDir, entry)) + .filter((entry) => statSync(entry).isDirectory()) + .sort(); + + return runs.at(-1) ?? null; +} + +// Media for the PR. The MP4 supersedes the WebM (and the GIF, where video plays inline). +function mediaFiles(manifest, { inlineVideo }) { + const files = []; + const video = ['video.mp4', 'video.webm'].find((file) => manifest.files.includes(file)); + + if (video) files.push(video); + if (!inlineVideo && manifest.files.includes('video.gif')) files.push('video.gif'); + + return [...files, ...manifest.steps.map((s) => s.screenshot)]; +} + +function uploadToBranch(runs, remote) { + const slug = githubSlug(remote) ?? fail(`Remote "${remote}" is not a GitHub remote.`); + const branch = `verification-evidence/${slugify(runs[0].manifest.git.branch || 'detached')}`; + const index = join(mkdtempSync(join(tmpdir(), 'verify-index-')), 'index'); + const env = { ...process.env, GIT_INDEX_FILE: index }; + const fetched = git(['fetch', '--quiet', remote, `refs/heads/${branch}`]); + const parent = fetched.ok ? git(['rev-parse', 'FETCH_HEAD']).stdout : null; + + git(parent ? ['read-tree', parent] : ['read-tree', '--empty'], { env }); + + for (const r of runs) { + for (const file of [...mediaFiles(r.manifest, { inlineVideo: false }), 'trace.zip']) { + if (!existsSync(join(r.dir, file))) continue; + + const blob = git(['hash-object', '-w', join(r.dir, file)]).stdout; + + git(['update-index', '--add', '--cacheinfo', `100644,${blob},${r.manifest.runId}/${file}`], { + env, + }); + } + } + + const tree = git(['write-tree'], { env }).stdout; + const commit = git( + ['commit-tree', tree, ...(parent ? ['-p', parent] : []), '-m', 'verification evidence'], + { env }, + ); + + rmSync(dirname(index), { recursive: true, force: true }); + + if (!commit.ok) fail(`git commit-tree failed: ${commit.stderr}`); + + const push = git(['push', '--quiet', remote, `${commit.stdout}:refs/heads/${branch}`]); + + if (!push.ok) fail(`Pushing ${branch} to ${remote} failed: ${push.stderr}`); + + console.log( + `Uploaded evidence to ${remote}/${branch} (outside the PR branch; the diff is untouched).`, + ); + + return (r) => (file) => + `https://github.com/${slug.owner}/${slug.repo}/raw/${commit.stdout}/${r.manifest.runId}/${file}`; +} + +function uploadToGist(runs) { + const login = + run('gh', ['api', 'user', '--jq', '.login']).stdout || fail('`gh` is not authenticated.'); + const tmp = mkdtempSync(join(tmpdir(), 'verify-gist-')); + const readme = join(tmp, '00-verification.md'); + const title = runs.map((r) => r.manifest.runId).join(', '); + + writeFileSync(readme, `Catalyst verification evidence: ${title}\n`); + + const created = run('gh', [ + 'gist', + 'create', + readme, + '--desc', + `Catalyst verification: ${title}`, + ]); + const id = created.stdout.match(/gist\.github\.com\/(?:[^/]+\/)?([0-9a-f]+)/)?.[1]; + + if (!created.ok || !id) fail(`gh gist create failed: ${created.stderr}`); + + // Gists are flat git repositories; binaries cannot go through `gh gist create`, but they can be + // pushed. Prefix each file with its device so runs do not collide. + const clone = join(tmp, 'gist'); + const cloned = git(['clone', '--quiet', `https://gist.github.com/${id}.git`, clone]); + + if (!cloned.ok) fail(`Cloning the gist failed (try \`gh auth setup-git\`): ${cloned.stderr}`); + + const name = (r, file) => + `${r.manifest.device}${r.manifest.label ? `-${r.manifest.label}` : ''}-${file}`; + + for (const r of runs) { + for (const file of [...mediaFiles(r.manifest, { inlineVideo: false }), 'trace.zip']) { + if (existsSync(join(r.dir, file))) + copyFileSync(join(r.dir, file), join(clone, name(r, file))); + } + } + + git(['add', '.'], { cwd: clone }); + git(['commit', '--quiet', '-m', 'verification evidence'], { cwd: clone }); + + const push = git(['push', '--quiet'], { cwd: clone }); + + if (!push.ok) fail(`Pushing to the gist failed (try \`gh auth setup-git\`): ${push.stderr}`); + + const sha = git(['rev-parse', 'HEAD'], { cwd: clone }).stdout; + + rmSync(tmp, { recursive: true, force: true }); + console.log(`Uploaded evidence to secret gist https://gist.github.com/${login}/${id}`); + + return (r) => (file) => + `https://gist.githubusercontent.com/${login}/${id}/raw/${sha}/${name(r, file)}`; +} + +function chooseDestination(values, prUrl) { + const remote = values.remote ?? 'origin'; + const version = has('gh') ? ghVersion() : null; + const authed = version && run('gh', ['auth', 'status']).ok; + + if (!authed) { + console.log( + `gh ${GH_ATTACH_MIN.join('.')}+ is not installed and signed in, so evidence cannot be uploaded from the CLI.`, + ); + + return 'manual'; + } + + const target = prRepo(prUrl) ?? githubSlug(remote); + const access = target ? repoAccess(target) : {}; + const canWrite = ['ADMIN', 'MAINTAIN', 'WRITE'].includes(access.viewerPermission); + + if (canWrite && supportsAttach(version)) return 'attach'; + + if (!supportsAttach(version)) { + console.log( + `gh ${version.join('.')} predates --attach; upgrade to ${GH_ATTACH_MIN.join('.')}+ (${ghUpgradeHint()}) to upload straight to the PR.`, + ); + } else { + console.log( + `No write access to ${target.owner}/${target.repo} (a fork contribution?), and GitHub only takes --attach uploads from writers.`, + ); + } + + // Secret gists are unlisted but readable by anyone with the link, so they are only used when + // GitHub confirms the repository is public. A private repository's evidence goes to a branch, + // where GitHub's access control applies. If the visibility lookup failed, fail closed: do not + // guess, and leave the upload to the user (or an explicit `--to gist`). + if (access.visibility === 'PUBLIC') return 'gist'; + if (access.visibility) return 'branch'; + + console.log( + `Could not read the visibility of ${target ? `${target.owner}/${target.repo}` : 'the repository'}, so evidence is not uploaded automatically. Pass --to gist if you know it is public.`, + ); + + return 'manual'; +} + +function publish(values, positionals) { + const dirs = positionals.length ? positionals.map((p) => resolve(p)) : [latestRunDir()]; + const runs = dirs.map((dir) => { + if (!dir || !existsSync(join(dir, 'manifest.json'))) { + fail(`No run at ${dir ?? EVIDENCE_DIR} — run \`capture\` first.`); + } + + return { dir, manifest: JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')) }; + }); + const cwd = dirname(runs[0].dir); + + if (runs.some((r) => dirname(r.dir) !== cwd)) fail('Publish runs from the same directory.'); + + const pr = resolvePr(values); + let to = values.to ?? 'auto'; + + if (to === 'auto') { + to = chooseDestination(values, pr); + console.log(`--to auto → ${to}`); + } + + const attach = to === 'attach'; + const local = (r) => (file) => `./${basename(r.dir)}/${file}`; + const urlsFor = + to === 'gist' + ? uploadToGist(runs) + : to === 'branch' + ? uploadToBranch(runs, values.remote ?? 'origin') + : local; + const render = (urlFor) => + runs + .map((r) => renderMarkdown(r.manifest, urlFor(r), { attach })) + .join('\n') + .concat( + attach + ? '\nRecorded with the verify-catalyst skill. Playwright traces stay local: `npx playwright show-trace /trace.zip`.\n' + : '\nRecorded with the verify-catalyst skill.\n', + ); + // `gh --attach` only rewrites markdown references (`![alt](./path)`), not sized `` tags. + // So attach mode posts plain references first, then rewrites them into the final layout. + const refs = attach + ? runs.flatMap((r) => + mediaFiles(r.manifest, { inlineVideo: true }).map((file) => local(r)(file)), + ) + : []; + const evidence = attach + ? `${UPLOAD_START}\n\n${refs.map((ref) => `![${ref}](${ref})`).join('\n\n')}\n\n${UPLOAD_END}` + : render(urlsFor); + const bodyFile = join(cwd, `pr-evidence-${timestamp()}.md`); + + if (to === 'manual') { + writeFileSync(bodyFile, evidence); + console.log( + `Drag the MP4s and screenshots from\n ${runs.map((r) => r.dir).join('\n ')}\ninto a comment on the PR at github.com (GitHub hosts them and plays MP4 inline).\nA text skeleton is in ${bodyFile}.`, + ); + + return; + } + + const into = values.into ?? 'comment'; + let args; + + if (into === 'body') { + const current = pr ? run('gh', ['pr', 'view', pr, '--json', 'body', '--jq', '.body']) : null; + const body = current?.ok ? current.stdout : ''; + + writeFileSync( + bodyFile, + body.includes(EVIDENCE_MARKER) + ? body.replace(EVIDENCE_MARKER, `\n\n${evidence}\n`) + : `${body}\n\n## Verification evidence\n\n${evidence}`, + ); + args = ['pr', 'edit', pr ?? '', '--body-file', bodyFile]; + } else { + writeFileSync(bodyFile, evidence); + args = ['pr', 'comment', pr ?? '', '--body-file', bodyFile]; + } + + if (attach) { + if (refs.length > ATTACH_LIMIT) { + fail( + `${refs.length} files exceed gh's ${ATTACH_LIMIT}-attachment limit; publish fewer runs at once.`, + ); + } + + for (const file of refs) args.push('--attach', file); + } + + const printable = `gh ${args.map((a) => (/[\s<>]/.test(a) ? `"${a}"` : a)).join(' ')}`; + + if (!pr || values['dry-run']) { + if (!pr) console.log('No pull request found for this branch; pass --pr .'); + console.log(`Evidence markdown: ${bodyFile}\nFrom ${cwd}, run:\n ${printable}`); + + return; + } + + const result = run('gh', args, { cwd }); + + if (!result.ok) { + fail( + `gh ${args[0]} ${args[1]} failed: ${result.stderr || result.stdout}\nFrom ${cwd}, retry with:\n ${printable}`, + ); + } + + if (attach) layOutAttachments({ pr, into, posted: result.stdout, refs, render, local, bodyFile }); + + console.log( + `Posted evidence to ${into === 'body' ? 'the body of' : 'a comment on'} ${pr}\n${result.stdout}`, + ); +} + +// Second pass of attach mode: read back the URLs `gh` uploaded (in reference order) and replace +// the plain references with the sized layout. Editing text needs no attachment rights. +function layOutAttachments({ pr, into, posted, refs, render, local, bodyFile }) { + const repo = prRepo(pr); + const commentId = posted.match(/#issuecomment-(\d+)/)?.[1]; + const read = + into === 'body' + ? run('gh', ['pr', 'view', pr, '--json', 'body', '--jq', '.body']) + : run('gh', [ + 'api', + `repos/${repo.owner}/${repo.repo}/issues/comments/${commentId}`, + '--jq', + '.body', + ]); + const text = read.stdout; + const start = text.indexOf(UPLOAD_START); + const end = text.indexOf(UPLOAD_END); + const warn = (why) => + console.log(`⚠ Uploaded, but ${why}; the PR shows unsized images. Edit it by hand if needed.`); + + if (!read.ok || start < 0 || end < 0) return warn('could not read the post back'); + + // Images keep their `![alt](url)` form; a video becomes a bare URL on its own line. + const urls = [ + ...text.slice(start, end).matchAll(/!\[[^\]]*\]\((https:\/\/[^)\s]+)\)|^(https:\/\/\S+)$/gm), + ].map((m) => m[1] ?? m[2]); + + if (urls.length !== refs.length) return warn(`found ${urls.length} of ${refs.length} uploads`); + + const uploaded = new Map(refs.map((ref, i) => [ref, urls[i]])); + const final = render((r) => (file) => uploaded.get(local(r)(file)) ?? local(r)(file)); + + writeFileSync(bodyFile, `${text.slice(0, start)}${final}${text.slice(end + UPLOAD_END.length)}`); + + const update = + into === 'body' + ? run('gh', ['pr', 'edit', pr, '--body-file', bodyFile]) + : run('gh', [ + 'api', + '-X', + 'PATCH', + `repos/${repo.owner}/${repo.repo}/issues/comments/${commentId}`, + '-F', + `body=@${bodyFile}`, + ]); + + if (!update.ok) warn(`the layout edit failed (${update.stderr})`); +} + +// --------------------------------------------------------------------------------------------- + +const HELP = `Usage: node /scripts/verify.mjs [options] + + doctor [--url URL] Read-only health check of tools, env, and the target + launch [--port ${DEFAULT_PORT}] [--prod] Start a storefront for verification and wait until it is ready + stop Stop the server started by \`launch\` (never anything else) + explore [path] [--selector css] [--device d] [--screenshot file] + Print the ARIA snapshot of a page to find stable handles + capture [--device desktop|tablet|mobile] [--label before|after] [--name slug] [--url URL] + Run a journey; record video, screenshots, and a trace + publish [run-dir ...] [--pr ] [--into comment|body] [--dry-run] + [--to auto|attach|gist|branch|manual] [--remote origin] + Upload runs to the pull request (gh 2.99.0+ --attach) + + --url defaults to the server started by \`launch\`. Evidence lives in ${relative(process.cwd(), EVIDENCE_DIR) || '.verification'}/runs/. + Set VERIFY_HEADED=1 to watch the browser.`; + +const { values, positionals } = parseArgs({ + allowPositionals: true, + options: { + url: { type: 'string' }, + port: { type: 'string' }, + prod: { type: 'boolean' }, + device: { type: 'string' }, + label: { type: 'string' }, + name: { type: 'string' }, + selector: { type: 'string' }, + screenshot: { type: 'string' }, + to: { type: 'string' }, + remote: { type: 'string' }, + pr: { type: 'string' }, + into: { type: 'string' }, + 'dry-run': { type: 'boolean' }, + help: { type: 'boolean', short: 'h' }, + }, +}); + +const [command, ...rest] = positionals; +const commands = { doctor, launch, stop, explore, capture, publish }; + +if (!command || values.help || !commands[command]) { + console.log(HELP); + process.exit(command && !values.help ? 1 : 0); +} + +await commands[command](values, rest); diff --git a/core/.gitignore b/core/.gitignore index 5d7da0f5f9..191bd9ab15 100644 --- a/core/.gitignore +++ b/core/.gitignore @@ -62,3 +62,6 @@ build-config.json # written by `npm run generate`. Commit them, so lint, typecheck and editor # tooling work without store credentials. See "GraphQL Schema and Types" in # README.md before adding them here. + +# Verification evidence (see .agents/skills/verify-catalyst) +/.verification diff --git a/core/AGENTS.md b/core/AGENTS.md index 9c419ba898..3dd427eaec 100644 --- a/core/AGENTS.md +++ b/core/AGENTS.md @@ -273,6 +273,10 @@ export default async function ProductPage({ params, searchParams }: Props) { 5. **Centralized API Access**: All BigCommerce API interactions go through the configured GraphQL client 6. **Proxy-First**: Critical functionality like routing, auth, and internationalization handled at the proxy layer +## Verifying UI Changes + +Before opening or updating a pull request that changes anything a shopper can see or do, prove it in a real browser and attach the evidence. Follow the [`verify-catalyst`](.agents/skills/verify-catalyst/SKILL.md) skill: it launches the storefront, drives it with Playwright, records video, screenshots, and a trace, and publishes them to the PR. The helper is plain Node, so it runs on macOS, Linux, and Windows. + ## Notes This codebase differs significantly from typical Next.js applications due to the custom routing proxy and e-commerce-specific patterns. The `with-routes` proxy (composed within `proxy.ts`) essentially turns Next.js into a headless CMS router, where content structure is determined by the BigCommerce backend rather than the filesystem. Understanding this fundamental difference is crucial for working effectively with the codebase. diff --git a/core/app/[locale]/(default)/(auth)/change-password/_actions/change-password.ts b/core/app/[locale]/(default)/(auth)/change-password/_actions/change-password.ts index 12bbaf3883..741bb06bd2 100644 --- a/core/app/[locale]/(default)/(auth)/change-password/_actions/change-password.ts +++ b/core/app/[locale]/(default)/(auth)/change-password/_actions/change-password.ts @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { z } from 'zod'; @@ -69,6 +70,8 @@ export async function changePassword( successMessage: t('passwordUpdated'), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/(auth)/login/_actions/login.ts b/core/app/[locale]/(default)/(auth)/login/_actions/login.ts index b4503e6d7e..c8f3898965 100644 --- a/core/app/[locale]/(default)/(auth)/login/_actions/login.ts +++ b/core/app/[locale]/(default)/(auth)/login/_actions/login.ts @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { AuthError } from 'next-auth'; import { getLocale, getTranslations } from 'next-intl/server'; @@ -36,6 +37,8 @@ export const login = async ( redirect: false, }); } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/(auth)/login/forgot-password/_actions/reset-password.ts b/core/app/[locale]/(default)/(auth)/login/forgot-password/_actions/reset-password.ts index 3001d9b27d..e231fc70f5 100644 --- a/core/app/[locale]/(default)/(auth)/login/forgot-password/_actions/reset-password.ts +++ b/core/app/[locale]/(default)/(auth)/login/forgot-password/_actions/reset-password.ts @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { schema } from '@/vibes/soul/sections/forgot-password-section/schema'; @@ -64,6 +65,8 @@ export const resetPassword = async ( successMessage: t('confirmResetPassword', { email: submission.value.email }), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/(faceted)/fetch-faceted-search.ts b/core/app/[locale]/(default)/(faceted)/fetch-faceted-search.ts index 49de0bc818..310a4a311f 100644 --- a/core/app/[locale]/(default)/(faceted)/fetch-faceted-search.ts +++ b/core/app/[locale]/(default)/(faceted)/fetch-faceted-search.ts @@ -383,6 +383,10 @@ export const PublicToPrivateParams = PublicSearchParamsSchema.catchall(SearchPar brandEntityIds: brand, categoryEntityId: category, categoryEntityIds: categoryIn, + // Without this, `categoryEntityIds` only matches products assigned directly to the selected + // categories, while the Category facet's options and counts include their sub-categories. + // Only set for the facet filter so category pages keep listing their own products. + searchSubCategories: categoryIn?.length ? true : undefined, hideOutOfStock: stock?.includes('in_stock'), isFreeShipping: shipping?.includes('free_shipping'), isFeatured, diff --git a/core/app/[locale]/(default)/account/addresses/_actions/create-address.ts b/core/app/[locale]/(default)/account/addresses/_actions/create-address.ts index 6d7df51ab1..f5ba3d35da 100644 --- a/core/app/[locale]/(default)/account/addresses/_actions/create-address.ts +++ b/core/app/[locale]/(default)/account/addresses/_actions/create-address.ts @@ -1,6 +1,7 @@ import { BigCommerceAPIError, BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { z } from 'zod'; @@ -248,6 +249,8 @@ export async function createAddress( defaultAddress: prevState.defaultAddress, }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/addresses/_actions/delete-address.ts b/core/app/[locale]/(default)/account/addresses/_actions/delete-address.ts index f1b1a1314e..ccc5890ef9 100644 --- a/core/app/[locale]/(default)/account/addresses/_actions/delete-address.ts +++ b/core/app/[locale]/(default)/account/addresses/_actions/delete-address.ts @@ -1,6 +1,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { z } from 'zod'; @@ -88,6 +89,8 @@ export async function deleteAddress(prevState: Awaited, formData: FormDat defaultAddress: prevState.defaultAddress, }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/addresses/_actions/update-address.ts b/core/app/[locale]/(default)/account/addresses/_actions/update-address.ts index 0435290bae..c91de04aee 100644 --- a/core/app/[locale]/(default)/account/addresses/_actions/update-address.ts +++ b/core/app/[locale]/(default)/account/addresses/_actions/update-address.ts @@ -1,6 +1,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { z } from 'zod'; @@ -257,6 +258,8 @@ export async function updateAddress( defaultAddress: prevState.defaultAddress, }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/settings/_actions/change-password.ts b/core/app/[locale]/(default)/account/settings/_actions/change-password.ts index 54cbaac684..ff1d3eee76 100644 --- a/core/app/[locale]/(default)/account/settings/_actions/change-password.ts +++ b/core/app/[locale]/(default)/account/settings/_actions/change-password.ts @@ -2,6 +2,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { z } from 'zod'; @@ -76,6 +77,8 @@ export const changePassword: ChangePasswordAction = async (prevState, formData) successMessage: t('passwordUpdated'), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/settings/_actions/update-customer.ts b/core/app/[locale]/(default)/account/settings/_actions/update-customer.ts index e29148c9ed..cd99ad740c 100644 --- a/core/app/[locale]/(default)/account/settings/_actions/update-customer.ts +++ b/core/app/[locale]/(default)/account/settings/_actions/update-customer.ts @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { Field, FieldGroup } from '@/vibes/soul/form/dynamic-form/schema'; @@ -164,6 +165,8 @@ export async function updateCustomer( lastResult: submission.reply(), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/settings/_actions/update-newsletter-subscription.ts b/core/app/[locale]/(default)/account/settings/_actions/update-newsletter-subscription.ts index 4fa3ee3975..97d046bdf2 100644 --- a/core/app/[locale]/(default)/account/settings/_actions/update-newsletter-subscription.ts +++ b/core/app/[locale]/(default)/account/settings/_actions/update-newsletter-subscription.ts @@ -4,6 +4,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { z } from 'zod'; @@ -129,6 +130,8 @@ export const updateNewsletterSubscription = async ( successMessage: t('marketingPreferencesUpdated'), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/wishlists/[id]/_actions/add-to-cart.tsx b/core/app/[locale]/(default)/account/wishlists/[id]/_actions/add-to-cart.tsx index 2cd0664423..210ae68105 100644 --- a/core/app/[locale]/(default)/account/wishlists/[id]/_actions/add-to-cart.tsx +++ b/core/app/[locale]/(default)/account/wishlists/[id]/_actions/add-to-cart.tsx @@ -3,6 +3,7 @@ import { BigCommerceAPIError, BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { z } from 'zod'; @@ -55,6 +56,8 @@ export async function addWishlistItemToCart(prevState: State, formData: FormData }), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/wishlists/_actions/change-wishlist-visibility.ts b/core/app/[locale]/(default)/account/wishlists/_actions/change-wishlist-visibility.ts index 3f8f8547da..5efa9e1f5f 100644 --- a/core/app/[locale]/(default)/account/wishlists/_actions/change-wishlist-visibility.ts +++ b/core/app/[locale]/(default)/account/wishlists/_actions/change-wishlist-visibility.ts @@ -4,6 +4,7 @@ import { BigCommerceAuthError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { getSessionCustomerAccessToken } from '~/auth'; @@ -70,6 +71,8 @@ export async function toggleWishlistVisibility( successMessage: t('Result.updateSuccess'), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/wishlists/_actions/delete-wishlist.ts b/core/app/[locale]/(default)/account/wishlists/_actions/delete-wishlist.ts index 8a5498671e..ead6666be7 100644 --- a/core/app/[locale]/(default)/account/wishlists/_actions/delete-wishlist.ts +++ b/core/app/[locale]/(default)/account/wishlists/_actions/delete-wishlist.ts @@ -4,6 +4,7 @@ import { BigCommerceAuthError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { getSessionCustomerAccessToken } from '~/auth'; @@ -70,6 +71,8 @@ export async function deleteWishlist( lastResult: submission.reply(), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/wishlists/_actions/new-wishlist.ts b/core/app/[locale]/(default)/account/wishlists/_actions/new-wishlist.ts index dbf86eb612..52c43f82b4 100644 --- a/core/app/[locale]/(default)/account/wishlists/_actions/new-wishlist.ts +++ b/core/app/[locale]/(default)/account/wishlists/_actions/new-wishlist.ts @@ -4,6 +4,7 @@ import { BigCommerceAuthError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { getSessionCustomerAccessToken } from '~/auth'; @@ -65,6 +66,8 @@ export async function newWishlist(prevState: Awaited, formData: FormData) successMessage: t('Result.createSuccess'), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/wishlists/_actions/remove-wishlist-item.ts b/core/app/[locale]/(default)/account/wishlists/_actions/remove-wishlist-item.ts index 39fcad84da..a079cdb140 100644 --- a/core/app/[locale]/(default)/account/wishlists/_actions/remove-wishlist-item.ts +++ b/core/app/[locale]/(default)/account/wishlists/_actions/remove-wishlist-item.ts @@ -4,6 +4,7 @@ import { BigCommerceAuthError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { getSessionCustomerAccessToken } from '~/auth'; @@ -73,6 +74,8 @@ export async function removeWishlistItem( lastResult: submission.reply(), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/account/wishlists/_actions/rename-wishlist.ts b/core/app/[locale]/(default)/account/wishlists/_actions/rename-wishlist.ts index 33d7c45ecd..7b889b1fd8 100644 --- a/core/app/[locale]/(default)/account/wishlists/_actions/rename-wishlist.ts +++ b/core/app/[locale]/(default)/account/wishlists/_actions/rename-wishlist.ts @@ -4,6 +4,7 @@ import { BigCommerceAuthError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { getSessionCustomerAccessToken } from '~/auth'; @@ -67,6 +68,8 @@ export async function renameWishlist( successMessage: t('Result.updateSuccess'), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/cart/_actions/update-coupon-code.ts b/core/app/[locale]/(default)/cart/_actions/update-coupon-code.ts index 01611007f7..727f73705f 100644 --- a/core/app/[locale]/(default)/cart/_actions/update-coupon-code.ts +++ b/core/app/[locale]/(default)/cart/_actions/update-coupon-code.ts @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { couponCodeActionFormDataSchema } from '@/vibes/soul/sections/cart/schema'; @@ -62,6 +63,8 @@ export const updateCouponCode = async ( couponCode: submission.value.couponCode, }); } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); @@ -102,6 +105,8 @@ export const updateCouponCode = async ( couponCode: submission.value.couponCode, }); } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/cart/_actions/update-gift-certificate.ts b/core/app/[locale]/(default)/cart/_actions/update-gift-certificate.ts index b7f2c52ac3..ecc60e7e7d 100644 --- a/core/app/[locale]/(default)/cart/_actions/update-gift-certificate.ts +++ b/core/app/[locale]/(default)/cart/_actions/update-gift-certificate.ts @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { giftCertificateCodeActionFormDataSchema } from '@/vibes/soul/sections/cart/schema'; @@ -64,6 +65,8 @@ export const updateGiftCertificate = async ( giftCertificateCode: submission.value.giftCertificateCode, }); } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); @@ -104,6 +107,8 @@ export const updateGiftCertificate = async ( giftCertificateCode: submission.value.giftCertificateCode, }); } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/cart/_actions/update-line-item.ts b/core/app/[locale]/(default)/cart/_actions/update-line-item.ts index a2d10c3d88..cc9e1b4b16 100644 --- a/core/app/[locale]/(default)/cart/_actions/update-line-item.ts +++ b/core/app/[locale]/(default)/cart/_actions/update-line-item.ts @@ -4,6 +4,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; import { FragmentOf } from 'gql.tada'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { CartLineItem } from '@/vibes/soul/sections/cart'; @@ -180,6 +181,8 @@ export const updateLineItem = async ( quantity, }); } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); @@ -211,6 +214,8 @@ export const updateLineItem = async ( try { await removeItem({ lineItemEntityId: submission.value.id }); } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/cart/_actions/update-shipping-info.ts b/core/app/[locale]/(default)/cart/_actions/update-shipping-info.ts index 662ba0f7a6..24a43d0424 100644 --- a/core/app/[locale]/(default)/cart/_actions/update-shipping-info.ts +++ b/core/app/[locale]/(default)/cart/_actions/update-shipping-info.ts @@ -2,6 +2,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { shippingActionFormDataSchema } from '@/vibes/soul/sections/cart/schema'; @@ -101,6 +102,8 @@ export const updateShippingInfo = async ( }; } } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); @@ -141,6 +144,8 @@ export const updateShippingInfo = async ( shippingOptionEntityId: submission.value.shippingOption, }); } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/cart/page-data.ts b/core/app/[locale]/(default)/cart/page-data.ts index 8b3188a7b0..214417c41f 100644 --- a/core/app/[locale]/(default)/cart/page-data.ts +++ b/core/app/[locale]/(default)/cart/page-data.ts @@ -25,6 +25,7 @@ export const PhysicalItemFragment = graphql( productEntityId variantEntityId parentEntityId + addedByAttributeId listPrice { currencyCode value @@ -43,6 +44,7 @@ export const PhysicalItemFragment = graphql( selectedOptions { __typename entityId + attributeId name ... on CartSelectedMultipleChoiceOption { value @@ -94,6 +96,7 @@ export const DigitalItemFragment = graphql( productEntityId variantEntityId parentEntityId + addedByAttributeId listPrice { currencyCode value @@ -112,6 +115,7 @@ export const DigitalItemFragment = graphql( selectedOptions { __typename entityId + attributeId name ... on CartSelectedMultipleChoiceOption { value diff --git a/core/app/[locale]/(default)/cart/page.tsx b/core/app/[locale]/(default)/cart/page.tsx index 74caf1f63d..0743823b6a 100644 --- a/core/app/[locale]/(default)/cart/page.tsx +++ b/core/app/[locale]/(default)/cart/page.tsx @@ -169,6 +169,58 @@ export default async function Cart({ params }: Props) { ...cart.lineItems.digitalItems, ].filter((item) => !('parentEntityId' in item) || !item.parentEntityId); + // Pick list options add their products as child line items. Show them under their parent. + const childItemsByParentId = Map.groupBy( + [...cart.lineItems.physicalItems, ...cart.lineItems.digitalItems].filter( + (item) => item.parentEntityId, + ), + (item) => item.parentEntityId, + ); + + const formatSelectedOption = ( + option: (typeof cart.lineItems.physicalItems)[number]['selectedOptions'][number], + ) => { + switch (option.__typename) { + case 'CartSelectedMultipleChoiceOption': + case 'CartSelectedCheckboxOption': + return `${option.name}: ${option.value}`; + + case 'CartSelectedNumberFieldOption': + return `${option.name}: ${option.number}`; + + case 'CartSelectedMultiLineTextFieldOption': + case 'CartSelectedTextFieldOption': + return `${option.name}: ${option.text}`; + + case 'CartSelectedDateFieldOption': + return `${option.name}: ${format.dateTime(new Date(option.date.utc))}`; + + default: + return ''; + } + }; + + const getChildItems = (parentEntityId: string) => childItemsByParentId.get(parentEntityId) ?? []; + + // The parent's price already includes its pick list items, so they're listed without prices. + const formatIncludedItem = ( + child: + | (typeof cart.lineItems.physicalItems)[number] + | (typeof cart.lineItems.digitalItems)[number], + parent: Pick<(typeof cart.lineItems.physicalItems)[number], 'quantity' | 'selectedOptions'>, + ) => { + const addedBy = parent.selectedOptions.find( + (option) => option.attributeId === child.addedByAttributeId, + ); + + return { + id: child.entityId, + title: addedBy ? formatSelectedOption(addedBy) : child.name, + subtitle: child.selectedOptions.map(formatSelectedOption).join(', ') || undefined, + quantity: child.quantity !== parent.quantity ? child.quantity : undefined, + }; + }; + const formattedLineItems = lineItems.map((item) => { if (item.__typename === 'CartGiftCertificate') { return { @@ -241,33 +293,20 @@ export default async function Cart({ params }: Props) { currency: item.listPrice.currencyCode, }); + const childItems = getChildItems(item.entityId); + const addedByAttributeIds = new Set(childItems.map((child) => child.addedByAttributeId)); + return { typename: item.__typename, id: item.entityId, quantity: item.quantity, price, subtitle: item.selectedOptions - .map((option) => { - switch (option.__typename) { - case 'CartSelectedMultipleChoiceOption': - case 'CartSelectedCheckboxOption': - return `${option.name}: ${option.value}`; - - case 'CartSelectedNumberFieldOption': - return `${option.name}: ${option.number}`; - - case 'CartSelectedMultiLineTextFieldOption': - case 'CartSelectedTextFieldOption': - return `${option.name}: ${option.text}`; - - case 'CartSelectedDateFieldOption': - return `${option.name}: ${format.dateTime(new Date(option.date.utc))}`; - - default: - return ''; - } - }) + // Pick list options move to the items they added, listed below. + .filter((option) => !addedByAttributeIds.has(option.attributeId)) + .map(formatSelectedOption) .join(', '), + includedItems: childItems.map((child) => formatIncludedItem(child, item)), title: item.name, image: item.image?.url ? { src: item.image.url, alt: item.name } : undefined, href: new URL(item.url).pathname, @@ -428,6 +467,7 @@ export default async function Cart({ params }: Props) { } : undefined } + includedItemsLabel={t('includedItems')} incrementLineItemLabel={t('increment')} // Keyed by entityId only; keying by version too would remount the section on // every mutation (see the pending-intent dispatcher notes in the Cart section). diff --git a/core/app/[locale]/(default)/compare/_actions/add-to-cart.tsx b/core/app/[locale]/(default)/compare/_actions/add-to-cart.tsx index d04cdc1536..b258ab3fbb 100644 --- a/core/app/[locale]/(default)/compare/_actions/add-to-cart.tsx +++ b/core/app/[locale]/(default)/compare/_actions/add-to-cart.tsx @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { ReactNode } from 'react'; @@ -57,6 +58,8 @@ export const addToCart = async ( }), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/gift-certificates/balance/_actions/get-gift-certificate-by-code.ts b/core/app/[locale]/(default)/gift-certificates/balance/_actions/get-gift-certificate-by-code.ts index f7382dd3fc..1e566308b8 100644 --- a/core/app/[locale]/(default)/gift-certificates/balance/_actions/get-gift-certificate-by-code.ts +++ b/core/app/[locale]/(default)/gift-certificates/balance/_actions/get-gift-certificate-by-code.ts @@ -2,6 +2,7 @@ import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getFormatter, getTranslations } from 'next-intl/server'; import { GiftCertificateData } from '@/vibes/soul/sections/gift-certificate-balance-section'; @@ -101,6 +102,8 @@ export async function getGiftCertificateByCode( data: giftCertificate, }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/gift-certificates/purchase/_actions/add-to-cart.tsx b/core/app/[locale]/(default)/gift-certificates/purchase/_actions/add-to-cart.tsx index 5946eb55b1..95f0063abb 100644 --- a/core/app/[locale]/(default)/gift-certificates/purchase/_actions/add-to-cart.tsx +++ b/core/app/[locale]/(default)/gift-certificates/purchase/_actions/add-to-cart.tsx @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getFormatter, getTranslations } from 'next-intl/server'; import { ReactNode } from 'react'; import { z } from 'zod'; @@ -162,6 +163,8 @@ export async function addGiftCertificateToCart( }), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/product/[slug]/_actions/add-to-cart.tsx b/core/app/[locale]/(default)/product/[slug]/_actions/add-to-cart.tsx index 57b429b99b..6c8016bfcf 100644 --- a/core/app/[locale]/(default)/product/[slug]/_actions/add-to-cart.tsx +++ b/core/app/[locale]/(default)/product/[slug]/_actions/add-to-cart.tsx @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { ReactNode } from 'react'; @@ -173,6 +174,8 @@ export const addToCart = async ( }), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/product/[slug]/_actions/submit-review.ts b/core/app/[locale]/(default)/product/[slug]/_actions/submit-review.ts index 385bd3813f..331e1a5171 100644 --- a/core/app/[locale]/(default)/product/[slug]/_actions/submit-review.ts +++ b/core/app/[locale]/(default)/product/[slug]/_actions/submit-review.ts @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { schema } from '@/vibes/soul/sections/reviews/schema'; @@ -86,6 +87,8 @@ export async function submitReview( successMessage: t('successMessage'), }; } catch (error) { + rethrow(error); + if (error instanceof BigCommerceGQLError) { return { ...prevState, diff --git a/core/app/[locale]/(default)/product/[slug]/_actions/wishlist-action.ts b/core/app/[locale]/(default)/product/[slug]/_actions/wishlist-action.ts index e8df8d9df7..5de272653a 100644 --- a/core/app/[locale]/(default)/product/[slug]/_actions/wishlist-action.ts +++ b/core/app/[locale]/(default)/product/[slug]/_actions/wishlist-action.ts @@ -8,6 +8,7 @@ import { import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getLocale, getTranslations } from 'next-intl/server'; import { z } from 'zod'; @@ -237,6 +238,8 @@ export async function wishlistAction(payload: FormData): Promise { revalidateTag(TAGS.customer, { expire: 0 }); } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/app/[locale]/(default)/webpages/[id]/contact/_actions/submit-contact-form.ts b/core/app/[locale]/(default)/webpages/[id]/contact/_actions/submit-contact-form.ts index 11ff4d368c..c339a6ef51 100644 --- a/core/app/[locale]/(default)/webpages/[id]/contact/_actions/submit-contact-form.ts +++ b/core/app/[locale]/(default)/webpages/[id]/contact/_actions/submit-contact-form.ts @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getLocale, getTranslations } from 'next-intl/server'; import { z } from 'zod'; @@ -104,6 +105,8 @@ export async function submitContactForm( }; } } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/components/header/_actions/search.ts b/core/components/header/_actions/search.ts index 5710f0ae03..3e446cde7d 100644 --- a/core/components/header/_actions/search.ts +++ b/core/components/header/_actions/search.ts @@ -3,6 +3,7 @@ import { BigCommerceGQLError, removeEdgesAndNodes } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { z } from 'zod'; @@ -106,6 +107,8 @@ export async function search( emptyStateSubtitle, }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/components/header/_actions/switch-locale.ts b/core/components/header/_actions/switch-locale.ts index 53e717dbac..b6c4e568b2 100644 --- a/core/components/header/_actions/switch-locale.ts +++ b/core/components/header/_actions/switch-locale.ts @@ -1,6 +1,7 @@ 'use server'; import { revalidateTag } from 'next/cache'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { client } from '~/client'; import { graphql } from '~/client/graphql'; @@ -61,6 +62,8 @@ export const switchLocale = async (locale: string): Promise => { revalidateTag(TAGS.cart, { expire: 0 }); } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error('Error updating cart locale', error); } diff --git a/core/components/subscribe/_actions/subscribe.ts b/core/components/subscribe/_actions/subscribe.ts index f4470c138d..9e243e38ac 100644 --- a/core/components/subscribe/_actions/subscribe.ts +++ b/core/components/subscribe/_actions/subscribe.ts @@ -3,6 +3,7 @@ import { BigCommerceGQLError } from '@bigcommerce/catalyst-client'; import { SubmissionResult } from '@conform-to/react'; import { parseWithZod } from '@conform-to/zod'; +import { unstable_rethrow as rethrow } from 'next/navigation'; import { getTranslations } from 'next-intl/server'; import { schema } from '@/vibes/soul/primitives/inline-email-form/schema'; @@ -96,6 +97,8 @@ export const subscribe = async ( successMessage: t('subscribedToNewsletter'), }; } catch (error) { + rethrow(error); + // eslint-disable-next-line no-console console.error(error); diff --git a/core/instrumentation.ts b/core/instrumentation.ts index 96cf5d6560..57b8181e52 100644 --- a/core/instrumentation.ts +++ b/core/instrumentation.ts @@ -1,5 +1,3 @@ -import { registerOTel } from '@vercel/otel'; - // eslint-disable-next-line valid-jsdoc /** * Initializes OpenTelemetry instrumentation for the Next.js application. @@ -12,6 +10,7 @@ import { registerOTel } from '@vercel/otel'; * * Configuration: * - Uses @vercel/otel for simplified OpenTelemetry setup + * - On Cloudflare Workers, spans go to Workers tracing instead (see ~/lib/otel/cloudflare) * - Automatically instruments Next.js internals (requests, rendering, fetches) * - Service name is read from OTEL_SERVICE_NAME environment variable * - If OTEL_SERVICE_NAME is not set, defaults to 'next-app' @@ -50,7 +49,22 @@ import { registerOTel } from '@vercel/otel'; * - OPENTELEMETRY.md in this directory * - Official Next.js guide: https://nextjs.org/docs/app/guides/open-telemetry */ -export function register() { +export async function register() { + // On Cloudflare Workers, hand spans to the runtime's native tracing instead. + // `@vercel/otel` must stay out of this branch: its Node build throws when + // workerd evaluates it, so it is only ever imported lazily below. + // `navigator` is undefined on Node 20, despite what the DOM types say. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (globalThis.navigator?.userAgent === 'Cloudflare-Workers') { + const { registerWorkersTracing } = await import('./lib/otel/cloudflare'); + + registerWorkersTracing(); + + return; + } + + const { registerOTel } = await import('@vercel/otel'); + // Service name is pulled from the OTEL_SERVICE_NAME env var. // If you wish to manually set it, you can remove the env var and set it here: // registerOTel({ serviceName: 'catalyst-storefront' }); diff --git a/core/lib/analytics/index.spec.ts b/core/lib/analytics/index.spec.ts new file mode 100644 index 0000000000..4b5f141234 --- /dev/null +++ b/core/lib/analytics/index.spec.ts @@ -0,0 +1,82 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { AnalyticsProvider } from './types'; + +function createProvider(name: string, calls: string[]): AnalyticsProvider { + return { + initialize: vi.fn(() => calls.push(`${name}:initialize`)), + cart: { + cartViewed: vi.fn(), + productAdded: vi.fn(), + productRemoved: vi.fn(), + }, + navigation: { + categoryViewed: vi.fn(), + productViewed: vi.fn(() => calls.push(`${name}:productViewed`)), + }, + consent: { + consentUpdated: vi.fn(), + }, + }; +} + +// Analytics is a singleton, so each test loads a fresh module. +async function createAnalytics(providers: AnalyticsProvider[]) { + vi.resetModules(); + + const { Analytics } = await import('.'); + + return new Analytics({ channelId: 1, providers }); +} + +const payload = { currency: 'USD', value: 10, items: [] }; + +describe('Analytics', () => { + beforeEach(() => { + vi.spyOn(console, 'error').mockImplementation(() => undefined); + }); + + it('initializes providers once, before the first event', async () => { + const calls: string[] = []; + const analytics = await createAnalytics([createProvider('ga', calls)]); + + analytics.navigation.productViewed(payload); + analytics.initialize(); + + expect(calls).toEqual(['ga:initialize', 'ga:productViewed']); + }); + + it('retries a provider whose initialization failed', async () => { + const calls: string[] = []; + const provider = createProvider('ga', calls); + + vi.mocked(provider.initialize).mockImplementationOnce(() => { + throw new Error('consent unavailable'); + }); + + const analytics = await createAnalytics([provider]); + + analytics.initialize(); + analytics.navigation.productViewed(payload); + + expect(provider.initialize).toHaveBeenCalledTimes(2); + expect(calls).toEqual(['ga:initialize', 'ga:productViewed']); + }); + + it('keeps sending events to other providers when one fails to initialize', async () => { + const calls: string[] = []; + const failing = createProvider('failing', calls); + const working = createProvider('working', calls); + + vi.mocked(failing.initialize).mockImplementation(() => { + throw new Error('broken'); + }); + + const analytics = await createAnalytics([failing, working]); + + analytics.navigation.productViewed(payload); + + expect(calls).toEqual(['working:initialize', 'working:productViewed']); + expect(failing.navigation.productViewed).not.toHaveBeenCalled(); + }); +}); diff --git a/core/lib/analytics/index.ts b/core/lib/analytics/index.ts index 8cc95be830..7135793e46 100644 --- a/core/lib/analytics/index.ts +++ b/core/lib/analytics/index.ts @@ -1,6 +1,6 @@ import { v4 as uuidV4 } from 'uuid'; -import type { AnalyticsConfig, Analytics as IAnalytics } from './types'; +import type { AnalyticsConfig, AnalyticsProvider, Analytics as IAnalytics } from './types'; export class Analytics implements IAnalytics { static #instance: Analytics | null = null; @@ -9,6 +9,8 @@ export class Analytics implements IAnalytics { readonly navigation = this.bindNavigationEvents(); readonly consent = this.bindConsentEvents(); + #initializedProviders = new Set(); + constructor(private readonly config: AnalyticsConfig) { if (!Analytics.#instance) { Analytics.#instance = this; @@ -17,16 +19,35 @@ export class Analytics implements IAnalytics { return Analytics.#instance; } + // Child components fire events from effects that run before the provider's own effect calls + // this, so events also initialize providers. A provider counts as ready only once its + // initialize() succeeds, so a failure is retried on the next event. initialize() { - this.config.providers.forEach((provider) => { - provider.initialize(); + this.readyProviders(); + } + + private readyProviders() { + return this.config.providers.filter((provider) => { + if (this.#initializedProviders.has(provider)) return true; + + try { + provider.initialize(); + this.#initializedProviders.add(provider); + + return true; + } catch (error) { + // eslint-disable-next-line no-console + console.error('Failed to initialize analytics provider', error); + + return false; + } }); } private bindCartEvents() { return { cartViewed: (payload) => { - this.config.providers.forEach((provider) => { + this.readyProviders().forEach((provider) => { provider.cart.cartViewed(payload, { channelId: this.config.channelId, eventUuid: uuidV4(), @@ -34,7 +55,7 @@ export class Analytics implements IAnalytics { }); }, productAdded: (payload) => { - this.config.providers.forEach((provider) => { + this.readyProviders().forEach((provider) => { provider.cart.productAdded(payload, { channelId: this.config.channelId, eventUuid: uuidV4(), @@ -42,7 +63,7 @@ export class Analytics implements IAnalytics { }); }, productRemoved: (payload) => { - this.config.providers.forEach((provider) => { + this.readyProviders().forEach((provider) => { provider.cart.productRemoved(payload, { channelId: this.config.channelId, eventUuid: uuidV4(), @@ -55,7 +76,7 @@ export class Analytics implements IAnalytics { private bindNavigationEvents() { return { categoryViewed: (payload) => { - this.config.providers.forEach((provider) => { + this.readyProviders().forEach((provider) => { provider.navigation.categoryViewed(payload, { channelId: this.config.channelId, eventUuid: uuidV4(), @@ -63,7 +84,7 @@ export class Analytics implements IAnalytics { }); }, productViewed: (payload) => { - this.config.providers.forEach((provider) => { + this.readyProviders().forEach((provider) => { provider.navigation.productViewed(payload, { channelId: this.config.channelId, eventUuid: uuidV4(), @@ -76,7 +97,7 @@ export class Analytics implements IAnalytics { private bindConsentEvents() { return { consentUpdated: (payload) => { - this.config.providers.forEach((provider) => { + this.readyProviders().forEach((provider) => { provider.consent.consentUpdated(payload, { channelId: this.config.channelId, eventUuid: uuidV4(), diff --git a/core/lib/makeswift/utils/use-products.ts b/core/lib/makeswift/utils/use-products.ts index 7b16bc24bb..4b4ee73be1 100644 --- a/core/lib/makeswift/utils/use-products.ts +++ b/core/lib/makeswift/utils/use-products.ts @@ -38,7 +38,7 @@ export function useProducts({ collection, collectionLimit = 20, additionalProduc const searchParams = new URLSearchParams(); - searchParams.append('ids', additionalProductIds.join(',')); + searchParams.append('ids', [...additionalProductIds].sort().join(',')); searchParams.append('locale', locale); const additionalProductsUrl = `/api/products/ids?${searchParams.toString()}`; diff --git a/core/lib/otel/cloudflare.spec.ts b/core/lib/otel/cloudflare.spec.ts new file mode 100644 index 0000000000..8ee66d607d --- /dev/null +++ b/core/lib/otel/cloudflare.spec.ts @@ -0,0 +1,191 @@ +import { context, SpanStatusCode, trace } from '@opentelemetry/api'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; + +import { registerWorkersTracing } from './cloudflare'; + +const CLOUDFLARE_CONTEXT_SYMBOL = Symbol.for('__cloudflare-context__'); + +interface RecordedSpan { + name: string; + attributes: Record; + statuses: unknown[]; + exceptions: unknown[]; + ended: boolean; +} + +// Records what the bridge hands the Workers runtime. +function createFakeTracing() { + const spans: RecordedSpan[] = []; + + const startSpan = (name: string) => { + const recorded: RecordedSpan = { + name, + attributes: {}, + statuses: [], + exceptions: [], + ended: false, + }; + + spans.push(recorded); + + const span = { + isTraced: true, + setAttribute(key: string, value: unknown) { + recorded.attributes[key] = value; + + return span; + }, + setAttributes(attributes: Record) { + Object.assign(recorded.attributes, attributes); + + return span; + }, + recordException(exception: unknown) { + recorded.exceptions.push(exception); + }, + setStatus(status: unknown) { + recorded.statuses.push(status); + + return span; + }, + updateName(newName: string) { + recorded.name = newName; + + return span; + }, + spanContext: () => ({ traceId: 'a'.repeat(32), spanId: 'b'.repeat(16), traceFlags: 1 }), + end() { + recorded.ended = true; + }, + }; + + return span; + }; + + return { + spans, + tracing: { + startSpan, + startActiveSpan: (name: string, callback: (span: ReturnType) => T) => + callback(startSpan(name)), + }, + }; +} + +function setCloudflareContext(value: unknown) { + Reflect.set(globalThis, CLOUDFLARE_CONTEXT_SYMBOL, value); +} + +beforeAll(() => { + registerWorkersTracing(); +}); + +afterAll(() => { + trace.disable(); + context.disable(); +}); + +afterEach(() => { + Reflect.deleteProperty(globalThis, CLOUDFLARE_CONTEXT_SYMBOL); +}); + +describe('registerWorkersTracing', () => { + it('records active spans on ctx.tracing and exposes them as the OTel active span', () => { + const { spans, tracing } = createFakeTracing(); + + setCloudflareContext({ ctx: { tracing } }); + + const tracer = trace.getTracer('test'); + + const traceId = tracer.startActiveSpan( + 'render', + { attributes: { 'next.route': '/[locale]', tags: ['a', 'b'] } }, + (span) => { + const active = trace.getActiveSpan(); + + span.setStatus({ code: SpanStatusCode.ERROR, message: 'boom' }); + span.recordException(new Error('boom')); + span.end(); + + return active?.spanContext().traceId; + }, + ); + + expect(traceId).toBe('a'.repeat(32)); + expect(spans).toEqual([ + { + name: 'render', + attributes: { 'next.route': '/[locale]', tags: '["a","b"]' }, + statuses: [{ code: 'error', message: 'boom' }], + exceptions: [expect.objectContaining({ name: 'Error', message: 'boom' })], + ended: true, + }, + ]); + }); + + it('records non-active spans with startSpan', () => { + const { spans, tracing } = createFakeTracing(); + + setCloudflareContext({ ctx: { tracing } }); + + const span = trace + .getTracer('test') + .startSpan('fetch', { attributes: { 'http.method': 'GET' } }); + + span.setAttribute('http.status_code', 200); + span.end(); + + expect(spans).toEqual([ + expect.objectContaining({ + name: 'fetch', + attributes: { 'http.method': 'GET', 'http.status_code': 200 }, + ended: true, + }), + ]); + }); + + it('tolerates runtimes whose spans lack the optional methods', () => { + const recorded = { ended: false }; + const span = { + isTraced: true, + setAttribute: () => span, + setAttributes: () => span, + end: () => { + recorded.ended = true; + }, + }; + + setCloudflareContext({ + ctx: { tracing: { startSpan: () => span, startActiveSpan: () => undefined } }, + }); + + const adapted = trace.getTracer('test').startSpan('fetch'); + + adapted.setStatus({ code: SpanStatusCode.ERROR }); + adapted.recordException(new Error('boom')); + adapted.updateName('renamed'); + adapted.end(); + + expect(adapted.spanContext().traceId).toBe('00000000000000000000000000000000'); + expect(recorded.ended).toBe(true); + }); + + it('keeps the receiver of context-bound callbacks', () => { + const bound = context.bind(context.active(), function name(this: { name: string }) { + return this.name; + }); + + expect(bound.call({ name: 'request' })).toBe('request'); + }); + + it('runs the callback with a non-recording span outside a Workers request', () => { + const result = trace.getTracer('test').startActiveSpan('render', (span) => { + expect(span.isRecording()).toBe(false); + span.end(); + + return 'rendered'; + }); + + expect(result).toBe('rendered'); + }); +}); diff --git a/core/lib/otel/cloudflare.ts b/core/lib/otel/cloudflare.ts new file mode 100644 index 0000000000..2b5d029aaf --- /dev/null +++ b/core/lib/otel/cloudflare.ts @@ -0,0 +1,272 @@ +// Adapters for the OTel API's span, tracer, provider and context-manager interfaces. +/* eslint-disable max-classes-per-file */ +import { + type Attributes, + type AttributeValue, + context, + type Context, + type ContextManager, + type Exception, + INVALID_SPAN_CONTEXT, + ROOT_CONTEXT, + type Span, + type SpanContext, + type SpanOptions, + type SpanStatus, + SpanStatusCode, + trace, + type Tracer, + type TracerProvider, +} from '@opentelemetry/api'; +import { AsyncLocalStorage } from 'node:async_hooks'; + +// Bridges `@opentelemetry/api` onto the Workers runtime's native tracing +// (`ctx.tracing`), so spans from Next.js and `~/lib/otel/tracer` land in +// Workers traces and whatever OTLP destination the Worker exports to. There is +// no SDK, exporter or flush here: the runtime records and ships the spans. +// +// https://developers.cloudflare.com/workers/observability/traces/custom-spans/ + +type PrimitiveAttribute = string | number | boolean; + +// Older workerd releases ship spans without the optional methods. +interface WorkersSpan { + readonly isTraced: boolean; + setAttribute(key: string, value: PrimitiveAttribute): this; + setAttributes(attributes: Record): this; + recordException?(exception: string | { name?: string; message?: string; stack?: string }): void; + setStatus?(status: { code: 'unset' | 'ok' | 'error'; message?: string }): this; + updateName?(name: string): this; + spanContext?(): { traceId: string; spanId: string; traceFlags: number }; + end(): void; +} + +interface WorkersTracing { + startActiveSpan(name: string, callback: (span: WorkersSpan) => T): T; + startSpan(name: string): WorkersSpan; +} + +// Same key `~/lib/kv/adapters/cloudflare-kv` reads; see the drift warning there. +const CLOUDFLARE_CONTEXT_SYMBOL = Symbol.for('__cloudflare-context__'); + +// Resolved per span rather than once at register() time: the context global +// only holds the request's `ctx` while OpenNext is handling a request. +function getWorkersTracing(): WorkersTracing | undefined { + const cloudflareContext: unknown = Reflect.get(globalThis, CLOUDFLARE_CONTEXT_SYMBOL); + + if (typeof cloudflareContext !== 'object' || cloudflareContext === null) return undefined; + + const ctx: unknown = Reflect.get(cloudflareContext, 'ctx'); + + if (typeof ctx !== 'object' || ctx === null) return undefined; + + const tracing: unknown = Reflect.get(ctx, 'tracing'); + + if ( + typeof tracing === 'object' && + tracing !== null && + typeof Reflect.get(tracing, 'startActiveSpan') === 'function' && + typeof Reflect.get(tracing, 'startSpan') === 'function' + ) { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + return tracing as WorkersTracing; + } + + return undefined; +} + +// Workers attributes are primitives only; OTel also allows homogeneous arrays. +function toPrimitive(value: AttributeValue | undefined): PrimitiveAttribute | undefined { + if (value === undefined) return undefined; + + if (Array.isArray(value)) return JSON.stringify(value); + + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + return value as PrimitiveAttribute; +} + +const STATUS_CODES = { + [SpanStatusCode.UNSET]: 'unset', + [SpanStatusCode.OK]: 'ok', + [SpanStatusCode.ERROR]: 'error', +} as const; + +class WorkersSpanAdapter implements Span { + constructor(private readonly span: WorkersSpan) {} + + spanContext(): SpanContext { + return this.span.spanContext?.() ?? INVALID_SPAN_CONTEXT; + } + + setAttribute(key: string, value: AttributeValue): this { + const primitive = toPrimitive(value); + + if (primitive !== undefined) this.span.setAttribute(key, primitive); + + return this; + } + + setAttributes(attributes: Attributes): this { + this.span.setAttributes( + Object.fromEntries( + Object.entries(attributes).map(([key, value]) => [key, toPrimitive(value)]), + ), + ); + + return this; + } + + // The Workers span API has no events or links. + addEvent(): this { + return this; + } + + addLink(): this { + return this; + } + + addLinks(): this { + return this; + } + + setStatus({ code, message }: SpanStatus): this { + this.span.setStatus?.({ code: STATUS_CODES[code], message }); + + return this; + } + + updateName(name: string): this { + this.span.updateName?.(name); + + return this; + } + + end(): void { + this.span.end(); + } + + isRecording(): boolean { + return this.span.isTraced; + } + + recordException(exception: Exception): void { + this.span.recordException?.( + typeof exception === 'string' + ? exception + : { name: exception.name, message: exception.message, stack: exception.stack }, + ); + } +} + +const nonRecordingSpan = () => trace.wrapSpanContext(INVALID_SPAN_CONTEXT); + +function adapt(span: WorkersSpan, options?: SpanOptions): Span { + const adapted = new WorkersSpanAdapter(span); + + if (options?.attributes) adapted.setAttributes(options.attributes); + + return adapted; +} + +function normalizeStartActiveSpanArgs( + args: [F] | [SpanOptions, F] | [SpanOptions, Context, F], +): [SpanOptions | undefined, Context, F] { + if (args.length === 1) return [undefined, context.active(), args[0]]; + + if (args.length === 2) return [args[0], context.active(), args[1]]; + + return args; +} + +// Parenting comes from the runtime's own async context, not the OTel `Context` +// argument: the Workers API has no way to pass an explicit parent. +class WorkersTracer implements Tracer { + startSpan(name: string, options?: SpanOptions): Span { + const tracing = getWorkersTracing(); + + return tracing ? adapt(tracing.startSpan(name), options) : nonRecordingSpan(); + } + + startActiveSpan unknown>(name: string, fn: F): ReturnType; + startActiveSpan unknown>( + name: string, + options: SpanOptions, + fn: F, + ): ReturnType; + startActiveSpan unknown>( + name: string, + options: SpanOptions, + parentContext: Context, + fn: F, + ): ReturnType; + startActiveSpan unknown>( + name: string, + ...args: [F] | [SpanOptions, F] | [SpanOptions, Context, F] + ): ReturnType { + const [options, parentContext, fn] = normalizeStartActiveSpanArgs(args); + const tracing = getWorkersTracing(); + + const run = (span: Span) => + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + context.with(trace.setSpan(parentContext, span), () => fn(span)) as ReturnType; + + if (!tracing) return run(nonRecordingSpan()); + + return tracing.startActiveSpan(name, (span) => run(adapt(span, options))); + } +} + +class WorkersTracerProvider implements TracerProvider { + private readonly tracer = new WorkersTracer(); + + getTracer(): Tracer { + return this.tracer; + } +} + +// `context.with()` / `context.active()` are no-ops without a context manager, +// and Next.js's tracer relies on them to find the active span. +class AsyncLocalStorageContextManager implements ContextManager { + private readonly storage = new AsyncLocalStorage(); + + active(): Context { + return this.storage.getStore() ?? ROOT_CONTEXT; + } + + with ReturnType>( + ctx: Context, + fn: F, + thisArg?: ThisParameterType, + ...args: A + ): ReturnType { + return this.storage.run(ctx, () => fn.apply(thisArg, args)); + } + + bind(ctx: Context, target: T): T { + if (typeof target !== 'function') return target; + + const run = this.with.bind(this); + + // A plain function, so callers' `this` (e.g. Next.js's `.apply`) reaches `target`. + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + return function bound(this: unknown, ...args: unknown[]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return run(ctx, () => Reflect.apply(target, this, args)); + } as T; + } + + enable(): this { + return this; + } + + disable(): this { + this.storage.disable(); + + return this; + } +} + +export function registerWorkersTracing() { + context.setGlobalContextManager(new AsyncLocalStorageContextManager()); + trace.setGlobalTracerProvider(new WorkersTracerProvider()); +} diff --git a/core/messages/da.json b/core/messages/da.json index 515ec9bffd..c01fd193c3 100644 --- a/core/messages/da.json +++ b/core/messages/da.json @@ -426,6 +426,7 @@ "cartCombined": "Vi bemærkede, at du havde gemt varer i en tidligere indkøbskurv, så vi har føjet dem til din nuværende indkøbskurv for dig.", "cartRestored": "Du startede en indkøbskurv på en anden enhed, og vi har gendannet den her, så du kan fortsætte, hvor du slap.", "cartUpdateInProgress": "Du har en igangværende opdatering af din indkøbskurv. Er du sikker på, at du vil forlade denne side? Dine ændringer kan gå tabt.", + "includedItems": "Inkluderet", "originalPrice": "Den oprindelige pris var {price}.", "currentPrice": "Den aktuelle pris er {price}.", "quantityReadyToShip": "{quantity, number} klar til forsendelse", diff --git a/core/messages/de.json b/core/messages/de.json index 98c8e74903..cbf331794e 100644 --- a/core/messages/de.json +++ b/core/messages/de.json @@ -426,6 +426,7 @@ "cartCombined": "Wir haben festgestellt, dass Sie Artikel in einem früheren Warenkorb gespeichert hatten, also haben wir diese Ihrem aktuellen Warenkorb hinzugefügt.", "cartRestored": "Sie haben einen Warenkorb auf einem anderen Gerät angelegt, und wir haben ihn hier wiederhergestellt, damit Sie dort weitermachen können, wo Sie aufgehört haben.", "cartUpdateInProgress": "Sie führen derzeit eine Aktualisierung Ihres Warenkorbs durch. Sind Sie sicher, dass Sie diese Seite verlassen möchten? Ihre Änderungen könnten verloren gehen.", + "includedItems": "Enthalten", "originalPrice": "Der ursprüngliche Preis war {price}.", "currentPrice": "Der aktuelle Preis beträgt {price}.", "quantityReadyToShip": "{quantity, number} bereit zum Versand", diff --git a/core/messages/en.json b/core/messages/en.json index 3c57699081..9399dffd00 100644 --- a/core/messages/en.json +++ b/core/messages/en.json @@ -427,6 +427,7 @@ "cartCombined": "We noticed you had items saved in a previous cart, so we've added them to your current cart for you.", "cartRestored": "You started a cart on another device, and we've restored it here so you can pick up where you left off.", "cartUpdateInProgress": "You have a cart update in progress. Are you sure you want to leave this page? Your changes may be lost.", + "includedItems": "Included", "originalPrice": "Original price was {price}.", "currentPrice": "Current price is {price}.", "quantityReadyToShip": "{quantity, number} ready to ship", diff --git a/core/messages/es-419.json b/core/messages/es-419.json index c8595af4ea..65fd08f119 100644 --- a/core/messages/es-419.json +++ b/core/messages/es-419.json @@ -426,6 +426,7 @@ "cartCombined": "Notamos que tenías artículos guardados en un carrito anterior, así que los hemos agregado a tu carrito actual.", "cartRestored": "Iniciaste un carrito en otro dispositivo y lo hemos restaurado aquí para que puedas continuar desde donde lo dejaste.", "cartUpdateInProgress": "Tiene una actualización de carrito en proceso. ¿Estás seguro de que quieres salir de esta página? Es posible que se pierdan sus cambios.", + "includedItems": "Incluido", "originalPrice": "El precio original era {price}.", "currentPrice": "El precio actual es {price}.", "quantityReadyToShip": "{cantidad, número} listo para enviar", diff --git a/core/messages/es-AR.json b/core/messages/es-AR.json index c8595af4ea..65fd08f119 100644 --- a/core/messages/es-AR.json +++ b/core/messages/es-AR.json @@ -426,6 +426,7 @@ "cartCombined": "Notamos que tenías artículos guardados en un carrito anterior, así que los hemos agregado a tu carrito actual.", "cartRestored": "Iniciaste un carrito en otro dispositivo y lo hemos restaurado aquí para que puedas continuar desde donde lo dejaste.", "cartUpdateInProgress": "Tiene una actualización de carrito en proceso. ¿Estás seguro de que quieres salir de esta página? Es posible que se pierdan sus cambios.", + "includedItems": "Incluido", "originalPrice": "El precio original era {price}.", "currentPrice": "El precio actual es {price}.", "quantityReadyToShip": "{cantidad, número} listo para enviar", diff --git a/core/messages/es-CL.json b/core/messages/es-CL.json index c8595af4ea..65fd08f119 100644 --- a/core/messages/es-CL.json +++ b/core/messages/es-CL.json @@ -426,6 +426,7 @@ "cartCombined": "Notamos que tenías artículos guardados en un carrito anterior, así que los hemos agregado a tu carrito actual.", "cartRestored": "Iniciaste un carrito en otro dispositivo y lo hemos restaurado aquí para que puedas continuar desde donde lo dejaste.", "cartUpdateInProgress": "Tiene una actualización de carrito en proceso. ¿Estás seguro de que quieres salir de esta página? Es posible que se pierdan sus cambios.", + "includedItems": "Incluido", "originalPrice": "El precio original era {price}.", "currentPrice": "El precio actual es {price}.", "quantityReadyToShip": "{cantidad, número} listo para enviar", diff --git a/core/messages/es-CO.json b/core/messages/es-CO.json index c8595af4ea..65fd08f119 100644 --- a/core/messages/es-CO.json +++ b/core/messages/es-CO.json @@ -426,6 +426,7 @@ "cartCombined": "Notamos que tenías artículos guardados en un carrito anterior, así que los hemos agregado a tu carrito actual.", "cartRestored": "Iniciaste un carrito en otro dispositivo y lo hemos restaurado aquí para que puedas continuar desde donde lo dejaste.", "cartUpdateInProgress": "Tiene una actualización de carrito en proceso. ¿Estás seguro de que quieres salir de esta página? Es posible que se pierdan sus cambios.", + "includedItems": "Incluido", "originalPrice": "El precio original era {price}.", "currentPrice": "El precio actual es {price}.", "quantityReadyToShip": "{cantidad, número} listo para enviar", diff --git a/core/messages/es-LA.json b/core/messages/es-LA.json index c8595af4ea..65fd08f119 100644 --- a/core/messages/es-LA.json +++ b/core/messages/es-LA.json @@ -426,6 +426,7 @@ "cartCombined": "Notamos que tenías artículos guardados en un carrito anterior, así que los hemos agregado a tu carrito actual.", "cartRestored": "Iniciaste un carrito en otro dispositivo y lo hemos restaurado aquí para que puedas continuar desde donde lo dejaste.", "cartUpdateInProgress": "Tiene una actualización de carrito en proceso. ¿Estás seguro de que quieres salir de esta página? Es posible que se pierdan sus cambios.", + "includedItems": "Incluido", "originalPrice": "El precio original era {price}.", "currentPrice": "El precio actual es {price}.", "quantityReadyToShip": "{cantidad, número} listo para enviar", diff --git a/core/messages/es-MX.json b/core/messages/es-MX.json index c8595af4ea..65fd08f119 100644 --- a/core/messages/es-MX.json +++ b/core/messages/es-MX.json @@ -426,6 +426,7 @@ "cartCombined": "Notamos que tenías artículos guardados en un carrito anterior, así que los hemos agregado a tu carrito actual.", "cartRestored": "Iniciaste un carrito en otro dispositivo y lo hemos restaurado aquí para que puedas continuar desde donde lo dejaste.", "cartUpdateInProgress": "Tiene una actualización de carrito en proceso. ¿Estás seguro de que quieres salir de esta página? Es posible que se pierdan sus cambios.", + "includedItems": "Incluido", "originalPrice": "El precio original era {price}.", "currentPrice": "El precio actual es {price}.", "quantityReadyToShip": "{cantidad, número} listo para enviar", diff --git a/core/messages/es-PE.json b/core/messages/es-PE.json index c8595af4ea..65fd08f119 100644 --- a/core/messages/es-PE.json +++ b/core/messages/es-PE.json @@ -426,6 +426,7 @@ "cartCombined": "Notamos que tenías artículos guardados en un carrito anterior, así que los hemos agregado a tu carrito actual.", "cartRestored": "Iniciaste un carrito en otro dispositivo y lo hemos restaurado aquí para que puedas continuar desde donde lo dejaste.", "cartUpdateInProgress": "Tiene una actualización de carrito en proceso. ¿Estás seguro de que quieres salir de esta página? Es posible que se pierdan sus cambios.", + "includedItems": "Incluido", "originalPrice": "El precio original era {price}.", "currentPrice": "El precio actual es {price}.", "quantityReadyToShip": "{cantidad, número} listo para enviar", diff --git a/core/messages/es.json b/core/messages/es.json index 88185580ac..a6c7af390c 100644 --- a/core/messages/es.json +++ b/core/messages/es.json @@ -426,6 +426,7 @@ "cartCombined": "Nos hemos dado cuenta de que tenías artículos guardados en un carrito anterior, así que los hemos añadido a tu carrito actual.", "cartRestored": "Empezaste a llenar un carrito en otro dispositivo y lo hemos restaurado aquí para que puedas seguir donde lo dejaste.", "cartUpdateInProgress": "Tienes una actualización del carrito en curso. ¿Seguro que quieres abandonar esta página? Es posible que se pierdan los cambios.", + "includedItems": "Incluido", "originalPrice": "El precio original era {price}.", "currentPrice": "El precio actual es {price}.", "quantityReadyToShip": "{quantity, number} listo para enviar", diff --git a/core/messages/fr.json b/core/messages/fr.json index a582622dd2..b0881936c3 100644 --- a/core/messages/fr.json +++ b/core/messages/fr.json @@ -426,6 +426,7 @@ "cartCombined": "Nous avons remarqué que votre panier précédent contenait des articles enregistrés. Nous avons donc ajouté ces articles à votre panier actuel.", "cartRestored": "Vous avez débuté vos achats sur un autre appareil. Nous avons restauré votre panier ici pour que vous puissiez reprendre là où vous en étiez.", "cartUpdateInProgress": "Une mise à jour de votre panier est en cours. Voulez-vous vraiment quitter cette page ? Vos modifications pourraient être perdues.", + "includedItems": "Inclus", "originalPrice": "Le prix initial était de {price}.", "currentPrice": "Le prix actuel est de {price}.", "quantityReadyToShip": "{quantity, number} prêts à être expédiés", diff --git a/core/messages/it.json b/core/messages/it.json index 0a568bf876..a11c4d556b 100644 --- a/core/messages/it.json +++ b/core/messages/it.json @@ -426,6 +426,7 @@ "cartCombined": "Abbiamo notato che avevi salvato degli articoli in un carrello precedente, quindi li abbiamo aggiunti al carrello attuale.", "cartRestored": "Hai avviato un carrello su un altro dispositivo e lo abbiamo ripristinato qui, così puoi riprendere da dove avevi lasciato.", "cartUpdateInProgress": "Hai un aggiornamento del carrello attivo in corso. Uscire dalla pagina? Le modifiche potrebbero andare perse.", + "includedItems": "Incluso", "originalPrice": "Il prezzo originale era {price}.", "currentPrice": "Il prezzo corrente è {price}.", "quantityReadyToShip": "{quantity, number} pronto per la spedizione", diff --git a/core/messages/ja.json b/core/messages/ja.json index 389ffbbfef..9223b82c33 100644 --- a/core/messages/ja.json +++ b/core/messages/ja.json @@ -426,6 +426,7 @@ "cartCombined": "以前のカートに商品が保存されていたので、それを現在のカートに追加しました。", "cartRestored": "別のデバイスでカートに商品が追加されていたため、中断されたところからお買い物を再開できるよう、こちらにカートの内容を復元しました。", "cartUpdateInProgress": "カートの更新が進行中です。このページを離れてもよろしいですか?変更内容が失われる可能性があります。", + "includedItems": "含まれる", "originalPrice": "元の価格は{price}でした。", "currentPrice": "現在の価格は{price}です。", "quantityReadyToShip": "{quantity, number} 個、発送準備完了", diff --git a/core/messages/nl.json b/core/messages/nl.json index 53c4613ae4..268e8beb1f 100644 --- a/core/messages/nl.json +++ b/core/messages/nl.json @@ -426,6 +426,7 @@ "cartCombined": "We hebben gezien dat je artikelen in een eerder winkelmandje had opgeslagen, dus we hebben ze voor je aan je huidige winkelmandje toegevoegd.", "cartRestored": "Je bent een winkelmandje begonnen op een ander apparaat en we hebben het hier hersteld, zodat je verder kunt gaan waar je was gebleven.", "cartUpdateInProgress": "Je winkelwagentje wordt bijgewerkt. Weet je zeker dat je deze pagina wilt verlaten? Je wijzigingen kunnen verloren gaan.", + "includedItems": "Inclusief", "originalPrice": "De oorspronkelijke prijs was {price}.", "currentPrice": "De huidige prijs is {price}.", "quantityReadyToShip": "{quantity, number} klaar voor verzending", diff --git a/core/messages/no.json b/core/messages/no.json index 2e5a6c0a16..c92ec74150 100644 --- a/core/messages/no.json +++ b/core/messages/no.json @@ -426,6 +426,7 @@ "cartCombined": "Vi la merke til at du hadde varer lagret i en tidligere handlekurv, så vi har lagt dem til i din nåværende handlekurv for deg.", "cartRestored": "Du startet en handlekurv på en annen enhet, og vi har gjenopprettet den her, slik at du kan fortsette der du slapp.", "cartUpdateInProgress": "Du har en handlekurvoppdatering i gang. Er du sikker på at du vil forlate denne siden? Endringene kan gå tapt.", + "includedItems": "Inkludert", "originalPrice": "Opprinnelig pris var {price}.", "currentPrice": "Nåværende pris er {price}.", "quantityReadyToShip": "{antall, number} klar til sending", diff --git a/core/messages/pl.json b/core/messages/pl.json index 5bcfefb15a..9c0b4db31a 100644 --- a/core/messages/pl.json +++ b/core/messages/pl.json @@ -426,6 +426,7 @@ "cartCombined": "Zauważyliśmy, że w poprzednim koszyku były zapisane produkty, więc dodaliśmy je do bieżącego koszyka.", "cartRestored": "Dodano produkty do koszyka na innym urządzeniu. Przywróciliśmy koszyk tutaj, aby umożliwić kontynuowanie zakupów.", "cartUpdateInProgress": "You have a cart update in progress. Are you sure you want to leave this page? Your changes may be lost.", + "includedItems": "W zestawie", "originalPrice": "Original price was {price}.", "currentPrice": "Current price is {price}.", "quantityReadyToShip": "{quantity, number} ready to ship", diff --git a/core/messages/pt-BR.json b/core/messages/pt-BR.json index e0179ad123..306b2540d4 100644 --- a/core/messages/pt-BR.json +++ b/core/messages/pt-BR.json @@ -426,6 +426,7 @@ "cartCombined": "Percebemos que você tinha itens salvos em um carrinho anterior, então colocamos esses itens no carrinho atual para você.", "cartRestored": "Você iniciou um carrinho em outro dispositivo, e restauramos esse carrinho aqui para que você possa continuar de onde parou.", "cartUpdateInProgress": "You have a cart update in progress. Are you sure you want to leave this page? Your changes may be lost.", + "includedItems": "Incluído", "originalPrice": "Original price was {price}.", "currentPrice": "Current price is {price}.", "quantityReadyToShip": "{quantity, number} ready to ship", diff --git a/core/messages/pt.json b/core/messages/pt.json index e0179ad123..306b2540d4 100644 --- a/core/messages/pt.json +++ b/core/messages/pt.json @@ -426,6 +426,7 @@ "cartCombined": "Percebemos que você tinha itens salvos em um carrinho anterior, então colocamos esses itens no carrinho atual para você.", "cartRestored": "Você iniciou um carrinho em outro dispositivo, e restauramos esse carrinho aqui para que você possa continuar de onde parou.", "cartUpdateInProgress": "You have a cart update in progress. Are you sure you want to leave this page? Your changes may be lost.", + "includedItems": "Incluído", "originalPrice": "Original price was {price}.", "currentPrice": "Current price is {price}.", "quantityReadyToShip": "{quantity, number} ready to ship", diff --git a/core/messages/sv.json b/core/messages/sv.json index e265176de4..247734e192 100644 --- a/core/messages/sv.json +++ b/core/messages/sv.json @@ -426,6 +426,7 @@ "cartCombined": "Vi märkte att du hade varor sparade i en tidigare kundvagn, så vi har lagt till dem i din nuvarande kundvagn åt dig.", "cartRestored": "Du startade en kundvagn på en annan enhet, och vi har återställt den här så att du kan fortsätta där du slutade.", "cartUpdateInProgress": "Du har en pågående kundvagnsuppdatering. Är du säker på att du vill lämna den här sidan? Dina ändringar kan gå förlorade.", + "includedItems": "Ingår", "originalPrice": "Ursprungligt pris var {price}.", "currentPrice": "Nuvarande pris är {price}.", "quantityReadyToShip": "{quantity, number} klara för leverans", diff --git a/core/package.json b/core/package.json index e9849c94df..6c06ebf4e6 100644 --- a/core/package.json +++ b/core/package.json @@ -65,7 +65,7 @@ "lodash.debounce": "^4.0.8", "lru-cache": "^11.1.0", "lucide-react": "^0.474.0", - "next": "~16.3.4", + "next": "~16.4.3", "next-auth": "5.0.0-beta.30", "next-intl": "^4.6.1", "nuqs": "^2.4.3", diff --git a/core/tests/ui/e2e/blog.spec.ts b/core/tests/ui/e2e/blog.spec.ts index df7e6a8fbb..22f990a396 100644 --- a/core/tests/ui/e2e/blog.spec.ts +++ b/core/tests/ui/e2e/blog.spec.ts @@ -25,6 +25,8 @@ test('Blog is accessible and displays posts', async ({ page, blog }) => { }); test('Blog can be filtered by tags', async ({ page, blog }) => { + test.setTimeout(90000); + const t = await getTranslations('Blog'); const { name, path } = await blog.getBlog(); const tag = faker.string.alpha(10); @@ -32,7 +34,12 @@ test('Blog can be filtered by tags', async ({ page, blog }) => { tags: [tag], }); - await page.goto(`${path}?tag=${tag}`); + // A new post can take a few seconds to reach the storefront, so reload until it shows. + await expect(async () => { + await page.goto(`${path}?tag=${tag}`); + await expect(page.getByRole('link', { name: post.title })).toBeVisible(); + }).toPass({ timeout: 60000, intervals: [2000] }); + await expect(page.getByRole('heading', { name })).toBeVisible(); // Streamed content sits in a hidden copy until React reveals it, so match visible text only. @@ -41,13 +48,14 @@ test('Blog can be filtered by tags', async ({ page, blog }) => { await expect(breadcrumbs.getByText(t('home')).filter({ visible: true })).toBeVisible(); await expect(breadcrumbs.getByText(name).filter({ visible: true })).toBeVisible(); await expect(breadcrumbs.getByText(tag).filter({ visible: true })).toBeVisible(); - await expect(page.getByRole('link', { name: post.title })).toBeVisible(); }); test('Blog post page displays content, breadcrumbs, tags, and author info', async ({ page, blog, }) => { + test.setTimeout(90000); + const t = await getTranslations('Blog'); const { name } = await blog.getBlog(); const post = await blog.createPost({ @@ -61,8 +69,11 @@ test('Blog post page displays content, breadcrumbs, tags, and author info', asyn tags: ['Tag 1', 'Tag 2'], }); - await page.goto(post.path); - await expect(page.getByRole('heading', { name: post.title })).toBeVisible(); + // A new post can take a few seconds to reach the storefront, so reload until it shows. + await expect(async () => { + await page.goto(post.path); + await expect(page.getByRole('heading', { name: post.title })).toBeVisible(); + }).toPass({ timeout: 60000, intervals: [2000] }); // Streamed content sits in a hidden copy until React reveals it, so match visible text only. const breadcrumbs = page.getByLabel('breadcrumb'); diff --git a/core/tests/ui/e2e/compare.spec.ts b/core/tests/ui/e2e/compare.spec.ts index 453257d9b0..aca97bb2c8 100644 --- a/core/tests/ui/e2e/compare.spec.ts +++ b/core/tests/ui/e2e/compare.spec.ts @@ -130,6 +130,8 @@ test("Product with variants 'View options' redirect to product page", async ({ p }); test('Disabled add to cart for out of stock products', async ({ page, catalog }) => { + test.setTimeout(90000); + const t = await getTranslations('Compare'); const product = await catalog.createSimpleProduct({ @@ -142,10 +144,13 @@ test('Disabled add to cart for out of stock products', async ({ page, catalog }) inventoryLevel: 0, }); - await page.goto(`/compare/?ids=${product.id},${productWithVariants.id}`); - + // New products can take a few seconds to reach the storefront, so reload until they show. // Simple products should have the add to cart button disabled - await expect(page.getByRole('button', { name: t('addToCart') })).toBeDisabled(); + await expect(async () => { + await page.goto(`/compare/?ids=${product.id},${productWithVariants.id}`); + await expect(page.getByRole('button', { name: t('addToCart') })).toBeDisabled(); + }).toPass({ timeout: 60000, intervals: [2000] }); + // Product with variants should have the view options link even when OOS await expect(page.getByRole('link', { name: t('viewOptions') })).toBeVisible(); }); diff --git a/core/vibes/soul/sections/cart/client.tsx b/core/vibes/soul/sections/cart/client.tsx index 776bee608b..118228eb57 100644 --- a/core/vibes/soul/sections/cart/client.tsx +++ b/core/vibes/soul/sections/cart/client.tsx @@ -46,6 +46,13 @@ interface CartLineIteminventoryMessages { backorderMessage?: string; } +export interface CartIncludedItem { + id: string; + title: string; + subtitle?: string; + quantity?: number; +} + export interface CartLineItem { typename: string; id: string; @@ -56,6 +63,7 @@ export interface CartLineItem { price: Price; href?: string; inventoryMessages?: CartLineIteminventoryMessages; + includedItems?: CartIncludedItem[]; } export interface CartGiftCertificateLineItem extends CartLineItem { @@ -176,6 +184,7 @@ export interface CartProps { giftCertificate?: GiftCertificate; shipping?: Shipping; lineItemActionPendingLabel?: string; + includedItemsLabel?: string; } const defaultEmptyState = { @@ -222,6 +231,7 @@ export function CartClient({ deleteLineItemLabel, lineItemAction, lineItemActionPendingLabel = 'You have a cart update in progress. Are you sure you want to leave this page? Your changes may be lost.', + includedItemsLabel = 'Included', checkoutAction, checkoutLabel = 'Checkout', emptyState = defaultEmptyState, @@ -621,6 +631,27 @@ export function CartClient({ {lineItem.subtitle} + {lineItem.includedItems != null && lineItem.includedItems.length > 0 && ( +
+ {includedItemsLabel} +
    + {lineItem.includedItems.map((includedItem) => ( +
  • + + {includedItem.title} + {includedItem.quantity != null && ` × ${includedItem.quantity}`} + {includedItem.subtitle != null && ( + + {' '} + ({includedItem.subtitle}) + + )} + +
  • + ))} +
+
+ )} -
+
{/* Counter */}
-