diff --git a/README.md b/README.md index 9571dd8..ebe4013 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,106 @@ # saleor-commerce -[Vercel's Next.js Saleor Commerce](https://github.com/saleor/storefront) on -**Cloudflare Workers**, deployed by [Orun](https://github.com/sourceplane/orun) to stage -and prod on every merge, and then packaged as an Orun baseline. - -This commit is the repository's frame: `intent.yaml` (with the placeholder -workspace `ws_CHANGE_ME`, so CI plans nothing until it is linked), the Orun -CI workflow, the shared TypeScript and ESLint configuration, and the spec -index. The work is tracked as an epic under [`specs/epics`](specs/epics/README.md). +[Saleor's Next.js storefront](https://github.com/saleor/storefront) ("Paper", +the storefront Vercel lists as Next.js Saleor Commerce) — home, categories, +collections, search with filters, product pages with variants, a cart and a +multi-step checkout, accounts and orders, in several languages and channels, +every Saleor read a `"use cache"` entry revalidated from Saleor's webhook — +running on **Cloudflare Workers + Static Assets** through +[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with the +Next.js data cache in an **R2 bucket** provisioned by Terraform through +[Orun](https://github.com/sourceplane/orun) and the tag cache and revalidation +queue in **Durable Objects** the Worker itself exports, deployed by +[Orun](https://github.com/sourceplane/orun) to stage and prod on every merge. +Packaging it as an Orun baseline is the next milestone (SC2). + +A fresh build needs no Saleor store: until its owner connects one, `/` says +"Connect your Saleor store" and every other page goes there — never a 500. +The owner connects a store by setting its API URL (and channel) as Orun +secrets and redeploying. The account must be on **Workers Paid** (the Worker +is about 3.4 MiB gzipped). See +[`specs/epics/saleor-commerce`](specs/epics/saleor-commerce/README.md) for the design, the +milestones and the as-built status. + +## What is here (the product) + +| Surface | Where | +|---|---| +| The storefront's routes: `/[locale]/[channel]/…`, `/checkout`, `/order`, `/api/revalidate`, `/api/og`, `/api/health` | `apps/web/src/app` | +| The store's name | `apps/web/src/config/brand.ts` (`SITE_NAME`) | +| Whether a Saleor store is connected; the page that says how to connect one | `apps/web/src/lib/saleor-connection.ts`, `apps/web/src/app/(root)/page.tsx`, `apps/web/src/middleware.ts` | +| Saleor's data layer: cached reads, their tags and profiles, the webhook's invalidation plan | `apps/web/src/lib/saleor`, `apps/web/src/graphql` | +| Saleor's GraphQL schema the types are generated from (3.23) | `apps/web/schema.graphql` | +| Workers build, cache bindings and deploy contract | `apps/web/next.config.js`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json` (→ the committed `wrangler.jsonc`), `component.yaml` | +| The R2 bucket (stage, prod) | `infra/terraform/cloudflare-r2` | +| The wrangler renderer | `tooling/wire` | +| Tests | `apps/web` (upstream's 787-test vitest suite), `tests/web` (the port's seams) | + +## Getting started + +```bash +pnpm install +pnpm run wire:fixture # render apps/web/wrangler.jsonc from the offline fixture +pnpm typecheck +pnpm lint +pnpm test +pnpm build # GraphQL types + next build + opennextjs-cloudflare build → apps/web/.open-next +``` + +```bash +pnpm --filter @app/web dev # http://localhost:3000, Next's dev server +pnpm --filter @app/web preview # wrangler dev over the built Worker, a local R2 bucket and local Durable Objects +``` + +With no `NEXT_PUBLIC_SALEOR_API_URL` both serve the "connect your Saleor +store" page. To run against a store, put its URL and channel in +`apps/web/.env.local` (from `apps/web/.env.example`). Offline, the e2e's +stand-in API answers every query from the schema: +`node testing/lib/fake-saleor.mjs --schema apps/web/schema.graphql --graphql apps/web --port 4010`. + +## How it maps to Vercel + +| Vercel | Here | +|---|---| +| Next.js hosting (SSR, server actions, route handlers, middleware, `next/og`) | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets (`ASSETS`) | +| Cache Components (partial prerendering) with `"use cache"` and named `cacheLife` profiles | `"use cache"`, its profiles and its tags kept through `experimental.useCache`; every route renders per request from those cached reads | +| Data Cache entries | The R2 bucket bound as `NEXT_INC_CACHE_R2_BUCKET` | +| `revalidateTag` from Saleor's webhook | A sharded Durable Object tag cache (`NEXT_TAG_CACHE_DO_SHARDED`) consulted on every cache read | +| Stale-while-revalidate | A Durable Object queue (`NEXT_CACHE_DO_QUEUE`) that re-renders stale entries through the Worker's `WORKER_SELF_REFERENCE` binding | +| Image Optimization | Off (`images.unoptimized`): Saleor's thumbnail endpoint already sizes the images | +| `NEXT_PUBLIC_SALEOR_API_URL`, `NEXT_PUBLIC_DEFAULT_CHANNEL` | The Orun secrets `SALEOR_API_URL`, `SALEOR_CHANNEL` (optional build env) — and, unset, the "connect your Saleor store" page instead of a failed build | +| `NEXT_PUBLIC_STOREFRONT_URL` | Each environment's `SITE_URL`, else its workers.dev URL, set by the build | +| `SALEOR_WEBHOOK_SECRET`, `REVALIDATE_SECRET`, `SALEOR_APP_TOKEN` | Worker secrets | +| Vercel Web Analytics, Speed Insights | Off unless the build runs on Vercel | +| Deploy on push | Orun applies the bucket and deploys `-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`) | +| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, deployed | + +Partial prerendering is off: `@opennextjs/cloudflare` 1.20 cannot run Next 16's +Cache Components on workerd yet (a Cache Components page answers 500 and then +hangs — opennextjs-cloudflare#1450), so the storefront keeps upstream's +`"use cache"` reads through `experimental.useCache` and renders every route at +request time. The epic's [IMPLEMENTATION-STATUS](specs/epics/saleor-commerce/IMPLEMENTATION-STATUS.md) +has the evidence. + +## How the bucket reaches the Worker + +``` +infra/terraform/cloudflare-r2 ──apply (r2-data token)──► orun secret WIRING_CLOUDFLARE_R2 (stage, prod) + │ (each deploy resolves it as it starts; + │ a missing one fails the lane) + ▼ +apps/web dependsOn cloudflare-r2 (enforced on main) · secretEnv WIRING_CLOUDFLARE_R2_ + build: tooling/wire/live.mjs → wrangler.jsonc with the environment's bucket name + (dev, verify-only, renders the fixture) → next build → opennextjs-cloudflare + deploy: workers-deploy token → -web-, its Durable Objects migrated on first deploy +``` + +`wrangler.jsonc` is committed as the fixture render of +`wrangler.template.jsonc`, because the deploy lane's `verify-app-structure` +step checks the config exists before it builds; `testing/e2e.test.sh` fails +if the two disagree. + +## CI + +| Workflow | What it runs | Ships to a product | +|---|---|---| +| `ci.yml` | the Orun pipeline, and the only workflow a product carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the R2 root planned for stage and prod, the storefront built and dry-deployed per environment; they neither lint nor run the tests, which `baseline.yml`'s e2e tier runs before every tag), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone runs and nothing waits for it (the landing checked its commit in the box); a merge applies the R2 bucket, then deploys stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes | diff --git a/apps/web/.env.configurator.local.example b/apps/web/.env.configurator.local.example new file mode 100644 index 0000000..8bc80d8 --- /dev/null +++ b/apps/web/.env.configurator.local.example @@ -0,0 +1,10 @@ +# Saleor Configurator — dev/staging ONLY (gitignored via .env*.local) +# +# Copy to .env.configurator.local and paste a staff or broad-permission app token. +# Never commit this file. Never use production admin tokens. +# Never import SALEOR_CONFIGURATOR_TOKEN in Next.js app code. +# +# Generate in Dashboard → Configuration → Staff → [your dev user] → Create token +# or create a dedicated "Configurator Dev" app with required permissions. +# +# SALEOR_CONFIGURATOR_TOKEN= diff --git a/apps/web/.env.example b/apps/web/.env.example new file mode 100644 index 0000000..1a63380 --- /dev/null +++ b/apps/web/.env.example @@ -0,0 +1,168 @@ +# Local development: copy to .env.local (Next's dev server) or .dev.vars (the +# Worker preview, `pnpm preview`); both are git-ignored. On the deployed +# Workers the API URL and the channel are the Orun secrets SALEOR_API_URL and +# SALEOR_CHANNEL, inlined by each environment's build, and the secrets below +# (SALEOR_WEBHOOK_SECRET, REVALIDATE_SECRET, SALEOR_APP_TOKEN) are Worker +# secrets — the repository's README, "Connecting Saleor". + +# Saleor API URL - keep the trailing slash. Unset, the storefront builds +# without calling Saleor and serves the "Connect your Saleor store" page. +NEXT_PUBLIC_SALEOR_API_URL=https://your-instance.saleor.cloud/graphql/ + +# Optional Paper handshake label for /api/cache-info identity (production|staging|preview|development). +# Leave unset on Vercel — VERCEL_ENV / NODE_ENV fill this in. Set only when those lie: +# e.g. a staging host with NODE_ENV=production, or any non-Vercel deploy that isn't prod. +# PAPER_STOREFRONT_ENVIRONMENT=staging + +# Storefront URL - canonical URLs, OG images, and the redirect allowlist. Each +# deployed environment's build sets it (its SITE_URL, else its workers.dev URL). +NEXT_PUBLIC_STOREFRONT_URL=http://localhost:3000 + +# Mobile dev via ngrok / LAN — hostnames only (no https://), comma-separated. +# Required when a real device loads the dev server through a tunnel; restart pnpm dev after change. +# ALLOWED_DEV_ORIGINS=servilely-quare-polly.ngrok-free.dev + +# Checkout-only deploy (optional) — absolute checkout links from storefront and redirect allowlist +# NEXT_PUBLIC_CHECKOUT_URL=https://checkout.example.com + +# Extra allowed redirect origins (optional) — comma-separated origins +# +# Must include the protocol + domain + optional port, for example: +# - https://example.com +# - http://localhost:3000 +# - http://127.0.0.1:3000 +# +# See ./docs/configuration/allowed-origins.md for more information +# +# ALLOWED_EXTRA_ORIGINS=https://preview.example.com,https://checkout-preview.example.com + +# Channel slug (required) - fallback when STOREFRONT_CHANNELS is not set +# The root "/" redirects to this channel (e.g., "/default-channel") +NEXT_PUBLIC_DEFAULT_CHANNEL=default-channel + +# Storefront channel allowlist (recommended for multi-channel) — comma-separated slugs +# Only these channels get routes, cache invalidation, and footer selector entries. +# STOREFRONT_CHANNELS=us,uk,eu + +# Storefront locale allowlist — comma-separated URL slugs (e.g. en,pl,de,fr,fi,nb,ja,ko). +# Must be NEXT_PUBLIC_* so client components (checkout logo, locale links) match SSR. +# NEXT_PUBLIC_STOREFRONT_LOCALES=en,pl,de,fr,fi,nb,ja,ko +# Also drives hreflang x-default (same target as root redirect / invalid-locale fallback). +# NEXT_PUBLIC_DEFAULT_LOCALE=en +# Optional hard locale↔market matrix: invalid pairs 404; language switch jumps to the paired +# channel; hreflang keys become region-aware (ja-JP). When unset, any locale × channel is OK. +# NEXT_PUBLIC_STOREFRONT_LOCALE_CHANNELS=en:default-channel,ja:japan,pl:channel-pln + +# Storefront marketing copy — default is saleor (Saleor Models). Opt out with code. +CONTENT_PROVIDER=saleor +# CONTENT_PROVIDER=code + +# Optional typography theme examples — default is Geist-only (Direction C). +# See config/themes/README.md and config/themes/typography-editorial.env.example +# Or: pnpm run dev:theme-editorial +# NEXT_PUBLIC_TYPOGRAPHY_THEME=editorial + +# App token (optional) — channel discovery and guest /order/find (needs MANAGE_ORDERS). +# SALEOR_APP_TOKEN= + +# Configurator (dev/staging only) — NOT loaded by Next.js. Copy .env.configurator.local.example +# SALEOR_CONFIGURATOR_TOKEN lives in .env.configurator.local — see config/saleor/README.md + +# Opt-in: discover ALL active Saleor channels from API (not recommended when Saleor has many channels). +# Prefer STOREFRONT_CHANNELS instead. Requires SALEOR_APP_TOKEN. +# STOREFRONT_DISCOVER_CHANNELS=true + +# Cache invalidation — use ≥32 character random strings in production +# Manual revalidation: GET /api/cache-info and GET /api/revalidate (Authorization: Bearer header) +# REVALIDATE_SECRET= +# Guest order-view HMAC (falls back to REVALIDATE_SECRET). Required in production if REVALIDATE_SECRET is unset. +# ORDER_VIEW_SECRET= +# Saleor webhook HMAC for POST /api/revalidate (Dashboard → Configuration → Webhooks) +# SALEOR_WEBHOOK_SECRET= + +# Checkout — Dummy Payment (local/staging test orders) +# Enabled automatically in development. Set to true on cloud/staging to allow dummy checkout. +# ALLOW_DUMMY_PAYMENT=true +# NEXT_PUBLIC_ALLOW_DUMMY_PAYMENT=true + +# Checkout — Stripe Elements (Saleor Stripe app) +# Required on cloud/staging (NODE_ENV=production). Auto-enabled in local development. +# Publishable keys come from Saleor paymentGatewayInitialize — configure Stripe in Saleor Dashboard. +# NEXT_PUBLIC_ENABLE_STRIPE_PAYMENTS=true +# ENABLE_STRIPE_PAYMENTS=true +# Express Checkout wallets (Apple Pay, Google Pay, Link) on payment step — on when Stripe is enabled. +# NEXT_PUBLIC_ENABLE_STRIPE_EXPRESS_CHECKOUT=false + +# Checkout contact step — "Email me with news and offers" (on by default; persisted as checkout metadata). +# NEXT_PUBLIC_ENABLE_CHECKOUT_MARKETING_OPT_IN=false + +# --------------------------------------------------------------------------- +# Cost controls (Vercel) +# --------------------------------------------------------------------------- +# Paper's defaults are tuned for a production catalogue. Each knob below trades +# money against freshness — see skills/saleor-paper-storefront/rules/data-caching.md +# § Cost controls and rules/ui-images.md for the reasoning. + +# Which pipeline serves catalog images. Default `saleor`: PLP cards and the PDP gallery +# render a plain against Saleor's CloudFront-backed thumbnails, so those +# images never touch /_next/image and are never billed as transformations. Set to +# `vercel` to route everything back through next/image without a code change — the +# escape hatch if your Saleor deployment does not front media with a CDN. +# NEXT_PUBLIC_PAPER_IMAGE_PIPELINE=saleor + +# Extra hostnames /_next/image is allowed to optimize (comma-separated, no scheme). +# Saleor Cloud hosts and the NEXT_PUBLIC_SALEOR_API_URL host are always allowed. +# Anything listed here can be optimized at your expense — keep it tight. +# IMAGE_ALLOWED_HOSTS=cdn.example.com,assets.example.com + +# How long Vercel keeps an optimized image before re-optimizing it (seconds). +# Default 2678400 (31 days). Saleor thumbnail URLs are stable, so this is nearly free — +# but replacing an image *in place* in Saleor reuses the URL, so the old bytes serve +# until this expires. Lower it if the catalogue is re-shot often. +# NEXT_IMAGE_MIN_CACHE_TTL=2678400 + +# Speed Insights sampling (0–1). Default 0.01: Vercel bills ~3–6 data points per hard +# navigation, and unsampled collection at high traffic can cost more than the rest of +# the storefront infrastructure. 1% is enough for a weekly P75 at scale; on a +# low-traffic / demo project the daily RES line becomes a random walk — raise this +# to 1 only for a short investigation, then set it back. +# NEXT_PUBLIC_SPEED_INSIGHTS_SAMPLE_RATE=0.01 +# Speed Insights itself, like Web Analytics below: on when building on Vercel +# (VERCEL=1), off elsewhere — on Cloudflare Workers its script would 404. +# NEXT_PUBLIC_VERCEL_SPEED_INSIGHTS=1 + +# Vercel Web Analytics (cookieless page views — the human page-view denominator). +# Default: on when building on Vercel (VERCEL=1), off elsewhere. No sampling knob exists; +# it is billed per event (~$3 per 100k on Pro), so the lever is on/off. Also enable Web +# Analytics in the Vercel project (Analytics tab) or the script 404s on every page. +# URLs are redacted before send (checkout id, order token, search terms, Stripe secrets). +# NEXT_PUBLIC_VERCEL_WEB_ANALYTICS=1 + +# Analytics consent. required (default): merchant tag + first-touch cookie wait for +# window.paperAnalytics.setConsent("granted") — Paper ships no banner. +# implied: visiting is enough; ads consents stay denied either way. +# NEXT_PUBLIC_ANALYTICS_CONSENT_MODE=required + +# Optional merchant tag (off until set). Ids must be G-…; containers are ignored. +# Server-side purchase delivery is not shipped yet. +# NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXX + +# Bust `listing:all:{channel}` on every listing-affecting product webhook. +# Default on. Set to 0 for high-churn catalogs: selling one unique SKU +# should not regenerate the all-products grid. Category and collection +# shards still bust; the all-products page then relies on the 1 h catalog backstop. +# PAPER_BUST_LISTING_ALL_ON_PRODUCT_EVENT=0 + +# Forced delay between Saleor GraphQL requests (ms). Defaults to 200 during `next build` +# (where generateStaticParams can trip Saleor's rate limiter) and 0 at runtime, where it +# would only add latency you pay for. Raise it if Saleor rate-limits your live traffic. +# SALEOR_MIN_REQUEST_DELAY_MS=0 + +# Discovering channels queries Saleor during generateStaticParams and then prerenders +# every locale x channel pair, so build minutes and prerendered output grow with the +# product of both. An explicit STOREFRONT_CHANNELS allowlist is the cheaper default; +# only opt in when the channel list genuinely changes without a deploy. +# STOREFRONT_DISCOVER_CHANNELS=true + +# Max concurrent Saleor GraphQL requests per instance (default 3). +# SALEOR_MAX_CONCURRENT_REQUESTS=3 diff --git a/apps/web/.gitignore b/apps/web/.gitignore new file mode 100644 index 0000000..f756f71 --- /dev/null +++ b/apps/web/.gitignore @@ -0,0 +1,81 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# Generated GraphQL types (regenerate with `pnpm generate` and `pnpm generate:checkout`) +gql/ +src/checkout/graphql/generated/ + +.env + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# Local catalog translation work (real slugs — never commit) +config/saleor/fixtures/catalog-translations/locales/* +!config/saleor/fixtures/catalog-translations/locales/.gitkeep + +# Local-only dev scripts (see scripts/local/README.md) +scripts/local/* +!scripts/local/README.md + +# misc +.DS_Store +*.pem +.agents/ + +# Saleor Configurator deploy reports (generated per deploy, env-specific) +.configurator/ + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# local env files +.env*.local +.env.local.* +# Demo credential dumps (e.g. .env.local.demo) — never commit +.env*.demo + +# Local HAR captures — often contain cookies and full response bodies +*.har + +# SALEOR_FIXTURES=record output. Public queries only, still local. +e2e/fixtures/saleor/** +!e2e/fixtures/saleor/README.md + +# vercel +.vercel + +# cloudflare / open-next build output (the Worker's typed bindings, +# cloudflare-env.d.ts, are committed) +/.open-next/ +/.wrangler/ +/vendor/ +/patches/ +.cf.env + +# typescript +*.tsbuildinfo +next-env.d.ts +/test-results/ + +.idea/ +.pnpm-store + +# Internal/marketing docs — keep local, never commit (strategy lives in the brain) +docs/marketing/ + +# Local notes — never commit +docs/plans/ diff --git a/apps/web/.graphqlrc.ts b/apps/web/.graphqlrc.ts new file mode 100644 index 0000000..240b333 --- /dev/null +++ b/apps/web/.graphqlrc.ts @@ -0,0 +1,70 @@ +/** + * GraphQL Code Generator Configuration + * + * This config generates TypeScript types from GraphQL queries/mutations. + * + * ## Usage + * Run `pnpm run generate` after modifying any `.graphql` file in `src/graphql/`. + * + * ## What it does + * 1. Reads Saleor's published schema (schema.graphql) + * 2. Reads all `.graphql` files from `src/graphql/` + * 3. Generates typed documents in `src/gql/` + * + * ## Important Notes + * - The `src/gql/` directory is AUTO-GENERATED - do not edit manually + * - The checkout module has its own types in `src/checkout/graphql/index.ts` + * - Always run `pnpm run generate` after changing GraphQL queries + */ +import { loadEnvConfig } from "@next/env"; +import type { CodegenConfig } from "@graphql-codegen/cli"; + +loadEnvConfig(process.cwd()); + +// Generated from Saleor's published schema (`schema.graphql`, Saleor 3.23 — +// saleor/saleor `saleor/graphql/schema.graphql`), not from the live API: +// the build, the type check and the tests then need no store, and a product +// generates the same types before and after its owner connects one. +const schemaUrl = "schema.graphql"; + +const config: CodegenConfig = { + overwrite: true, + schema: schemaUrl, + // Storefront GraphQL queries - add new queries here + documents: "src/graphql/**/*.graphql", + generates: { + // Output directory for generated types (DO NOT EDIT MANUALLY) + "src/gql/": { + preset: "client", + plugins: [], + config: { + documentMode: "string", + useTypeImports: true, + strictScalars: true, + scalars: { + Date: "string", + DateTime: "string", + Day: "number", + Decimal: "number", + GenericScalar: "unknown", + JSON: "unknown", + JSONString: "string", + Metadata: "Record", + Hour: "number", + Minute: "number", + PositiveInt: "number", + PositiveDecimal: "number", + UUID: "string", + Upload: "unknown", + WeightScalar: "unknown", + _Any: "unknown", + }, + }, + presetConfig: { + fragmentMasking: false, + }, + }, + }, +}; + +export default config; diff --git a/apps/web/.prettierignore b/apps/web/.prettierignore new file mode 100644 index 0000000..cb8cb1b --- /dev/null +++ b/apps/web/.prettierignore @@ -0,0 +1,5 @@ +pnpm-lock.yaml +.next +# Machine-written SoT — formatting is owned by formatStorefrontContentSnapshotJson +# (JSON.stringify + tabs). Prettier collapses short arrays and breaks content:verify-seed. +config/saleor/storefront-content.snapshot.json diff --git a/apps/web/.prettierrc.json b/apps/web/.prettierrc.json new file mode 100644 index 0000000..056b524 --- /dev/null +++ b/apps/web/.prettierrc.json @@ -0,0 +1,10 @@ +{ + "$schema": "http://json.schemastore.org/prettierrc", + "semi": true, + "singleQuote": false, + "trailingComma": "all", + "printWidth": 110, + "useTabs": true, + "plugins": ["prettier-plugin-tailwindcss"], + "tailwindConfig": "./tailwind.config.cjs" +} diff --git a/apps/web/.vscode/launch.json b/apps/web/.vscode/launch.json new file mode 100644 index 0000000..711f3be --- /dev/null +++ b/apps/web/.vscode/launch.json @@ -0,0 +1,12 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "attach", + "name": "Attach to application", + "skipFiles": ["/**"], + "port": 9229 + } + ] +} diff --git a/apps/web/.vscode/settings.json b/apps/web/.vscode/settings.json new file mode 100644 index 0000000..bdaf139 --- /dev/null +++ b/apps/web/.vscode/settings.json @@ -0,0 +1,43 @@ +{ + // === Editor Settings === + "editor.formatOnSave": true, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.codeActionsOnSave": { + "source.fixAll": "always" + }, + "editor.quickSuggestions": { + "strings": true + }, + + // === TypeScript === + "typescript.tsdk": "node_modules/typescript/lib", + "typescript.preferences.importModuleSpecifier": "non-relative", + + // === ESLint === + "eslint.run": "onSave", + + // === Tailwind CSS === + "tailwindCSS.classAttributes": ["className", "clsx", "cn"], + "tailwindCSS.experimental.classRegex": [["cn\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"]], + "css.validate": true, + "files.associations": { + "*.css": "tailwindcss" + }, + + // === GraphQL === + "graphql-config.load.filePath": ".graphqlrc.ts", + + // === File Nesting (cleaner explorer) === + "explorer.fileNesting.enabled": true, + "explorer.fileNesting.patterns": { + "*.graphql": "${capture}.generated.ts", + "package.json": "pnpm-lock.yaml, .npmrc, .nvmrc, .env*, .graphqlrc.*" + }, + + // === Search Exclusions === + "search.exclude": { + "**/src/gql/**": true, + "**/node_modules": true, + "**/.next": true + } +} diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md new file mode 100644 index 0000000..3c42786 --- /dev/null +++ b/apps/web/AGENTS.md @@ -0,0 +1,73 @@ +# Saleor Paper — agent guide (always-on) + +Paper is a Saleor **3.23+** headless storefront on **Next.js 16** (App Router, Server Components, Server Actions, Cache Components/PPR, BFF auth). This file is the **thin always-on router** — depth lives in bundled docs and skills, loaded on demand, not here. + +## How to get context (read in this order; stop when answered) + +1. **Next.js mechanics** (`use cache`, PPR, Suspense, routing, metadata, build/prerender errors) → read the **version-matched** docs bundled at `node_modules/next/dist/docs/`, and `nextjs.org/docs/messages/*` for actionable error fixes. This Next.js diverges from your training data — do not answer from memory. +2. **Paper decisions** (how _this_ repo does Saleor commerce) → read `skills/saleor-paper-storefront/SKILL.md`, then the **one** `rules/.md` whose frontmatter `description` matches the task. **Never** load the compiled `skills/saleor-paper-storefront/AGENTS.md` (≈75k tokens; quarantined in `.cursorignore`). +3. **Saleor API shape** (fields, enums, nullability) → grep `src/gql/graphql.ts`, or use the `saleor-storefront` skill / `user-saleor-search` MCP. Don't restate the schema from memory. + +## Precedence + +Paper rules are **authoritative on architecture**: Server Components by default, Server Actions for mutations, Cache Components/PPR boundaries, BFF auth, no client-side Saleor GraphQL. Use the external Vercel skills (`vercel-react-best-practices`, `vercel-composition-patterns`, `web-design-guidelines`) only for micro-patterns _inside_ an already-correct Paper structure. **On any conflict, Paper wins.** + +## Project skill index (read `SKILL.md`, then the one matching rule) + +- **Architecture:** `paper-architecture`, `paper-vercel-cost` +- **Data:** `data-access`, `data-caching`, `data-graphql`, `data-auth-routes`, `data-analytics`, `data-storefront-content`, `data-storefront-content-saleor`, `data-storefront-content-attributes` +- **Product:** `product-pdp`, `product-variants`, `product-high-cardinality`, `product-filtering`, `plp-listing` +- **Checkout:** `paper-surfaces`, `checkout-design-principles`, `checkout-management`, `checkout-payment-gateways`, `checkout-components` +- **Design:** `ui-design-system`, `design-quality-rubric`, `ui-sections`, `page-composition`, `ui-templates`, `design-from-image`, `design-verification` +- **UI & channels:** `ui-components`, `ui-images`, `ui-channels`, `ui-locale-routing`, `ui-i18n` +- **SEO:** `seo-metadata` +- **Dev:** `dev-local`, `dev-investigation`, `third-party-embeds` +- **Fork upgrades:** `skills/saleor-paper-storefront/migrations/SKILL.md` (triggers: "upgrade Paper", "apply Paper migrations") + +External skills are pinned in `skills-lock.json`; run `pnpm skills:bootstrap` after clone (symlinks the project skill into `.agents/skills/` and restores external skills). Maintainers: `npx skills add …` then commit the lockfile. Full setup detail: `skills/saleor-paper-storefront/README.md`. + +## Critical commands + +- **`pnpm run verify`** — the single "am I done?" gate (docs drift + design-tokens + typecheck + lint + tests, fail-fast). Iterate until green before declaring done. `pnpm run verify:quick` = design-tokens + typecheck for a fast styling loop. +- `pnpm generate` / `pnpm generate:checkout` — **required** after editing `src/graphql/*.graphql` / `src/checkout/graphql/*.graphql` (`verify`/`typecheck` auto-run this via prehook). +- `pnpm run build` — only gate that catches PPR dynamic-hole regressions; run on PPR-sensitive layout changes. Then `pnpm check:ppr-resume`: a route can build ◐ and still fail to resume at request time (a `new Date()` during render), which empties the nav or `
` in the browser. +- After editing `skills/.../rules/*.md`, run `pnpm run docs:compile` (or `verify` will flag the drift). +- `pnpm run doctor` — verify the agent setup is actually healthy (project skill linked, external skills installed, docs in sync, compiled doc quarantined). Run it if a session seems off; `pnpm doctor --env` also checks required env. +- A `stop` hook (`.cursor/hooks.json` → `scripts/agent-stop-hook.sh`) runs `lint:design-tokens` when you finish a turn and nudges you if banned color literals slipped in — fix them before declaring done. Fail-open; disable by removing the entry. +- **Opt-in workflow skills** (PPR/build & cache-tightening work): `next-dev-loop`, `next-cache-components-optimizer` — see `skills/saleor-paper-storefront/README.md` for install + preconditions. Not installed by `skills:bootstrap`. + +## Non-negotiable rules + +1. Run the matching `generate` after any `.graphql` change (never edit `src/gql/` or `src/checkout/graphql/generated/`). +2. Server Components by default; `"use client"` only for state, effects, event handlers, or browser APIs. +3. Style with `brand.css` tokens (`bg-background`, `text-foreground`) — never hardcoded colors. +4. Handle nullable Saleor fields intentionally — optional-chain for display, guard/throw when null is a real bug. +5. Import via the `@/` alias. The storefront must not import `@/checkout/*` — cross-surface URLs go through `@paper/session-bridge`. +6. Saleor only through loaders on `@/lib/saleor` (`cachedQuery`, `liveQuery`, `sessionQuery`, `mutate`). Run `pnpm data:lock` after a data change and review `data-layer.lock.md`. +7. A new PDP layout is a template in `src/templates/pdp/`, selected in `src/config/template-selection.ts`. Do not edit the product route or `src/lib/storefront` to change layout. Read `rules/ui-templates.md`. +8. A new listing backend is a provider in `src/lib/listing/providers/`, selected per surface in `src/config/listing-providers.ts`. A new PLP layout is a template in `src/templates/plp/`. Do not edit the listing routes or `src/lib/listing/policy.ts` for either. Read `rules/plp-listing.md`. + +Do not add plan writeups to the repo (forbidden: `docs/plans/`) unless the user explicitly asks to publish one. + +## Key locations + +| Purpose | Path | +| --------------------------------------- | ---------------------------------------------------------------------------------- | +| Storefront GraphQL → generated | `src/graphql/*.graphql` → `src/gql/` (generated, do not edit) | +| Checkout GraphQL → generated | `src/checkout/graphql/*.graphql` → `src/checkout/graphql/generated/` (do not edit) | +| UI components / sections / tokens | `src/ui/components/` · `src/ui/sections/` · `src/styles/brand.css` | +| PDP layout templates | `src/templates/pdp/` · `src/config/template-selection.ts` | +| Saleor kernel (all Saleor calls) | `src/lib/saleor/` · operation registry `src/lib/saleor/operations.ts` | +| Cache manifest (single source of truth) | `src/lib/saleor/cache/manifest.ts` | +| Listing contract / providers | `src/lib/listing/` · `src/config/listing-providers.ts` · `src/templates/plp/` | +| SEO helpers | `src/lib/seo/` | + + + +# This is NOT the Next.js you know + +This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. + +This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean. + + diff --git a/apps/web/LICENSE b/apps/web/LICENSE new file mode 100644 index 0000000..0d6b831 --- /dev/null +++ b/apps/web/LICENSE @@ -0,0 +1,105 @@ +# Functional Source License, Version 1.1, ALv2 Future License + +## Abbreviation + +FSL-1.1-ALv2 + +## Notice + +Copyright 2026 Saleor Commerce + +## Terms and Conditions + +### Licensor ("We") + +The party offering the Software under these Terms and Conditions. + +### The Software + +The "Software" is each version of the software that we make available under +these Terms and Conditions, as indicated by our inclusion of these Terms and +Conditions with the Software. + +### License Grant + +Subject to your compliance with this License Grant and the Patents, +Redistribution and Trademark clauses below, we hereby grant you the right to +use, copy, modify, create derivative works, publicly perform, publicly display +and redistribute the Software for any Permitted Purpose identified below. + +### Permitted Purpose + +A Permitted Purpose is any purpose other than a Competing Use. A Competing Use +means making the Software available to others in a commercial product or +service that: + +1. substitutes for the Software; + +2. substitutes for any other product or service we offer using the Software + that exists as of the date we make the Software available; or + +3. offers the same or substantially similar functionality as the Software. + +Permitted Purposes specifically include using the Software: + +1. for your internal use and access; + +2. for non-commercial education; + +3. for non-commercial research; and + +4. in connection with professional services that you provide to a licensee + using the Software in accordance with these Terms and Conditions. + +### Patents + +To the extent your use for a Permitted Purpose would necessarily infringe our +patents, the license grant above includes a license under our patents. If you +make a claim against any party that the Software infringes or contributes to +the infringement of any patent, then your patent license to the Software ends +immediately. + +### Redistribution + +The Terms and Conditions apply to all copies, modifications and derivatives of +the Software. + +If you redistribute any copies, modifications or derivatives of the Software, +you must include a copy of or a link to these Terms and Conditions and not +remove any copyright notices provided in or with the Software. + +### Disclaimer + +THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR +PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT. + +IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE +SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, +EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE. + +### Trademarks + +Except for displaying the License Details and identifying us as the origin of +the Software, you have no right under these Terms and Conditions to use our +trademarks, trade names, service marks or product names. + +## Grant of Future License + +We hereby irrevocably grant you an additional license to use the Software under +the Apache License, Version 2.0 that is effective on the second anniversary of +the date we make the Software available. On or after that date, you may use the +Software under the Apache License, Version 2.0, in which case the following +will apply: + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. + +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. diff --git a/apps/web/README.md b/apps/web/README.md new file mode 100644 index 0000000..7dde1e5 --- /dev/null +++ b/apps/web/README.md @@ -0,0 +1,69 @@ +# apps/web — the storefront + +Saleor's Next.js storefront, "Paper" ([saleor/storefront](https://github.com/saleor/storefront) +at `a6e357a`, the Functional Source License 1.1 — `LICENSE`), on Cloudflare +Workers + Static Assets. Its pages, components, data layer, checkout and +tests are upstream's; what this app adds is the Workers build, the cache +bindings, the schema its types are generated from, and a storefront that +deploys before a Saleor store is connected. + +- `src/app/` — the routes: `(root)` (`/`, which redirects to the default + locale and channel — or, with no store connected, says how to connect one), + `(storefront)/[locale]/[channel]` (home, categories, collections, products, + search, cart, account, orders, sign-in), `(checkout)` (`/checkout`, + `/order`), and `api/` (`revalidate` for Saleor's webhook, `og`, `auth`, + `listing`, `cache-info`, `health`) +- `src/lib/saleor/` — the data layer: every read is a `"use cache"` function + tagged by entity with a named `cacheLife` profile (`cache/`), and the + webhook's invalidation plan (`invalidation/`) +- `src/lib/saleor-connection.ts` — whether the build had a Saleor API URL; the + middleware, the channel list and the checkout layout ask it first +- `src/config/brand.ts` — the store's name (`SITE_NAME`) +- `schema.graphql` — Saleor's published GraphQL schema (Saleor 3.23, + `saleor/graphql/schema.graphql` in saleor/saleor), which codegen + (`.graphqlrc.ts`, `src/checkout/graphql/codegen.ts`) and the GraphQL lint + read instead of a live API +- `docs/`, `skills/saleor-paper-storefront/` — Saleor's own guides to the + storefront: configuration, caching, checkout and payments, international + stores, its architecture decisions + +```bash +pnpm dev # GraphQL types, then next dev on http://localhost:3000 +pnpm build # GraphQL types, next build, opennextjs-cloudflare build → .open-next/ +pnpm preview # wrangler dev over the built Worker: a local R2 bucket, local Durable Objects +pnpm test # GraphQL types, then the storefront's vitest suite +``` + +The cache's bucket is not hand-written. `wrangler.template.jsonc` names it as +a wiring token; `wrangler.jsonc` is that template rendered from +`wiring.fixture.json` (`pnpm run wire:fixture`) for local work, and on every +deploy from the wiring document the `cloudflare-r2` root publishes. The +Durable Objects (the tag cache and the revalidation queue) are classes the +generated Worker exports; the config's `migrations` create them. + +What differs from upstream, and why: + +- **Cache Components and Instant Navigations are off.** On Workers through + @opennextjs/cloudflare 1.20 a Cache Components page answers 500 and then + hangs (opennextjs-cloudflare#1450). `experimental.useCache` keeps every + `"use cache"` read, its `cacheLife` profile and its tags; routes render per + request from those cached reads. The five `instant` / `prefetch` route + segment configs are Cache Components options and went with it. +- **Next.js 16.3.8, not 16.4.1**: the adapter's newest npm release cannot + serve 16.4 yet. +- **The GraphQL types come from `schema.graphql`**, not from the live API, so + the build, the type check, the lint and the tests need no store. +- **No store, no calls**: with no `NEXT_PUBLIC_SALEOR_API_URL` the storefront + has no channels, the middleware sends every page to `/`, `/` says "Connect + your Saleor store", and the checkout layout redirects there too; the auth + client reads the URL when it is made, not when it is imported. +- **One store-name seam**: upstream spelled "Saleor Store" in five places; + each reads `SITE_NAME` now. +- **Images unoptimized** (Workers has no Next.js image optimizer; Saleor's + thumbnail endpoint already sizes them), and **Speed Insights off unless the + build runs on Vercel**, as upstream already does for Web Analytics. +- **`/api/health`** for the deploy's smoke test. +- **Lint has a 4 GiB heap**: upstream's type-aware lint outgrows Node's + default on a small machine. Its warnings are upstream's. +- Not carried: the Dockerfile and docker-compose, the Vercel and GitHub + workflows, the husky hooks, the Cursor and MCP configuration. diff --git a/apps/web/SECURITY.md b/apps/web/SECURITY.md new file mode 100644 index 0000000..41fb536 --- /dev/null +++ b/apps/web/SECURITY.md @@ -0,0 +1,5 @@ +# Reporting a Vulnerability + +If you discover a security vulnerability in storefront please disclose it via [our huntr page](https://huntr.dev/repos/saleor/storefront/). Information about bounties, CVEs, response times and past reports are all there. + +Thank you for improving the security of storefront. diff --git a/apps/web/cloudflare-env.d.ts b/apps/web/cloudflare-env.d.ts new file mode 100644 index 0000000..1116f21 --- /dev/null +++ b/apps/web/cloudflare-env.d.ts @@ -0,0 +1,15 @@ +// The bindings the app reads through getCloudflareContext(). `wrangler types` +// would generate this from wrangler.jsonc; the one binding the code touches +// is kept by hand so the build needs no rendered config. +declare global { + interface CloudflareEnv { + ASSETS: { + fetch( + input: string | URL | Request, + init?: RequestInit, + ): Promise; + }; + } +} + +export {}; diff --git a/apps/web/component.yaml b/apps/web/component.yaml new file mode 100644 index 0000000..fd7616d --- /dev/null +++ b/apps/web/component.yaml @@ -0,0 +1,120 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: web + description: The Saleor storefront (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment; R2 + Durable Objects as the Next.js cache; a "connect your Saleor store" page until a store is connected) +spec: + type: cloudflare-workers-assets-turbo + lifecycle: production + owner: platform + # Its pages, attached to it in the workspace's catalog: what the Docs + # library shows for it, and what the catalog's docs and runbook checks read. + # Generated from what this manifest and its sources declare. + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + # `app`, not `web`: a domain and a component share one name space in the + # catalog, and a domain called `web` hid this component from it. + domain: app + path: apps/web + # Its own lane per environment: the Next.js build is the longest job in the + # plan, and a shared lane would wait on it. + lane: isolated + # INFRA BEFORE APP. The R2 bucket is the Worker's incremental cache, bound + # by name, and the name is rendered into its config during the build from + # the wiring document the cloudflare-r2 root lease-publishes after its + # apply. A job resolves its secrets when it STARTS, so on a merge to main + # this deploy waits for that environment's apply (enforced) and the document + # is there; a pull request deploys nothing, so nothing on one waits + # (advisory). The Durable Objects (tag cache, revalidation queue) need no + # root — the Worker exports their classes and the migration creates them on + # deploy. + dependsOn: + - component: cloudflare-r2 + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + secretEnv: + WIRING_CLOUDFLARE_R2_STAGE: "secret://saleor-commerce/saleor-commerce/stage/WIRING_CLOUDFLARE_R2" + WIRING_CLOUDFLARE_R2_PROD: "secret://saleor-commerce/saleor-commerce/prod/WIRING_CLOUDFLARE_R2" + # The store, connected after the build by its owner: the Saleor API's + # GraphQL URL and the channel to sell in, per environment. The build inlines + # both (the browser's checkout talks to the same API), so they are build + # env, not Worker secrets; when absent — every fresh product — the + # storefront builds without calling Saleor and says "Connect your Saleor + # store" (src/lib/saleor-connection.ts). The URL is not a credential; + # the revalidation secrets and an app token are Worker secrets the owner + # sets (the README's "Connecting Saleor"). + optionalSecretEnv: + NEXT_PUBLIC_SALEOR_API_URL: "secret://saleor-commerce/saleor-commerce/{{ .environment }}/SALEOR_API_URL" + NEXT_PUBLIC_DEFAULT_CHANNEL: "secret://saleor-commerce/saleor-commerce/{{ .environment }}/SALEOR_CHANNEL" + subscribe: + environments: + - name: dev + profile: verify + - name: stage + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + - name: prod + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + + workspaceDir: ../.. + appDir: . + + turboFilter: "@app/web" + wranglerConfig: wrangler.jsonc + + # @opennextjs/cloudflare emits a Worker entrypoint plus a static-assets + # directory bound via ASSETS — both deploy in one `wrangler deploy`. + workerEntrypoint: .open-next/worker.js + assetsDir: .open-next/assets + + # Per-env worker name: saleor-commerce-web-{dev,stage,prod}. The rendered + # wrangler.jsonc names the same Worker (its self-reference binding needs it). + workerName: saleor-commerce-web + environmentAwareWorkerName: true + + # The account's workers.dev subdomain; exported to the smoke step as + # ${WORKERS_DEV_SUBDOMAIN} and used to build ${DEPLOYED_URL}. + workersDevSubdomain: your-workers-subdomain + + installCommand: pnpm install --frozen-lockfile + # Render this environment's wrangler config, then build. stage and prod + # render from the wiring document their cloudflare-r2 apply published + # (secretEnv above, resolved before the job's first step); dev, which no + # root applies to and which only verifies, renders from the committed + # fixture. The committed wrangler.jsonc (the fixture render) is what the + # composition's verify-app-structure step finds before this runs. The + # build is for this environment's origin: NEXT_PUBLIC_STOREFRONT_URL (the + # storefront's canonical, Open Graph and redirect-allowlist origin) is the + # environment's SITE_URL (intent.yaml), else its workers.dev URL; the + # channel is Saleor's own default unless the owner named one. + buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-r2 --env "${ORUN_ENVIRONMENT}" --fixture wiring.fixture.json --fixture-envs dev && NEXT_PUBLIC_STOREFRONT_URL="${SITE_URL:-https://saleor-commerce-web-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" NEXT_PUBLIC_DEFAULT_CHANNEL="${NEXT_PUBLIC_DEFAULT_CHANNEL:-default-channel}" pnpm exec turbo run build --filter=@app/web + + # Smoke: the storefront answers (`/` is the store's home, or before a + # store is connected the page that says how to connect one), and the + # Worker itself answers /api/health, which no static file can. Not the + # store's name: that is the owner's to change, and HTML-escaped when it + # carries an `&` or `'`. Not a product either: before a store is connected + # there is none, and a connected store may be empty. Buffered before grep + # so an early match cannot SIGPIPE curl. + smokeCommand: 'curl -sfL -o /dev/null "${DEPLOYED_URL}/" && health=$(curl -sf "${DEPLOYED_URL}/api/health") && echo "${health}" | grep -q "\"ok\":true"' + labels: + team: platform + layer: delivery + surface: web + runtime: cloudflare diff --git a/apps/web/config/saleor/README.md b/apps/web/config/saleor/README.md new file mode 100644 index 0000000..eda22c4 --- /dev/null +++ b/apps/web/config/saleor/README.md @@ -0,0 +1,257 @@ +# Storefront content — Saleor Configurator + +Deploys **Storefront — \*** model types, content attributes, and seed models for Paper's `CONTENT_PROVIDER=saleor` layer. + +## Copy ownership (source of truth) + +| Layer | English | Other locales | Ongoing edits | +| -------------------------- | --------------------------------------------------- | ----------------------------------------------- | ------------------------------------------------- | +| **Runtime** | `src/lib/content/defaults.ts` | Saleor Model translations | Dashboard → Models when `CONTENT_PROVIDER=saleor` | +| **Configurator bootstrap** | `models:` in YAML — **exported from `defaults.ts`** | `fixtures/translations/*.yaml` (demo seed only) | Export + deploy on greenfield or schema changes | + +**YAML is a deploy vehicle, not the editorial system.** Configurator needs YAML to create PageTypes and seed Pages; merchants edit copy in Dashboard once bootstrapped. + +### Changing English copy + +1. Edit `src/lib/content/defaults.ts` (and `src/lib/content/types.ts` when the shape changes). +2. Export Configurator seed + Paper snapshot: `pnpm content:export-seed` (runs verify automatically) +3. Verify (CI / `pnpm test:run`): `pnpm content:verify-seed` +4. Deploy when bootstrapping Saleor: Paper app init (merchants) or `pnpm configurator:storefront-content:deploy` (dev/advanced) +5. When the snapshot version changes, bump the vendored copy in [`saleor-paper-app`](https://github.com/saleor/saleor-paper-app) + +Do **not** hand-edit English strings under `models:` in `storefront-content.config.yml` — `content:verify-seed` fails on drift. + +Schema sections (`contentAttributes`, `modelTypes`) stay hand-edited in YAML when adding new attributes or PageTypes. + +**Paper app snapshot:** `config/saleor/storefront-content.snapshot.json` is the machine-readable SoT the Paper Dashboard app applies on init. Regenerated by `content:export-seed`; do not maintain a fork of the schema in the app. + +### Required vs optional Models (blank merchant) + +| Tier | Models | Notes | +| --------------------------------- | -------------------------- | ----------------------------------------------------------- | +| Recommended for Dashboard editing | policies, chrome, homepage | Site-wide copy + free-shipping facts | +| Recommended | cart, checkout | Brand voice on bag/checkout | +| Optional | products | PLP title/description only | +| Skip | — | Forks / code-only: uncheck init, or `CONTENT_PROVIDER=code` | + +Paper app init seeds **all six** when “Add storefront Models” is checked. + +## Safe token setup (dev) + +Use **two tokens**, in **two files**: + +| File | Purpose | Loaded by | +| ------------------------- | ------------------------------------------------------ | ---------------------------------- | +| `.env.local` | Storefront runtime (`SALEOR_APP_TOKEN`, narrow) | `next dev` / `next build` | +| `.env.configurator.local` | Configurator only (`SALEOR_CONFIGURATOR_TOKEN`, broad) | `pnpm configurator:*` scripts only | + +```bash +cp .env.configurator.local.example .env.configurator.local +# Edit .env.configurator.local — paste dev/staging staff token +``` + +**Rules** + +1. **Dev/staging Saleor only** — never point a broad token at production. +2. **Dedicated dev staff user** — e.g. `configurator-dev@yourshop.dev`, not your personal admin on prod. +3. **Never `NEXT_PUBLIC_`** — configurator token must stay server-side / CLI-only. +4. **Never import in app code** — `SALEOR_CONFIGURATOR_TOKEN` is not used by the Next.js app; only `scripts/configurator-storefront-content.sh`. +5. **Keep `SALEOR_APP_TOKEN` narrow** — channels list, webhooks, etc.; read-only where possible. +6. **Rotate** — revoke when someone leaves or after accidental exposure. + +Both files match `.env*.local` in `.gitignore` — they are never committed. + +### Token permissions (Configurator) + +Configurator introspects the whole shop before deploy. The token needs at least: + +- `MANAGE_PAGES`, `MANAGE_PAGE_TYPES_AND_ATTRIBUTES` +- `MANAGE_SETTINGS`, `MANAGE_PRODUCTS`, `MANAGE_ORDERS`, `MANAGE_SHIPPING` (remote diff) + +A narrow storefront app token is usually **not** sufficient. + +## Prerequisites + +1. **Saleor 3.23+** (Paper's floor; assigned page attributes landed in 3.22) — Configurator targets **3.23.x** schema. +2. **`NEXT_PUBLIC_SALEOR_API_URL`** in `.env.local` (same as storefront). +3. **`SALEOR_CONFIGURATOR_TOKEN`** in `.env.configurator.local`. + +## Commands + +```bash +# Schema check (offline, no token) +pnpm configurator:storefront-content:validate + +# Preview remote changes (dry-run) +pnpm configurator:storefront-content:plan + +# Apply to Saleor (blocked if remote entities would be deleted) +pnpm configurator:storefront-content:deploy + +# Drop all storefront-* Pages + PageTypes, redeploy schema/seed, push locale translations +pnpm configurator:storefront-content:reset +# Note: reset runs deploy twice — Configurator needs page types committed before models on greenfield. + +# Push translation fixtures only (after deploy — demo/bootstrap locales) +pnpm configurator:storefront-content:translations + +# Verify EN seed models match defaults.ts (also in pnpm test:run) +pnpm content:verify-seed + +# Regenerate models: section from defaults.ts +pnpm content:export-seed +``` + +### Translation fixtures (bootstrap only) + +Configurator / bootstrap scripts seed **English** attribute values via the exported `models:` block (from `defaults.ts`). Non-default locales live in separate YAML files used **once** to populate a fresh Saleor instance: + +``` +config/saleor/fixtures/translations/ + pl.yaml # languageCode: PL + de.yaml + fr.yaml + fi.yaml + nb.yaml # Norwegian Bokmål — Saleor enum NB + ja.yaml + ko.yaml +``` + +These fixtures are **demo/bootstrap samples** — they may lag neutralized English defaults in `defaults.ts`. Prefer editing locale copy in **Dashboard → Models** after bootstrap. When re-running translation deploy on a shop that already has Dashboard edits, expect overwrites. + +Each file maps `page slug → attribute slug → translated plain text`. Policy placeholders (`{freeShippingThreshold}`, `{returnsWindowDays}`, `{amount}`, `{label}`) must be preserved. Apply with `pnpm configurator:storefront-content:translations` (GraphQL `attributeValueTranslate` — not supported by Configurator itself). + +After bootstrap, locale copy is maintained in **Dashboard → Models**, not in these YAML files. + +### Catalog translations (products, categories, collections) + +> **Experimental — not officially supported.** May change or be removed. Typically a merchandiser/Dashboard or TMS-export concern, not a developer workflow. + +**Advanced, opt-in tooling** for translating native Saleor catalog copy. Real fixture files are **gitignored** (`fixtures/catalog-translations/locales/`); only fictional templates ship in `examples/`. + +See [`fixtures/catalog-translations/README.md`](fixtures/catalog-translations/README.md): + +```bash +pnpm catalog:translations:fetch # pull English baseline from your Saleor (local, gitignored) +pnpm catalog:translations:plan # preflight — fails on slug mismatch +pnpm catalog:translations:deploy # push locales/*.yaml (after plan passes) +``` + +Requires `SALEOR_CONFIGURATOR_TOKEN` in `.env.configurator.local` — same rules as Configurator above. + +## How Configurator actually behaves (from `../configurator` source) + +**Diff vs deploy are not the same.** + +| Layer | Omitted section in YAML (e.g. no `products:`) | +| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **`diff` / `plan`** | Treated as empty `[]` → remote entities show as **DELETE** (drift). Our partial file plans ~139 deletes. | +| **`deploy` pipeline** | Stage no-ops when that section is missing/empty. **Channels, products, menus, etc. are not removed.** Deploy only bootstraps entities listed in the YAML (create/update). | + +So the scary delete list in `plan` does **not** mean deploy will wipe the catalog. `deploy` even notes that items “marked for deletion may not have been removed”. Entity-level delete (drop a channel/product) is not implemented in the deploy stages. + +`pnpm configurator:storefront-content:deploy` still uses `--failOnDelete` because the diff noise is alarming and easy to misread — not because deploy would execute those deletes. + +### Option A — Additive deploy (dev, smallest diff) + +Use `storefront-content.config.yml` as-is. Preview creates, then deploy **without** expecting real deletions: + +```bash +pnpm configurator:storefront-content:plan # ~47 creates + noisy delete drift +# To apply in dev, temporarily remove --failOnDelete from scripts/configurator-storefront-content.sh +# or run deploy directly with your token — only contentAttributes, modelTypes, models run. +``` + +Safe for catalog/channels because those stages see an empty/missing config section and return early. + +**Caveats:** menus/shipping zones **in the YAML** can still be destructive on update (menus are recreated item-by-item). Omitted sections avoid that. + +### Option B — Full baseline + merge (shop-as-code, CI-friendly) + +Recommended when you want `diff` to mean “safe to merge” and `--failOnDelete` to be meaningful. + +```bash +# 1. Download current remote state (large; exclude products if you only need structure) +pnpm dlx @saleor/configurator introspect \ + --config config/saleor/shop-baseline.config.yml \ + --url "$NEXT_PUBLIC_SALEOR_API_URL" \ + --token "$SALEOR_CONFIGURATOR_TOKEN" \ + --exclude products + +# 2. Merge into baseline (do not replace wholesale): +# - Union contentAttributes from storefront-content.config.yml +# - Append storefront modelTypes + models +# - Keep existing modelTypes/models (Brand, Refund Reason, …) from introspect + +# 3. Preview — expect ~47 creates, 0 deletes, maybe minor updates (normalization) +pnpm dlx @saleor/configurator diff \ + --config config/saleor/shop-baseline.config.yml \ + --url "$NEXT_PUBLIC_SALEOR_API_URL" \ + --token "$SALEOR_CONFIGURATOR_TOKEN" \ + --failOnDelete + +# 4. Deploy baseline; second deploy should be idempotent (0 changes) +pnpm dlx @saleor/configurator deploy \ + --config config/saleor/shop-baseline.config.yml \ + --url "$NEXT_PUBLIC_SALEOR_API_URL" \ + --token "$SALEOR_CONFIGURATOR_TOKEN" \ + --failOnDelete +``` + +**Merge rules** + +- Never drop introspected sections you still need in Saleor. +- Never replace the whole `models:` block — **append** `storefront-*` models alongside `about`, `cozynest`, etc. +- Deduplicate `contentAttributes` by name. +- Commit `shop-baseline.config.yml` (or gitignore if too large / env-specific). + +**When `--failOnDelete` should pass:** after a full introspect merge, deletes mean you intentionally removed something from the baseline — review each one. For CI, that is the guardrail you want. + +### Option C — Manual Dashboard + +Fastest one-off: create the six **Storefront — \*** types/models by hand (Policies, Chrome, Products, Homepage, Cart, Checkout). `CONTENT_PROVIDER` already defaults to `saleor`. + +## After deploy + +1. Dashboard → **Models** → tabs **Storefront — Policies / Chrome / Products / Homepage / Cart / Checkout**. +2. Prefer bootstrapping via the **Paper app** init screen (“Add storefront Models”). Configurator (`pnpm configurator:storefront-content:deploy`) remains the advanced/dev path. +3. Optional: set `CONTENT_PROVIDER=code` in `.env.local` only if you want code defaults without Models. +4. Restart the dev server after changing `CONTENT_PROVIDER`. + +Attribute slugs are defined in `src/lib/content/attribute-slugs.ts` and must stay in sync with `storefront-content.config.yml`. + +Verify locally (and optionally against Saleor): + +```bash +pnpm content:verify-attribute-slugs +pnpm content:verify-seed +``` + +### Supported Saleor attribute types (storefront GraphQL) + +The storefront fragment currently reads: + +| `inputType` | Supported | +| --------------------------------- | ------------------------------------------------------ | +| `PLAIN_TEXT` | Yes | +| `BOOLEAN` | Yes | +| `SINGLE_REFERENCE` + `COLLECTION` | Yes (`Featured collection` on homepage) | +| Other types | See `skills/.../data-storefront-content-attributes.md` | + +### Cache after Dashboard edits + +Storefront copy is cached (`storefront-content:{channel}:{locale}`, ~5 min stale). Options: + +1. **Webhook** — `PAGE_UPDATED` → `/api/revalidate` (wired for `storefront-*` slugs). +2. **Manual** — `curl -H "Authorization: Bearer $REVALIDATE_SECRET" "http://localhost:3000/api/revalidate?tag=storefront-content:default-channel:en-US"` +3. **Wait** — menus-tier revalidate window. + +Restart `next dev` after changing `CONTENT_PROVIDER`. + +### Cart trust copy (UX) + +Cart drawer trust labels render only when the cart has line items — empty cart shows the empty state instead. + +## Channel overrides + +Optional per-channel copy: duplicate a model with slug `storefront-homepage-{channelSlug}` (e.g. `storefront-homepage-channel-pln`). diff --git a/apps/web/config/saleor/fixtures/catalog-translations/README.md b/apps/web/config/saleor/fixtures/catalog-translations/README.md new file mode 100644 index 0000000..9bb2827 --- /dev/null +++ b/apps/web/config/saleor/fixtures/catalog-translations/README.md @@ -0,0 +1,177 @@ +# Catalog translations + +> [!WARNING] > **Experimental — not officially supported.** These scripts are provided as-is and may change or be removed without notice. They are not part of the supported storefront surface; use against dev/staging instances you control. + +**Advanced tooling** for locale-specific copy on native Saleor catalog entities (products, categories, collections, attributes). Separate from: + +| Layer | Tool | +| ----------------------------- | --------------------------------------------------- | +| Storefront marketing (Models) | `pnpm configurator:storefront-content:translations` | +| Catalog entities | `pnpm catalog:translations:*` (this folder) | +| UI chrome | next-intl JSON | + +## Who is this for? + +In most real shops, **translating catalog copy is a merchandiser's job**, done in the Saleor Dashboard — not something developers run from a repo. So this is intentionally niche. It exists for cases like: + +- **Seeding a demo or fresh environment** with multilingual catalog copy. +- **Importing from an external translation system / TMS** — export your translations to the `locales/*.yaml` shape and push them in bulk (the create-only default means re-imports won't clobber Dashboard edits). +- **Bootstrapping** a catalog before merchandisers take over editing in the Dashboard. + +If your translation workflow lives in the Dashboard or a dedicated TMS integration, you probably don't need these scripts at all. + +## Safety model + +- **Create-only by default** — deploy writes a field only when no translation exists yet. Existing translations (e.g. hand-edited in the Dashboard) are **left untouched** and reported as `protected`. Pass `--overwrite` to update them. +- **Idempotent** — fields already matching the fixture are classified `unchanged` and skipped, so re-runs make no redundant writes. +- **`locales/` is gitignored** — your real slugs and translations never ship in the repo. +- **`examples/` are fictional** — templates only; deploy never reads this folder. +- **Plan before write** — the run builds a full plan and aborts before any mutation if data errors (`--fail-on-skip`) are found. +- **English (`EN`) is rejected** — Saleor default language must not be overwritten via fixtures. +- **Permission checked first** — `SALEOR_CONFIGURATOR_TOKEN` (staff or app) must hold `MANAGE_TRANSLATIONS`, verified before any write. + +## Workflow + +### 1. Credentials + +Same as Configurator — broad staff token in `.env.configurator.local` (never commit): + +```env +NEXT_PUBLIC_SALEOR_API_URL=https://your-instance.saleor.cloud/graphql/ +SALEOR_CONFIGURATOR_TOKEN=... +NEXT_PUBLIC_DEFAULT_CHANNEL=default-channel +``` + +### 2. Fetch English baseline + +Pulls your live catalog into a local reference file (gitignored): + +```bash +pnpm catalog:translations:fetch +# → config/saleor/fixtures/catalog-translations/locales/catalog-source.json +``` + +Use `catalog-source.json` as the slug checklist when writing translations. + +### 3. Create locale fixtures + +Copy templates from `examples/` into `locales/` and replace fictional slugs with yours: + +```bash +cp config/saleor/fixtures/catalog-translations/examples/example.pl.yaml \ + config/saleor/fixtures/catalog-translations/locales/pl.yaml +``` + +Split files merge automatically by `languageCode`: + +``` +locales/ + pl.yaml + pl.attributes.yaml + pl.product-attributes.yaml + de.yaml + ... +``` + +Fixture format: + +```yaml +languageCode: PL # Saleor LanguageCodeEnum — not EN + +categories: + your-category-slug: + name: "Translated name" + slug: "translated-url-handle" # optional — Saleor translation.slug (ADR 0004) + seoDescription: "Translated SEO" + +collections: + your-collection-slug: + name: "..." + slug: "..." + description: "Plain text — deploy converts to EditorJS" + +products: + your-product-slug: + name: "..." + slug: "..." + description: "..." +``` + +URL `slug` values should be lowercase ASCII with hyphens. For CJK locales, prefer romanization over native-script handles (encoding / tooling). + +Attribute labels and per-product text attributes use `*.attributes.yaml` and `*.product-attributes.yaml` — see `examples/`. + +### 4. Preflight (required) + +```bash +pnpm catalog:translations:plan +``` + +Reports slug coverage against your Saleor instance. Exits with an error if any fixture slug is missing (`--fail-on-skip`). Fix mismatches before deploying. + +### 5. Deploy + +```bash +pnpm catalog:translations:deploy +``` + +Create-only: applies **new** translations, skips **unchanged**, and leaves any **differing existing** translation untouched (reported as `protected`). Uses `--fail-on-skip`, so data errors abort before any write. + +To update existing translations (overwrites Dashboard/manual edits — use deliberately): + +```bash +node scripts/deploy-catalog-translations.mjs --overwrite +``` + +To proceed despite unknown-slug data errors (not recommended): + +```bash +node scripts/deploy-catalog-translations.mjs --allow-skip +``` + +## Commands + +| Command | What it does | +| ---------------------------------- | ------------------------------------------------------------------------------------------ | +| `pnpm catalog:translations:fetch` | Pull English baseline → `locales/catalog-source.json` | +| `pnpm catalog:translations:plan` | Dry-run + preflight (`--dry-run --fail-on-skip`) — shows new/overwrite/unchanged/protected | +| `pnpm catalog:translations:deploy` | Apply new translations only (`--fail-on-skip`); existing left intact | + +### Flags + +| Flag | Effect | +| ---------------- | ------------------------------------------------------------------------------------- | +| `--dry-run` | Plan only; no writes | +| `--fail-on-skip` | Abort before writing if any fixture entry is a data error (unknown slug, empty value) | +| `--overwrite` | Also update existing translations that differ from the fixture | +| `--allow-skip` | Don't abort on data errors | +| `--env ` | Load credentials from a specific env file | + +## When slugs do not match + +If you customized the Configurator catalog, bundled Paper slugs will not match yours. Always: + +1. `pnpm catalog:translations:fetch` on **your** instance +2. Write `locales/*.yaml` keyed to **your** slugs from `catalog-source.json` +3. `pnpm catalog:translations:plan` until coverage is 100% + +## Throughput & rate limiting + +All requests (reads, permission probe, and writes) share one throttled client so a deploy can't stampede Saleor. It honors the same env vars as the storefront (`src/lib/graphql.ts`): + +| Env var | Default | Effect | +| -------------------------------- | ------- | -------------------------------------- | +| `SALEOR_MAX_CONCURRENT_REQUESTS` | `3` | Max in-flight requests | +| `SALEOR_MIN_REQUEST_DELAY_MS` | `200` | Minimum spacing between request starts | +| `SALEOR_REQUEST_TIMEOUT_MS` | `15000` | Per-request timeout (aborts + retries) | +| `NEXT_BUILD_RETRIES` | `3` | Retries on `429`/`5xx`/timeout | + +`429` and `5xx` responses are retried with exponential backoff, honoring `Retry-After`. On a large catalog the deploy is intentionally slow rather than aggressive — raise the limits only against an instance you control. + +## Permissions + +`SALEOR_CONFIGURATOR_TOKEN` must be a staff-user **or** app token with `MANAGE_TRANSLATIONS` (dev/staging only). + +## Supported locales + +Match `NEXT_PUBLIC_STOREFRONT_LOCALES`: `pl`, `de`, `fr`, `fi`, `nb`, `ja`, `ko`. English lives in Saleor as the default — do not add `languageCode: EN` fixtures. diff --git a/apps/web/config/saleor/fixtures/catalog-translations/examples/example.pl.attributes.yaml b/apps/web/config/saleor/fixtures/catalog-translations/examples/example.pl.attributes.yaml new file mode 100644 index 0000000..83a99af --- /dev/null +++ b/apps/web/config/saleor/fixtures/catalog-translations/examples/example.pl.attributes.yaml @@ -0,0 +1,9 @@ +# Polish attribute translations — fictional template only (Saleor LanguageCodeEnum: PL) +languageCode: PL + +attributes: + example-attribute: + name: "Przykładowy atrybut" + values: + example-value-a: "Przykładowa wartość A" + example-value-b: "Przykładowa wartość B" diff --git a/apps/web/config/saleor/fixtures/catalog-translations/examples/example.pl.product-attributes.yaml b/apps/web/config/saleor/fixtures/catalog-translations/examples/example.pl.product-attributes.yaml new file mode 100644 index 0000000..cdffdd2 --- /dev/null +++ b/apps/web/config/saleor/fixtures/catalog-translations/examples/example.pl.product-attributes.yaml @@ -0,0 +1,6 @@ +# Polish per-product text attributes — fictional template only (Saleor LanguageCodeEnum: PL) +languageCode: PL + +productAttributes: + example-product: + care-instructions: "Przykładowa instrukcja pielęgnacji." diff --git a/apps/web/config/saleor/fixtures/catalog-translations/examples/example.pl.yaml b/apps/web/config/saleor/fixtures/catalog-translations/examples/example.pl.yaml new file mode 100644 index 0000000..2e36091 --- /dev/null +++ b/apps/web/config/saleor/fixtures/catalog-translations/examples/example.pl.yaml @@ -0,0 +1,25 @@ +# Polish catalog translations — fictional template only (Saleor LanguageCodeEnum: PL) +# +# Copy this file to ../locales/ and replace slugs with YOUR catalog slugs +# from locales/catalog-source.json (generated by pnpm catalog:translations:fetch). +# +# Never commit locales/*.yaml — they are gitignored. +languageCode: PL + +categories: + example-category: + name: "Przykładowa kategoria" + slug: "przykladowa-kategoria" + seoDescription: "Krótki opis SEO kategorii." + +collections: + example-collection: + name: "Przykładowa kolekcja" + slug: "przykladowa-kolekcja" + description: "Krótki opis kolekcji po polsku." + +products: + example-product: + name: "Przykładowy produkt" + slug: "przykladowy-produkt" + description: "Opis produktu w języku polskim." diff --git a/apps/web/config/saleor/fixtures/catalog-translations/locales/.gitkeep b/apps/web/config/saleor/fixtures/catalog-translations/locales/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/apps/web/config/saleor/fixtures/translations/de.yaml b/apps/web/config/saleor/fixtures/translations/de.yaml new file mode 100644 index 0000000..1e56fcb --- /dev/null +++ b/apps/web/config/saleor/fixtures/translations/de.yaml @@ -0,0 +1,52 @@ +# German storefront model translations (Saleor LanguageCodeEnum: DE) +languageCode: DE + +pages: + storefront-chrome: + announcement-message: "Kostenloser Versand ab {freeShippingThreshold}" + nav-all-products-label: "Alle" + nav-view-all-label: "Alle {label} anzeigen" + + storefront-products: + listing-title: "Alle Produkte" + listing-description: "Entdecken Sie unsere vollständige Kollektion an Premium-Produkten." + + storefront-homepage: + hero-heading: "Entdecken Sie unsere Kollektion" + hero-subheading: "Premium-Produkte von außergewöhnlicher Qualität. Entdecken Sie unsere kuratierte Auswahl." + hero-cta-label: "Alles shoppen" + featured-heading: "Empfohlene Produkte" + brand-story-heading: "Für echten Handel gebaut" + brand-story-paragraph-1: "Paper ist ein minimaler, produktionsreifer Storefront für Saleor — sauber wie eine leere Seite, bereit zum Start." + brand-story-paragraph-2: "Passen Sie Bereiche im Code an, verbinden Sie Ihren Katalog und nutzen Sie erprobte Warenkorb-, Checkout- und Produktseiten." + values-heading: "Warum bei uns einkaufen" + values-column-1-title: "Kuratierte Qualität" + values-column-1-text: "Jedes Produkt wird wegen Handwerk und Langlebigkeit ausgewählt — nicht wegen Trends." + values-column-2-title: "Schnelle Abwicklung" + values-column-2-text: "Bestellungen werden aus regionalen Lagern mit Sendungsverfolgung vom Checkout bis zur Lieferung versendet." + values-column-3-title: "Einfache Rückgaben" + values-column-3-text: "Unkomplizierte Rückgaben innerhalb von {returnsWindowDays} Tagen. Wir stehen hinter dem, was wir verkaufen." + editorial-heading: "Für die Ewigkeit gemacht" + editorial-paragraph-1: "Durchdachte Materialien und zeitlose Silhouetten — Stücke, die Sie Saison für Saison tragen." + editorial-cta-label: "Kollektionen entdecken" + + storefront-cart: + empty-title: "Ihre Tasche ist leer" + empty-body: "Noch keine Artikel hinzugefügt." + empty-cta-label: "Einkauf starten" + trust-free-shipping-prefix: "Kostenlose Lieferung ab" + trust-returns-label: "{returnsWindowDays}-Tage-Rückgabe" + drawer-title: "Ihre Tasche" + drawer-add-for-free-shipping: "Noch {amount} bis zum kostenlosen Versand" + drawer-free-shipping-qualified: "Kostenloser Versand!" + + storefront-checkout: + empty-cart-title: "Ihr Warenkorb ist leer" + empty-cart-body: "Noch keine Artikel hinzugefügt." + empty-cart-start-label: "Einkauf starten" + empty-cart-go-back-label: "Zurück" + empty-session-title: "Ihr Warenkorb ist leer" + empty-session-message: "Artikel hinzufügen und hier zurückkehren." + marketing-opt-in-label: "Angebote per E-Mail" + trust-secure-checkout: "Sicherer Checkout" + trust-stripe-processor: "Zahlungen via Stripe" diff --git a/apps/web/config/saleor/fixtures/translations/fi.yaml b/apps/web/config/saleor/fixtures/translations/fi.yaml new file mode 100644 index 0000000..be14815 --- /dev/null +++ b/apps/web/config/saleor/fixtures/translations/fi.yaml @@ -0,0 +1,52 @@ +# Finnish storefront model translations (Saleor LanguageCodeEnum: FI) +languageCode: FI + +pages: + storefront-chrome: + announcement-message: "Ilmainen toimitus yli {freeShippingThreshold}" + nav-all-products-label: "Kaikki" + nav-view-all-label: "Näytä kaikki {label}" + + storefront-products: + listing-title: "Kaikki tuotteet" + listing-description: "Tutustu koko premium-tuotevalikoimaamme." + + storefront-homepage: + hero-heading: "Tutustu kokoelmaamme" + hero-subheading: "Premium-tuotteita poikkeuksellisella laadulla. Tutustu huolellisesti kuratoituun valikoimaamme." + hero-cta-label: "Osta kaikki" + featured-heading: "Suositellut tuotteet" + brand-story-heading: "Rakennettu oikeaa kauppaa varten" + brand-story-paragraph-1: "Paper on minimalistinen, tuotantovalmis myymälä Saleorille — puhdas kuin tyhjä sivu, valmis julkaistavaksi." + brand-story-paragraph-2: "Mukauta osioita koodissa, yhdistä katalogisi ja pidä ostoskori-, kassa- ja tuotesivut testattuina valmiina." + values-heading: "Miksi ostaa meiltä" + values-column-1-title: "Kuratoitu laatu" + values-column-1-text: "Jokainen tuote valitaan käsityön ja kestävyyden perusteella — ei trendien perässä." + values-column-2-title: "Nopea toimitus" + values-column-2-text: "Tilaukset lähtevät alueellisista varastoista seurannalla kassalta toimitukseen." + values-column-3-title: "Helppopalautukset" + values-column-3-text: "Vaivattomat palautukset {returnsWindowDays} päivän sisällä. Seisomme myymiemme tuotteiden takana." + editorial-heading: "Suunniteltu kestämään" + editorial-paragraph-1: "Harkitut materiaalit ja ajattomat siluetit — kappaleita, joihin palaat kausi toisensa jälkeen." + editorial-cta-label: "Tutustu kokoelmiin" + + storefront-cart: + empty-title: "Ostoskorisi on tyhjä" + empty-body: "Et ole vielä lisännyt mitään." + empty-cta-label: "Aloita ostokset" + trust-free-shipping-prefix: "Ilmainen toimitus yli" + trust-returns-label: "{returnsWindowDays} päivän palautusoikeus" + drawer-title: "Ostoskorisi" + drawer-add-for-free-shipping: "Vielä {amount} ilmaiseen toimitukseen" + drawer-free-shipping-qualified: "Ilmainen toimitus!" + + storefront-checkout: + empty-cart-title: "Ostoskorisi on tyhjä" + empty-cart-body: "Et ole vielä lisännyt mitään." + empty-cart-start-label: "Aloita ostokset" + empty-cart-go-back-label: "Takaisin" + empty-session-title: "Ostoskorisi on tyhjä" + empty-session-message: "Lisää tuotteita ja palaa viimeistelemään." + marketing-opt-in-label: "Tarjoukset sähköpostitse" + trust-secure-checkout: "Turvallinen kassa" + trust-stripe-processor: "Maksut käsitellään Stripen kautta" diff --git a/apps/web/config/saleor/fixtures/translations/fr.yaml b/apps/web/config/saleor/fixtures/translations/fr.yaml new file mode 100644 index 0000000..42edc97 --- /dev/null +++ b/apps/web/config/saleor/fixtures/translations/fr.yaml @@ -0,0 +1,52 @@ +# French storefront model translations (Saleor LanguageCodeEnum: FR) +languageCode: FR + +pages: + storefront-chrome: + announcement-message: "Livraison gratuite dès {freeShippingThreshold}" + nav-all-products-label: "Tout" + nav-view-all-label: "Voir tout {label}" + + storefront-products: + listing-title: "Tous les produits" + listing-description: "Découvrez notre collection complète de produits premium." + + storefront-homepage: + hero-heading: "Découvrez notre collection" + hero-subheading: "Des produits premium d'une qualité exceptionnelle. Découvrez notre sélection soignée." + hero-cta-label: "Tout voir" + featured-heading: "Produits en vedette" + brand-story-heading: "Conçu pour le commerce réel" + brand-story-paragraph-1: "Paper est une vitrine minimaliste et prête pour la production pour Saleor — propre comme une page blanche, prête à être déployée." + brand-story-paragraph-2: "Personnalisez les sections dans le code, connectez votre catalogue et conservez des pages panier, paiement et produit éprouvées." + values-heading: "Pourquoi acheter chez nous" + values-column-1-title: "Qualité sélectionnée" + values-column-1-text: "Chaque produit est choisi pour son savoir-faire et sa durabilité — pas pour suivre les tendances." + values-column-2-title: "Expédition rapide" + values-column-2-text: "Les commandes partent d'entrepôts régionaux avec suivi du paiement à la livraison." + values-column-3-title: "Retours faciles" + values-column-3-text: "Retours sans tracas sous {returnsWindowDays} jours. Nous garantissons ce que nous vendons." + editorial-heading: "Conçu pour durer" + editorial-paragraph-1: "Des matériaux réfléchis et des silhouettes intemporelles — des pièces que vous porterez saison après saison." + editorial-cta-label: "Explorer les collections" + + storefront-cart: + empty-title: "Votre panier est vide" + empty-body: "Vous n'avez encore rien ajouté." + empty-cta-label: "Commencer vos achats" + trust-free-shipping-prefix: "Livraison gratuite à partir de" + trust-returns-label: "Retours sous {returnsWindowDays} jours" + drawer-title: "Votre panier" + drawer-add-for-free-shipping: "Plus que {amount} pour la livraison gratuite" + drawer-free-shipping-qualified: "Livraison gratuite !" + + storefront-checkout: + empty-cart-title: "Votre panier est vide" + empty-cart-body: "Vous n'avez encore rien ajouté." + empty-cart-start-label: "Commencer vos achats" + empty-cart-go-back-label: "Retour" + empty-session-title: "Votre panier est vide" + empty-session-message: "Ajoutez des articles, puis revenez pour payer." + marketing-opt-in-label: "Recevoir les offres par e-mail" + trust-secure-checkout: "Paiement sécurisé" + trust-stripe-processor: "Paiements traités par Stripe" diff --git a/apps/web/config/saleor/fixtures/translations/ja.yaml b/apps/web/config/saleor/fixtures/translations/ja.yaml new file mode 100644 index 0000000..c2a1401 --- /dev/null +++ b/apps/web/config/saleor/fixtures/translations/ja.yaml @@ -0,0 +1,52 @@ +# Japanese storefront model translations (Saleor LanguageCodeEnum: JA) +languageCode: JA + +pages: + storefront-chrome: + announcement-message: "{freeShippingThreshold}以上で送料無料" + nav-all-products-label: "すべて" + nav-view-all-label: "{label}をすべて見る" + + storefront-products: + listing-title: "すべての商品" + listing-description: "厳選されたプレミアム商品のコレクションをご覧ください。" + + storefront-homepage: + hero-heading: "コレクションを見る" + hero-subheading: "卓越した品質のプレミアム商品。丁寧に選んだセレクションをお楽しみください。" + hero-cta-label: "すべて見る" + featured-heading: "おすすめ商品" + brand-story-heading: "実際のコマースのために設計" + brand-story-paragraph-1: "PaperはSaleor向けのミニマルで本番運用可能なストアフロントです — 白紙のように清潔で、すぐにデプロイできます。" + brand-story-paragraph-2: "コードでセクションをカスタマイズし、カタログをつなぎ、実績のあるカート・チェックアウト・商品ページをそのまま活用できます。" + values-heading: "選ばれる理由" + values-column-1-title: "厳選された品質" + values-column-1-text: "どの商品も流行ではなく、職人技と耐久性を基準に選びます。" + values-column-2-title: "スピーディーな配送" + values-column-2-text: "ご注文は地域倉庫から発送され、決済から配送まで追跡できます。" + values-column-3-title: "かんたん返品" + values-column-3-text: "{returnsWindowDays}日以内の負担の少ない返品。販売する商品に責任を持ちます。" + editorial-heading: "長く使えるように設計" + editorial-paragraph-1: "吟味した素材と時代を超えるシルエット — シーズンを超えて手に取れるアイテム。" + editorial-cta-label: "コレクションを見る" + + storefront-cart: + empty-title: "カートは空です" + empty-body: "まだ商品が追加されていません。" + empty-cta-label: "ショッピングを始める" + trust-free-shipping-prefix: "送料無料 · 最低" + trust-returns-label: "{returnsWindowDays}日返品" + drawer-title: "カート" + drawer-add-for-free-shipping: "送料無料まであと {amount}" + drawer-free-shipping-qualified: "送料無料が適用されます!" + + storefront-checkout: + empty-cart-title: "カートは空です" + empty-cart-body: "まだ商品が追加されていません。" + empty-cart-start-label: "ショッピングを始める" + empty-cart-go-back-label: "戻る" + empty-session-title: "カートは空です" + empty-session-message: "商品を追加してから、戻って決済を完了してください。" + marketing-opt-in-label: "お得な情報をメールで受け取る" + trust-secure-checkout: "安全な決済" + trust-stripe-processor: "決済はStripeで処理されます" diff --git a/apps/web/config/saleor/fixtures/translations/ko.yaml b/apps/web/config/saleor/fixtures/translations/ko.yaml new file mode 100644 index 0000000..7bc4ecf --- /dev/null +++ b/apps/web/config/saleor/fixtures/translations/ko.yaml @@ -0,0 +1,52 @@ +# Korean storefront model translations (Saleor LanguageCodeEnum: KO) +languageCode: KO + +pages: + storefront-chrome: + announcement-message: "{freeShippingThreshold} 이상 무료 배송" + nav-all-products-label: "전체" + nav-view-all-label: "{label} 모두 보기" + + storefront-products: + listing-title: "전체 상품" + listing-description: "엄선한 프리미엄 상품 컬렉션을 만나 보세요." + + storefront-homepage: + hero-heading: "컬렉션 살펴보기" + hero-subheading: "탁월한 품질의 프리미엄 상품. 정성껏 고른 셀렉션을 즐겨 보세요." + hero-cta-label: "전체 보기" + featured-heading: "추천 상품" + brand-story-heading: "실제 커머스를 위해 설계" + brand-story-paragraph-1: "Paper는 Saleor를 위한 미니멀하고 프로덕션 레디한 스토어프론트입니다 — 흰 종이처럼 깔끔하고, 바로 배포할 수 있습니다." + brand-story-paragraph-2: "코드로 섹션을 커스터마이즈하고, 카탈로그를 연결한 뒤, 검증된 장바구니·결제·상품 페이지를 그대로 활용하세요." + values-heading: "선택하는 이유" + values-column-1-title: "엄선한 품질" + values-column-1-text: "유행이 아니라 장인 정신과 내구성을 기준으로 모든 상품을 고릅니다." + values-column-2-title: "빠른 배송" + values-column-2-text: "주문은 지역 창고에서 발송되며, 결제부터 배송까지 추적할 수 있습니다." + values-column-3-title: "간편한 반품" + values-column-3-text: "{returnsWindowDays}일 이내 부담 없는 반품. 판매하는 상품에 책임을 집니다." + editorial-heading: "오래 쓰도록 설계" + editorial-paragraph-1: "고른 소재와 시대를 초월하는 실루엣 — 시즌을 넘어 손이 가는 아이템." + editorial-cta-label: "컬렉션 보기" + + storefront-cart: + empty-title: "장바구니가 비어 있습니다" + empty-body: "아직 담은 상품이 없습니다." + empty-cta-label: "쇼핑 시작하기" + trust-free-shipping-prefix: "무료 배송 · 최소" + trust-returns-label: "{returnsWindowDays}일 반품" + drawer-title: "장바구니" + drawer-add-for-free-shipping: "무료 배송까지 {amount} 남음" + drawer-free-shipping-qualified: "무료 배송이 적용됩니다!" + + storefront-checkout: + empty-cart-title: "장바구니가 비어 있습니다" + empty-cart-body: "아직 담은 상품이 없습니다." + empty-cart-start-label: "쇼핑 시작하기" + empty-cart-go-back-label: "돌아가기" + empty-session-title: "장바구니가 비어 있습니다" + empty-session-message: "상품을 담은 뒤 돌아와 결제를 완료해 주세요." + marketing-opt-in-label: "혜택 소식을 이메일로 받기" + trust-secure-checkout: "안전한 결제" + trust-stripe-processor: "결제는 Stripe로 처리됩니다" diff --git a/apps/web/config/saleor/fixtures/translations/nb.yaml b/apps/web/config/saleor/fixtures/translations/nb.yaml new file mode 100644 index 0000000..7cb4ccf --- /dev/null +++ b/apps/web/config/saleor/fixtures/translations/nb.yaml @@ -0,0 +1,52 @@ +# Norwegian Bokmål storefront model translations (Saleor LanguageCodeEnum: NB) +languageCode: NB + +pages: + storefront-chrome: + announcement-message: "Gratis frakt over {freeShippingThreshold}" + nav-all-products-label: "Alle" + nav-view-all-label: "Se alle {label}" + + storefront-products: + listing-title: "Alle produkter" + listing-description: "Utforsk hele vår kolleksjon av premiumprodukter." + + storefront-homepage: + hero-heading: "Utforsk kolleksjonen vår" + hero-subheading: "Premiumprodukter med eksepsjonell kvalitet. Oppdag vårt kuraterte utvalg." + hero-cta-label: "Handle alt" + featured-heading: "Utvalgte produkter" + brand-story-heading: "Bygget for ekte handel" + brand-story-paragraph-1: "Paper er en minimal, produksjonsklar nettbutikk for Saleor — ren som et blankt ark, klar til lansering." + brand-story-paragraph-2: "Tilpass seksjoner i koden, koble til katalogen din og behold testede handlekurv-, kasse- og produktsider." + values-heading: "Hvorfor handle hos oss" + values-column-1-title: "Kuratert kvalitet" + values-column-1-text: "Hvert produkt er valgt for håndverk og holdbarhet — ikke for trender." + values-column-2-title: "Rask oppfyllelse" + values-column-2-text: "Bestillinger sendes fra regionale lagre med sporing fra kasse til levering." + values-column-3-title: "Enkle returer" + values-column-3-text: "Problemfrie returer innen {returnsWindowDays} dager. Vi står bak det vi selger." + editorial-heading: "Designet for å vare" + editorial-paragraph-1: "Gjennomtenkte materialer og tidløse silhuetter — plagg du bruker sesong etter sesong." + editorial-cta-label: "Utforsk kolleksjoner" + + storefront-cart: + empty-title: "Handlekurven din er tom" + empty-body: "Du har ikke lagt til noe ennå." + empty-cta-label: "Start shopping" + trust-free-shipping-prefix: "Gratis levering over" + trust-returns-label: "{returnsWindowDays} dagers retur" + drawer-title: "Handlekurven din" + drawer-add-for-free-shipping: "{amount} igjen til gratis frakt" + drawer-free-shipping-qualified: "Gratis frakt!" + + storefront-checkout: + empty-cart-title: "Handlekurven din er tom" + empty-cart-body: "Du har ikke lagt til noe ennå." + empty-cart-start-label: "Start shopping" + empty-cart-go-back-label: "Gå tilbake" + empty-session-title: "Handlekurven din er tom" + empty-session-message: "Legg til varer og kom tilbake for å betale." + marketing-opt-in-label: "Tilbud på e-post" + trust-secure-checkout: "Sikker kasse" + trust-stripe-processor: "Betalinger behandles av Stripe" diff --git a/apps/web/config/saleor/fixtures/translations/pl.yaml b/apps/web/config/saleor/fixtures/translations/pl.yaml new file mode 100644 index 0000000..8dc007f --- /dev/null +++ b/apps/web/config/saleor/fixtures/translations/pl.yaml @@ -0,0 +1,52 @@ +# Polish storefront model translations (Saleor LanguageCodeEnum: PL) +languageCode: PL + +pages: + storefront-chrome: + announcement-message: "Darmowa dostawa od {freeShippingThreshold}" + nav-all-products-label: "Wszystko" + nav-view-all-label: "Zobacz wszystkie {label}" + + storefront-products: + listing-title: "Wszystkie produkty" + listing-description: "Odkryj naszą pełną kolekcję produktów premium." + + storefront-homepage: + hero-heading: "Odkryj naszą kolekcję" + hero-subheading: "Produkty premium o wyjątkowej jakości. Poznaj naszą starannie wyselekcjonowaną ofertę." + hero-cta-label: "Zobacz wszystko" + featured-heading: "Polecane produkty" + brand-story-heading: "Stworzone do prawdziwego handlu" + brand-story-paragraph-1: "Paper to minimalistyczny, gotowy do produkcji storefront dla Saleor — czysty jak biała kartka, gotowy do wdrożenia." + brand-story-paragraph-2: "Dostosuj sekcje w kodzie, połącz katalog i korzystaj ze sprawdzonych stron koszyka, kasy i produktów." + values-heading: "Dlaczego warto u nas kupować" + values-column-1-title: "Starannie wyselekcjonowana jakość" + values-column-1-text: "Każdy produkt wybieramy ze względu na rzemiosło i trwałość — nie za modą." + values-column-2-title: "Szybka realizacja" + values-column-2-text: "Zamówienia wysyłamy z regionalnych magazynów z pełnym śledzeniem przesyłki." + values-column-3-title: "Łatwe zwroty" + values-column-3-text: "Bezproblemowe zwroty w ciągu {returnsWindowDays} dni. Stoimy za tym, co sprzedajemy." + editorial-heading: "Zaprojektowane na lata" + editorial-paragraph-1: "Przemyślane materiały i ponadczasowe kroje — rzeczy, po które sięgniesz sezon za sezonem." + editorial-cta-label: "Przeglądaj kolekcje" + + storefront-cart: + empty-title: "Twój koszyk jest pusty" + empty-body: "Nie dodałeś jeszcze nic do koszyka." + empty-cta-label: "Rozpocznij zakupy" + trust-free-shipping-prefix: "Darmowa dostawa powyżej" + trust-returns-label: "Zwroty przez {returnsWindowDays} dni" + drawer-title: "Twój koszyk" + drawer-add-for-free-shipping: "Brakuje {amount} do darmowej dostawy" + drawer-free-shipping-qualified: "Darmowa dostawa!" + + storefront-checkout: + empty-cart-title: "Twój koszyk jest pusty" + empty-cart-body: "Nie dodałeś jeszcze nic do koszyka." + empty-cart-start-label: "Rozpocznij zakupy" + empty-cart-go-back-label: "Wróć" + empty-session-title: "Twój koszyk jest pusty" + empty-session-message: "Dodaj produkty i wróć tutaj, by dokończyć." + marketing-opt-in-label: "Oferty e-mailem" + trust-secure-checkout: "Bezpieczna płatność" + trust-stripe-processor: "Płatności obsługiwane przez Stripe" diff --git a/apps/web/config/saleor/storefront-content.config.yml b/apps/web/config/saleor/storefront-content.config.yml new file mode 100644 index 0000000..d250a9d --- /dev/null +++ b/apps/web/config/saleor/storefront-content.config.yml @@ -0,0 +1,308 @@ +# Paper storefront marketing copy — Saleor Configurator 3.23+ +# +# Deploy: +# pnpm configurator:storefront-content:plan +# pnpm configurator:storefront-content:deploy +# +# Requires SALEOR_APP_TOKEN with MANAGE_PAGES + MANAGE_PAGE_TYPES_AND_ATTRIBUTES (or admin). +# CONTENT_PROVIDER defaults to saleor; set CONTENT_PROVIDER=code to use code defaults only. +# +# Page slug convention (globally unique in Saleor): +# storefront-chrome, storefront-homepage, storefront-cart, storefront-checkout +# Channel override: storefront-chrome-{channelSlug} +# +# Attribute slugs must match src/lib/content/attribute-slugs.ts +# Greenfield: pnpm configurator:storefront-content:deploy — creates PageTypes, attributes, and seed models below. +# +# Scope (ADR 0002): this layer holds *editorial / merchant-editable* copy only. Functional +# UI strings (cart totals/buttons/a11y labels, item count, cart-page chrome, breadcrumbs) +# are code-owned via next-intl (messages/*.json) and intentionally NOT modeled here. + +contentAttributes: + # Storefront — Policies (channel-wide facts; NUMERIC so the Dashboard validates them + # and the storefront can reuse the same value in cart math and in copy placeholders) + - name: Free shipping threshold + inputType: NUMERIC + - name: Returns window days + inputType: NUMERIC + # Storefront — Chrome + - name: Announcement ID + inputType: PLAIN_TEXT + # Seed + translations: keep {freeShippingThreshold} (value from storefront-policy model) + - name: Announcement message + inputType: PLAIN_TEXT + - name: Announcement href + inputType: PLAIN_TEXT + - name: Announcement link label + inputType: PLAIN_TEXT + - name: Announcement dismissible + inputType: BOOLEAN + - name: Nav all products label + inputType: PLAIN_TEXT + - name: Nav view all label + inputType: PLAIN_TEXT + # Storefront — Products listing + - name: Listing title + inputType: PLAIN_TEXT + - name: Listing description + inputType: PLAIN_TEXT + # Storefront — Homepage + - name: Hero eyebrow + inputType: PLAIN_TEXT + - name: Hero heading + inputType: PLAIN_TEXT + - name: Hero subheading + inputType: PLAIN_TEXT + - name: Hero CTA label + inputType: PLAIN_TEXT + - name: Hero image + inputType: FILE + - name: Featured heading + inputType: PLAIN_TEXT + - name: Featured collection + inputType: SINGLE_REFERENCE + entityType: COLLECTION + - name: Featured limit + inputType: NUMERIC + - name: Categories heading + inputType: PLAIN_TEXT + - name: Categories eyebrow + inputType: PLAIN_TEXT + - name: Brand story heading + inputType: PLAIN_TEXT + - name: Brand story paragraph 1 + inputType: PLAIN_TEXT + - name: Brand story paragraph 2 + inputType: PLAIN_TEXT + - name: Values heading + inputType: PLAIN_TEXT + - name: Values columns desktop + inputType: PLAIN_TEXT + - name: Values column 1 title + inputType: PLAIN_TEXT + - name: Values column 1 text + inputType: PLAIN_TEXT + - name: Values column 2 title + inputType: PLAIN_TEXT + # Seed + translations: keep {returnsWindowDays} (value from storefront-policy model) + - name: Values column 2 text + inputType: PLAIN_TEXT + - name: Values column 3 title + inputType: PLAIN_TEXT + - name: Values column 3 text + inputType: PLAIN_TEXT + - name: Editorial heading + inputType: PLAIN_TEXT + - name: Editorial paragraph 1 + inputType: PLAIN_TEXT + - name: Editorial image position + inputType: PLAIN_TEXT + - name: Editorial CTA label + inputType: PLAIN_TEXT + - name: Photo credits + inputType: PLAIN_TEXT + # JSON array: [{"name":"Artist","href":"https://unsplash.com/@handle"}, ...] + # Storefront — Cart + - name: Empty title + inputType: PLAIN_TEXT + - name: Empty body + inputType: PLAIN_TEXT + - name: Empty CTA label + inputType: PLAIN_TEXT + - name: Trust free shipping prefix + inputType: PLAIN_TEXT + # Seed + translations: keep {returnsWindowDays} + - name: Trust returns label + inputType: PLAIN_TEXT + - name: Drawer title + inputType: PLAIN_TEXT + - name: Drawer add for free shipping + inputType: PLAIN_TEXT + - name: Drawer free shipping qualified + inputType: PLAIN_TEXT + # Storefront — Checkout + - name: Empty cart title + inputType: PLAIN_TEXT + - name: Empty cart body + inputType: PLAIN_TEXT + - name: Empty cart start label + inputType: PLAIN_TEXT + - name: Empty cart go back label + inputType: PLAIN_TEXT + - name: Empty session title + inputType: PLAIN_TEXT + - name: Empty session message + inputType: PLAIN_TEXT + - name: Marketing opt-in label + inputType: PLAIN_TEXT + - name: Trust secure checkout + inputType: PLAIN_TEXT + - name: Trust Stripe processor + inputType: PLAIN_TEXT + +modelTypes: + - name: "Storefront — Policies" + slug: storefront-policies + attributes: + - attribute: Free shipping threshold + - attribute: Returns window days + + - name: "Storefront — Chrome" + slug: storefront-chrome + attributes: + - attribute: Announcement ID + - attribute: Announcement message + - attribute: Announcement href + - attribute: Announcement link label + - attribute: Announcement dismissible + - attribute: Nav all products label + - attribute: Nav view all label + + - name: "Storefront — Products" + slug: storefront-products + attributes: + - attribute: Listing title + - attribute: Listing description + + - name: "Storefront — Homepage" + slug: storefront-homepage + attributes: + - attribute: Hero eyebrow + - attribute: Hero heading + - attribute: Hero subheading + - attribute: Hero CTA label + - attribute: Hero image + - attribute: Featured heading + - attribute: Featured collection + - attribute: Featured limit + - attribute: Categories heading + - attribute: Categories eyebrow + - attribute: Brand story heading + - attribute: Brand story paragraph 1 + - attribute: Brand story paragraph 2 + - attribute: Values heading + - attribute: Values columns desktop + - attribute: Values column 1 title + - attribute: Values column 1 text + - attribute: Values column 2 title + - attribute: Values column 2 text + - attribute: Values column 3 title + - attribute: Values column 3 text + - attribute: Editorial heading + - attribute: Editorial paragraph 1 + - attribute: Editorial image position + - attribute: Editorial CTA label + - attribute: Photo credits + + - name: "Storefront — Cart" + slug: storefront-cart + attributes: + - attribute: Empty title + - attribute: Empty body + - attribute: Empty CTA label + - attribute: Trust free shipping prefix + - attribute: Trust returns label + - attribute: Drawer title + - attribute: Drawer add for free shipping + - attribute: Drawer free shipping qualified + + - name: "Storefront — Checkout" + slug: storefront-checkout + attributes: + - attribute: Empty cart title + - attribute: Empty cart body + - attribute: Empty cart start label + - attribute: Empty cart go back label + - attribute: Empty session title + - attribute: Empty session message + - attribute: Marketing opt-in label + - attribute: Trust secure checkout + - attribute: Trust Stripe processor + +# Model attribute keys use contentAttribute *names* (Configurator). Saleor assigns slugs +# (see src/lib/content/attribute-slugs.ts) which Paper mappers read at runtime. +# +# EN seed values below are generated from src/lib/content/defaults.ts — do not edit by hand. +# After changing defaults.ts: pnpm content:export-seed | CI: pnpm content:verify-seed +models: + - title: Storefront Policies + slug: storefront-policy + modelType: Storefront — Policies + isPublished: true + attributes: + Free shipping threshold: 75 + Returns window days: 30 + - title: Storefront Chrome + slug: storefront-chrome + modelType: Storefront — Chrome + isPublished: true + attributes: + Announcement ID: "" + Announcement message: Free shipping on orders over {freeShippingThreshold} + Announcement dismissible: true + Nav all products label: All + Nav view all label: View all {label} + - title: Storefront Products + slug: storefront-products + modelType: Storefront — Products + isPublished: true + attributes: + Listing title: All Products + Listing description: Browse our full catalog. + - title: Storefront Homepage + slug: storefront-homepage + modelType: Storefront — Homepage + isPublished: true + attributes: + Hero eyebrow: "" + Hero heading: Discover our collection + Hero subheading: Discover our collection. + Hero CTA label: Shop all + Featured heading: Featured products + Featured collection: featured-products + Featured limit: 8 + Categories heading: Shop by category + Categories eyebrow: "" + Brand story heading: Our story + Brand story paragraph 1: Tell shoppers who you are and what you stand for. + Brand story paragraph 2: Edit this copy in Dashboard → Models → Storefront — Homepage. + Values heading: Why shop with us + Values columns desktop: 3 + Values column 1 title: Quality + Values column 1 text: Share what makes your products worth choosing. + Values column 2 title: Shipping + Values column 2 text: Describe how and when orders arrive. + Values column 3 title: Returns + Values column 3 text: Easy returns within {returnsWindowDays} days. + Editorial heading: From the shop + Editorial paragraph 1: Highlight a collection, seasonal story, or campaign — then edit this block in Models. + Editorial image position: right + Editorial CTA label: Explore collections + Photo credits: "[]" + - title: Storefront Cart + slug: storefront-cart + modelType: Storefront — Cart + isPublished: true + attributes: + Empty title: Your bag is empty + Empty body: Looks like you haven't added anything to your bag yet. + Empty CTA label: Start Shopping + Trust free shipping prefix: Free delivery over + Trust returns label: "{returnsWindowDays}-day returns" + Drawer title: Your Bag + Drawer add for free shipping: Add {amount} more for free shipping + Drawer free shipping qualified: You qualify for free shipping! + - title: Storefront Checkout + slug: storefront-checkout + modelType: Storefront — Checkout + isPublished: true + attributes: + Empty cart title: Your cart is empty + Empty cart body: Looks like you haven't added anything to your cart yet. + Empty cart start label: Start Shopping + Empty cart go back label: Go back + Empty session title: Your cart is empty + Empty session message: Add items from the store, then return here to complete your purchase. + Marketing opt-in label: Email me with news and offers + Trust secure checkout: Secure checkout + Trust Stripe processor: Payments processed by Stripe diff --git a/apps/web/config/saleor/storefront-content.snapshot.json b/apps/web/config/saleor/storefront-content.snapshot.json new file mode 100644 index 0000000..f663b2f --- /dev/null +++ b/apps/web/config/saleor/storefront-content.snapshot.json @@ -0,0 +1,470 @@ +{ + "paperContentSchemaVersion": 1, + "contentAttributes": [ + { + "name": "Free shipping threshold", + "slug": "free-shipping-threshold", + "inputType": "NUMERIC" + }, + { + "name": "Returns window days", + "slug": "returns-window-days", + "inputType": "NUMERIC" + }, + { + "name": "Announcement ID", + "slug": "announcement-id", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Announcement message", + "slug": "announcement-message", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Announcement href", + "slug": "announcement-href", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Announcement link label", + "slug": "announcement-link-label", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Announcement dismissible", + "slug": "announcement-dismissible", + "inputType": "BOOLEAN" + }, + { + "name": "Nav all products label", + "slug": "nav-all-products-label", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Nav view all label", + "slug": "nav-view-all-label", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Listing title", + "slug": "listing-title", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Listing description", + "slug": "listing-description", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Hero eyebrow", + "slug": "hero-eyebrow", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Hero heading", + "slug": "hero-heading", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Hero subheading", + "slug": "hero-subheading", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Hero CTA label", + "slug": "hero-cta-label", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Hero image", + "slug": "hero-image", + "inputType": "FILE" + }, + { + "name": "Featured heading", + "slug": "featured-heading", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Featured collection", + "slug": "featured-collection", + "inputType": "SINGLE_REFERENCE", + "entityType": "COLLECTION" + }, + { + "name": "Featured limit", + "slug": "featured-limit", + "inputType": "NUMERIC" + }, + { + "name": "Categories heading", + "slug": "categories-heading", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Categories eyebrow", + "slug": "categories-eyebrow", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Brand story heading", + "slug": "brand-story-heading", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Brand story paragraph 1", + "slug": "brand-story-paragraph-1", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Brand story paragraph 2", + "slug": "brand-story-paragraph-2", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Values heading", + "slug": "values-heading", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Values columns desktop", + "slug": "values-columns-desktop", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Values column 1 title", + "slug": "values-column-1-title", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Values column 1 text", + "slug": "values-column-1-text", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Values column 2 title", + "slug": "values-column-2-title", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Values column 2 text", + "slug": "values-column-2-text", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Values column 3 title", + "slug": "values-column-3-title", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Values column 3 text", + "slug": "values-column-3-text", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Editorial heading", + "slug": "editorial-heading", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Editorial paragraph 1", + "slug": "editorial-paragraph-1", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Editorial image position", + "slug": "editorial-image-position", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Editorial CTA label", + "slug": "editorial-cta-label", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Photo credits", + "slug": "photo-credits", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Empty title", + "slug": "empty-title", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Empty body", + "slug": "empty-body", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Empty CTA label", + "slug": "empty-cta-label", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Trust free shipping prefix", + "slug": "trust-free-shipping-prefix", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Trust returns label", + "slug": "trust-returns-label", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Drawer title", + "slug": "drawer-title", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Drawer add for free shipping", + "slug": "drawer-add-for-free-shipping", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Drawer free shipping qualified", + "slug": "drawer-free-shipping-qualified", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Empty cart title", + "slug": "empty-cart-title", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Empty cart body", + "slug": "empty-cart-body", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Empty cart start label", + "slug": "empty-cart-start-label", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Empty cart go back label", + "slug": "empty-cart-go-back-label", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Empty session title", + "slug": "empty-session-title", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Empty session message", + "slug": "empty-session-message", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Marketing opt-in label", + "slug": "marketing-opt-in-label", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Trust secure checkout", + "slug": "trust-secure-checkout", + "inputType": "PLAIN_TEXT" + }, + { + "name": "Trust Stripe processor", + "slug": "trust-stripe-processor", + "inputType": "PLAIN_TEXT" + } + ], + "modelTypes": [ + { + "name": "Storefront — Policies", + "slug": "storefront-policies", + "attributes": [ + "Free shipping threshold", + "Returns window days" + ] + }, + { + "name": "Storefront — Chrome", + "slug": "storefront-chrome", + "attributes": [ + "Announcement ID", + "Announcement message", + "Announcement href", + "Announcement link label", + "Announcement dismissible", + "Nav all products label", + "Nav view all label" + ] + }, + { + "name": "Storefront — Products", + "slug": "storefront-products", + "attributes": [ + "Listing title", + "Listing description" + ] + }, + { + "name": "Storefront — Homepage", + "slug": "storefront-homepage", + "attributes": [ + "Hero eyebrow", + "Hero heading", + "Hero subheading", + "Hero CTA label", + "Hero image", + "Featured heading", + "Featured collection", + "Featured limit", + "Categories heading", + "Categories eyebrow", + "Brand story heading", + "Brand story paragraph 1", + "Brand story paragraph 2", + "Values heading", + "Values columns desktop", + "Values column 1 title", + "Values column 1 text", + "Values column 2 title", + "Values column 2 text", + "Values column 3 title", + "Values column 3 text", + "Editorial heading", + "Editorial paragraph 1", + "Editorial image position", + "Editorial CTA label", + "Photo credits" + ] + }, + { + "name": "Storefront — Cart", + "slug": "storefront-cart", + "attributes": [ + "Empty title", + "Empty body", + "Empty CTA label", + "Trust free shipping prefix", + "Trust returns label", + "Drawer title", + "Drawer add for free shipping", + "Drawer free shipping qualified" + ] + }, + { + "name": "Storefront — Checkout", + "slug": "storefront-checkout", + "attributes": [ + "Empty cart title", + "Empty cart body", + "Empty cart start label", + "Empty cart go back label", + "Empty session title", + "Empty session message", + "Marketing opt-in label", + "Trust secure checkout", + "Trust Stripe processor" + ] + } + ], + "models": [ + { + "title": "Storefront Policies", + "slug": "storefront-policy", + "modelType": "Storefront — Policies", + "isPublished": true, + "attributes": { + "Free shipping threshold": 75, + "Returns window days": 30 + } + }, + { + "title": "Storefront Chrome", + "slug": "storefront-chrome", + "modelType": "Storefront — Chrome", + "isPublished": true, + "attributes": { + "Announcement ID": "", + "Announcement message": "Free shipping on orders over {freeShippingThreshold}", + "Announcement dismissible": true, + "Nav all products label": "All", + "Nav view all label": "View all {label}" + } + }, + { + "title": "Storefront Products", + "slug": "storefront-products", + "modelType": "Storefront — Products", + "isPublished": true, + "attributes": { + "Listing title": "All Products", + "Listing description": "Browse our full catalog." + } + }, + { + "title": "Storefront Homepage", + "slug": "storefront-homepage", + "modelType": "Storefront — Homepage", + "isPublished": true, + "attributes": { + "Hero eyebrow": "", + "Hero heading": "Discover our collection", + "Hero subheading": "Discover our collection.", + "Hero CTA label": "Shop all", + "Featured heading": "Featured products", + "Featured collection": "featured-products", + "Featured limit": 8, + "Categories heading": "Shop by category", + "Categories eyebrow": "", + "Brand story heading": "Our story", + "Brand story paragraph 1": "Tell shoppers who you are and what you stand for.", + "Brand story paragraph 2": "Edit this copy in Dashboard → Models → Storefront — Homepage.", + "Values heading": "Why shop with us", + "Values columns desktop": 3, + "Values column 1 title": "Quality", + "Values column 1 text": "Share what makes your products worth choosing.", + "Values column 2 title": "Shipping", + "Values column 2 text": "Describe how and when orders arrive.", + "Values column 3 title": "Returns", + "Values column 3 text": "Easy returns within {returnsWindowDays} days.", + "Editorial heading": "From the shop", + "Editorial paragraph 1": "Highlight a collection, seasonal story, or campaign — then edit this block in Models.", + "Editorial image position": "right", + "Editorial CTA label": "Explore collections", + "Photo credits": "[]" + } + }, + { + "title": "Storefront Cart", + "slug": "storefront-cart", + "modelType": "Storefront — Cart", + "isPublished": true, + "attributes": { + "Empty title": "Your bag is empty", + "Empty body": "Looks like you haven't added anything to your bag yet.", + "Empty CTA label": "Start Shopping", + "Trust free shipping prefix": "Free delivery over", + "Trust returns label": "{returnsWindowDays}-day returns", + "Drawer title": "Your Bag", + "Drawer add for free shipping": "Add {amount} more for free shipping", + "Drawer free shipping qualified": "You qualify for free shipping!" + } + }, + { + "title": "Storefront Checkout", + "slug": "storefront-checkout", + "modelType": "Storefront — Checkout", + "isPublished": true, + "attributes": { + "Empty cart title": "Your cart is empty", + "Empty cart body": "Looks like you haven't added anything to your cart yet.", + "Empty cart start label": "Start Shopping", + "Empty cart go back label": "Go back", + "Empty session title": "Your cart is empty", + "Empty session message": "Add items from the store, then return here to complete your purchase.", + "Marketing opt-in label": "Email me with news and offers", + "Trust secure checkout": "Secure checkout", + "Trust Stripe processor": "Payments processed by Stripe" + } + } + ], + "contentHash": "bb0b30f65eabcc6a" +} diff --git a/apps/web/config/themes/README.md b/apps/web/config/themes/README.md new file mode 100644 index 0000000..9cc80c6 --- /dev/null +++ b/apps/web/config/themes/README.md @@ -0,0 +1,36 @@ +# Storefront theme examples + +Optional visual directions you can try locally. **The shipped default is always Direction C** (Geist + semantic type scale) unless you opt in. + +## Typography themes + +| Theme | Env value | Display headings | Body / UI | +| --------------------------- | ----------- | ---------------- | --------- | +| **Default (Direction C)** | _(omit)_ | Geist | Geist | +| **Editorial (Direction A)** | `editorial` | Fraunces (serif) | Geist | + +Editorial is an **example** for heritage / outdoor-adventure positioning — not maintained as a second production default. Forks can copy the pattern for their own display fonts. + +### Try Editorial locally + +**Option 1 — one-off dev session (no `.env` edit):** + +```bash +pnpm run dev:theme-editorial +``` + +**Option 2 — merge into `.env.local`:** + +```bash +cat config/themes/typography-editorial.env.example >> .env.local +``` + +Then restart the dev server (`rm -rf .next` if fonts do not update). + +### How it works + +- `NEXT_PUBLIC_TYPOGRAPHY_THEME=editorial` sets `data-typography="editorial"` on ``. +- `src/styles/brand.css` switches `--font-display` to Fraunces; body stays Geist. +- Semantic tokens (`text-display`, `text-h1`–`text-h3`) pick up the display family automatically — no component changes. + +See also: [`src/styles/README.md`](../src/styles/README.md) (type scale tokens). diff --git a/apps/web/config/themes/typography-editorial.env.example b/apps/web/config/themes/typography-editorial.env.example new file mode 100644 index 0000000..0fafea1 --- /dev/null +++ b/apps/web/config/themes/typography-editorial.env.example @@ -0,0 +1,3 @@ +# Direction A — Editorial Adventure (example typography theme) +# Fraunces display headings + Geist body. See config/themes/README.md. +NEXT_PUBLIC_TYPOGRAPHY_THEME=editorial diff --git a/apps/web/cost-rates.json b/apps/web/cost-rates.json new file mode 100644 index 0000000..2593f31 --- /dev/null +++ b/apps/web/cost-rates.json @@ -0,0 +1,8 @@ +{ + "note": "Shape of the Vercel bill used by pnpm cost:estimate. Not a quote. See paper-vercel-cost.", + "perMillion": { + "functionInvocations": 0.6, + "edgeRequests": 2, + "isrWrites8kb": 4 + } +} diff --git a/apps/web/data-layer.lock.md b/apps/web/data-layer.lock.md new file mode 100644 index 0000000..5cbd13c --- /dev/null +++ b/apps/web/data-layer.lock.md @@ -0,0 +1,73 @@ +# Data layer lock + +Generated by `pnpm data:lock`. Do not edit by hand. +A diff here is a Saleor access or cache-profile change — review it for cost and freshness. +Rows are keyed by file and enclosing function, not line, so formatting does not move them. + +| Call | Target | Profile | Where | +| ---------------- | --------------------------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------- | +| mutate | checkoutAddPromoCodeDocument | — | src/app/(checkout)/actions.ts › applyCheckoutPromoCode | +| mutate | checkoutCustomerAttachDocument | — | src/app/(checkout)/actions.ts › attachCustomerToCheckout | +| mutate | deliveryOptionsCalculateDocument | — | src/app/(checkout)/actions.ts › calculateDeliveryOptions | +| liveQuery | addressValidationRulesDocument | — | src/app/(checkout)/actions.ts › getAddressValidationRules | +| mutate | transactionInitializeDocument | — | src/app/(checkout)/actions.ts › initializeCheckoutTransaction | +| mutate | paymentGatewaysInitializeDocument | — | src/app/(checkout)/actions.ts › initializePaymentGateways | +| mutate | transactionProcessDocument | — | src/app/(checkout)/actions.ts › processCheckoutTransaction | +| mutate | checkoutCreateDocument | — | src/app/(checkout)/actions.ts › recoverOrphanedCheckout | +| mutate | checkoutLinesAddDocument | — | src/app/(checkout)/actions.ts › recoverOrphanedCheckout | +| rawMutation | — | — | src/app/(checkout)/actions.ts › registerCheckoutAccount | +| mutate | checkoutLineDeleteDocument | — | src/app/(checkout)/actions.ts › removeCheckoutLine | +| mutate | checkoutRemovePromoCodeDocument | — | src/app/(checkout)/actions.ts › removeCheckoutPromoCode | +| rawMutation | — | — | src/app/(checkout)/actions.ts › requestCheckoutPasswordReset | +| mutate | checkoutCompleteDocument | — | src/app/(checkout)/actions.ts › runCheckoutComplete | +| mutate | userSetDefaultAddressDocument | — | src/app/(checkout)/actions.ts › setUserDefaultAddress | +| mutate | checkoutBillingAddressUpdateDocument | — | src/app/(checkout)/actions.ts › updateCheckoutBillingAddress | +| mutate | checkoutDeliveryMethodUpdateDocument | — | src/app/(checkout)/actions.ts › updateCheckoutDeliveryMethod | +| mutate | checkoutEmailUpdateDocument | — | src/app/(checkout)/actions.ts › updateCheckoutEmail | +| mutate | checkoutMetadataUpdateDocument | — | src/app/(checkout)/actions.ts › updateCheckoutMarketingConsent | +| mutate | checkoutShippingAddressUpdateDocument | — | src/app/(checkout)/actions.ts › updateCheckoutShippingAddress | +| mutate | PasswordChangeDocument | — | src/app/(storefront)/[locale]/[channel]/(main)/account/actions.ts › changePassword | +| mutate | AccountAddressCreateDocument | — | src/app/(storefront)/[locale]/[channel]/(main)/account/actions.ts › createAddress | +| mutate | AccountAddressDeleteDocument | — | src/app/(storefront)/[locale]/[channel]/(main)/account/actions.ts › deleteAddress | +| mutate | AccountRequestDeletionDocument | — | src/app/(storefront)/[locale]/[channel]/(main)/account/actions.ts › requestAccountDeletion | +| mutate | AccountSetDefaultAddressDocument | — | src/app/(storefront)/[locale]/[channel]/(main)/account/actions.ts › setDefaultAddress | +| mutate | AccountAddressUpdateDocument | — | src/app/(storefront)/[locale]/[channel]/(main)/account/actions.ts › updateAddress | +| mutate | AccountUpdateDocument | — | src/app/(storefront)/[locale]/[channel]/(main)/account/actions.ts › updateProfile | +| mutate | CheckoutAddLineDocument | — | src/app/actions.ts › addVariantToCart | +| mutate | CheckoutDeleteLinesDocument | — | src/app/actions.ts › deleteCartLine | +| mutate | CheckoutLinesUpdateDocument | — | src/app/actions.ts › updateCartLineQuantity | +| rawMutation | — | — | src/app/api/auth/register/route.ts › POST | +| rawMutation | — | — | src/app/api/auth/reset-password/route.ts › POST | +| mutate | checkoutMetadataUpdateDocument | — | src/checkout/lib/server/enrich-commerce-context.ts › enrichCheckoutCommerceContext | +| liveQuery | checkoutCommerceContextDocument | — | src/checkout/lib/server/enrich-commerce-context.ts › readCheckoutMetadata | +| liveQuery | channelQueryDocument | — | src/checkout/lib/server/fetch-channel-countries.ts › fetchChannelCountriesOnServer | +| rawMutation | — | — | src/checkout/lib/server/fetch-channel-default-country.ts › fetchChannelDefaultCountryOnServer | +| liveQuery | checkoutQueryDocument | — | src/checkout/lib/server/fetch-checkout.ts › fetchCheckoutOnServer | +| liveQuery | ordersByNumberDocument | — | src/checkout/lib/server/fetch-order-by-number.ts › fetchOrderByNumberOnServer | +| liveQuery | orderQueryDocument | — | src/checkout/lib/server/fetch-order.ts › fetchOrderOnServer | +| sessionQuery | CurrentUserOrdersPaginatedDocument | — | src/lib/account/get-orders.ts › getCurrentUserOrders | +| sessionQuery | OrderByNumberDocument | — | src/lib/account/get-orders.ts › getOrdersForNumberLookup | +| rawMutation | — | — | src/lib/auth/confirm-account.ts › confirmAccountWithToken | +| sessionQuery | operation | — | src/lib/auth/fetch-authenticated-user.ts › fetchAuthenticatedUserIfSession | +| cachedQuery | ProductListByCategoryDocument | CACHE_PROFILES.categories | src/lib/catalog/get-category-data.ts › getCategoryData.fetchCategory | +| cachedQuery | ProductListByCollectionDocument | CACHE_PROFILES.collections | src/lib/catalog/get-collection-data.ts › getCollectionData.fetchCollection | +| cachedQuery | ProductListByCollectionDocument | CACHE_PROFILES.collections | src/lib/catalog/get-featured-products.ts › getFeaturedProducts | +| cachedQuery | PageGetBySlugDocument | CACHE_PROFILES.pages | src/lib/catalog/get-page-data.ts › getPageData.fetchPage | +| cachedQuery | ProductVariantsForPdpDocument | CACHE_PROFILES.products | src/lib/catalog/get-product-data.ts › fetchVariantPage | +| cachedQuery | ProductDetailsDocument | CACHE_PROFILES.products | src/lib/catalog/get-product-data.ts › getProductData.fetchProduct | +| cachedQuery | ProductVariantForPdpDocument | CACHE_PROFILES.products | src/lib/catalog/get-product-data.ts › getProductVariantForPdp | +| cachedQuery | CategoriesBySlugDocument | CACHE_PROFILES.categories | src/lib/catalog/resolve-category-slugs.ts › resolveCategorySlugsCached | +| cachedQuery | ChannelsListDocument | CACHE_PROFILES.channels (allows partial data) | src/lib/channels/get-channels-data.ts › readChannelsList | +| mutate | CheckoutCreateDocument | — | src/lib/checkout.ts › create | +| mutate | CheckoutCustomerDetachDocument | — | src/lib/checkout.ts › detachCustomer | +| liveQuery | CheckoutFindDocument | — | src/lib/checkout.ts › find | +| bindCacheProfile | — | — | src/lib/content/get-announcement-bar-props.ts › getAnnouncementBarProps | +| bindCacheProfile | — | — | src/lib/content/get-storefront-content.ts › getStorefrontContent | +| cachedQuery | StorefrontContentPagesDocument | CACHE_PROFILES.storefrontContent | src/lib/content/saleor/saleor-provider.ts › fetchStorefrontPages | +| cachedQuery | ProductListByCategoryProductsDocument | input.profile | src/lib/listing/providers/saleor/index.ts › kernelTransport | +| cachedQuery | ProductListByCollectionProductsDocument | input.profile | src/lib/listing/providers/saleor/index.ts › kernelTransport | +| cachedQuery | ProductListPaginatedDocument | input.profile | src/lib/listing/providers/saleor/index.ts › kernelTransport | +| liveQuery | ProductListByCategoryProductsDocument | — | src/lib/listing/providers/saleor/index.ts › kernelTransport | +| liveQuery | ProductListByCollectionProductsDocument | — | src/lib/listing/providers/saleor/index.ts › kernelTransport | +| liveQuery | ProductListPaginatedDocument | — | src/lib/listing/providers/saleor/index.ts › kernelTransport | +| cachedQuery | MenuGetBySlugDocument | STOREFRONT_MENU_SLUGS[slug] | src/lib/menus/get-menu-data.ts › getCachedMenuItems | diff --git a/apps/web/docs/adr/0001-locale-channel-url-routing.md b/apps/web/docs/adr/0001-locale-channel-url-routing.md new file mode 100644 index 0000000..570826a --- /dev/null +++ b/apps/web/docs/adr/0001-locale-channel-url-routing.md @@ -0,0 +1,118 @@ +# ADR 0001: Locale and channel URL routing + +**Status:** Accepted +**Date:** 2026-06-12 +**Deciders:** Paper storefront team +**Implementation:** Shipped — `src/app/(storefront)/[locale]/[channel]/…`, middleware 308 from legacy `/{channel}/…`, GraphQL `languageCode` on catalog/menus/search/CMS. + +## Context + +Paper storefronts scope commerce by **Saleor channel** (currency, pricing, tax, shipping zones, stock). Language is a separate Saleor concern (`LanguageCodeEnum` translations on products, categories, menus, and Models). + +Today: + +- Browse routes: `/{channel}/…` (e.g. `/uk/products/hoodie`) +- Locale: single global `en-US` in `src/config/locale.ts` +- Channel picker: footer `` (often `SearchBar` in the header): + +```diff +
+- __gcruniqueid="1" + +- __gcruniqueid="2" +``` + +Paper does **not** render these attributes — grep the repo finds nothing. + +### Cause + +**Chrome (and Chromium-based Edge) on iOS** inject `__gcruniqueid` / `__gchrome_uniqueid` on form fields for autofill **after** the server HTML is sent but **before** React hydrates. React then warns because client DOM ≠ server HTML. + +This is a [known Chromium + React limitation](https://github.com/vercel/next.js/issues/77710). Safari on iOS typically does not inject these attributes. + +### What to do + +| Goal | Action | +| ------------------- | ---------------------------------------------------------------------------------------------------------- | +| Confirm it's benign | Reproduce in **Safari** on the same phone — warning usually disappears | +| Ignore in dev | Safe — **no user-visible breakage** in production per Next.js/React guidance | +| Quieter dev console | Avoid Chrome on iOS for day-to-day mobile QA; use Safari | +| Last resort | `suppressHydrationWarning` on affected inputs — silences real mismatches too; not recommended project-wide | + +Do **not** refactor `SearchBar` or disable SSR on the header to silence this. + +--- + +## Debugging checklist (mobile-only issues) + +1. **Console on the phone** — Safari Web Inspector (Mac) or Eruda; look for Next.js "Cross-origin access to Next.js dev resources" first. +2. **`ALLOWED_DEV_ORIGINS`** — tunnel hostname listed? Dev server restarted? +3. **Origin mismatch** — ngrok URL in the address bar must match the hostname in `ALLOWED_DEV_ORIGINS` (subdomain changes when ngrok restarts free tunnels). +4. **Component layer** — only after dev origins are clean; e.g. Embla carousels need `touch-pan-y` on the viewport for real iOS touch (see `src/ui/components/ui/carousel.tsx`). +5. **Hydration on `__gcruniqueid`** — Chrome on iOS autofill injection; not a storefront bug (see above). + +--- + +## Anti-patterns + +❌ **Don't debug carousel swipe on ngrok** before fixing `allowedDevOrigins` — client JS may not load +❌ **Don't commit personal ngrok hostnames** — use `ALLOWED_DEV_ORIGINS` in `.env.local` +❌ **Don't assume Chrome device toolbar = real phone** — it uses localhost + mouse events, not tunnel + touch + +--- + +### 7.2 Saleor API Investigation + +Investigate Saleor API behavior by checking source code when documentation is unclear or you need to understand exact data models. + +## Step 1: Check the Generated Types (Schema) + +The fastest way to confirm any type, field, enum, or input is the generated types file in this repo: + +```bash +# src/gql/graphql.ts — full schema generated from your running Saleor instance +grep -A 20 "^export type Product " src/gql/graphql.ts +grep -A 10 "^export enum StockAvailability" src/gql/graphql.ts +grep -A 30 "^export type ProductFilterInput" src/gql/graphql.ts +``` + +This file contains the **full Saleor schema** as TypeScript types (all types, enums, inputs -- not just the ones used in declared queries). Generated by `pnpm generate` via API introspection, so it always matches your exact Saleor version. + +If the types confirm what you need, stop here. + +## Step 2: Check Saleor Source for Behavior + +Types tell you _what_ fields exist. For _how_ they behave (permission checks, filtering logic, side effects), check the Saleor core source: + +- [Saleor API Reference](https://docs.saleor.io/api-reference) - Online docs +- [Saleor Developer Docs](https://docs.saleor.io/developer) - Guides and concepts + +If the Saleor core repo is available locally (e.g. `../saleor/`), or clone it: + +```bash +cd /tmp && git clone --depth 1 https://github.com/saleor/saleor.git saleor-core +``` + +For directory structure and grep patterns, see [saleor-key-directories.md](../references/saleor-key-directories.md). + +| Path | Purpose | +| -------------------------- | --------------------------- | +| `saleor/graphql/product/` | Resolvers, permission logic | +| `saleor/product/models.py` | Django models | + +## Examples + +### Example: Does `product.attributes` filter by `visibleInStorefront`? + +**Investigation** in `saleor/graphql/product/resolvers.py`: + +```python +def resolve_product_attributes(root, info, *, limit): + if requestor_has_access_to_all_attributes(info.context): + dataloader = AttributesByProductIdAndLimitLoader # Admin: ALL + else: + dataloader = AttributesVisibleToCustomerByProductIdAndLimitLoader # Customer: FILTERED +``` + +**Conclusion**: Yes, storefront users only see `visibleInStorefront=True` attributes. No client-side filtering needed. + +### Example: Token-Based Data Filtering + +Saleor filters data based on authentication: + +| Token | `product.attributes` returns | +| -------------------------- | ------------------------------- | +| None (anonymous) | Only `visibleInStorefront=True` | +| Customer JWT | Only `visibleInStorefront=True` | +| App with `MANAGE_PRODUCTS` | ALL attributes | + +This applies to many "visible in storefront" flags across Saleor. + +## Key Insights + +### Storefront Auto-Filtering + +When building storefront features, you typically don't need to: + +- Fetch `visibleInStorefront` field +- Filter data client-side + +The API already returns only what's meant to be shown based on your token. + +### Product Types Control Variant Attributes + +Which attributes appear on variants is configured at the **ProductType** level: + +Dashboard → Configuration → Product Types → [Type] → Variant Attributes + +If an attribute doesn't appear in `variant.attributes`, check the ProductType configuration. + +## Anti-patterns + +❌ **Don't guess API behavior** - Check the source +❌ **Don't filter `visibleInStorefront` client-side** - API does it +❌ **Don't assume attribute presence** - Check ProductType config + +--- + +### 7.3 Third-Party Widget Embeds + +How to add external marketing widgets (reviews, ratings, social proof loaders) without breaking Paper's Server Component / PPR architecture or performance budget. + +> Read together with [`page-composition`](page-composition.md) (where embeds live on PDP), [`product-pdp`](product-pdp.md) (shell vs islands), [`design-verification`](design-verification.md) (gates). + +--- + +## When to use + +- Reviews/ratings providers (Yotpo, Judge.me, etc.) +- Social proof or UGC widgets loaded from a vendor script +- Any `next/script` third-party loader on browse surfaces + +For **static** social proof without a live vendor API, prefer [`ui-sections`](ui-sections.md) (`TestimonialSection`) with content-layer copy. + +--- + +## Architecture + +``` +ProductShell (Server — cached, no scripts) +├── static sections (h1, breadcrumbs, …) +├── YotpoStarSummary (client leaf — optional, near title) +└── … +└── Suspense islands (gallery, buy box) + +Below buy box / accordion (still in shell, static placement): +└── YotpoReviewsWidget (client leaf — loads script + widget div) +``` + +| Layer | Rule | +| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| **Script loader** | `"use client"` leaf component only — never in `ProductShell` as inline `` / U+2028 / U+2029 for inline scripts): +{jsonLd && ` +> breaks out of the script tag (CodeQL "improper code sanitization"). Use `jsonLdScriptProps`, +> or `serializeForInlineScript` from `@/lib/html/inline-script` for other inline scripts. + +## Dynamic OG Images + +The `/api/og` route generates branded images: + +``` +/api/og?title=Product%20Name&price=€29.99 +``` + +Use in metadata: + +```typescript +buildPageMetadata({ + title: product.name, + image: `/api/og?title=${encodeURIComponent(product.name)}`, +}); +``` + +## Examples + +### Complete Product Page SEO + +Use `buildBrowsePageMetadata` + `resolveSeoDescription` + JSON-LD (see International URLs and Product JSON-LD above). The live PDP is `src/app/(storefront)/[locale]/[channel]/(main)/products/[slug]/page.tsx` — `ProductShell` hoists `og:type=product` after the product resolves; `generateMetadata` sets `ogType: "product"` so Next never receives an invalid `openGraph.type`. + +## International URLs + +Browse canonical URLs include locale and channel: `/{locale}/{channel}/…` (see `docs/adr/0001-locale-channel-url-routing.md`, `ui-locale-routing.md`). + +- Use `buildBrowsePageMetadata()` for catalog/CMS pages — sets canonical + `hreflang` alternates, plus `og:locale` (from the URL locale's `ogLocale`) and `og:locale:alternate` for other **reachable** locales (matrix locales when `LOCALE_CHANNELS` is set; otherwise all `STOREFRONT_LOCALES`). +- Non-browse pages inherit `og:locale` from the storefront locale layout's `generateMetadata` — never hardcode a locale in OG tags. +- Meta/OG/JSON-LD descriptions: use `resolveSeoDescription()` — `seoDescription` → translated Editor.js plain text → name. Don't let them collapse to the bare entity name. +- **PDP `og:type=product`:** Next's metadata API **rejects** OG types outside its union at runtime (**E237** — throws and drops the page's whole metadata). `ogType: "product"` therefore omits `openGraph.type`, and `ProductShell` hoists `` **only after the product resolves** (never on the missing-slug `notFound()` path — a sync-shell tag would advertise `product` on 404s). Trade-off: the tag sits behind the page `Suspense` boundary; bot UAs that wait on `generateMetadata` still get the rest of OG, and cached shells resolve quickly. Do **not** use `metadata.other: { "og:type": "product" }` — Next renders that as `name=`, not `property=`. +- `generateMetadata` `pathSuffix` is the path after locale/channel for **this** locale, e.g. `/products/${pickTranslatedSlug(product)}`. +- For translated catalog slugs (ADR 0004), also pass `pathSuffixByLocale` from `buildCatalogPathSuffixByLocale` / `buildLocaleSlugMap` so each `hreflang` points at that language’s handle. +- `` is rendered server-side by the storefront root layout (`(storefront)/[locale]/layout.tsx`), derived from the URL locale segment (`htmlLang`, language-only) — no client patching. + +```typescript +import { buildBrowsePageMetadata, resolveSeoDescription } from "@/lib/seo"; +import { buildCatalogPathSuffixByLocale, buildLocaleSlugMap } from "@/lib/catalog/locale-slugs"; +import { catalogPathSuffix } from "@/lib/catalog/canonical-slug"; + +return buildBrowsePageMetadata({ + title: category.name, + description: resolveSeoDescription({ + seoDescription: category.seoDescription, + body: category.description, + fallbackName: category.name, + }), + locale: params.locale, + channel: params.channel, + pathSuffix: catalogPathSuffix("categories", category), + pathSuffixByLocale: buildCatalogPathSuffixByLocale("categories", buildLocaleSlugMap(category)), +}); +``` + +### hreflang keys and `x-default` + +`buildLocaleHreflangAlternates()` (used by `buildBrowsePageMetadata`): + +| Config | hreflang keys | URLs | +| ------------------------------------------- | -------------------------------------------- | ------------------------------------------------ | +| No `NEXT_PUBLIC_STOREFRONT_LOCALE_CHANNELS` | Language-only (`ja`, `en`) from `htmlLang` | Each locale keeps the **current** page’s channel | +| Pairs set (`ja:japan,en:default,…`) | Region-aware (`ja-JP`, `en-US`) from `bcp47` | Each locale uses its **paired** channel | + +**`x-default`** points at `NEXT_PUBLIC_DEFAULT_LOCALE` + that locale’s paired/default channel — same knob as the root redirect and invalid-locale fallback. Paper intentionally does **not** add a separate `x-default` env; change the demo/default locale if the fallback URL is wrong. + +### Locale×channel pairs (SEO + navigation) + +Optional `NEXT_PUBLIC_STOREFRONT_LOCALE_CHANNELS=en:uk,pl:pl` (see `src/config/locale-channel.ts`): + +1. Invalid pairs → `notFound()` +2. Language switch navigates to the paired channel (Japanese → `japan`, etc.) +3. Region picker filters languages per market +4. hreflang becomes region-aware (table above) + +When unset, any allowlisted locale × channel is valid and language switch **keeps** the current channel. + +## Known Next.js / audit findings + +- **Streaming metadata “duplicates”:** For normal browser UAs, Next may stream metadata into `` then also place copies in `` after hydration — DevTools can show 2× canonical / 18× hreflang. Bot UAs get blocking `` metadata (`htmlLimitedBots`). Not a Paper double-`generateMetadata` bug; soft locale/market navigations can make leftovers more visible. Prefer curl/bot UA or settled head counts when auditing. +- **E237 `Invalid OpenGraph type: product`:** Closed OG type union in Next’s Metadata API; unknown types throw and abort the metadata RSC payload. Workaround: omit `openGraph.type` + hoist `` in `ProductShell` only after the product resolves (never on 404). + +## Sitemap & robots (do not ship naive) + +Paper ships `src/app/robots.ts` (faceted/sorted/search listing queries + cart/checkout/account/search). It still has **no** `sitemap.ts` (middleware already reserves `sitemap.xml`). On-page canonical + hreflang cover most crawl signals; a wrong sitemap is worse than none. + +**Why a single `sitemap.ts` dump fails at scale** + +- URL cardinality ≈ products × locales × channels (plus categories / collections / pages). 10k SKUs × 8 locales × 5 channels ≈ 400k product URLs alone. +- Protocol / Google limits: **≤50k URLs and ≤50MB per sitemap file**. +- Live Saleor GraphQL walks of the full catalog risk timeouts, serverless memory, and slow TTFB. +- Translated slugs (ADR 0004) mean each locale may need its own handle — you cannot stamp one primary-slug list across languages. + +**Required shape when implementing** + +1. **Sitemap index + chunks** via Next [`generateSitemaps`](https://nextjs.org/docs/app/api-reference/functions/generate-sitemaps) (`/sitemap.xml` → `/sitemap/0.xml`, …), ~≤40–50k URLs each. +2. **Paginate Saleor with cursors** (`first` / `after`) per chunk — never load the full catalog into memory. +3. **Chunk by stable dimensions** (e.g. `{channel}:{locale}:{entity}:{page}` or at least `{channel}:{page}`), not one global product offset. +4. **Respect `LOCALE_CHANNELS`:** when set, emit only paired locale×channel URLs (same set as hreflang). When unset, avoid a blind full cross-product — prefer channel-scoped chunks; on-page hreflang already advertises language alternates. +5. **Cache aggressively** (long CDN/`Cache-Control`); invalidate via existing PRODUCT\_\* / catalog webhook tags. Mega catalogs may need a background export / blob rather than GraphQL-at-request. +6. Ship **`robots.ts` first** (disallow `noIndexPaths`, eventually `Sitemap:` → index URL), then chunked sitemaps. + +| Catalog size | Approach | +| ------------------------- | ------------------------------------------------------------------- | +| Demo / ≲5k SKUs × few L×C | Few chunks; on-demand GraphQL OK | +| Mid (tens of k) | `generateSitemaps` + cursor pagination per channel | +| Huge (100k+) | Precompute / background pipeline; storefront serves cached XML only | + +## Disabling SEO + +To remove SEO features entirely: + +1. Delete `src/lib/seo/` folder +2. Remove `rootMetadata` / locale `generateMetadata` from layouts +3. Remove `buildPageMetadata`/`buildProductJsonLd` from pages +4. Delete `src/app/api/og/` + +## Anti-patterns + +❌ **Don't hardcode metadata** — Use the helpers +❌ **Don't skip JSON-LD on product pages** — Important for search +❌ **Don't forget `noIndexPaths`** — Exclude checkout, cart +❌ **Don't set `openGraph.type: "product"`** — Triggers Next E237 and drops all page metadata +❌ **Don't hoist PDP `og:type` on the sync shell before the product resolves** — 404 URLs would advertise `product` +❌ **Don't hardcode `og:locale` to `en_US`** — Derive from the URL locale +❌ **Don't list unpaired locales in `og:locale:alternate`** — When `LOCALE_CHANNELS` is set, alternate locales must match the matrix (same as hreflang) +❌ **Don't treat DevTools double tags as a Paper SEO bug** — Check streaming metadata / bot UA first +❌ **Don't add a monolithic `sitemap.ts` that loads every product×locale×channel** — Use index + chunks; see Sitemap & robots above diff --git a/apps/web/skills/saleor-paper-storefront/rules/third-party-embeds.md b/apps/web/skills/saleor-paper-storefront/rules/third-party-embeds.md new file mode 100644 index 0000000..304daef --- /dev/null +++ b/apps/web/skills/saleor-paper-storefront/rules/third-party-embeds.md @@ -0,0 +1,101 @@ +--- +name: third-party-embeds +description: Embedding external marketing widgets (reviews/ratings) without breaking Server Components/PPR: next/script in a client leaf, env keys, placement. Use when adding a vendor widget like Yotpo. +--- + +# Third-Party Widget Embeds + +How to add external marketing widgets (reviews, ratings, social proof loaders) without breaking Paper's Server Component / PPR architecture or performance budget. + +> Read together with [`page-composition`](page-composition.md) (where embeds live on PDP), [`product-pdp`](product-pdp.md) (shell vs islands), [`design-verification`](design-verification.md) (gates). + +--- + +## When to use + +- Reviews/ratings providers (Yotpo, Judge.me, etc.) +- Social proof or UGC widgets loaded from a vendor script +- Any `next/script` third-party loader on browse surfaces + +For **static** social proof without a live vendor API, prefer [`ui-sections`](ui-sections.md) (`TestimonialSection`) with content-layer copy. + +--- + +## Architecture + +``` +ProductShell (Server — cached, no scripts) +├── static sections (h1, breadcrumbs, …) +├── YotpoStarSummary (client leaf — optional, near title) +└── … +└── Suspense islands (gallery, buy box) + +Below buy box / accordion (still in shell, static placement): +└── YotpoReviewsWidget (client leaf — loads script + widget div) +``` + +| Layer | Rule | +| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| **Script loader** | `"use client"` leaf component only — never in `ProductShell` as inline ` breakout attempt", () => { + const result = serializeForInlineScript(""); + expect(result).not.toContain(""); + expect(result).not.toContain("<"); + expect(result).not.toContain("/"); + expect(JSON.parse(result)).toBe(""); + }); + + it("escapes U+2028 and U+2029 line separators", () => { + const result = serializeForInlineScript("line\u2028and\u2029more"); + expect(result).not.toContain("\u2028"); + expect(result).not.toContain("\u2029"); + expect(JSON.parse(result)).toBe("line\u2028and\u2029more"); + }); + + it("escapes unsafe characters nested in objects", () => { + const result = serializeForInlineScript({ name: "" }); + expect(result).not.toContain(""); + expect(JSON.parse(result)).toEqual({ name: "" }); + }); +}); diff --git a/apps/web/src/lib/html/inline-script.ts b/apps/web/src/lib/html/inline-script.ts new file mode 100644 index 0000000..6abdf0e --- /dev/null +++ b/apps/web/src/lib/html/inline-script.ts @@ -0,0 +1,24 @@ +const INLINE_SCRIPT_UNSAFE_CHARS: Record = { + "<": "\\u003C", + ">": "\\u003E", + "/": "\\u002F", + "\u2028": "\\u2028", + "\u2029": "\\u2029", +}; + +/** + * Serialize a value to JSON for safe embedding inside an inline HTML `` would + * terminate the script element early, and `U+2028`/`U+2029` are valid JSON yet invalid in + * a JS string literal in older engines — both are code-injection / breakage vectors when + * the value originates from CMS content. Escaping them as `\uXXXX` keeps the JSON valid + * while preventing breakout. + */ +export function serializeForInlineScript(value: unknown): string { + return JSON.stringify(value).replace( + /[<>/\u2028\u2029]/g, + (char) => INLINE_SCRIPT_UNSAFE_CHARS[char] ?? char, + ); +} diff --git a/apps/web/src/lib/images.test.ts b/apps/web/src/lib/images.test.ts new file mode 100644 index 0000000..bbdff25 --- /dev/null +++ b/apps/web/src/lib/images.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import { buildSaleorSrcSet, CATALOG_CARD_RUNGS, PDP_GALLERY_RUNGS, SALEOR_THUMBNAIL_RUNGS } from "./images"; + +describe("buildSaleorSrcSet", () => { + it("emits one width descriptor per usable rung", () => { + expect( + buildSaleorSrcSet([ + { width: 256, url: "https://cdn.test/a_256.webp" }, + { width: 512, url: "https://cdn.test/a_512.webp" }, + { width: 1024, url: "https://cdn.test/a_1024.webp" }, + ]), + ).toBe( + "https://cdn.test/a_256.webp 256w, https://cdn.test/a_512.webp 512w, https://cdn.test/a_1024.webp 1024w", + ); + }); + + it("drops rungs Saleor did not return", () => { + expect( + buildSaleorSrcSet([ + { width: 256, url: null }, + { width: 512, url: "https://cdn.test/a_512.webp" }, + { width: 1024, url: undefined }, + { width: 2048, url: "https://cdn.test/a_2048.webp" }, + ]), + ).toBe("https://cdn.test/a_512.webp 512w, https://cdn.test/a_2048.webp 2048w"); + }); + + // A one-candidate srcset tells the browser nothing `src` doesn't, and the + // undefined is what makes SaleorImage fall back to next/image. + it("returns undefined when fewer than two rungs are usable", () => { + expect(buildSaleorSrcSet([{ width: 512, url: "https://cdn.test/a_512.webp" }])).toBeUndefined(); + expect(buildSaleorSrcSet([{ width: 512, url: null }])).toBeUndefined(); + expect(buildSaleorSrcSet([])).toBeUndefined(); + }); + + // Saleor returns the same storage URL for two sizes when both snap to one rung; + // repeating a descriptor would make the browser's selection non-deterministic. + it("keeps the first URL when a width repeats", () => { + expect( + buildSaleorSrcSet([ + { width: 512, url: "https://cdn.test/a_512.webp" }, + { width: 512, url: "https://cdn.test/duplicate.webp" }, + { width: 1024, url: "https://cdn.test/a_1024.webp" }, + ]), + ).toBe("https://cdn.test/a_512.webp 512w, https://cdn.test/a_1024.webp 1024w"); + }); +}); + +describe("rung sets", () => { + // Off-ladder sizes snap to a ladder rung, so the width descriptor we publish + // would not match the pixels Saleor actually returns. + it("only request sizes that exist on Saleor's ladder", () => { + for (const rung of [...CATALOG_CARD_RUNGS, ...PDP_GALLERY_RUNGS]) { + expect(SALEOR_THUMBNAIL_RUNGS).toContain(rung); + } + }); + + it("lists rungs in ascending order so srcset descriptors are monotonic", () => { + for (const rungs of [CATALOG_CARD_RUNGS, PDP_GALLERY_RUNGS]) { + expect([...rungs]).toEqual([...rungs].sort((a, b) => a - b)); + } + }); +}); diff --git a/apps/web/src/lib/images.ts b/apps/web/src/lib/images.ts new file mode 100644 index 0000000..471a6ac --- /dev/null +++ b/apps/web/src/lib/images.ts @@ -0,0 +1,143 @@ +/** + * Shared Next.js Image props for catalog surfaces. + * Keeps `sizes` aligned with layout breakpoints so the optimizer requests appropriately sized variants. + */ + +/** + * Homepage featured collection grid: 2 col → 4 col (lg). + * Pair with ProductGrid desktopColumns={4}. + */ +export const FEATURED_COLLECTION_IMAGE_SIZES = + "(max-width: 1024px) calc((100vw - 3rem) / 2), calc((min(100vw, 80rem) - 4rem - 4.5rem) / 4)"; + +/** + * PLP / collection / category grid: 2 col → 3 col (lg). + * Accounts for px-4/px-8 padding and gap-4/gap-6 between cards. + */ +export const PLP_IMAGE_SIZES = + "(max-width: 1024px) calc((100vw - 3rem) / 2), calc((min(100vw, 80rem) - 4rem - 3rem) / 3)"; + +/** + * Full-bleed hero background. `100vw` is honest here — the image really does span the + * viewport — and `deviceSizes` in next.config.js caps the widest variant at 1920. + * Only use this on edge-to-edge surfaces; a half-width panel wants + * {@link SPLIT_PANEL_IMAGE_SIZES} instead, or it requests double the pixels it shows. + */ +export const PLP_HERO_IMAGE_SIZES = "100vw"; + +/** Two-column section where the image occupies one column on desktop (lg:grid-cols-2) */ +export const SPLIT_PANEL_IMAGE_SIZES = "(max-width: 1024px) 100vw, 50vw"; + +/** PDP main gallery: full width on mobile, half viewport on desktop split layout */ +export const PDP_MAIN_IMAGE_SIZES = "(max-width: 768px) 100vw, 50vw"; + +/** + * PDP immersive gallery: full-width square on mobile, height-driven square that + * fills the viewport (≈ 60% width) on desktop. Width follows the fixed height, + * so request a generously sized variant on large screens. + */ +export const PDP_IMMERSIVE_IMAGE_SIZES = "(max-width: 1024px) 100vw, 60vw"; + +/** + * PDP mosaic gallery: all images tiled in a 2-column grid. + * Each tile is ~half the gallery column — half viewport on mobile, ~30vw on the + * wide editorial column on desktop. + */ +export const PDP_MOSAIC_IMAGE_SIZES = "(max-width: 1024px) 50vw, 30vw"; + +/** PDP desktop thumbnail strip */ +export const PDP_THUMBNAIL_IMAGE_SIZES = "80px"; + +/** Cart drawer line item — fixed 80px slot (h-24 w-20) */ +export const CART_THUMBNAIL_IMAGE_SIZES = "80px"; + +/** LCP candidate on Home, PLP, and PDP — only one high-priority image per viewport */ +export const LCP_IMAGE_PRIORITY_COUNT = 1; + +/** Match Next.js default — higher values slow cold /_next/image encoding on Vercel */ +export const PRODUCT_IMAGE_QUALITY = 75; + +/* -------------------------------------------------------------------------- */ +/* Saleor-native responsive images */ +/* -------------------------------------------------------------------------- */ + +/** + * Saleor's fixed thumbnail ladder (`saleor/thumbnail/__init__.py`). Every selection + * passes `sizeRounding: UP`, so an off-ladder size snaps to the next rung up — asking + * for 300 returns 512. Only ever request values from this list, or the width you get + * back is not the width you put in the `srcset` descriptor. + */ +export const SALEOR_THUMBNAIL_RUNGS = [32, 64, 128, 256, 512, 1024, 2048, 4096] as const; + +/** + * Rungs requested for PLP/collection/category cards. Covers a 2-up mobile grid at 2x + * (~340px) through a 3-up desktop grid at 2x (~780px). + */ +export const CATALOG_CARD_RUNGS = [256, 512, 1024] as const; + +/** Rungs requested for the PDP gallery, which runs up to full-bleed on desktop. */ +export const PDP_GALLERY_RUNGS = [512, 1024, 2048] as const; + +/** + * Which pipeline serves catalog images. + * + * - `saleor` — plain `` pointing at Saleor's CDN-backed thumbnails. + * Saleor has already produced a correctly-sized WebP, so this skips `/_next/image` + * entirely and the transformation is never billed. + * - `vercel` — route everything through `next/image`. The escape hatch: set + * `NEXT_PUBLIC_PAPER_IMAGE_PIPELINE=vercel` to revert without a code change. + * + * Surfaces without a Saleor rung set (local assets, CMS uploads) always use + * `next/image` regardless of this setting. + */ +export const PAPER_IMAGE_PIPELINE: "saleor" | "vercel" = + process.env.NEXT_PUBLIC_PAPER_IMAGE_PIPELINE === "vercel" ? "vercel" : "saleor"; + +/** + * Origin to `preconnect` when the Saleor pipeline is active. + * + * Under `next/image` every image is same-origin (`/_next/image?url=…`) and rides the + * connection the document already opened. Pointing `` straight at Saleor makes the + * LCP image cross-origin, so without this hint the browser pays DNS + TCP + TLS before + * requesting its first byte. + * + * Returns `null` when the pipeline is `vercel` (the hint would open a socket nothing + * uses) or when the API URL is unset or unparseable. Assumes media is served from the + * API origin, which holds for Saleor Cloud and typical self-hosted deploys; a separate + * media domain needs its own hint. + */ +export function saleorMediaPreconnectOrigin(): string | null { + if (PAPER_IMAGE_PIPELINE !== "saleor") return null; + + try { + return new URL(process.env.NEXT_PUBLIC_SALEOR_API_URL ?? "").origin; + } catch { + return null; + } +} + +export interface SaleorSrcSetEntry { + /** Must be a value from {@link SALEOR_THUMBNAIL_RUNGS} that was actually requested. */ + width: number; + url: string | null | undefined; +} + +/** + * Builds a `srcset` from aliased Saleor thumbnail fields. + * + * Returns `undefined` for fewer than two usable rungs: a single-candidate `srcset` + * tells the browser nothing that `src` doesn't, and the caller uses that signal to + * fall back to `next/image`. + */ +export function buildSaleorSrcSet(entries: readonly SaleorSrcSetEntry[]): string | undefined { + const seen = new Set(); + const candidates: string[] = []; + + for (const { width, url } of entries) { + if (!url || seen.has(width)) continue; + seen.add(width); + candidates.push(`${url} ${width}w`); + } + + return candidates.length > 1 ? candidates.join(", ") : undefined; +} diff --git a/apps/web/src/lib/listing/__contracts__/allowlist.contract.test.ts b/apps/web/src/lib/listing/__contracts__/allowlist.contract.test.ts new file mode 100644 index 0000000..ef7ae2e --- /dev/null +++ b/apps/web/src/lib/listing/__contracts__/allowlist.contract.test.ts @@ -0,0 +1,37 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +const source = readFileSync(join(import.meta.dirname, "../../../../eslint/paper-data-layer.mjs"), "utf8"); + +function allowlist(name: string): string[] { + const match = source.match(new RegExp(`const ${name} = new Set\\(\\[([\\s\\S]*?)\\]\\);`)); + if (!match?.[1]) throw new Error(`missing ${name}`); + return [...match[1].matchAll(/"([^"]+)"/g)].map((entry) => entry[1]!); +} + +/** + * These lists may shrink. Adding a path is a new hole in the view-model boundary. + */ +describe("data-layer allowlists", () => { + it("does not grow GQL_UI_ALLOW", () => { + expect(allowlist("GQL_UI_ALLOW")).toEqual([ + "src/ui/components/account/address-card.tsx", + "src/ui/components/account/address-form-dialog.tsx", + "src/ui/components/account/order-row.tsx", + "src/ui/components/account/order-row-labels.ts", + "src/ui/components/account/order-status-badge.tsx", + "src/ui/components/account/order-status-config.ts", + "src/ui/components/account/order-timeline.tsx", + "src/ui/components/nav/components/user-menu/components/user-avatar.tsx", + "src/ui/components/nav/components/user-menu/components/user-info.tsx", + "src/ui/components/nav/components/user-menu/user-menu.tsx", + "src/ui/components/order-list-item.tsx", + "src/ui/components/payment-status.tsx", + ]); + }); + + it("does not grow LIB_UI_ALLOW", () => { + expect(allowlist("LIB_UI_ALLOW")).toEqual(["src/lib/cart-checkout.ts"]); + }); +}); diff --git a/apps/web/src/lib/listing/__contracts__/invalidate.contract.test.ts b/apps/web/src/lib/listing/__contracts__/invalidate.contract.test.ts new file mode 100644 index 0000000..865785e --- /dev/null +++ b/apps/web/src/lib/listing/__contracts__/invalidate.contract.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vitest"; +import { listingTagsForDelivery, planListingTags } from "@/lib/listing/invalidate"; +import { resolveWebhookEventScope } from "@/lib/saleor"; + +describe("listing invalidation", () => { + it("busts the product's category and named collections, plus the all-products grid", () => { + const tags = planListingTags("product", { categorySlug: "shoes", collectionSlugs: ["summer"] }, "us").map( + (entry) => entry.tag, + ); + expect(tags).toContain("listing:all:us"); + expect(tags).toContain("listing:category:us:shoes"); + expect(tags).toContain("listing:collection:us:summer"); + expect(tags).not.toContain("listing:collection-any:us"); + }); + + it("uses the collection catch-all when the payload does not name collections", () => { + const tags = planListingTags("product", { categorySlug: "shoes" }, "us").map((entry) => entry.tag); + expect(tags).toContain("listing:collection-any:us"); + }); + + it("skips listing:all when the env flag is off", () => { + const previous = process.env.PAPER_BUST_LISTING_ALL_ON_PRODUCT_EVENT; + process.env.PAPER_BUST_LISTING_ALL_ON_PRODUCT_EVENT = "0"; + try { + const tags = planListingTags("product", { categorySlug: "shoes", collectionSlugs: [] }, "us").map( + (entry) => entry.tag, + ); + expect(tags).not.toContain("listing:all:us"); + expect(tags).toContain("listing:category:us:shoes"); + } finally { + if (previous === undefined) delete process.env.PAPER_BUST_LISTING_ALL_ON_PRODUCT_EVENT; + else process.env.PAPER_BUST_LISTING_ALL_ON_PRODUCT_EVENT = previous; + } + }); + + it("does not bust listings for stock or metadata, and does for product updates", () => { + const stock = resolveWebhookEventScope("product_variant_stock_updated"); + const updated = resolveWebhookEventScope("product_updated"); + expect(stock?.affectsListing).toBe(false); + expect(updated?.affectsListing).toBe(true); + expect(listingTagsForDelivery(stock, "product", { categorySlug: "shoes" }, "us")).toEqual([]); + expect( + listingTagsForDelivery(updated, "product", { categorySlug: "shoes" }, "us").length, + ).toBeGreaterThan(0); + expect( + listingTagsForDelivery(null, "category", { slug: "shoes" }, "us").map((entry) => entry.tag), + ).toEqual(["listing:category:us:shoes"]); + }); +}); diff --git a/apps/web/src/lib/listing/__contracts__/policy.contract.test.ts b/apps/web/src/lib/listing/__contracts__/policy.contract.test.ts new file mode 100644 index 0000000..21f2437 --- /dev/null +++ b/apps/web/src/lib/listing/__contracts__/policy.contract.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it } from "vitest"; +import { fixtureListingProvider } from "@/lib/listing/providers/fixture"; +import { saleorListingProvider } from "@/lib/listing/providers/saleor"; +import { listingFetchMode } from "@/lib/listing/policy"; +import { assertProviderSupportsSurface, normalizeListingQuery } from "@/lib/listing/provider"; +import { listingProviderFor, resolveListingProviderId } from "@/lib/listing/registry"; +import type { ListingQuery } from "@/lib/storefront/contract/listing"; + +function query(overrides: Partial = {}): ListingQuery { + return { + surface: { kind: "category", slug: "hoodies" }, + channel: "default-channel", + locale: "en", + selections: {}, + page: { mode: "cursor", direction: "next" }, + pageSize: 12, + ...overrides, + }; +} + +describe("listing cache policy", () => { + it("keeps search and filtered queries live", () => { + expect(listingFetchMode(query(), saleorListingProvider)).toBe("cached-saleor"); + expect(listingFetchMode(query({ sort: "newest" }), saleorListingProvider)).toBe("cached-saleor"); + expect(listingFetchMode(query({ selections: { colors: ["blue"] } }), saleorListingProvider)).toBe("live"); + expect( + listingFetchMode( + query({ page: { mode: "cursor", direction: "next", cursor: "abc" } }), + saleorListingProvider, + ), + ).toBe("live"); + expect( + listingFetchMode(query({ surface: { kind: "search", text: "hoodie" } }), saleorListingProvider), + ).toBe("live"); + expect(listingFetchMode(query(), fixtureListingProvider)).toBe("cached-ttl"); + expect(listingFetchMode(query({ selections: { sizes: ["m"] } }), fixtureListingProvider)).toBe("live"); + }); +}); + +describe("listing query normalization", () => { + it("drops a sort the provider does not declare for the surface", () => { + expect(normalizeListingQuery(saleorListingProvider, query({ sort: "name" })).sort).toBeUndefined(); + expect(normalizeListingQuery(saleorListingProvider, query({ sort: "newest" })).sort).toBe("newest"); + const search = query({ surface: { kind: "search", text: "tee" }, sort: "bestselling" }); + expect(normalizeListingQuery(saleorListingProvider, search).sort).toBeUndefined(); + }); + + it("serves the first page when the page is in the other pagination mode", () => { + const deep = query({ page: { mode: "offset", number: 2 } }); + expect(normalizeListingQuery(saleorListingProvider, deep).page).toEqual({ + mode: "cursor", + direction: "next", + }); + + const cursor = query({ page: { mode: "cursor", direction: "next", cursor: "abc" } }); + expect(normalizeListingQuery(fixtureListingProvider, cursor).page).toEqual({ mode: "offset", number: 1 }); + expect(normalizeListingQuery(fixtureListingProvider, query()).page).toEqual({ + mode: "offset", + number: 1, + }); + }); + + it("keeps a cacheable first page cacheable after normalization", () => { + const shared = query({ sort: "name", page: { mode: "offset", number: 3 } }); + expect( + listingFetchMode(normalizeListingQuery(saleorListingProvider, shared), saleorListingProvider), + ).toBe("cached-saleor"); + }); +}); + +describe("listing provider routing", () => { + it("lets one surface use a different provider", () => { + const previous = process.env.LISTING_PROVIDER_SEARCH; + process.env.LISTING_PROVIDER_SEARCH = "fixture"; + try { + expect(listingProviderFor("search").id).toBe("fixture"); + expect(listingProviderFor("category").id).toBe("saleor"); + } finally { + if (previous === undefined) delete process.env.LISTING_PROVIDER_SEARCH; + else process.env.LISTING_PROVIDER_SEARCH = previous; + } + }); + + it("ignores env overrides on Vercel production", () => { + const previous = { search: process.env.LISTING_PROVIDER_SEARCH, env: process.env.VERCEL_ENV }; + process.env.LISTING_PROVIDER_SEARCH = "fixture"; + process.env.VERCEL_ENV = "production"; + try { + expect(resolveListingProviderId("search")).toBe("saleor"); + process.env.VERCEL_ENV = "preview"; + expect(resolveListingProviderId("search")).toBe("fixture"); + } finally { + if (previous.search === undefined) delete process.env.LISTING_PROVIDER_SEARCH; + else process.env.LISTING_PROVIDER_SEARCH = previous.search; + if (previous.env === undefined) delete process.env.VERCEL_ENV; + else process.env.VERCEL_ENV = previous.env; + } + }); + + it("falls back when the env override is unknown", () => { + const previous = process.env.LISTING_PROVIDER_CATEGORY; + process.env.LISTING_PROVIDER_CATEGORY = "nope"; + try { + expect(resolveListingProviderId("category")).toBe("saleor"); + } finally { + if (previous === undefined) delete process.env.LISTING_PROVIDER_CATEGORY; + else process.env.LISTING_PROVIDER_CATEGORY = previous; + } + }); + + it("throws when a provider is assigned a surface it does not serve", () => { + expect(() => + assertProviderSupportsSurface( + { + ...fixtureListingProvider, + capabilities: { ...fixtureListingProvider.capabilities, surfaces: ["search"] }, + }, + "category", + ), + ).toThrow(/does not serve/); + }); +}); diff --git a/apps/web/src/lib/listing/__contracts__/provider.contract.test.ts b/apps/web/src/lib/listing/__contracts__/provider.contract.test.ts new file mode 100644 index 0000000..0b96134 --- /dev/null +++ b/apps/web/src/lib/listing/__contracts__/provider.contract.test.ts @@ -0,0 +1,25 @@ +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { LISTING_PROVIDER_REGISTRY } from "@/config/listing-providers"; + +const ROOT = join(import.meta.dirname, "../../../.."); + +describe("listing provider contract coverage", () => { + it("gives every registered provider a contract test", () => { + for (const id of Object.keys(LISTING_PROVIDER_REGISTRY)) { + const file = join(ROOT, "src/lib/listing/providers", id, "contract.test.ts"); + expect( + existsSync(file), + `add src/lib/listing/providers/${id}/contract.test.ts (pnpm paper:new provider listing ${id})`, + ).toBe(true); + expect(readFileSync(file, "utf8"), `${id} contract test`).toContain("runListingProviderContract"); + } + }); + + it("registers each provider under its own id", () => { + for (const [id, provider] of Object.entries(LISTING_PROVIDER_REGISTRY)) { + expect(provider.id, `LISTING_PROVIDER_REGISTRY.${id}`).toBe(id); + } + }); +}); diff --git a/apps/web/src/lib/listing/cacheability.ts b/apps/web/src/lib/listing/cacheability.ts new file mode 100644 index 0000000..6345c21 --- /dev/null +++ b/apps/web/src/lib/listing/cacheability.ts @@ -0,0 +1,15 @@ +import type { ListingQuery } from "@/lib/storefront/contract/listing"; + +/** + * True when a listing is safe to cache. + * Filters, cursors, offset pages, and search are the long tail and stay live. + * Sort-only is cacheable: it is part of the cache key, not a new filter space. + */ +export function isCacheableListingQuery(query: ListingQuery): boolean { + if (query.surface.kind === "search") return false; + if (query.page.mode === "offset" && query.page.number > 1) return false; + if (query.page.mode === "cursor" && (query.page.cursor || query.page.direction === "prev")) return false; + if (Object.values(query.selections).some((values) => values.length > 0)) return false; + if (query.range && Object.keys(query.range).length > 0) return false; + return true; +} diff --git a/apps/web/src/lib/listing/invalidate.ts b/apps/web/src/lib/listing/invalidate.ts new file mode 100644 index 0000000..22cd3d6 --- /dev/null +++ b/apps/web/src/lib/listing/invalidate.ts @@ -0,0 +1,80 @@ +import { + CACHE_PROFILES, + buildCatchAllTag, + buildTag, + bustListingAllOnProductEvent, + type CacheProfile, + type PaperCacheLifeProfile, + type WebhookEntity, +} from "@/lib/saleor"; + +export type ListingTag = { tag: string; profile: PaperCacheLifeProfile }; + +export type ListingInvalidationTarget = { + slug?: string; + categorySlug?: string; + /** + * `undefined` — payload did not say, use the channel catch-all. + * `[]` — known to be in no collection. + */ + collectionSlugs?: string[]; +}; + +function listingTag(profile: CacheProfile, channel: string, slug: string | undefined): ListingTag { + return { + tag: slug ? buildTag(profile, { slug, channel }) : buildCatchAllTag(profile, channel), + profile: profile.cacheProfile, + }; +} + +/** + * Sharded listing tags for one product, category, or collection event. + * Stock and metadata must not call this — see `listingTagsForDelivery`. + */ +export function planListingTags( + entity: "product" | "category" | "collection", + parsed: ListingInvalidationTarget, + channel: string, +): ListingTag[] { + switch (entity) { + case "product": { + const tags: ListingTag[] = []; + if (bustListingAllOnProductEvent()) { + tags.push({ + tag: buildTag(CACHE_PROFILES.listingAll, { channel }), + profile: CACHE_PROFILES.listingAll.cacheProfile, + }); + } + tags.push(listingTag(CACHE_PROFILES.listingCategory, channel, parsed.categorySlug)); + if (parsed.collectionSlugs) { + for (const collectionSlug of parsed.collectionSlugs) { + tags.push(listingTag(CACHE_PROFILES.listingCollection, channel, collectionSlug)); + } + } else { + tags.push(listingTag(CACHE_PROFILES.listingCollection, channel, undefined)); + } + return tags; + } + case "category": + return [listingTag(CACHE_PROFILES.listingCategory, channel, parsed.slug)]; + case "collection": + return [listingTag(CACHE_PROFILES.listingCollection, channel, parsed.slug)]; + } +} + +/** + * Tags to bust for one webhook delivery. + * A missing scope (manual POST) still busts listings. `affectsListing: false` + * (stock, metadata) busts none. + */ +export function listingTagsForDelivery( + eventScope: { entity: WebhookEntity; affectsListing: boolean } | null, + parsedType: string, + parsed: ListingInvalidationTarget, + channel: string, +): ListingTag[] { + if (eventScope && !eventScope.affectsListing) return []; + const entity = eventScope?.entity ?? parsedType; + if (entity !== "product" && entity !== "category" && entity !== "collection") return []; + return planListingTags(entity, parsed, channel); +} diff --git a/apps/web/src/lib/listing/load.ts b/apps/web/src/lib/listing/load.ts new file mode 100644 index 0000000..ab70ee8 --- /dev/null +++ b/apps/web/src/lib/listing/load.ts @@ -0,0 +1,20 @@ +import "server-only"; + +import type { ListingPayload, ListingSurface } from "@/lib/catalog/listing-query"; +import type { ListingViewParams } from "@/lib/catalog/listing-view"; +import { loadListing } from "@/lib/listing/policy"; +import { toListingPayload } from "@/lib/listing/payload"; +import { listingQueryFromInput } from "@/lib/listing/query"; + +export async function loadListingView(input: { + surface: ListingSurface; + locale: string; + channel: string; + slug?: string; + view: ListingViewParams; +}): Promise { + const query = listingQueryFromInput(input); + if (!query) return null; + const result = await loadListing(query); + return result ? toListingPayload(result) : null; +} diff --git a/apps/web/src/lib/listing/payload.ts b/apps/web/src/lib/listing/payload.ts new file mode 100644 index 0000000..fbf2537 --- /dev/null +++ b/apps/web/src/lib/listing/payload.ts @@ -0,0 +1,27 @@ +import type { ListingPayload, ListingPageInfo } from "@/lib/catalog/listing-query"; +import type { ListingResult } from "@/lib/storefront/contract/listing"; + +export function toListingPayload(result: ListingResult): ListingPayload { + const pageInfo: ListingPageInfo = + result.page.mode === "cursor" + ? { + hasNextPage: result.page.hasNextPage, + hasPreviousPage: result.page.hasPreviousPage, + startCursor: result.page.startCursor, + endCursor: result.page.endCursor, + } + : { + hasNextPage: result.page.hasNextPage, + hasPreviousPage: result.page.hasPreviousPage, + }; + return { + products: result.items, + pageInfo, + totalCount: result.total.value, + resolvedCategories: result.resolvedCategories ?? [], + facets: result.facets, + sorts: result.sorts, + page: result.page, + totalExact: result.total.exact, + }; +} diff --git a/apps/web/src/lib/listing/policy.ts b/apps/web/src/lib/listing/policy.ts new file mode 100644 index 0000000..0875c90 --- /dev/null +++ b/apps/web/src/lib/listing/policy.ts @@ -0,0 +1,44 @@ +import "server-only"; + +import { applyListingTtl } from "@/lib/saleor"; +import type { ListingQuery, ListingResult } from "@/lib/storefront/contract/listing"; +import { isCacheableListingQuery } from "@/lib/listing/cacheability"; +import { getListingProvider, listingProviderFor } from "@/lib/listing/registry"; +import { normalizeListingQuery, type ListingProvider } from "@/lib/listing/provider"; + +export { isCacheableListingQuery } from "@/lib/listing/cacheability"; + +/** Which cache wrapper `loadListing` will use. Search and filtered queries are always live. */ +export function listingFetchMode( + query: ListingQuery, + provider: ListingProvider, +): "cached-saleor" | "cached-ttl" | "live" { + if (!isCacheableListingQuery(query)) return "live"; + return provider.freshness.kind === "ttl" ? "cached-ttl" : "cached-saleor"; +} + +async function loadCachedSaleor(providerId: string, query: ListingQuery): Promise { + "use cache"; + return getListingProvider(providerId).load(query); +} + +async function loadCachedTtl(providerId: string, query: ListingQuery): Promise { + "use cache"; + applyListingTtl(); + return getListingProvider(providerId).load(query); +} + +/** + * Listing data for one query. The provider is chosen from the surface. + * The query is normalized to the provider's sorts and pagination before the cache key. + * Canonical category, collection, and all-products grids are cached. + * Search, filters, and cursors are live so a provider cannot explode the cache key space. + */ +export async function loadListing(input: ListingQuery): Promise { + const provider = listingProviderFor(input.surface.kind); + const query = normalizeListingQuery(provider, input); + const mode = listingFetchMode(query, provider); + if (mode === "cached-saleor") return loadCachedSaleor(provider.id, query); + if (mode === "cached-ttl") return loadCachedTtl(provider.id, query); + return provider.load(query); +} diff --git a/apps/web/src/lib/listing/provider.ts b/apps/web/src/lib/listing/provider.ts new file mode 100644 index 0000000..ebe7352 --- /dev/null +++ b/apps/web/src/lib/listing/provider.ts @@ -0,0 +1,70 @@ +import type { + ListingQuery, + ListingResult, + ListingSurfaceKind, + SortId, +} from "@/lib/storefront/contract/listing"; + +/** + * One backend for one or more listing surfaces. + * Cache policy is not a provider concern — `load` only fetches. + */ +export type ListingProvider = { + id: string; + capabilities: { + surfaces: ListingSurfaceKind[]; + facetCounts: boolean; + pagination: "cursor" | "offset"; + sorts: Partial>; + }; + freshness: { kind: "saleor-webhooks" } | { kind: "ttl"; profile: "listingTtl" }; + /** + * `query` is already normalized by core (`normalizeListingQuery`): the sort is one this + * provider declared for the surface, and the page is in its pagination mode. + * `null` means the category or collection slug does not exist. Transport failures throw. + */ + load(query: ListingQuery): Promise; +}; + +/** + * A shared URL can ask for a sort this provider does not offer (Bestselling on + * search, Name on a category). Fall back to the surface default instead of + * failing the page. + */ +export function listingQueryWithSupportedSort(provider: ListingProvider, query: ListingQuery): ListingQuery { + if (!query.sort) return query; + const allowed = provider.capabilities.sorts[query.surface.kind] ?? []; + if (allowed.includes(query.sort)) return query; + return { ...query, sort: undefined }; +} + +/** + * A page request in the other pagination mode (`?page=2` from a search engine on a + * cursor provider, or a Saleor cursor on an offset provider) cannot be honored. + * Serve the first page instead of failing the page. + */ +export function listingQueryWithSupportedPage(provider: ListingProvider, query: ListingQuery): ListingQuery { + const mode = provider.capabilities.pagination; + if (query.page.mode === mode) return query; + return { + ...query, + page: mode === "offset" ? { mode: "offset", number: 1 } : { mode: "cursor", direction: "next" }, + }; +} + +/** + * Fit a URL-derived query to what the provider declares. Core calls this before + * choosing the cache key, so a provider never sees a query it cannot serve and an + * unsupported sort does not create its own cache entry. + */ +export function normalizeListingQuery(provider: ListingProvider, query: ListingQuery): ListingQuery { + return listingQueryWithSupportedPage(provider, listingQueryWithSupportedSort(provider, query)); +} + +export function assertProviderSupportsSurface(provider: ListingProvider, kind: ListingSurfaceKind): void { + if (!provider.capabilities.surfaces.includes(kind)) { + throw new Error( + `Listing provider "${provider.id}" does not serve "${kind}". Its capabilities.surfaces list must include that surface. Change src/config/listing-providers.ts.`, + ); + } +} diff --git a/apps/web/src/lib/listing/providers/fixture/contract.test.ts b/apps/web/src/lib/listing/providers/fixture/contract.test.ts new file mode 100644 index 0000000..b219c5d --- /dev/null +++ b/apps/web/src/lib/listing/providers/fixture/contract.test.ts @@ -0,0 +1,16 @@ +import { describe } from "vitest"; +import { fixtureListingProvider } from "@/lib/listing/providers/fixture"; +import { runListingProviderContract } from "@/lib/listing/testing"; + +describe("fixture listing provider", () => { + runListingProviderContract(fixtureListingProvider, { + query: { + surface: { kind: "category", slug: "hoodies" }, + channel: "default-channel", + locale: "en", + selections: {}, + page: { mode: "offset", number: 1 }, + pageSize: 12, + }, + }); +}); diff --git a/apps/web/src/lib/listing/providers/fixture/index.ts b/apps/web/src/lib/listing/providers/fixture/index.ts new file mode 100644 index 0000000..3a3bcf6 --- /dev/null +++ b/apps/web/src/lib/listing/providers/fixture/index.ts @@ -0,0 +1,192 @@ +import type { ListingQuery, ListingResult, ProductCardView, SortId } from "@/lib/storefront/contract/listing"; +import type { ListingProvider } from "@/lib/listing/provider"; + +const LISTING_SORTS = [ + "featured", + "newest", + "price_asc", + "price_desc", + "bestselling", +] as const satisfies readonly SortId[]; +const SEARCH_SORTS = [ + "relevance", + "newest", + "price_asc", + "price_desc", + "name", +] as const satisfies readonly SortId[]; + +type FixtureItem = { + card: ProductCardView; + category: string; + collections: string[]; + text: string; +}; + +function card(index: number, color: "blue" | "red", size: "m" | "l", price: number): FixtureItem { + const slug = `hoodie-${index}`; + return { + category: "hoodies", + collections: index < 3 ? ["summer"] : [], + text: `hoodie ${color} ${size}`, + card: { + id: `fixture-${index}`, + name: `Hoodie ${index}`, + slug, + price, + currency: "USD", + image: "/placeholder.svg", + href: `/products/${slug}`, + colors: [{ name: color, slug: color, hex: color === "blue" ? "#1d4ed8" : "#b91c1c" }], + sizes: [{ name: size.toUpperCase(), slug: size }], + category: { id: "cat-hoodies", name: "Hoodies", slug: "hoodies" }, + createdAt: new Date(Date.UTC(2024, 0, index + 1)).toISOString(), + }, + }; +} + +const ITEMS: FixtureItem[] = [ + ...Array.from({ length: 10 }, (_, index) => card(index, "blue", "m", 40 + index)), + ...Array.from({ length: 5 }, (_, index) => card(index + 10, "red", "l", 80 + index)), +]; + +function inSurface(item: FixtureItem, query: ListingQuery): boolean { + switch (query.surface.kind) { + case "all": + return true; + case "category": + return item.category === query.surface.slug; + case "collection": + return item.collections.includes(query.surface.slug); + case "search": { + const text = query.surface.text.toLowerCase(); + return item.text.includes(text) || item.card.name.toLowerCase().includes(text); + } + } +} + +function matchesRange(item: FixtureItem, query: ListingQuery): boolean { + const price = query.range?.price; + if (!price) return true; + if (price.min != null && item.card.price < price.min) return false; + if (price.max != null && item.card.price > price.max) return false; + return true; +} + +function matchesSelection(item: FixtureItem, query: ListingQuery, skip?: string): boolean { + for (const [id, values] of Object.entries(query.selections)) { + if (values.length === 0 || id === skip) continue; + if (id === "colors" && !item.card.colors?.some((color) => values.includes(color.slug))) return false; + if (id === "sizes" && !item.card.sizes?.some((size) => values.includes(size.slug))) return false; + if (id === "categories" && !values.includes(item.category)) return false; + } + return true; +} + +function sortItems(items: FixtureItem[], sort: SortId | undefined): FixtureItem[] { + const copy = [...items]; + switch (sort) { + case "price_asc": + return copy.sort((a, b) => a.card.price - b.card.price || a.card.id.localeCompare(b.card.id)); + case "price_desc": + return copy.sort((a, b) => b.card.price - a.card.price || a.card.id.localeCompare(b.card.id)); + case "newest": + return copy.sort((a, b) => (b.card.createdAt ?? "").localeCompare(a.card.createdAt ?? "")); + case "name": + return copy.sort((a, b) => a.card.name.localeCompare(b.card.name)); + default: + return copy; + } +} + +function counts(pool: FixtureItem[], pick: (item: FixtureItem) => string[]): Map { + const map = new Map(); + for (const item of pool) { + for (const value of pick(item)) map.set(value, (map.get(value) ?? 0) + 1); + } + return map; +} + +export const fixtureListingProvider: ListingProvider = { + id: "fixture", + capabilities: { + surfaces: ["all", "category", "collection", "search"], + facetCounts: true, + pagination: "offset", + sorts: { + all: LISTING_SORTS, + category: LISTING_SORTS, + collection: LISTING_SORTS, + search: SEARCH_SORTS, + }, + }, + freshness: { kind: "ttl", profile: "listingTtl" }, + async load(query) { + if ( + (query.surface.kind === "category" || query.surface.kind === "collection") && + query.surface.slug === "missing" + ) { + return null; + } + if (query.channel === "boom") { + throw new Error("fixture transport down"); + } + + const surfacePool = ITEMS.filter((item) => inSurface(item, query)); + const filtered = sortItems( + surfacePool.filter((item) => matchesRange(item, query) && matchesSelection(item, query)), + query.sort, + ); + const pageNumber = query.page.mode === "offset" ? query.page.number : 1; + const start = (pageNumber - 1) * query.pageSize; + const items = filtered.slice(start, start + query.pageSize).map((item) => item.card); + + const colorPool = surfacePool.filter( + (item) => matchesRange(item, query) && matchesSelection(item, query, "colors"), + ); + const sizePool = surfacePool.filter( + (item) => matchesRange(item, query) && matchesSelection(item, query, "sizes"), + ); + const colorCounts = counts(colorPool, (item) => item.card.colors?.map((color) => color.slug) ?? []); + const sizeCounts = counts(sizePool, (item) => item.card.sizes?.map((size) => size.slug) ?? []); + const colorSelected = new Set(query.selections.colors ?? []); + const sizeSelected = new Set(query.selections.sizes ?? []); + + const result: ListingResult = { + items, + facets: [ + { + id: "colors", + labelKey: "colors", + control: "swatch", + values: [...colorCounts.entries()].map(([value, count]) => ({ + value, + label: value, + count, + selected: colorSelected.has(value), + })), + }, + { + id: "sizes", + labelKey: "sizes", + control: "chip", + values: [...sizeCounts.entries()].map(([value, count]) => ({ + value, + label: value.toUpperCase(), + count, + selected: sizeSelected.has(value), + })), + }, + ], + sorts: [...(fixtureListingProvider.capabilities.sorts[query.surface.kind] ?? [])], + page: { + mode: "offset", + number: pageNumber, + hasNextPage: start + query.pageSize < filtered.length, + hasPreviousPage: pageNumber > 1, + }, + total: { value: filtered.length, exact: true }, + }; + return result; + }, +}; diff --git a/apps/web/src/lib/listing/providers/saleor/constraints.ts b/apps/web/src/lib/listing/providers/saleor/constraints.ts new file mode 100644 index 0000000..b1da51b --- /dev/null +++ b/apps/web/src/lib/listing/providers/saleor/constraints.ts @@ -0,0 +1,136 @@ +/** + * Saleor listing constraints. + * + * Saleor allows only one of `filter` or `where`. Attribute facets use `where` + * so aliases (`size` | `shoe-size`) can OR. Search text is the top-level + * `products(search:)` argument, which combines with either, so every surface + * (search included) uses the same constraints. + */ + +import type { ProductFilterInput, ProductOrder, ProductWhereInput } from "@/gql/graphql"; +import { OrderDirection, ProductOrderField } from "@/gql/graphql"; +import { PLP_FACETS, normalizeFacetValueSlug, parseFacetParam, type PlpFacetConfig } from "@/config/facets"; + +export type AttributeFacetSelections = { + [param: string]: string[] | undefined; +}; + +export type ProductListingConstraints = { + filter?: ProductFilterInput; + where?: ProductWhereInput; +}; + +type ListingFilterParams = { + priceRange?: string | null; + categoryIds?: string[]; + facets?: AttributeFacetSelections; + colors?: string[] | string | null; + sizes?: string[] | string | null; +}; + +function resolveFacetSelections(params: ListingFilterParams): AttributeFacetSelections { + const facetSelections: AttributeFacetSelections = { ...params.facets }; + if (params.colors != null) { + facetSelections.colors = Array.isArray(params.colors) ? params.colors : parseFacetParam(params.colors); + } + if (params.sizes != null) { + facetSelections.sizes = Array.isArray(params.sizes) ? params.sizes : parseFacetParam(params.sizes); + } + return facetSelections; +} + +function parsePriceRange(priceRange: string): { gte: number; lte?: number } { + const [minStr, maxStr] = priceRange.split("-"); + const min = parseFloat(minStr ?? "") || 0; + const max = maxStr ? parseFloat(maxStr) : undefined; + return { gte: min, ...(max !== undefined && !Number.isNaN(max) ? { lte: max } : {}) }; +} + +function facetAttributeSlugs(facet: PlpFacetConfig): string[] { + return [...facet.source.saleor.attributes]; +} + +function hasSelectedFacets(facets: AttributeFacetSelections): boolean { + return PLP_FACETS.some((facet) => (facets[facet.param]?.length ?? 0) > 0); +} + +export function buildAttributeWhereInput(facets: AttributeFacetSelections): ProductWhereInput | undefined { + const facetClauses: ProductWhereInput[] = []; + for (const facet of PLP_FACETS) { + const raw = facets[facet.param]; + if (!raw?.length) continue; + const values = [...new Set(raw.map(normalizeFacetValueSlug).filter(Boolean))].sort(); + if (values.length === 0) continue; + const slugs = facetAttributeSlugs(facet); + facetClauses.push({ + OR: slugs.map((slug) => ({ + attributes: [{ slug, values }], + })), + }); + } + if (facetClauses.length === 0) return undefined; + if (facetClauses.length === 1) return facetClauses[0]; + return { AND: facetClauses }; +} + +function buildWhereConstraints( + params: ListingFilterParams, + facets: AttributeFacetSelections, +): ProductWhereInput { + const clauses: ProductWhereInput[] = []; + if (params.categoryIds?.length) { + clauses.push({ category: { oneOf: params.categoryIds } }); + } + if (params.priceRange) { + const { gte, lte } = parsePriceRange(params.priceRange); + clauses.push({ + price: { range: { gte, ...(lte !== undefined ? { lte } : {}) } }, + }); + } + const attributeWhere = buildAttributeWhereInput(facets); + if (attributeWhere) clauses.push(attributeWhere); + if (clauses.length === 1) return clauses[0]!; + return { AND: clauses }; +} + +export function buildFilterVariables(params: { + priceRange?: string | null; + categoryIds?: string[]; +}): ProductFilterInput | undefined { + const filter: ProductFilterInput = {}; + let hasFilter = false; + if (params.categoryIds?.length) { + filter.categories = params.categoryIds; + hasFilter = true; + } + if (params.priceRange) { + const { gte, lte } = parsePriceRange(params.priceRange); + filter.price = { gte, ...(lte !== undefined ? { lte } : {}) }; + hasFilter = true; + } + return hasFilter ? filter : undefined; +} + +export function buildProductListingConstraints(params: ListingFilterParams): ProductListingConstraints { + const facets = resolveFacetSelections(params); + if (hasSelectedFacets(facets)) { + return { where: buildWhereConstraints(params, facets) }; + } + const filter = buildFilterVariables({ + priceRange: params.priceRange, + categoryIds: params.categoryIds, + }); + return filter ? { filter } : {}; +} + +export function buildSortVariables(sort: string | undefined): ProductOrder | undefined { + if (!sort || sort === "featured" || sort === "relevance") return undefined; + const sortMap: Record = { + newest: { field: ProductOrderField.Date, direction: OrderDirection.Desc }, + price_asc: { field: ProductOrderField.Price, direction: OrderDirection.Asc }, + price_desc: { field: ProductOrderField.Price, direction: OrderDirection.Desc }, + bestselling: { field: ProductOrderField.Rating, direction: OrderDirection.Desc }, + name: { field: ProductOrderField.Name, direction: OrderDirection.Asc }, + }; + return sortMap[sort]; +} diff --git a/apps/web/src/lib/listing/providers/saleor/contract.test.ts b/apps/web/src/lib/listing/providers/saleor/contract.test.ts new file mode 100644 index 0000000..ace1181 --- /dev/null +++ b/apps/web/src/lib/listing/providers/saleor/contract.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from "vitest"; +import { createSaleorListingProvider, type SaleorTransportData } from "@/lib/listing/providers/saleor"; +import { runListingProviderContract } from "@/lib/listing/testing"; +import type { ListingProvider } from "@/lib/listing/provider"; +import type { ListingQuery } from "@/lib/storefront/contract/listing"; + +function cardNode(index: number) { + return { + id: `p-${index}`, + name: `Product ${index}`, + slug: `product-${index}`, + created: "2024-01-01T00:00:00Z", + pricing: { + priceRange: { + start: { gross: { amount: 10 + index, currency: "USD" } }, + stop: { gross: { amount: 10 + index, currency: "USD" } }, + }, + priceRangeUndiscounted: { + start: { gross: { amount: 10 + index, currency: "USD" } }, + stop: { gross: { amount: 10 + index, currency: "USD" } }, + }, + }, + thumbnail: null, + productVariants: { edges: [], totalCount: 1 }, + category: null, + }; +} + +const CATALOG = Array.from({ length: 15 }, (_, index) => cardNode(index)); + +function sliceConnection(variables: Record): SaleorTransportData { + const first = typeof variables.first === "number" ? variables.first : undefined; + const last = typeof variables.last === "number" ? variables.last : undefined; + const after = typeof variables.after === "string" ? Number(variables.after) : 0; + const before = typeof variables.before === "string" ? Number(variables.before) : CATALOG.length; + const start = last != null ? Math.max(0, before - last) : after; + const end = last != null ? before : start + (first ?? CATALOG.length); + const slice = CATALOG.slice(start, end); + const connection = { + edges: slice.map((node) => ({ node })), + pageInfo: { + hasNextPage: end < CATALOG.length, + hasPreviousPage: start > 0, + startCursor: String(start), + endCursor: String(end), + }, + totalCount: CATALOG.length, + }; + if (variables.slug === "missing") return { category: null, collection: null }; + return { + products: connection, + category: { products: connection }, + collection: { products: connection }, + } as unknown as SaleorTransportData; +} + +function saleorStub(): ListingProvider { + return createSaleorListingProvider(async (input) => { + if (input.variables.channel === "boom") throw new Error("saleor down"); + return sliceConnection(input.variables); + }); +} + +const categoryQuery = { + surface: { kind: "category", slug: "hoodies" }, + channel: "default-channel", + locale: "en", + selections: {}, + page: { mode: "cursor", direction: "next" }, + pageSize: 12, +} satisfies ListingQuery; + +describe("saleor listing provider", () => { + runListingProviderContract(saleorStub(), { query: categoryQuery }); + + function capture() { + const seen: Array> = []; + const provider = createSaleorListingProvider(async (input) => { + seen.push(input.variables); + return sliceConnection(input.variables); + }); + return { provider, seen }; + } + + it("asks Saleor for last/before when paging backwards", async () => { + const { provider, seen } = capture(); + await provider.load({ + ...categoryQuery, + page: { mode: "cursor", direction: "prev", cursor: "cursor-1" }, + }); + expect(seen[0]?.last).toBe(12); + expect(seen[0]?.before).toBe("cursor-1"); + expect(seen[0]?.first).toBeUndefined(); + }); + + it("searches with the top-level search argument, RANK, and the grid's facet aliases", async () => { + const { provider, seen } = capture(); + await provider.load({ + ...categoryQuery, + surface: { kind: "search", text: "hoodie" }, + selections: { colors: ["black"] }, + }); + const variables = seen[0]!; + expect(variables.search).toBe("hoodie"); + expect(variables.filter).toBeUndefined(); + expect(variables.sortBy).toEqual({ field: "RANK", direction: "DESC" }); + expect(JSON.stringify(variables.where)).toContain('"colour"'); + }); + + it("sends no search argument outside the search surface", async () => { + const { provider, seen } = capture(); + await provider.load(categoryQuery); + expect(seen[0]?.search).toBeUndefined(); + }); +}); diff --git a/apps/web/src/lib/listing/providers/saleor/index.ts b/apps/web/src/lib/listing/providers/saleor/index.ts new file mode 100644 index 0000000..68fdd65 --- /dev/null +++ b/apps/web/src/lib/listing/providers/saleor/index.ts @@ -0,0 +1,236 @@ +import "server-only"; + +import { OrderDirection, ProductOrderField } from "@/gql/graphql"; +import { + ProductListByCategoryProductsDocument, + ProductListByCollectionProductsDocument, + ProductListPaginatedDocument, + type ProductListItemFragment, +} from "@/gql/graphql"; +import { graphqlLanguageCodeVariables } from "@/lib/graphql-locale"; +import { CACHE_PROFILES, cachedQuery, liveQuery, type CacheProfile } from "@/lib/saleor"; +import { resolveCategorySlugsToIds } from "@/lib/catalog/resolve-category-slugs"; +import { isCacheableListingQuery } from "@/lib/listing/cacheability"; +import type { ListingProvider } from "@/lib/listing/provider"; +import type { ListingQuery, ListingResult, SortId } from "@/lib/storefront/contract/listing"; +import { buildProductListingConstraints, buildSortVariables } from "./constraints"; +import { sampleFacets } from "./sample-facets"; +import { toProductCardData } from "./to-card"; + +const LISTING_SORTS = [ + "featured", + "newest", + "price_asc", + "price_desc", + "bestselling", +] as const satisfies readonly SortId[]; +const SEARCH_SORTS = [ + "relevance", + "newest", + "price_asc", + "price_desc", + "name", +] as const satisfies readonly SortId[]; + +type Connection = { + edges: Array<{ node: ProductListItemFragment }>; + pageInfo: { + hasNextPage: boolean; + hasPreviousPage: boolean; + startCursor?: string | null; + endCursor?: string | null; + }; + totalCount?: number | null; +}; + +export type SaleorTransportData = { + products?: Connection | null; + category?: { products?: Connection | null } | null; + collection?: { products?: Connection | null } | null; +}; + +export type SaleorListingTransport = (input: { + kind: ListingQuery["surface"]["kind"]; + variables: Record; + cached: boolean; + profile?: CacheProfile; + tag?: { channel: string; slug?: string }; +}) => Promise; + +function priceToken(range?: { min?: number; max?: number }): string | undefined { + if (!range) return undefined; + const min = range.min ?? 0; + return range.max != null ? `${min}-${range.max}` : `${min}-`; +} + +function paginationVariables(query: ListingQuery): { + first?: number; + after?: string | null; + last?: number; + before?: string; +} { + if (query.page.mode !== "cursor") { + // Core normalizes pages to cursor mode first (`normalizeListingQuery`). A direct + // caller may still pass `?page=1`; deeper offset pages are a search-engine shape. + if (query.page.number <= 1) return { first: query.pageSize, after: null }; + throw new Error('Listing provider "saleor" does not support offset pagination.'); + } + if (query.page.direction === "prev" && query.page.cursor) { + return { last: query.pageSize, before: query.page.cursor }; + } + return { first: query.pageSize, after: query.page.cursor ?? null }; +} + +function saleorSort(query: ListingQuery) { + // `RANK` is Saleor's search relevance. It is valid only together with `search`. + if (query.surface.kind === "search" && (!query.sort || query.sort === "relevance")) { + return { field: ProductOrderField.Rank, direction: OrderDirection.Desc }; + } + const fromUrl = buildSortVariables(query.sort); + if (fromUrl) return fromUrl; + if (query.surface.kind === "collection") { + return { field: ProductOrderField.Collection, direction: OrderDirection.Asc }; + } + return undefined; +} + +function unwrap(kind: ListingQuery["surface"]["kind"], data: SaleorTransportData): Connection | null { + if (kind === "category") return data.category?.products ?? null; + if (kind === "collection") return data.collection?.products ?? null; + return data.products ?? null; +} + +async function kernelTransport(input: Parameters[0]): Promise { + const variables = input.variables as never; + if (input.kind === "category") { + if (input.cached && input.profile && input.tag) { + return cachedQuery(ProductListByCategoryProductsDocument, { + profile: input.profile, + tag: input.tag, + variables, + }); + } + const result = await liveQuery(ProductListByCategoryProductsDocument, { variables }); + if (!result.ok) throw new Error(`[listing:saleor] category: ${result.error.message}`); + return result.data; + } + if (input.kind === "collection") { + if (input.cached && input.profile && input.tag) { + return cachedQuery(ProductListByCollectionProductsDocument, { + profile: input.profile, + tag: input.tag, + variables, + }); + } + const result = await liveQuery(ProductListByCollectionProductsDocument, { variables }); + if (!result.ok) throw new Error(`[listing:saleor] collection: ${result.error.message}`); + return result.data; + } + if (input.cached && input.profile && input.tag) { + return cachedQuery(ProductListPaginatedDocument, { + profile: input.profile, + tag: input.tag, + variables, + }); + } + const result = await liveQuery(ProductListPaginatedDocument, { variables }); + if (!result.ok) throw new Error(`[listing:saleor] ${input.kind}: ${result.error.message}`); + return result.data; +} + +export function createSaleorListingProvider( + transport: SaleorListingTransport = kernelTransport, +): ListingProvider { + const provider: ListingProvider = { + id: "saleor", + capabilities: { + surfaces: ["all", "category", "collection", "search"], + facetCounts: false, + pagination: "cursor", + sorts: { + all: LISTING_SORTS, + category: LISTING_SORTS, + collection: LISTING_SORTS, + search: SEARCH_SORTS, + }, + }, + freshness: { kind: "saleor-webhooks" }, + async load(query) { + const kind = query.surface.kind; + const slug = kind === "category" || kind === "collection" ? query.surface.slug : undefined; + + const resolvedCategories = + kind === "all" && query.selections.categories?.length + ? await resolveCategories(query.selections.categories) + : []; + const categoryIds = resolvedCategories.map((category) => category.id); + const priceRange = priceToken(query.range?.price); + const constraintInput = { + priceRange, + categoryIds: kind === "all" ? categoryIds : undefined, + facets: query.selections, + }; + // Search text is the top-level `search` argument, so search shares the grid's + // `where` constraints (facet aliases OR the same way on every surface). + const constraints = buildProductListingConstraints(constraintInput); + const search = query.surface.kind === "search" ? query.surface.text : undefined; + + const cached = isCacheableListingQuery(query); + const profile = + kind === "category" + ? CACHE_PROFILES.listingCategory + : kind === "collection" + ? CACHE_PROFILES.listingCollection + : CACHE_PROFILES.listingAll; + const tag = slug ? { channel: query.channel, slug } : { channel: query.channel }; + + const data = await transport({ + kind, + cached, + profile, + tag, + variables: { + ...paginationVariables(query), + ...(slug ? { slug } : {}), + channel: query.channel, + sortBy: saleorSort(query), + ...(constraints.filter ? { filter: constraints.filter } : {}), + ...(constraints.where ? { where: constraints.where } : {}), + ...(search ? { search } : {}), + ...graphqlLanguageCodeVariables(query.locale), + }, + }); + + const connection = unwrap(kind, data); + if (!connection && kind !== "search") return null; + const edges = connection?.edges ?? []; + const items = edges.map((edge) => toProductCardData(edge.node, query.locale, query.channel)); + const sorts = provider.capabilities.sorts[kind] ?? []; + return { + items, + facets: sampleFacets(items, query, resolvedCategories), + sorts: [...sorts], + page: { + mode: "cursor", + hasNextPage: connection?.pageInfo.hasNextPage ?? false, + hasPreviousPage: connection?.pageInfo.hasPreviousPage ?? false, + startCursor: connection?.pageInfo.startCursor, + endCursor: connection?.pageInfo.endCursor, + }, + total: { value: connection?.totalCount ?? items.length, exact: true }, + resolvedCategories, + } satisfies ListingResult; + }, + }; + return provider; +} + +async function resolveCategories(slugs: string[]) { + const categoryMap = await resolveCategorySlugsToIds(slugs); + return slugs.flatMap((slug) => { + const category = categoryMap.get(slug); + return category ? [{ slug, id: category.id, name: category.name }] : []; + }); +} + +export const saleorListingProvider = createSaleorListingProvider(); diff --git a/apps/web/src/lib/listing/providers/saleor/sample-facets.ts b/apps/web/src/lib/listing/providers/saleor/sample-facets.ts new file mode 100644 index 0000000..03a3ed7 --- /dev/null +++ b/apps/web/src/lib/listing/providers/saleor/sample-facets.ts @@ -0,0 +1,101 @@ +import { PLP_FACETS, STATIC_PRICE_RANGES } from "@/config/facets"; +import type { FacetView, ListingQuery, ProductCardView } from "@/lib/storefront/contract/listing"; + +function selected(query: ListingQuery, id: string): Set { + return new Set(query.selections[id] ?? []); +} + +function priceToken(range?: { min?: number; max?: number }): string | undefined { + if (!range) return undefined; + const min = range.min ?? 0; + return range.max != null ? `${min}-${range.max}` : `${min}-`; +} + +/** + * Facets from the current page sample. Saleor does not return aggregations, + * so these values have no `count`. Selected values stay visible even when the + * page no longer contains them. + */ +export function sampleFacets( + items: ProductCardView[], + query: ListingQuery, + resolvedCategories: Array<{ slug: string; id: string; name: string }> = [], +): FacetView[] { + const colorSelected = selected(query, "colors"); + const sizeSelected = selected(query, "sizes"); + const colors = new Map(); + const sizes = new Map(); + for (const item of items) { + for (const color of item.colors ?? []) { + if (!colors.has(color.slug)) colors.set(color.slug, { label: color.name, hex: color.hex }); + } + for (const size of item.sizes ?? []) { + if (!sizes.has(size.slug)) sizes.set(size.slug, size.name); + } + } + for (const value of colorSelected) { + if (!colors.has(value)) colors.set(value, { label: value }); + } + for (const value of sizeSelected) { + if (!sizes.has(value)) sizes.set(value, value); + } + + const chosenPrice = priceToken(query.range?.price); + const facets: FacetView[] = [ + { + id: "colors", + labelKey: PLP_FACETS.find((facet) => facet.id === "colors")?.labelKey ?? "colors", + control: "swatch", + values: [...colors.entries()].map(([value, meta]) => ({ + value, + label: meta.label, + selected: colorSelected.has(value), + ...(meta.hex ? { hex: meta.hex } : {}), + })), + }, + { + id: "sizes", + labelKey: "sizes", + control: "chip", + values: [...sizes.entries()].map(([value, label]) => ({ + value, + label, + selected: sizeSelected.has(value), + })), + }, + { + id: "price", + labelKey: "price", + control: "range", + values: STATIC_PRICE_RANGES.map((range) => ({ + value: range.value, + label: range.label, + selected: range.value === chosenPrice, + })), + }, + ]; + + if (query.surface.kind === "all") { + const categorySelected = selected(query, "categories"); + const categories = new Map(); + for (const item of items) { + if (item.category) categories.set(item.category.slug, item.category.name); + } + for (const category of resolvedCategories) categories.set(category.slug, category.name); + for (const value of categorySelected) { + if (!categories.has(value)) categories.set(value, value); + } + facets.push({ + id: "categories", + labelKey: "categories", + control: "chip", + values: [...categories.entries()].map(([value, label]) => ({ + value, + label, + selected: categorySelected.has(value), + })), + }); + } + + return facets; +} diff --git a/apps/web/src/lib/listing/providers/saleor/to-card.ts b/apps/web/src/lib/listing/providers/saleor/to-card.ts new file mode 100644 index 0000000..ac17f93 --- /dev/null +++ b/apps/web/src/lib/listing/providers/saleor/to-card.ts @@ -0,0 +1,128 @@ +import "server-only"; + +import type { ProductListItemFragment } from "@/gql/graphql"; +import { getColorHex, isColorAttribute, isSizeAttribute } from "@/lib/colors"; +import { sortByOptionLabel } from "@/lib/sizes"; +import { localeConfig, resolveLocaleFromSlug } from "@/config/locale"; +import { PDP_VARIANT_CAP } from "@/config/variants"; +import { normalizeFacetValueSlug } from "@/config/facets"; +import { calculateDiscountPercent, hasDiscount, hasDiscountInPriceRange } from "@/lib/pricing"; +import { buildStorefrontPath } from "@/lib/storefront-path"; +import { pickTranslatedName, pickTranslatedSlug } from "@/lib/saleor-translations"; +import { isBestseller } from "@/lib/catalog/product-flags"; +import { buildSaleorSrcSet } from "@/lib/images"; +import type { ProductCardView } from "@/lib/storefront/contract/listing"; + +type ListVariantNode = NonNullable< + NonNullable["edges"][number] +>["node"]; + +function listVariantNodes(product: ProductListItemFragment): ListVariantNode[] { + return product.productVariants?.edges.map((edge) => edge.node) ?? []; +} + +function attributeValueSlug(value: { name?: string | null; slug?: string | null }): string { + const slug = value.slug?.trim(); + if (slug) return normalizeFacetValueSlug(slug); + const name = value.name?.trim(); + return name ? normalizeFacetValueSlug(name) : ""; +} + +function extractColorsFromVariants( + variants: ListVariantNode[], +): { name: string; slug: string; hex: string }[] { + const colorSet = new Map(); + variants.forEach((variant) => { + variant.selectionAttributes?.forEach((attr) => { + if (!isColorAttribute(attr.attribute?.slug ?? "")) return; + attr.values?.forEach((value) => { + const slug = attributeValueSlug(value); + const colorName = value.name; + if (!slug || !colorName || colorSet.has(slug)) return; + colorSet.set(slug, { name: colorName, hex: getColorHex(value) ?? "#6b7280" }); + }); + }); + }); + return Array.from(colorSet.entries()).map(([slug, { name, hex }]) => ({ name, slug, hex })); +} + +function extractSizesFromVariants(variants: ListVariantNode[]): { name: string; slug: string }[] { + const sizeSet = new Map(); + variants.forEach((variant) => { + variant.selectionAttributes?.forEach((attr) => { + if (!isSizeAttribute(attr.attribute?.slug ?? "")) return; + attr.values?.forEach((value) => { + const slug = attributeValueSlug(value); + const name = value.name; + if (!slug || !name || sizeSet.has(slug)) return; + sizeSet.set(slug, name); + }); + }); + }); + return sortByOptionLabel(Array.from(sizeSet.entries()).map(([slug, name]) => ({ name, slug }))); +} + +/** Map a Saleor list item to the listing card view. */ +export function toProductCardData( + product: ProductListItemFragment, + locale: string, + channel: string, +): ProductCardView { + const startPrice = product.pricing?.priceRange?.start?.gross; + const stopPrice = product.pricing?.priceRange?.stop?.gross; + const undiscountedStartPrice = product.pricing?.priceRangeUndiscounted?.start?.gross; + const startAmount = startPrice?.amount ?? 0; + const stopAmount = stopPrice?.amount; + const isSale = hasDiscountInPriceRange( + product.pricing?.priceRange, + product.pricing?.priceRangeUndiscounted, + ); + const undiscountedStartAmount = undiscountedStartPrice?.amount; + const discountPercent = + isSale && hasDiscount(startAmount, undiscountedStartAmount) + ? calculateDiscountPercent(startAmount, undiscountedStartAmount) + : null; + const variantSample = listVariantNodes(product); + const variantSampleSize = variantSample.length; + const variantTotalCount = product.productVariants?.totalCount ?? variantSampleSize; + const productName = pickTranslatedName(product); + const categoryName = product.category ? pickTranslatedName(product.category) : null; + + return { + id: product.id, + name: productName, + slug: product.slug, + brand: categoryName, + price: startAmount, + priceStop: stopAmount != null && stopAmount !== startAmount ? stopAmount : null, + compareAtPrice: isSale ? undiscountedStartAmount : null, + discountPercent, + currency: startPrice?.currency ?? localeConfig.fallbackCurrency, + image: product.thumbnail?.url ?? "/placeholder.svg", + imageSrcSet: buildSaleorSrcSet([ + { width: 256, url: product.thumbnail256?.url }, + { width: 512, url: product.thumbnail512?.url }, + { width: 1024, url: product.thumbnail?.url }, + ]), + imageAlt: product.thumbnail?.alt ?? productName, + hoverImage: null, + localeBcp47: resolveLocaleFromSlug(locale).bcp47, + href: buildStorefrontPath(locale, channel, `/products/${pickTranslatedSlug(product)}`), + badge: isSale ? "Sale" : null, + isBestseller: isBestseller(product), + colors: extractColorsFromVariants(variantSample), + sizes: extractSizesFromVariants(variantSample), + category: product.category + ? { + id: product.category.id, + name: categoryName ?? product.category.name, + slug: product.category.slug, + } + : null, + createdAt: product.created, + hasVariants: variantTotalCount > 1, + variantTotalCount, + variantSampleSize, + isOverVariantCap: variantTotalCount > PDP_VARIANT_CAP, + }; +} diff --git a/apps/web/src/lib/listing/query.ts b/apps/web/src/lib/listing/query.ts new file mode 100644 index 0000000..229d218 --- /dev/null +++ b/apps/web/src/lib/listing/query.ts @@ -0,0 +1,91 @@ +import { ProductsPerPage } from "@/app/config"; +import { PLP_FACETS, parseFacetParam } from "@/config/facets"; +import { listingViewFromRecord, type ListingSurface } from "@/lib/catalog/listing-query"; +import type { ListingViewParams } from "@/lib/catalog/listing-view"; +import { SORT_IDS, type ListingQuery, type SortId } from "@/lib/storefront/contract/listing"; + +const SORT_ALIASES: Record = { + "price-asc": "price_asc", + "price-desc": "price_desc", +}; + +export function canonicalSortId(raw: string | undefined): SortId | undefined { + if (!raw || raw === "featured") return undefined; + const mapped = SORT_ALIASES[raw] ?? raw; + return (SORT_IDS as readonly string[]).includes(mapped) ? (mapped as SortId) : undefined; +} + +function selectionValues(raw: string | string[] | undefined): string[] { + if (Array.isArray(raw)) return parseFacetParam(raw.join(",")); + return parseFacetParam(raw); +} + +/** + * URL view → `ListingQuery`. Returns null when a slug or search text is required + * and missing. Unknown sort tokens are dropped so a junk URL does not 500. + */ +export function listingQueryFromInput(input: { + surface: ListingSurface; + locale: string; + channel: string; + slug?: string; + view: ListingViewParams; + pageSize?: number; +}): ListingQuery | null { + const view = listingViewFromRecord(input.view); + const selections: Record = {}; + for (const facet of PLP_FACETS) { + const values = selectionValues(view[facet.param as keyof ListingViewParams] as string | undefined); + if (values.length > 0) selections[facet.id] = values; + } + const categories = selectionValues(typeof view.categories === "string" ? view.categories : undefined); + if (categories.length > 0) selections.categories = categories; + + let range: ListingQuery["range"]; + if (typeof view.price === "string" && view.price) { + const [minRaw, maxRaw] = view.price.split("-"); + const min = Number(minRaw); + const max = maxRaw ? Number(maxRaw) : undefined; + range = { + price: { + min: Number.isFinite(min) ? min : 0, + ...(max !== undefined && Number.isFinite(max) ? { max } : {}), + }, + }; + } + + const pageNumber = typeof view.page === "string" ? Number(view.page) : Number.NaN; + const direction = view.direction === "prev" || view.direction === "backward" ? "prev" : "next"; + const page: ListingQuery["page"] = + Number.isInteger(pageNumber) && pageNumber > 0 + ? { mode: "offset", number: pageNumber } + : { + mode: "cursor", + cursor: typeof view.cursor === "string" ? view.cursor : undefined, + direction, + }; + + const text = typeof view.query === "string" ? view.query : ""; + let surface: ListingQuery["surface"]; + if (input.surface === "all") { + surface = { kind: "all" }; + } else if (input.surface === "search") { + if (!text) return null; + surface = { kind: "search", text }; + } else if (!input.slug) { + return null; + } else { + surface = { kind: input.surface, slug: input.slug }; + } + + return { + surface, + channel: input.channel, + locale: input.locale, + selections, + range, + sort: canonicalSortId(typeof view.sort === "string" ? view.sort : undefined), + page, + pageSize: input.pageSize ?? ProductsPerPage, + }; +} diff --git a/apps/web/src/lib/listing/registry.ts b/apps/web/src/lib/listing/registry.ts new file mode 100644 index 0000000..58cef4b --- /dev/null +++ b/apps/web/src/lib/listing/registry.ts @@ -0,0 +1,50 @@ +import "server-only"; + +import { LISTING_PROVIDER_REGISTRY, LISTING_PROVIDERS } from "@/config/listing-providers"; +import type { ListingSurfaceKind } from "@/lib/storefront/contract/listing"; +import { assertProviderSupportsSurface, type ListingProvider } from "@/lib/listing/provider"; + +const SURFACE_KINDS: readonly ListingSurfaceKind[] = ["all", "category", "collection", "search"]; + +/** + * `LISTING_PROVIDER_` swaps one surface for local runs, tests, and previews. + * Production on Vercel ignores it: the provider map in `src/config/listing-providers.ts` + * is the reviewed choice, and a stray env var must not serve fixture products. + */ +export function resolveListingProviderId(kind: ListingSurfaceKind): string { + const configured = LISTING_PROVIDERS[kind]; + const envName = `LISTING_PROVIDER_${kind.toUpperCase()}`; + const override = process.env[envName]?.trim().toLowerCase(); + if (!override) return configured; + if (process.env["VERCEL_ENV"] === "production") { + if (override !== configured) { + console.warn(`[listing] Ignoring ${envName}="${override}" on Vercel production; using ${configured}.`); + } + return configured; + } + if (override in LISTING_PROVIDER_REGISTRY) return override; + console.warn(`[listing] Unknown ${envName}="${override}"; using ${configured}.`); + return configured; +} + +export function getListingProvider(id: string): ListingProvider { + const registry: Record = LISTING_PROVIDER_REGISTRY; + const provider = registry[id]; + if (!provider) { + throw new Error( + `[listing] Unknown listing provider "${id}". Register it in src/config/listing-providers.ts.`, + ); + } + return provider; +} + +export function listingProviderFor(kind: ListingSurfaceKind): ListingProvider { + const provider = getListingProvider(resolveListingProviderId(kind)); + assertProviderSupportsSurface(provider, kind); + return provider; +} + +/** Fail at startup when a surface points at a provider that cannot serve it. */ +export function assertListingProviders(): void { + for (const kind of SURFACE_KINDS) listingProviderFor(kind); +} diff --git a/apps/web/src/lib/listing/testing.ts b/apps/web/src/lib/listing/testing.ts new file mode 100644 index 0000000..7c9327a --- /dev/null +++ b/apps/web/src/lib/listing/testing.ts @@ -0,0 +1,110 @@ +/** + * Listing provider contract suite. Test-only: import it from a provider's + * `contract.test.ts`, never from runtime code. + * + * describe("algolia listing provider", () => { + * runListingProviderContract(createAlgoliaListingProvider(stubTransport), { query }); + * }); + * + * Every call goes through `normalizeListingQuery`, the same path `loadListing` uses, + * so the suite checks what a shopper's URL actually reaches. + */ +import { expect, it } from "vitest"; + +import { normalizeListingQuery, type ListingProvider } from "@/lib/listing/provider"; +import { SORT_IDS, type ListingQuery, type ListingResult } from "@/lib/storefront/contract/listing"; + +export type ListingProviderContractCase = { + /** A first-page query the stub answers with more than one page of items. */ + query: ListingQuery; + /** A query whose transport fails. Default: `query` on channel `boom`. */ + failing?: ListingQuery; + /** + * A category or collection that does not exist. Default: `query` on category slug + * `missing`, when the provider serves categories. Search-only providers skip this. + */ + missing?: ListingQuery; +}; + +function ids(result: ListingResult | null): string[] { + return result?.items.map((item) => item.id) ?? []; +} + +export function runListingProviderContract( + provider: ListingProvider, + contractCase: ListingProviderContractCase, +) { + const { query } = contractCase; + const failing = contractCase.failing ?? { ...query, channel: "boom" }; + const missing = + contractCase.missing ?? + (provider.capabilities.surfaces.includes("category") + ? { ...query, surface: { kind: "category", slug: "missing" } } + : null); + const load = (next: ListingQuery) => provider.load(normalizeListingQuery(provider, next)); + + it("serves the surface default for a sort it did not declare", async () => { + const declared = provider.capabilities.sorts[query.surface.kind] ?? []; + const undeclared = SORT_IDS.find((sort) => !declared.includes(sort)); + if (!undeclared) return; + const result = await load({ ...query, sort: undeclared }); + expect(ids(result)).toEqual(ids(await load(query))); + }); + + it("serves the first page for a page in the other pagination mode", async () => { + const other: ListingQuery["page"] = + provider.capabilities.pagination === "cursor" + ? { mode: "offset", number: 2 } + : { mode: "cursor", direction: "next", cursor: "opaque" }; + const result = await load({ ...query, page: other }); + expect(ids(result)).toEqual(ids(await load(query))); + }); + + it("returns only sorts it declared for the surface", async () => { + const result = await load(query); + const declared = provider.capabilities.sorts[query.surface.kind] ?? []; + for (const sort of result?.sorts ?? []) expect(declared).toContain(sort); + }); + + it("marks selections and includes counts only when the provider says so", async () => { + const result = await load({ ...query, selections: { colors: ["blue"] } }); + expect(result).not.toBeNull(); + const colors = result?.facets.find((facet) => facet.id === "colors"); + expect(colors?.values.find((value) => value.value === "blue")?.selected).toBe(true); + for (const facet of result?.facets ?? []) { + for (const value of facet.values) { + if (provider.capabilities.facetCounts) expect(typeof value.count).toBe("number"); + else expect(value.count).toBeUndefined(); + } + } + }); + + it("returns null for an unknown slug and throws on transport failure", async () => { + if (missing) await expect(load(missing)).resolves.toBeNull(); + await expect(load(failing)).rejects.toThrow(); + }); + + it("returns the same first page after paging forward and back", async () => { + if (provider.capabilities.pagination === "offset") { + const first = await load({ ...query, page: { mode: "offset", number: 1 } }); + const second = await load({ ...query, page: { mode: "offset", number: 2 } }); + const back = await load({ ...query, page: { mode: "offset", number: 1 } }); + expect(second?.items.length).toBeGreaterThan(0); + expect(ids(back)).toEqual(ids(first)); + return; + } + const first = await load({ ...query, page: { mode: "cursor", direction: "next" } }); + const end = first?.page.mode === "cursor" ? first.page.endCursor : undefined; + const second = await load({ + ...query, + page: { mode: "cursor", direction: "next", cursor: end ?? undefined }, + }); + const start = second?.page.mode === "cursor" ? second.page.startCursor : undefined; + const back = await load({ + ...query, + page: { mode: "cursor", direction: "prev", cursor: start ?? undefined }, + }); + expect(second?.items.length).toBeGreaterThan(0); + expect(ids(back)).toEqual(ids(first)); + }); +} diff --git a/apps/web/src/lib/locale-display.test.ts b/apps/web/src/lib/locale-display.test.ts new file mode 100644 index 0000000..8125b91 --- /dev/null +++ b/apps/web/src/lib/locale-display.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vitest"; +import { getLocaleEndonym, getStorefrontLocaleOptions } from "./locale-display"; + +describe("getLocaleEndonym", () => { + it("returns endonyms in the language's own name", () => { + expect(getLocaleEndonym("en")).toBe("English"); + expect(getLocaleEndonym("de")).toBe("Deutsch"); + expect(getLocaleEndonym("pl")).toBe("polski"); + }); +}); + +describe("getStorefrontLocaleOptions", () => { + it("includes slug and label for each configured locale", () => { + const options = getStorefrontLocaleOptions(); + expect(options.length).toBeGreaterThanOrEqual(1); + expect(options[0]).toMatchObject({ + slug: expect.any(String), + label: expect.any(String), + }); + }); +}); diff --git a/apps/web/src/lib/locale-display.ts b/apps/web/src/lib/locale-display.ts new file mode 100644 index 0000000..4a0e9ed --- /dev/null +++ b/apps/web/src/lib/locale-display.ts @@ -0,0 +1,25 @@ +import { getStorefrontLocaleSlugs, LOCALE_DEFINITIONS, type LocaleSlug } from "@/config/locale"; + +export type LocaleSelectOption = { + slug: LocaleSlug; + /** Language name in its own language (endonym) — e.g. Deutsch, Polski, English */ + label: string; +}; + +/** + * Endonym for a locale slug — each language shown in its own language (W3C / global UX norm). + * Uses `htmlLang` (ISO 639-1) so "en" → English, not "American English". + */ +export function getLocaleEndonym(slug: LocaleSlug): string { + const { htmlLang } = LOCALE_DEFINITIONS[slug]; + const displayNames = new Intl.DisplayNames([htmlLang], { type: "language" }); + return displayNames.of(htmlLang) ?? slug; +} + +/** Configured storefront locales with display labels for pickers. */ +export function getStorefrontLocaleOptions(): LocaleSelectOption[] { + return getStorefrontLocaleSlugs().map((slug) => ({ + slug, + label: getLocaleEndonym(slug), + })); +} diff --git a/apps/web/src/lib/market-display.test.ts b/apps/web/src/lib/market-display.test.ts new file mode 100644 index 0000000..2c190d7 --- /dev/null +++ b/apps/web/src/lib/market-display.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest"; +import { enrichMarketOptions, getCurrencySymbol } from "./market-display"; + +describe("enrichMarketOptions", () => { + it("uses Saleor channel name for the market label", () => { + expect( + enrichMarketOptions([{ id: "1", name: "Channel PLN", slug: "channel-pln", currencyCode: "PLN" }]), + ).toEqual([ + { + id: "1", + name: "Channel PLN", + slug: "channel-pln", + currencyCode: "PLN", + displayLabel: "Channel PLN", + currencyHint: "PLN", + }, + ]); + }); + + it("falls back to currency code when name is empty", () => { + expect(enrichMarketOptions([{ id: "1", name: " ", slug: "uk", currencyCode: "GBP" }])).toEqual([ + { + id: "1", + name: " ", + slug: "uk", + currencyCode: "GBP", + displayLabel: "GBP", + currencyHint: undefined, + }, + ]); + }); +}); + +describe("getCurrencySymbol", () => { + it("returns a symbol for known currencies", () => { + expect(getCurrencySymbol("GBP", "en-GB")).toBe("£"); + expect(getCurrencySymbol("USD", "en-US")).toBe("$"); + }); +}); diff --git a/apps/web/src/lib/market-display.ts b/apps/web/src/lib/market-display.ts new file mode 100644 index 0000000..1b3cea9 --- /dev/null +++ b/apps/web/src/lib/market-display.ts @@ -0,0 +1,34 @@ +import type { ChannelSelectOption } from "@/config/channels"; + +export type MarketSelectOption = ChannelSelectOption & { + /** Saleor channel name, or currency code when name is missing */ + displayLabel: string; + /** Shown beside the label when a channel name is available */ + currencyHint?: string; +}; + +export function enrichMarketOptions(channels: ChannelSelectOption[]): MarketSelectOption[] { + return channels.map((channel) => { + const name = channel.name.trim(); + + return { + ...channel, + displayLabel: name || channel.currencyCode, + currencyHint: name ? channel.currencyCode : undefined, + }; + }); +} + +/** Narrow currency symbol for compact trigger labels. */ +export function getCurrencySymbol(currencyCode: string, localeBcp47: string): string { + try { + const parts = new Intl.NumberFormat(localeBcp47, { + style: "currency", + currency: currencyCode, + currencyDisplay: "narrowSymbol", + }).formatToParts(0); + return parts.find((part) => part.type === "currency")?.value ?? currencyCode; + } catch { + return currencyCode; + } +} diff --git a/apps/web/src/lib/menus/get-menu-data.ts b/apps/web/src/lib/menus/get-menu-data.ts new file mode 100644 index 0000000..7e24e67 --- /dev/null +++ b/apps/web/src/lib/menus/get-menu-data.ts @@ -0,0 +1,37 @@ +import "server-only"; + +import { MenuGetBySlugDocument, type MenuGetBySlugQuery } from "@/gql/graphql"; +import { graphqlLanguageCodeVariables } from "@/lib/graphql-locale"; +import { + cachedQuery, + FOOTER_MENU_SLUG, + NAVBAR_MENU_SLUG, + STOREFRONT_MENU_SLUGS, + type StorefrontMenuSlug, +} from "@/lib/saleor"; + +export type MenuItem = NonNullable["items"]>[number]>; + +async function getCachedMenuItems( + slug: StorefrontMenuSlug, + channel: string, + localeSlug: string, +): Promise { + "use cache"; + + const data = await cachedQuery(MenuGetBySlugDocument, { + profile: STOREFRONT_MENU_SLUGS[slug], + tag: { channel }, + variables: { slug, channel, ...graphqlLanguageCodeVariables(localeSlug) }, + }); + + return data.menu?.items ?? []; +} + +export async function getNavbarMenuItems(channel: string, localeSlug: string) { + return getCachedMenuItems(NAVBAR_MENU_SLUG, channel, localeSlug); +} + +export async function getFooterMenuItems(channel: string, localeSlug: string) { + return getCachedMenuItems(FOOTER_MENU_SLUG, channel, localeSlug); +} diff --git a/apps/web/src/lib/menus/menu-item-utils.test.ts b/apps/web/src/lib/menus/menu-item-utils.test.ts new file mode 100644 index 0000000..ee4b731 --- /dev/null +++ b/apps/web/src/lib/menus/menu-item-utils.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from "vitest"; +import { + getMenuItemChildren, + getMenuItemHref, + getMenuItemLabel, + hasMenuChildren, + isExternalMenuHref, +} from "./menu-item-utils"; +import type { MenuItem } from "./get-menu-data"; + +const baseItem = { + id: "1", + name: "Custom link", + level: 0, + category: null, + collection: null, + page: null, + url: null, + children: null, +} satisfies MenuItem; + +describe("menu-item-utils", () => { + it("resolves category href and label", () => { + const item: MenuItem = { + ...baseItem, + category: { id: "c1", slug: "apparel", name: "Apparel" }, + }; + + expect(getMenuItemLabel(item)).toBe("Apparel"); + expect(getMenuItemHref(item)).toBe("/categories/apparel"); + }); + + it("resolves collection and page links", () => { + expect( + getMenuItemHref({ + ...baseItem, + collection: { id: "col1", slug: "summer", name: "Summer" }, + }), + ).toBe("/collections/summer"); + + expect( + getMenuItemHref({ + ...baseItem, + page: { id: "p1", slug: "about", title: "About us" }, + }), + ).toBe("/pages/about"); + }); + + it("detects safe external urls", () => { + expect(isExternalMenuHref("https://saleor.io")).toBe(true); + expect(isExternalMenuHref("mailto:hello@example.com")).toBe(true); + expect(isExternalMenuHref("/products")).toBe(false); + expect(isExternalMenuHref("javascript:alert(1)")).toBe(false); + }); + + it("drops unsafe custom menu URLs", () => { + expect( + getMenuItemHref({ + ...baseItem, + url: "javascript:alert(1)", + }), + ).toBeNull(); + }); + + it("reads nested children", () => { + const child = { ...baseItem, id: "2", name: "Child" }; + const item: MenuItem = { ...baseItem, children: [child] }; + + expect(hasMenuChildren(item)).toBe(true); + expect(getMenuItemChildren(item)).toHaveLength(1); + }); +}); diff --git a/apps/web/src/lib/menus/menu-item-utils.ts b/apps/web/src/lib/menus/menu-item-utils.ts new file mode 100644 index 0000000..09b10be --- /dev/null +++ b/apps/web/src/lib/menus/menu-item-utils.ts @@ -0,0 +1,31 @@ +import type { MenuItem } from "@/lib/menus/get-menu-data"; +import { pickTranslatedName, pickTranslatedSlug, pickTranslatedTitle } from "@/lib/saleor-translations"; +import { isSafeExternalHref, isSafeMailtoHref, sanitizeNavHref } from "@/lib/url/safe-href"; + +export function getMenuItemLabel(item: MenuItem): string | null { + if (item.category?.name) return pickTranslatedName(item.category); + if (item.collection?.name) return pickTranslatedName(item.collection); + if (item.page?.title) return pickTranslatedTitle(item.page); + if (item.name) return pickTranslatedName(item); + return null; +} + +export function getMenuItemHref(item: MenuItem): string | null { + if (item.category?.slug) return `/categories/${pickTranslatedSlug(item.category)}`; + if (item.collection?.slug) return `/collections/${pickTranslatedSlug(item.collection)}`; + if (item.page?.slug) return `/pages/${pickTranslatedSlug(item.page)}`; + if (item.url) return sanitizeNavHref(item.url); + return null; +} + +export function getMenuItemChildren(item: MenuItem): MenuItem[] { + return item.children ?? []; +} + +export function hasMenuChildren(item: MenuItem): boolean { + return getMenuItemChildren(item).length > 0; +} + +export function isExternalMenuHref(href: string): boolean { + return isSafeExternalHref(href) || isSafeMailtoHref(href); +} diff --git a/apps/web/src/lib/menus/serialize-menu-for-nav.test.ts b/apps/web/src/lib/menus/serialize-menu-for-nav.test.ts new file mode 100644 index 0000000..3dc0462 --- /dev/null +++ b/apps/web/src/lib/menus/serialize-menu-for-nav.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from "vitest"; +import { hasNavMenuChildren, serializeMenuForNav } from "./serialize-menu-for-nav"; +import type { MenuItem } from "./get-menu-data"; + +const baseItem = { + id: "1", + name: "Shop", + level: 0, + category: null, + collection: null, + page: null, + url: null, + children: null, +} satisfies MenuItem; + +describe("serializeMenuForNav", () => { + it("maps nested items to minimal nav tree", () => { + const items: MenuItem[] = [ + { + ...baseItem, + category: { id: "c1", slug: "apparel", name: "Apparel" }, + children: [ + { + ...baseItem, + id: "2", + category: { id: "c2", slug: "shirts", name: "Shirts" }, + children: [ + { + ...baseItem, + id: "3", + collection: { id: "col1", slug: "tees", name: "Tees" }, + }, + ], + }, + ], + }, + ]; + + const nav = serializeMenuForNav(items); + + expect(nav).toHaveLength(1); + expect(nav[0]?.label).toBe("Apparel"); + expect(nav[0]?.href).toBe("/categories/apparel"); + expect(nav[0]?.children?.[0]?.label).toBe("Shirts"); + expect(nav[0]?.children?.[0]?.children?.[0]?.href).toBe("/collections/tees"); + expect(hasNavMenuChildren(nav[0]!)).toBe(true); + }); + + it("drops items without a resolvable label", () => { + expect(serializeMenuForNav([{ ...baseItem, name: "" }])).toHaveLength(0); + }); +}); diff --git a/apps/web/src/lib/menus/serialize-menu-for-nav.ts b/apps/web/src/lib/menus/serialize-menu-for-nav.ts new file mode 100644 index 0000000..537c5d6 --- /dev/null +++ b/apps/web/src/lib/menus/serialize-menu-for-nav.ts @@ -0,0 +1,36 @@ +import type { MenuItem } from "@/lib/menus/get-menu-data"; +import { getMenuItemHref, getMenuItemLabel, isExternalMenuHref } from "@/lib/menus/menu-item-utils"; + +export { isExternalMenuHref as isExternalNavHref }; + +/** Minimal menu tree for client nav — avoids serializing full Saleor MenuItem payloads. */ +export type NavMenuItem = { + id: string; + label: string; + href: string | null; + children?: NavMenuItem[]; +}; + +export function serializeMenuForNav(items: MenuItem[]): NavMenuItem[] { + return items + .map((item) => { + const label = getMenuItemLabel(item); + if (!label) { + return null; + } + + const children = item.children?.length ? serializeMenuForNav(item.children) : undefined; + + return { + id: item.id, + label, + href: getMenuItemHref(item), + ...(children && children.length > 0 ? { children } : {}), + }; + }) + .filter((item): item is NavMenuItem => item !== null); +} + +export function hasNavMenuChildren(item: NavMenuItem): boolean { + return (item.children?.length ?? 0) > 0; +} diff --git a/apps/web/src/lib/order-status.ts b/apps/web/src/lib/order-status.ts new file mode 100644 index 0000000..c289fbf --- /dev/null +++ b/apps/web/src/lib/order-status.ts @@ -0,0 +1,17 @@ +export type CustomerOrderStatusKey = "UNFULFILLED" | "UNCONFIRMED" | "PARTIALLY_FULFILLED" | "FULFILLED"; + +const CUSTOMER_ORDER_STATUS_KEYS: Record = { + UNFULFILLED: "UNFULFILLED", + UNCONFIRMED: "UNCONFIRMED", + PARTIALLY_FULFILLED: "PARTIALLY_FULFILLED", + FULFILLED: "FULFILLED", +}; + +export function getCustomerOrderStatusLabel( + t: (key: CustomerOrderStatusKey) => string, + status: string, + statusDisplay: string, +): string { + const key = CUSTOMER_ORDER_STATUS_KEYS[status]; + return key ? t(key) : statusDisplay; +} diff --git a/apps/web/src/lib/order-view/classify.test.ts b/apps/web/src/lib/order-view/classify.test.ts new file mode 100644 index 0000000..d083b1a --- /dev/null +++ b/apps/web/src/lib/order-view/classify.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("server-only", () => ({})); + +import { classifyOrderViewKey, isSaleorOrderGlobalId } from "./classify"; + +describe("classifyOrderViewKey", () => { + it("classifies HMAC tokens", () => { + expect(classifyOrderViewKey("ov1.abc.def")).toEqual({ kind: "hmac", token: "ov1.abc.def" }); + }); + + it("classifies numeric order numbers", () => { + expect(classifyOrderViewKey("1042")).toEqual({ kind: "number", number: "1042" }); + }); + + it("classifies Saleor global ids as orderId", () => { + const id = Buffer.from("Order:1", "utf8").toString("base64"); + expect(isSaleorOrderGlobalId(id)).toBe(true); + expect(classifyOrderViewKey(id)).toEqual({ kind: "orderId", orderId: id }); + }); +}); diff --git a/apps/web/src/lib/order-view/classify.ts b/apps/web/src/lib/order-view/classify.ts new file mode 100644 index 0000000..b595fd9 --- /dev/null +++ b/apps/web/src/lib/order-view/classify.ts @@ -0,0 +1,29 @@ +import { isOrderViewHmacToken } from "./token"; + +export type ClassifiedOrderViewKey = + | { kind: "hmac"; token: string } + | { kind: "orderId"; orderId: string } + | { kind: "number"; number: string }; + +export function isSaleorOrderGlobalId(value: string): boolean { + try { + const decoded = Buffer.from(value, "base64").toString("utf8"); + return decoded.startsWith("Order:"); + } catch { + return false; + } +} + +export function classifyOrderViewKey(raw: string): ClassifiedOrderViewKey { + const key = raw.trim(); + + if (isOrderViewHmacToken(key)) { + return { kind: "hmac", token: key }; + } + + if (/^\d+$/.test(key)) { + return { kind: "number", number: key }; + } + + return { kind: "orderId", orderId: key }; +} diff --git a/apps/web/src/lib/order-view/constants.ts b/apps/web/src/lib/order-view/constants.ts new file mode 100644 index 0000000..5e4e2e0 --- /dev/null +++ b/apps/web/src/lib/order-view/constants.ts @@ -0,0 +1,5 @@ +export const ORDER_VIEW_TOKEN_PREFIX = "ov1"; +export const ORDER_VIEW_COOKIE_NAME = "paper_order_view"; +export const ORDER_VIEW_TOKEN_TTL_MS = 14 * 24 * 60 * 60 * 1000; +export const ORDER_VIEW_COOKIE_MAX_AGE_SECONDS = 60 * 60; +export const ORDER_VIEW_FIND_RATE_LIMIT = { limit: 5, windowMs: 15 * 60 * 1000 } as const; diff --git a/apps/web/src/lib/order-view/cookie.ts b/apps/web/src/lib/order-view/cookie.ts new file mode 100644 index 0000000..aa12ca4 --- /dev/null +++ b/apps/web/src/lib/order-view/cookie.ts @@ -0,0 +1,38 @@ +import "server-only"; +import { cookies } from "next/headers"; + +import { ORDER_VIEW_COOKIE_MAX_AGE_SECONDS, ORDER_VIEW_COOKIE_NAME } from "./constants"; +import { verifyOrderViewToken } from "./token"; + +function shouldUseHttps(): boolean { + return ( + process.env.NEXT_PUBLIC_STOREFRONT_URL?.startsWith("https") === true || + Boolean(process.env.NEXT_PUBLIC_VERCEL_URL) + ); +} + +export async function setOrderViewCookie(token: string): Promise { + (await cookies()).set(ORDER_VIEW_COOKIE_NAME, token, { + httpOnly: true, + sameSite: "lax", + secure: shouldUseHttps(), + path: "/", + maxAge: ORDER_VIEW_COOKIE_MAX_AGE_SECONDS, + }); +} + +export async function readOrderViewCookie(): Promise { + try { + return (await cookies()).get(ORDER_VIEW_COOKIE_NAME)?.value ?? null; + } catch { + return null; + } +} + +export async function readVerifiedOrderIdFromCookie(): Promise { + const token = await readOrderViewCookie(); + if (!token) { + return null; + } + return verifyOrderViewToken(token)?.orderId ?? null; +} diff --git a/apps/web/src/lib/order-view/email.test.ts b/apps/web/src/lib/order-view/email.test.ts new file mode 100644 index 0000000..19086f5 --- /dev/null +++ b/apps/web/src/lib/order-view/email.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; + +import { emailsMatch, normalizeOrderEmail } from "./email"; + +describe("emailsMatch", () => { + it("matches ignoring case and surrounding space", () => { + expect(emailsMatch("Ada@Shop.example ", "ada@shop.example")).toBe(true); + expect(normalizeOrderEmail(" Ada@Shop.example ")).toBe("ada@shop.example"); + }); + + it("rejects a different email", () => { + expect(emailsMatch("ada@shop.example", "other@shop.example")).toBe(false); + }); + + it("rejects an empty stored email", () => { + expect(emailsMatch(null, "ada@shop.example")).toBe(false); + expect(emailsMatch("", "ada@shop.example")).toBe(false); + }); +}); diff --git a/apps/web/src/lib/order-view/email.ts b/apps/web/src/lib/order-view/email.ts new file mode 100644 index 0000000..aa08d72 --- /dev/null +++ b/apps/web/src/lib/order-view/email.ts @@ -0,0 +1,22 @@ +import { timingSafeEqual } from "crypto"; + +export function normalizeOrderEmail(value: string): string { + return value.trim().toLowerCase(); +} + +/** + * Constant-time-ish compare. Always hashes both sides to the same length so a miss + * does not confirm that the order exists. + */ +export function emailsMatch(stored: string | null | undefined, submitted: string): boolean { + const left = Buffer.from(normalizeOrderEmail(stored ?? "\0"), "utf8"); + const right = Buffer.from(normalizeOrderEmail(submitted), "utf8"); + const size = Math.max(left.length, right.length, 1); + const a = Buffer.alloc(size); + const b = Buffer.alloc(size); + left.copy(a); + right.copy(b); + const equalBytes = timingSafeEqual(a, b); + const equalLength = left.length === right.length; + return Boolean(stored) && equalBytes && equalLength; +} diff --git a/apps/web/src/lib/order-view/index.ts b/apps/web/src/lib/order-view/index.ts new file mode 100644 index 0000000..7d5c526 --- /dev/null +++ b/apps/web/src/lib/order-view/index.ts @@ -0,0 +1,17 @@ +import "server-only"; + +export { ORDER_VIEW_COOKIE_NAME, ORDER_VIEW_FIND_RATE_LIMIT, ORDER_VIEW_TOKEN_PREFIX } from "./constants"; +export { classifyOrderViewKey, isSaleorOrderGlobalId } from "./classify"; +export type { ClassifiedOrderViewKey } from "./classify"; +export { parseOrderNumber } from "./parse-number"; +export { readOrderViewCookie, readVerifiedOrderIdFromCookie, setOrderViewCookie } from "./cookie"; +export { emailsMatch, normalizeOrderEmail } from "./email"; +export { billingCityCountry, sanitizeOrderForClient } from "./sanitize"; +export type { OrderViewAccess } from "./sanitize"; +export { + inspectOrderViewToken, + isOrderViewHmacToken, + signOrderViewToken, + verifyOrderViewToken, +} from "./token"; +export type { InspectedOrderViewToken } from "./token"; diff --git a/apps/web/src/lib/order-view/parse-number.test.ts b/apps/web/src/lib/order-view/parse-number.test.ts new file mode 100644 index 0000000..907d13f --- /dev/null +++ b/apps/web/src/lib/order-view/parse-number.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest"; + +import { parseOrderNumber } from "./parse-number"; + +describe("parseOrderNumber", () => { + it("accepts a plain Saleor order number", () => { + expect(parseOrderNumber("848")).toBe(848); + }); + + it("rejects trailing junk that parseInt would accept", () => { + expect(parseOrderNumber("848abc")).toBeNull(); + expect(parseOrderNumber("848.0")).toBeNull(); + }); + + it("rejects zero, signs, and blanks", () => { + expect(parseOrderNumber("0")).toBeNull(); + expect(parseOrderNumber("+848")).toBeNull(); + expect(parseOrderNumber(" ")).toBeNull(); + }); +}); diff --git a/apps/web/src/lib/order-view/parse-number.ts b/apps/web/src/lib/order-view/parse-number.ts new file mode 100644 index 0000000..f44b973 --- /dev/null +++ b/apps/web/src/lib/order-view/parse-number.ts @@ -0,0 +1,14 @@ +/** Saleor `order.number` is digits only. Reject `848abc` / `848.0` — `parseInt` would accept those. */ +export function parseOrderNumber(value: string): number | null { + const trimmed = value.trim(); + if (!/^\d+$/.test(trimmed)) { + return null; + } + + const parsed = Number.parseInt(trimmed, 10); + if (!Number.isSafeInteger(parsed) || parsed < 1) { + return null; + } + + return parsed; +} diff --git a/apps/web/src/lib/order-view/sanitize.test.ts b/apps/web/src/lib/order-view/sanitize.test.ts new file mode 100644 index 0000000..9222fd8 --- /dev/null +++ b/apps/web/src/lib/order-view/sanitize.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; + +import { billingCityCountry, sanitizeOrderForClient } from "./sanitize"; + +const order = { + id: "T3JkZXI6MQ==", + number: "1042", + userEmail: "ada@shop.example", + shippingAddress: { streetAddress1: "1 Main", city: "Paris" }, + billingAddress: { city: "Lyon", country: { country: "France" } }, + deliveryMethod: { name: "DHL" }, + voucher: { code: "SAVE10" }, + fulfillments: [{ trackingNumber: "1Z999" }], + isPaid: true, + chargeStatus: "FULLY_CHARGED", + authorizeStatus: "FULLY_AUTHORIZED", + totalBalance: { amount: 0, currency: "EUR" }, + totalCaptured: { amount: 10, currency: "EUR" }, + total: { gross: { amount: 10, currency: "EUR" } }, +}; + +describe("sanitizeOrderForClient", () => { + it("strips PII on the public view and keeps totals", () => { + const publicOrder = sanitizeOrderForClient(order, "public"); + expect(publicOrder.userEmail).toBeNull(); + expect(publicOrder.shippingAddress).toBeNull(); + expect(publicOrder.billingAddress).toBeNull(); + expect(publicOrder.deliveryMethod).toBeNull(); + expect(publicOrder.voucher).toBeNull(); + expect(publicOrder.fulfillments).toEqual([]); + expect(publicOrder.isPaid).toBeNull(); + expect(publicOrder.chargeStatus).toBeNull(); + expect(publicOrder.totalCaptured).toBeNull(); + expect(publicOrder.total).toEqual(order.total); + expect(publicOrder.number).toBe("1042"); + }); + + it("keeps addresses when verified but drops the voucher code", () => { + const verified = sanitizeOrderForClient(order, "verified"); + expect(verified.userEmail).toBe("ada@shop.example"); + expect(verified.shippingAddress).toEqual(order.shippingAddress); + expect(verified.voucher).toBeNull(); + }); +}); + +describe("billingCityCountry", () => { + it("joins city and country", () => { + expect(billingCityCountry({ city: "Lyon", country: { country: "France" } })).toBe("Lyon, France"); + }); +}); diff --git a/apps/web/src/lib/order-view/sanitize.ts b/apps/web/src/lib/order-view/sanitize.ts new file mode 100644 index 0000000..6a56bdb --- /dev/null +++ b/apps/web/src/lib/order-view/sanitize.ts @@ -0,0 +1,57 @@ +export type OrderViewAccess = "public" | "verified"; + +type OrderViewSanitizable = { + userEmail?: string | null; + shippingAddress?: unknown; + billingAddress?: unknown; + deliveryMethod?: unknown; + voucher?: { code?: string | null } | null; + fulfillments?: unknown; + isPaid?: unknown; + chargeStatus?: unknown; + authorizeStatus?: unknown; + totalBalance?: unknown; + totalCaptured?: unknown; +}; + +/** + * Strip PII before the order crosses to the client. Public = shop window + * (lines + totals + status). Verified still drops voucher codes (cash). + */ +export function sanitizeOrderForClient(order: T, access: OrderViewAccess): T { + if (access === "public") { + return { + ...order, + userEmail: null, + shippingAddress: null, + billingAddress: null, + deliveryMethod: null, + voucher: null, + fulfillments: [], + isPaid: null, + chargeStatus: null, + authorizeStatus: null, + totalBalance: null, + totalCaptured: null, + }; + } + + return { + ...order, + voucher: null, + }; +} + +export function billingCityCountry( + address: { + city?: string | null; + country?: { country?: string | null } | null; + } | null, +): string | null { + if (!address) { + return null; + } + + const parts = [address.city, address.country?.country].filter(Boolean); + return parts.length > 0 ? parts.join(", ") : null; +} diff --git a/apps/web/src/lib/order-view/secret.ts b/apps/web/src/lib/order-view/secret.ts new file mode 100644 index 0000000..c4645cd --- /dev/null +++ b/apps/web/src/lib/order-view/secret.ts @@ -0,0 +1,16 @@ +import "server-only"; + +/** HMAC secret for guest order-view tokens. Fail closed in production. */ +export function getOrderViewSecret(): string { + const secret = process.env.ORDER_VIEW_SECRET || process.env.REVALIDATE_SECRET; + + if (secret) { + return secret; + } + + if (process.env.NODE_ENV === "production") { + throw new Error("ORDER_VIEW_SECRET or REVALIDATE_SECRET is required to sign order-view tokens"); + } + + return "dev-order-view-secret-not-for-production"; +} diff --git a/apps/web/src/lib/order-view/token.test.ts b/apps/web/src/lib/order-view/token.test.ts new file mode 100644 index 0000000..aa48a94 --- /dev/null +++ b/apps/web/src/lib/order-view/token.test.ts @@ -0,0 +1,45 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.mock("server-only", () => ({})); + +import { inspectOrderViewToken, signOrderViewToken, verifyOrderViewToken } from "./token"; + +const ORIGINAL_SECRET = process.env.ORDER_VIEW_SECRET; +const ORIGINAL_REVALIDATE = process.env.REVALIDATE_SECRET; + +afterEach(() => { + process.env.ORDER_VIEW_SECRET = ORIGINAL_SECRET; + process.env.REVALIDATE_SECRET = ORIGINAL_REVALIDATE; +}); + +describe("order-view token", () => { + it("round-trips a signed token", () => { + process.env.ORDER_VIEW_SECRET = "test-secret-at-least-32-characters!!"; + const token = signOrderViewToken("T3JkZXI6MQ==", 60_000, 1_000); + expect(token.startsWith("ov1.")).toBe(true); + expect(verifyOrderViewToken(token, 1_000)).toEqual({ orderId: "T3JkZXI6MQ==" }); + }); + + it("rejects a tampered mac", () => { + process.env.ORDER_VIEW_SECRET = "test-secret-at-least-32-characters!!"; + const token = signOrderViewToken("T3JkZXI6MQ==", 60_000, 1_000); + const parts = token.split("."); + parts[2] = "a".repeat(parts[2].length); + expect(verifyOrderViewToken(parts.join("."), 1_000)).toBeNull(); + }); + + it("rejects an expired token for elevation but still yields the order id", () => { + process.env.ORDER_VIEW_SECRET = "test-secret-at-least-32-characters!!"; + const token = signOrderViewToken("T3JkZXI6MQ==", 1_000, 1_000); + expect(verifyOrderViewToken(token, 3_000)).toBeNull(); + expect(inspectOrderViewToken(token, 3_000)).toEqual({ + status: "expired", + orderId: "T3JkZXI6MQ==", + }); + }); + + it("rejects a Saleor order id as a token", () => { + process.env.ORDER_VIEW_SECRET = "test-secret-at-least-32-characters!!"; + expect(verifyOrderViewToken("T3JkZXI6MQ==")).toBeNull(); + }); +}); diff --git a/apps/web/src/lib/order-view/token.ts b/apps/web/src/lib/order-view/token.ts new file mode 100644 index 0000000..f50add1 --- /dev/null +++ b/apps/web/src/lib/order-view/token.ts @@ -0,0 +1,63 @@ +import "server-only"; +import { createHmac, timingSafeEqual } from "crypto"; + +import { ORDER_VIEW_TOKEN_PREFIX, ORDER_VIEW_TOKEN_TTL_MS } from "./constants"; +import { getOrderViewSecret } from "./secret"; + +export type InspectedOrderViewToken = + | { status: "valid"; orderId: string } + | { status: "expired"; orderId: string } + | { status: "invalid" }; + +export function signOrderViewToken( + orderId: string, + ttlMs: number = ORDER_VIEW_TOKEN_TTL_MS, + now: number = Date.now(), +): string { + const payload = Buffer.from(JSON.stringify({ id: orderId, exp: now + ttlMs }), "utf8").toString( + "base64url", + ); + const mac = createHmac("sha256", getOrderViewSecret()).update(payload).digest("base64url"); + return `${ORDER_VIEW_TOKEN_PREFIX}.${payload}.${mac}`; +} + +export function inspectOrderViewToken(token: string, now: number = Date.now()): InspectedOrderViewToken { + const parts = token.split("."); + if (parts.length !== 3 || parts[0] !== ORDER_VIEW_TOKEN_PREFIX) { + return { status: "invalid" }; + } + + const [, payload, mac] = parts; + const expected = createHmac("sha256", getOrderViewSecret()).update(payload).digest("base64url"); + + const macBytes = Buffer.from(mac); + const expectedBytes = Buffer.from(expected); + if (macBytes.length !== expectedBytes.length || !timingSafeEqual(macBytes, expectedBytes)) { + return { status: "invalid" }; + } + + try { + const data = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as { + id?: unknown; + exp?: unknown; + }; + if (typeof data.id !== "string" || data.id.length === 0 || typeof data.exp !== "number") { + return { status: "invalid" }; + } + if (now > data.exp) { + return { status: "expired", orderId: data.id }; + } + return { status: "valid", orderId: data.id }; + } catch { + return { status: "invalid" }; + } +} + +export function verifyOrderViewToken(token: string, now: number = Date.now()): { orderId: string } | null { + const inspected = inspectOrderViewToken(token, now); + return inspected.status === "valid" ? { orderId: inspected.orderId } : null; +} + +export function isOrderViewHmacToken(value: string): boolean { + return value.startsWith(`${ORDER_VIEW_TOKEN_PREFIX}.`); +} diff --git a/apps/web/src/lib/pricing.ts b/apps/web/src/lib/pricing.ts new file mode 100644 index 0000000..0ff7243 --- /dev/null +++ b/apps/web/src/lib/pricing.ts @@ -0,0 +1,117 @@ +/** + * Shared pricing utilities for discount calculations. + * Used by PDP, PLP, variant selection, cart, and other pricing-related components. + * + * SINGLE SOURCE OF TRUTH for all discount/sale detection logic. + */ + +export interface PriceInfo { + amount?: number | null; + currency?: string | null; +} + +export interface DiscountInfo { + isOnSale: boolean; + discountPercent: number | null; +} + +export interface PriceRange { + start?: { gross?: { amount?: number | null } | null } | null; + stop?: { gross?: { amount?: number | null } | null } | null; +} + +/** + * Check if a price pair represents a discount. + * Uses typeof to handle $0 prices correctly (0 is falsy in JS). + */ +export function hasDiscount( + currentPrice: number | null | undefined, + undiscountedPrice: number | null | undefined, +): boolean { + return ( + typeof undiscountedPrice === "number" && + typeof currentPrice === "number" && + undiscountedPrice > currentPrice + ); +} + +/** + * Calculate discount percentage from price and undiscounted price. + * Returns 0 if no discount or invalid prices. + */ +export function calculateDiscountPercent( + currentPrice: number | null | undefined, + undiscountedPrice: number | null | undefined, +): number { + if (!hasDiscount(currentPrice, undiscountedPrice)) return 0; + // TypeScript knows these are numbers after hasDiscount check + return Math.round(((undiscountedPrice! - currentPrice!) / undiscountedPrice!) * 100); +} + +/** + * Get complete discount info from pricing data. + * Useful for components that need both the flag and percentage. + */ +export function getDiscountInfo( + currentPrice: number | null | undefined, + undiscountedPrice: number | null | undefined, +): DiscountInfo { + const isOnSale = hasDiscount(currentPrice, undiscountedPrice); + const discountPercent = isOnSale ? calculateDiscountPercent(currentPrice, undiscountedPrice) : null; + return { isOnSale, discountPercent }; +} + +/** + * Get max discount info across a list of items with pricing. + * Useful for showing "up to X% off" on variant options. + */ +export function getMaxDiscountInfo( + items: T[], + getPrices: (item: T) => { current: number | null | undefined; undiscounted: number | null | undefined }, +): DiscountInfo { + let hasAnyDiscount = false; + let maxPercent = 0; + + for (const item of items) { + const { current, undiscounted } = getPrices(item); + if (hasDiscount(current, undiscounted)) { + hasAnyDiscount = true; + const percent = calculateDiscountPercent(current, undiscounted); + if (percent > maxPercent) maxPercent = percent; + } + } + + return { + isOnSale: hasAnyDiscount, + discountPercent: hasAnyDiscount ? maxPercent : null, + }; +} + +/** + * Check if ANY variant in a product is on sale using price ranges. + * + * For PLP product cards where we only have aggregated price ranges (not per-variant pricing). + * Checks both start (cheapest) and stop (most expensive) to catch discounts on any variant. + * + * @example + * // Variant A: $50 -> $30 (on sale), Variant B: $20 -> $20 (not on sale) + * // priceRange: { start: $20, stop: $30 } + * // priceRangeUndiscounted: { start: $20, stop: $50 } + * // Result: true (because stop shows a discount) + */ +export function hasDiscountInPriceRange( + priceRange: PriceRange | null | undefined, + priceRangeUndiscounted: PriceRange | null | undefined, +): boolean { + const startPrice = priceRange?.start?.gross?.amount; + const stopPrice = priceRange?.stop?.gross?.amount; + const undiscountedStart = priceRangeUndiscounted?.start?.gross?.amount; + const undiscountedStop = priceRangeUndiscounted?.stop?.gross?.amount; + + // Check if cheapest variant is on sale + const hasStartDiscount = hasDiscount(startPrice, undiscountedStart); + // Check if most expensive variant is on sale + const hasStopDiscount = hasDiscount(stopPrice, undiscountedStop); + + return hasStartDiscount || hasStopDiscount; +} diff --git a/apps/web/src/lib/public-asset-cache.data.mjs b/apps/web/src/lib/public-asset-cache.data.mjs new file mode 100644 index 0000000..15e7f59 --- /dev/null +++ b/apps/web/src/lib/public-asset-cache.data.mjs @@ -0,0 +1,55 @@ +/** + * Browser Cache-Control for same-origin files under `/public`. + * + * Next.js defaults unmatched responses to `public, max-age=0, must-revalidate` + * (document caching). A hero video that misses this list is re-downloaded on + * every visit and billed as Fast Data Transfer. + * + * Keep an allowlist — a catch-all `*.*` would also pin `/sitemap.xml` and + * `/robots.txt` for a month if those App Router routes are added later. + * + * Catalog and CMS media should not live in `/public`: serve them from Saleor's + * CDN (see the `ui-images` rule). This list is the guardrail for leftovers. + */ + +export const PUBLIC_ASSET_FILE_EXTENSIONS = [ + "ico", + "png", + "jpg", + "jpeg", + "gif", + "svg", + "webp", + "avif", + "woff", + "woff2", + "ttf", + "otf", + "eot", + "webmanifest", + "mp3", + "ogg", + "wav", + "mp4", + "webm", + "mov", + "m4v", +]; + +/** 30 days fresh, then stale-while-revalidate for a year. */ +export const PUBLIC_ASSET_CACHE_CONTROL = "public, max-age=2592000, stale-while-revalidate=31536000"; + +/** `headers().source` for `next.config.js` — path-to-regexp, not a JS RegExp. */ +export function publicAssetCacheHeaderSource() { + return `/(.*)\\.(${PUBLIC_ASSET_FILE_EXTENSIONS.join("|")})`; +} + +/** Same membership test as the header source: last path segment's extension. */ +export function isPublicAssetCachePath(pathname) { + const base = (pathname.split("?")[0] ?? "").toLowerCase(); + const slash = base.lastIndexOf("/"); + const filename = slash === -1 ? base : base.slice(slash + 1); + const dot = filename.lastIndexOf("."); + if (dot <= 0 || dot === filename.length - 1) return false; + return PUBLIC_ASSET_FILE_EXTENSIONS.includes(filename.slice(dot + 1)); +} diff --git a/apps/web/src/lib/public-asset-cache.test.ts b/apps/web/src/lib/public-asset-cache.test.ts new file mode 100644 index 0000000..a4bb404 --- /dev/null +++ b/apps/web/src/lib/public-asset-cache.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import { + PUBLIC_ASSET_CACHE_CONTROL, + PUBLIC_ASSET_FILE_EXTENSIONS, + isPublicAssetCachePath, + publicAssetCacheHeaderSource, +} from "./public-asset-cache.data.mjs"; + +describe("public asset browser cache", () => { + it("caches same-origin videos so a hero loop is not billed as FDT on every visit", () => { + for (const path of ["/videos/hero.mp4", "/hero.webm", "/promo.MOV", "/clip.m4v"]) { + expect(isPublicAssetCachePath(path), path).toBe(true); + } + }); + + it("caches the public-folder types Paper already ships", () => { + expect(isPublicAssetCachePath("/logo.svg")).toBe(true); + expect(isPublicAssetCachePath("/site.webmanifest")).toBe(true); + expect(isPublicAssetCachePath("/android-chrome-192x192.png")).toBe(true); + }); + + it("does not treat documents or app routes as public assets", () => { + for (const path of ["/en/us", "/api/og", "/sitemap.xml", "/robots.txt", "/favicon", "/"]) { + expect(isPublicAssetCachePath(path), path).toBe(false); + } + }); + + it("header source enumerates every allowlisted extension", () => { + const source = publicAssetCacheHeaderSource(); + expect(source.startsWith("/(.*)\\.(")).toBe(true); + for (const ext of PUBLIC_ASSET_FILE_EXTENSIONS) { + expect(source).toContain(ext); + } + }); + + it("uses a month-long browser TTL, not document caching", () => { + expect(PUBLIC_ASSET_CACHE_CONTROL).toContain("max-age=2592000"); + expect(PUBLIC_ASSET_CACHE_CONTROL).not.toContain("max-age=0"); + }); +}); diff --git a/apps/web/src/lib/saleor-connection.ts b/apps/web/src/lib/saleor-connection.ts new file mode 100644 index 0000000..a600281 --- /dev/null +++ b/apps/web/src/lib/saleor-connection.ts @@ -0,0 +1,11 @@ +/** + * Whether this storefront is connected to a Saleor store. + * + * A product built from this baseline deploys before its owner has a Saleor + * store: with no NEXT_PUBLIC_SALEOR_API_URL at build time, the storefront + * has no channels, every storefront path redirects to `/`, and `/` says how + * to connect one. Nothing calls Saleor until it is set. + */ +export const saleorApiUrl: string | null = process.env.NEXT_PUBLIC_SALEOR_API_URL?.trim() || null; + +export const isSaleorConnected: boolean = saleorApiUrl !== null; diff --git a/apps/web/src/lib/saleor-translations.test.ts b/apps/web/src/lib/saleor-translations.test.ts new file mode 100644 index 0000000..289dd65 --- /dev/null +++ b/apps/web/src/lib/saleor-translations.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from "vitest"; +import { pickTranslatedName, pickTranslatedSlug, withTranslatedProductFields } from "./saleor-translations"; + +describe("pickTranslatedName", () => { + it("prefers translation over default name", () => { + expect( + pickTranslatedName({ + name: "Hoodie", + translation: { name: "Bluza" }, + }), + ).toBe("Bluza"); + }); + + it("falls back to default name", () => { + expect( + pickTranslatedName({ + name: "Hoodie", + translation: null, + }), + ).toBe("Hoodie"); + }); +}); + +describe("pickTranslatedSlug", () => { + it("prefers translated slug for URLs", () => { + expect( + pickTranslatedSlug({ + slug: "hoodie", + translation: { slug: "bluza" }, + }), + ).toBe("bluza"); + }); + + it("falls back to primary slug when translation slug is empty", () => { + expect( + pickTranslatedSlug({ + slug: "hoodie", + translation: { slug: "" }, + }), + ).toBe("hoodie"); + }); +}); + +describe("withTranslatedProductFields", () => { + it("merges product and category translations without overwriting primary slug", () => { + const product = withTranslatedProductFields({ + name: "Hoodie", + slug: "hoodie", + translation: { name: "Bluza", slug: "bluza" }, + category: { + name: "Apparel", + slug: "apparel", + translation: { name: "Odzież", slug: "odziez" }, + }, + variants: [{ name: "M", translation: { name: "Średni" } }], + }); + + expect(product.name).toBe("Bluza"); + expect(product.slug).toBe("hoodie"); + expect(pickTranslatedSlug(product)).toBe("bluza"); + expect(product.category?.name).toBe("Odzież"); + expect(product.variants?.[0]?.name).toBe("Średni"); + }); +}); diff --git a/apps/web/src/lib/saleor-translations.ts b/apps/web/src/lib/saleor-translations.ts new file mode 100644 index 0000000..0182e3a --- /dev/null +++ b/apps/web/src/lib/saleor-translations.ts @@ -0,0 +1,165 @@ +/** + * Pick Saleor translation fields with fallback to the default (channel) language. + */ + +type TranslationRecord = Record | null | undefined; + +export function pickTranslatedField( + translation: TranslationRecord, + field: string, + fallback: string | null | undefined, +): string | null | undefined { + const value = translation?.[field]; + if (typeof value === "string" && value.trim().length > 0) { + return value; + } + return fallback; +} + +export function pickTranslatedName(entity: { + name: string; + translation?: { name?: string | null } | null; +}): string { + return pickTranslatedField(entity.translation, "name", entity.name) ?? entity.name; +} + +/** + * Locale-canonical catalog URL slug. Keeps `entity.slug` (primary) untouched for + * cache tags / webhooks — use this only when building browse paths. + * + * @see docs/adr/0004-translatable-slugs.md + */ +export function pickTranslatedSlug(entity: { + slug: string; + translation?: { slug?: string | null } | null; +}): string { + return pickTranslatedField(entity.translation, "slug", entity.slug) ?? entity.slug; +} + +export function pickTranslatedTitle(entity: { + title: string; + translation?: { title?: string | null } | null; +}): string { + return pickTranslatedField(entity.translation, "title", entity.title) ?? entity.title; +} + +export function pickTranslatedDescription(entity: { + description?: string | null; + translation?: { description?: string | null } | null; +}): string | null | undefined { + return pickTranslatedField(entity.translation, "description", entity.description); +} + +export function pickTranslatedSeoTitle(entity: { + seoTitle?: string | null; + translation?: { seoTitle?: string | null } | null; +}): string | null | undefined { + return pickTranslatedField(entity.translation, "seoTitle", entity.seoTitle); +} + +export function pickTranslatedSeoDescription(entity: { + seoDescription?: string | null; + translation?: { seoDescription?: string | null } | null; +}): string | null | undefined { + return pickTranslatedField(entity.translation, "seoDescription", entity.seoDescription); +} + +export function pickTranslatedContent(entity: { + content?: string | null; + translation?: { content?: string | null } | null; +}): string | null | undefined { + return pickTranslatedField(entity.translation, "content", entity.content); +} + +type TranslatableCategory = { + name: string; + description?: string | null; + seoTitle?: string | null; + seoDescription?: string | null; + translation?: { + name?: string | null; + description?: string | null; + seoTitle?: string | null; + seoDescription?: string | null; + slug?: string | null; + } | null; +}; + +/** Apply Saleor translations to category/collection display fields. */ +export function withTranslatedCategoryFields(entity: T): T { + return { + ...entity, + name: pickTranslatedName(entity), + description: pickTranslatedDescription(entity) ?? entity.description, + seoTitle: pickTranslatedSeoTitle(entity) ?? entity.seoTitle, + seoDescription: pickTranslatedSeoDescription(entity) ?? entity.seoDescription, + }; +} + +type TranslatablePage = { + title: string; + content?: string | null; + seoTitle?: string | null; + seoDescription?: string | null; + translation?: { + title?: string | null; + content?: string | null; + seoTitle?: string | null; + seoDescription?: string | null; + slug?: string | null; + } | null; +}; + +export function withTranslatedPageFields(page: T): T { + return { + ...page, + title: pickTranslatedTitle(page), + content: pickTranslatedContent(page) ?? page.content, + seoTitle: pickTranslatedSeoTitle(page) ?? page.seoTitle, + seoDescription: pickTranslatedSeoDescription(page) ?? page.seoDescription, + }; +} + +type TranslatableProduct = { + name: string; + description?: string | null; + seoTitle?: string | null; + seoDescription?: string | null; + translation?: { + name?: string | null; + description?: string | null; + seoTitle?: string | null; + seoDescription?: string | null; + slug?: string | null; + } | null; + category?: { + name: string; + slug?: string; + translation?: { name?: string | null; slug?: string | null } | null; + } | null; + variants?: Array<{ + name: string; + translation?: { name?: string | null } | null; + }> | null; +}; + +export function withTranslatedProductFields(product: T): T { + return { + ...product, + name: pickTranslatedName(product), + description: pickTranslatedDescription(product) ?? product.description, + seoTitle: pickTranslatedSeoTitle(product) ?? product.seoTitle, + seoDescription: pickTranslatedSeoDescription(product) ?? product.seoDescription, + category: product.category + ? { + ...product.category, + name: pickTranslatedName(product.category), + } + : null, + variants: + product.variants?.map((variant) => ({ + ...variant, + name: pickTranslatedName(variant), + })) ?? null, + }; +} diff --git a/apps/web/src/lib/saleor/AGENTS.md b/apps/web/src/lib/saleor/AGENTS.md new file mode 100644 index 0000000..f38456f --- /dev/null +++ b/apps/web/src/lib/saleor/AGENTS.md @@ -0,0 +1,14 @@ +# Saleor kernel (Paper core) + +Forks do not edit this directory. Paper replaces it wholesale on upgrade. + +- Call `cachedQuery`, `liveQuery`, `sessionQuery`, or `mutate` from `@/lib/saleor`. +- `cachedQuery` throws on transport failures and on any GraphQL `errors`, even with partial data. Never return `null` from a cached loader to hide a failure. +- An optional cached read that must not fail the build passes `allowPartialData: true`. A try/catch around a cached loader does not help: Next fails the prerender when a `"use cache"` fill throws. +- App-token operations (`auth: "app"` in `operations.ts`) are callable only from `APP_AUTH_CALLERS` in `eslint/paper-data-layer.mjs`. +- Extra fields go in `src/graphql/extensions/`. +- Extra profiles, webhook events, and operations go in `src/config/data-extensions.ts`. +- Fork loaders go in `src/lib/custom/`. +- A hash mismatch against `paper-core.lock.json` must be declared in `paper-version.json` `coreOverrides`. + +See `skills/saleor-paper-storefront/rules/data-access.md`. diff --git a/apps/web/src/lib/saleor/__contracts__/cached-query.contract.test.ts b/apps/web/src/lib/saleor/__contracts__/cached-query.contract.test.ts new file mode 100644 index 0000000..cc787e3 --- /dev/null +++ b/apps/web/src/lib/saleor/__contracts__/cached-query.contract.test.ts @@ -0,0 +1,96 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("next/cache", () => ({ + cacheLife: vi.fn(), + cacheTag: vi.fn(), + io: vi.fn(async () => {}), +})); + +import { ProductDetailsDocument } from "@/gql/graphql"; +import { CACHE_PROFILES, SaleorDataError, cachedQuery, liveQuery } from "@/lib/saleor"; + +const variables = { slug: "tee", channel: "default-channel" } as never; + +function respondWith(body: unknown, status = 200) { + globalThis.fetch = vi.fn( + async () => + new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }), + ) as unknown as typeof fetch; +} + +function readCached() { + return cachedQuery(ProductDetailsDocument, { + profile: CACHE_PROFILES.products, + tag: "tee", + variables, + maxRetries: 0, + }); +} + +describe("cachedQuery failure semantics", () => { + const originalFetch = globalThis.fetch; + const originalUrl = process.env.NEXT_PUBLIC_SALEOR_API_URL; + + beforeEach(() => { + process.env.NEXT_PUBLIC_SALEOR_API_URL = "https://saleor.test/graphql/"; + vi.spyOn(console, "warn").mockImplementation(() => {}); + }); + + afterEach(() => { + globalThis.fetch = originalFetch; + process.env.NEXT_PUBLIC_SALEOR_API_URL = originalUrl; + vi.restoreAllMocks(); + }); + + it("returns null for a missing entity", async () => { + respondWith({ data: { product: null } }); + await expect(readCached()).resolves.toEqual({ product: null }); + }); + + it("throws when Saleor fails the whole request", async () => { + respondWith({ data: null, errors: [{ message: "boom" }] }); + await expect(readCached()).rejects.toBeInstanceOf(SaleorDataError); + }); + + it("throws on partial data so a failed resolver is not cached as a 404", async () => { + respondWith({ + data: { product: null }, + errors: [{ message: "statement timeout", path: ["product"], extensions: { code: "GRAPHQL_ERROR" } }], + }); + const error = await readCached().catch((e: unknown) => e); + expect(error).toBeInstanceOf(SaleorDataError); + expect((error as SaleorDataError).type).toBe("graphql"); + expect((error as SaleorDataError).message).toContain("statement timeout"); + }); + + it("caches partial data only when the call opts in", async () => { + respondWith({ + data: { product: null }, + errors: [{ message: "permission denied", path: ["product"] }], + }); + await expect( + cachedQuery(ProductDetailsDocument, { + profile: CACHE_PROFILES.products, + tag: "tee", + variables, + maxRetries: 0, + allowPartialData: true, + }), + ).resolves.toEqual({ product: null }); + }); + + it("keeps partial data on uncached reads and reports the errors", async () => { + respondWith({ + data: { product: null }, + errors: [{ message: "statement timeout", path: ["product"] }], + }); + const result = await liveQuery(ProductDetailsDocument, { variables, maxRetries: 0 }); + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.data).toEqual({ product: null }); + expect(result.partialErrors).toEqual([{ message: "statement timeout", path: ["product"] }]); + }); +}); diff --git a/apps/web/src/lib/saleor/__contracts__/data-layer.contract.test.ts b/apps/web/src/lib/saleor/__contracts__/data-layer.contract.test.ts new file mode 100644 index 0000000..82c2797 --- /dev/null +++ b/apps/web/src/lib/saleor/__contracts__/data-layer.contract.test.ts @@ -0,0 +1,147 @@ +import { createHash } from "node:crypto"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { paperCacheLifeProfiles } from "../cache/life-profiles"; +import { CACHE_PROFILE_LIST, CACHE_PROFILES } from "../cache/manifest"; +import { getOperation, listCoreOperations } from "../operations"; +import { APP_AUTH_DOCUMENTS } from "../../../../eslint/paper-data-layer.mjs"; + +const ROOT = join(import.meta.dirname, "../../../.."); + +function operationNames(dir: string): string[] { + const names: string[] = []; + for (const file of readdirSync(dir, { recursive: true })) { + if (typeof file !== "string" || !file.endsWith(".graphql")) continue; + const text = readFileSync(join(dir, file), "utf8"); + for (const match of text.matchAll(/^(?:query|mutation|subscription)\s+(\w+)/gm)) { + names.push(match[1]!); + } + } + return names; +} + +describe("cache life floors", () => { + it("keeps catalog and menu backstops at an hour or more", () => { + expect(paperCacheLifeProfiles.catalog.revalidate).toBeGreaterThanOrEqual(3600); + expect(paperCacheLifeProfiles.menus.revalidate).toBeGreaterThanOrEqual(3600); + expect(paperCacheLifeProfiles.channels.revalidate).toBeGreaterThanOrEqual(86400); + for (const tier of Object.values(paperCacheLifeProfiles)) { + expect(tier.expire).toBeGreaterThan(tier.revalidate); + expect(tier.stale).toBeGreaterThan(0); + } + }); +}); + +describe("operation registry", () => { + const storefront = operationNames(join(ROOT, "src/graphql")); + const checkout = operationNames(join(ROOT, "src/checkout/graphql")); + const declared = new Set([...storefront, ...checkout]); + + it("registers every operation and no stale names", () => { + const missing = [...declared].filter((name) => !getOperation(name)); + const stale = Object.keys(listCoreOperations()).filter((name) => !declared.has(name)); + expect(missing, `add to operations.ts or data-extensions.ts: ${missing.join(", ")}`).toEqual([]); + expect(stale, `remove from operations.ts: ${stale.join(", ")}`).toEqual([]); + }); + + it("never caches a mutation", () => { + for (const dir of ["src/graphql", "src/checkout/graphql"]) { + for (const file of readdirSync(join(ROOT, dir), { recursive: true })) { + if (typeof file !== "string" || !file.endsWith(".graphql")) continue; + const text = readFileSync(join(ROOT, dir, file), "utf8"); + for (const match of text.matchAll(/^mutation\s+(\w+)/gm)) { + const spec = getOperation(match[1]!); + expect(spec?.access, match[1]).toBe("mutate"); + } + } + } + }); + + it("requires channel and language variables on channel-locale cached operations", () => { + const files = new Map(); + for (const dir of ["src/graphql", "src/checkout/graphql"]) { + for (const file of readdirSync(join(ROOT, dir), { recursive: true })) { + if (typeof file !== "string" || !file.endsWith(".graphql")) continue; + files.set(file, readFileSync(join(ROOT, dir, file), "utf8")); + } + } + const all = [...files.values()].join("\n"); + for (const [name, spec] of Object.entries(listCoreOperations())) { + if (spec.access !== "cached") continue; + const match = all.match(new RegExp(`(?:query|mutation)\\s+${name}\\b\\s*(?:\\(([^)]*)\\))?`, "s")); + expect(match, `${name} declaration`).toBeTruthy(); + const vars = match?.[1] ?? ""; + if (spec.scope === "channel-locale") { + expect(vars, name).toContain("$channel"); + expect(vars, name).toMatch(/\$languageCode/); + } + if (spec.scope === "locale") { + expect(vars, name).toMatch(/\$languageCode/); + } + expect(spec.scope, `${name} needs an explicit scope`).toBeTruthy(); + } + }); + + it("lists every app-token operation in the app-auth-callers lint rule", () => { + const appDocuments = Object.entries(listCoreOperations()) + .filter(([, spec]) => spec.auth === "app") + .map(([name]) => `${name[0]!.toUpperCase()}${name.slice(1)}Document`) + .sort(); + expect(appDocuments, "update APP_AUTH_DOCUMENTS in eslint/paper-data-layer.mjs").toEqual( + [...APP_AUTH_DOCUMENTS].sort(), + ); + }); +}); + +describe("manifest tag contract", () => { + it("pins tag patterns so a silent rename fails the paper-app handshake", () => { + const patterns = CACHE_PROFILE_LIST.map((profile) => `${profile.id}:${profile.tagPattern}`).sort(); + const fingerprint = createHash("sha256").update(patterns.join("|")).digest("hex").slice(0, 16); + expect(patterns).toEqual([ + "categories:category:{slug}", + "channels:channels", + "collections:collection:{slug}", + "footer-menu:footer-menu:{channel}", + "listing-all:listing:all:{channel}", + "listing-category:listing:category:{channel}:{slug}", + "listing-collection:listing:collection:{channel}:{slug}", + "navigation:navigation:{channel}", + "pages:page:{slug}", + "products:product:{slug}", + "storefront-content:storefront-content:{channel}:{locale}", + ]); + expect(fingerprint).toHaveLength(16); + }); +}); + +describe("invalidation wiring", () => { + it("busts every core cache profile from the revalidate route", () => { + const route = readFileSync(join(ROOT, "src/app/api/revalidate/route.ts"), "utf8"); + const direct = ["products", "categories", "collections", "channels"]; + const viaPlanner: Record = { + pages: "planPageRevalidation", + navigation: "planMenuRevalidation", + footerMenu: "planMenuRevalidation", + storefrontContent: "planStorefrontContentRevalidation", + listingAll: "listingTagsForDelivery", + listingCategory: "listingTagsForDelivery", + listingCollection: "listingTagsForDelivery", + }; + + for (const key of Object.keys(CACHE_PROFILES)) { + if (direct.includes(key)) { + expect(route, key).toContain(`CACHE_PROFILES.${key}`); + } else { + const planner = viaPlanner[key]; + expect(planner, `${key} has no invalidation plan`).toBeTruthy(); + expect(route, key).toContain(planner!); + } + } + + const listing = readFileSync(join(ROOT, "src/lib/listing/invalidate.ts"), "utf8"); + for (const key of ["listingAll", "listingCategory", "listingCollection"]) { + expect(listing, key).toContain(`CACHE_PROFILES.${key}`); + } + }); +}); diff --git a/apps/web/src/lib/saleor/access.ts b/apps/web/src/lib/saleor/access.ts new file mode 100644 index 0000000..89a9c14 --- /dev/null +++ b/apps/web/src/lib/saleor/access.ts @@ -0,0 +1,169 @@ +import "server-only"; + +import { cache } from "react"; +import type { TypedDocumentString } from "../../gql/graphql"; +import { + executeGraphQL, + getUserMessage, + type GraphQLAuth, + type GraphQLError, + type GraphQLOptions, + type GraphQLResult, +} from "./client"; +import { applyCacheProfile, type CacheProfile, type CacheTagParams } from "./cache/manifest"; +import { operationNameFromDocument, resolveOperationCall } from "./operations"; + +type CallExtras = { + maxRetries?: number; + timeoutMs?: number; + headers?: HeadersInit; +}; + +export class SaleorDataError extends Error { + readonly isRetryable: boolean; + readonly type: GraphQLError["type"]; + readonly userMessage: string; + + constructor(readonly graphqlError: GraphQLError) { + super(graphqlError.message); + this.name = "SaleorDataError"; + this.isRetryable = graphqlError.isRetryable; + this.type = graphqlError.type; + this.userMessage = getUserMessage(graphqlError); + } +} + +/** + * Cached catalog read. Call only from inside `"use cache"`. + * Applies the manifest profile (so a call outside `"use cache"` throws) and + * throws on transport or GraphQL failure so Next does not cache the outage. + * Partial data with `errors` also throws. A missing entity (no errors) is `null`. + * + * Note: Next.js fails a prerender when a `"use cache"` fill throws, even if a caller + * catches it. An optional read that must not break the build opts in to + * `allowPartialData` instead of wrapping the loader in try/catch. + */ +export async function cachedQuery( + operation: TypedDocumentString, + options: { + profile: CacheProfile; + tag?: string | CacheTagParams; + variables?: Variables; + /** + * Cache partial data (failed fields are `null`) instead of throwing. Only for + * optional reads whose degraded result is safe for the whole profile TTL, such as + * channel metadata behind an app token that lacks a permission. Never for catalog + * entities. Shows up in `data-layer.lock.md`. + */ + allowPartialData?: boolean; + } & CallExtras, +): Promise { + const spec = resolveOperationCall(operationNameFromDocument(operation), "cached"); + applyCacheProfile(options.profile, options.tag); + + const result = await executeGraphQL(operation, { + variables: options.variables as Variables, + headers: options.headers, + maxRetries: options.maxRetries, + timeoutMs: options.timeoutMs, + auth: spec.auth, + ledgerMode: "cached", + } as unknown as GraphQLOptions & { auth: GraphQLAuth }); + + if (!result.ok) { + throw new SaleorDataError(result.error); + } + // A resolver failure comes back as `{ product: null, errors }`. Caching that would + // serve a 404 (or a price-less card) until the profile revalidates. + if (result.partialErrors?.length && !options.allowPartialData) { + throw new SaleorDataError({ + type: "graphql", + message: result.partialErrors.map((e) => e.message).join("\n"), + isRetryable: false, + codes: result.partialErrors.flatMap((e) => (e.code ? [e.code] : [])), + }); + } + return result.data; +} + +const memoizedRead = cache( + async ( + query: string, + variablesJson: string, + auth: GraphQLAuth, + mode: string, + maxRetries: number | null, + timeoutMs: number | null, + ): Promise> => { + const operation = { toString: () => query } as TypedDocumentString>; + return executeGraphQL(operation, { + // Omit variables entirely when the caller passed none. `{}` is still a variables + // payload and changes the request Saleor sees. + ...(variablesJson === "null" + ? {} + : { variables: JSON.parse(variablesJson) as Record }), + auth, + cache: "no-cache", + ledgerMode: mode, + ...(maxRetries !== null ? { maxRetries } : {}), + ...(timeoutMs !== null ? { timeoutMs } : {}), + } as unknown as GraphQLOptions> & { auth: GraphQLAuth }); + }, +); + +async function uncachedRead( + operation: TypedDocumentString, + via: "live" | "session", + options: CallExtras & { variables?: Variables }, +): Promise> { + const spec = resolveOperationCall(operationNameFromDocument(operation), via); + if (via === "live" && spec.auth === "session") { + throw new Error( + `[saleor] "${operationNameFromDocument(operation)}" needs the customer session. Use sessionQuery().`, + ); + } + + const result = await memoizedRead( + operation.toString(), + JSON.stringify(options.variables ?? null), + spec.auth, + via, + options.maxRetries ?? null, + options.timeoutMs ?? null, + ); + return result as GraphQLResult; +} + +/** Public, uncached read. Also the escape hatch for a cached operation's long tail (filters, search). */ +export async function liveQuery( + operation: TypedDocumentString, + options?: CallExtras & { variables?: Variables }, +): Promise> { + return uncachedRead(operation, "live", options ?? {}); +} + +/** Per-user read. Request-memoized. Never cached in the shared cache. */ +export async function sessionQuery( + operation: TypedDocumentString, + options?: CallExtras & { variables?: Variables }, +): Promise> { + return uncachedRead(operation, "session", options ?? {}); +} + +/** Mutation. Server actions only. Always `no-cache`. */ +export async function mutate( + operation: TypedDocumentString, + options?: CallExtras & { variables?: Variables }, +): Promise> { + const spec = resolveOperationCall(operationNameFromDocument(operation), "mutate"); + const resolved = options ?? {}; + return executeGraphQL(operation, { + variables: resolved.variables as Variables, + headers: resolved.headers, + maxRetries: resolved.maxRetries, + timeoutMs: resolved.timeoutMs, + auth: spec.auth, + cache: "no-cache", + ledgerMode: "mutate", + } as unknown as GraphQLOptions & { auth: GraphQLAuth }); +} diff --git a/apps/web/src/lib/saleor/cache/life-profiles.data.mjs b/apps/web/src/lib/saleor/cache/life-profiles.data.mjs new file mode 100644 index 0000000..85349ba --- /dev/null +++ b/apps/web/src/lib/saleor/cache/life-profiles.data.mjs @@ -0,0 +1,41 @@ +/** @typedef {{ stale: number; revalidate: number; expire: number }} CacheLifeTier */ + +const MINUTE = 60; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +const WEEK = 7 * DAY; + +/** + * Custom cacheLife profiles for Paper — single source for next.config.js and TypeScript. + * @type {Record<"catalog" | "menus" | "channels" | "listingTtl", CacheLifeTier>} + */ +export const paperCacheLifeProfiles = { + // Webhook invalidation (PRODUCT_*, CATEGORY_*, COLLECTION_*) is the primary freshness + // mechanism for catalog data, so `revalidate` is only the backstop for a webhook that + // was never configured or was dropped. Regeneration is request-triggered: a cold + // entry costs nothing. A hot entry with a 1-minute backstop can approach ~1440 + // regenerations/day; an hour keeps the safety net without paying for it on every + // request. + catalog: { + stale: 5 * MINUTE, + revalidate: 1 * HOUR, + expire: 1 * DAY, + }, + menus: { + stale: 5 * MINUTE, + revalidate: 1 * HOUR, + expire: 1 * DAY, + }, + channels: { + stale: 5 * MINUTE, + revalidate: 1 * DAY, + expire: 1 * WEEK, + }, + // External search indexes are not busted by Saleor webhooks. A short TTL is the + // whole freshness story until an indexer calls /api/revalidate itself. + listingTtl: { + stale: 1 * MINUTE, + revalidate: 2 * MINUTE, + expire: 10 * MINUTE, + }, +}; diff --git a/apps/web/src/lib/saleor/cache/life-profiles.ts b/apps/web/src/lib/saleor/cache/life-profiles.ts new file mode 100644 index 0000000..30a17bc --- /dev/null +++ b/apps/web/src/lib/saleor/cache/life-profiles.ts @@ -0,0 +1,112 @@ +import { paperCacheLifeProfiles as paperCacheLifeProfilesData } from "./life-profiles.data.mjs"; + +/** + * Paper storefront — cacheLife profile definitions + * + * ## What this is + * + * Next.js `"use cache"` functions call `cacheLife(name)` to set how long cached + * data lives. These names are **custom profiles** declared in `next.config.js` + * (via `paperCacheLifeProfiles` in life-profiles.data.mjs) and referenced from `manifest.ts`. + * + * ## You usually do NOT touch this file + * + * - **Fresh data on publish?** Configure Saleor webhooks → `/api/revalidate` + * (instant invalidation via `cacheTag`, regardless of TTL). + * - **Cart/checkout prices?** Always live (`cache: "no-cache"`) — not affected here. + * + * Change timings in `life-profiles.data.mjs` only when you intentionally want different **fallback** + * TTLs (e.g. slower background refresh when webhooks are missing). + * + * @see https://nextjs.org/docs/app/api-reference/functions/cacheLife + * @see src/lib/saleor/cache/manifest.ts — maps each cache tag to a profile + */ + +/** Profile names registered in `next.config.js` → `cacheLife`. */ +export type PaperCacheLifeProfile = "catalog" | "menus" | "channels" | "listingTtl"; + +/** Seconds-based config passed to Next.js `cacheLife` in next.config.js. */ +export type PaperCacheLifeConfig = Record< + PaperCacheLifeProfile, + { stale: number; revalidate: number; expire: number } +>; + +/** + * Custom cacheLife profiles for Paper. + * Values live in life-profiles.data.mjs (imported by next.config.js). + */ +export const paperCacheLifeProfiles: PaperCacheLifeConfig = paperCacheLifeProfilesData; + +/** Default profile when a tag is not in the manifest (conservative catalog tier). */ +export const DEFAULT_PAPER_CACHE_LIFE_PROFILE: PaperCacheLifeProfile = "catalog"; + +/** All tier names registered in next.config.js — use for validation/tests. */ +export const PAPER_CACHE_LIFE_PROFILE_NAMES = Object.keys(paperCacheLifeProfiles) as PaperCacheLifeProfile[]; + +/** Built-in Next.js preset names → Paper tiers (manual revalidation backward compat). */ +const LEGACY_PROFILE_ALIASES: Record = { + minutes: "catalog", + hours: "menus", + days: "channels", +}; + +export function isPaperCacheLifeProfile(value: string): value is PaperCacheLifeProfile { + return value in paperCacheLifeProfiles; +} + +/** + * Resolve the cacheLife profile for revalidateTag(tag, profile). + * Profile must match the tier used in cacheLife() when the entry was cached. + */ +export function resolveRevalidateCacheLifeProfile( + tag: string, + override: string | null | undefined, + resolveFromTag: (tag: string) => PaperCacheLifeProfile, +): PaperCacheLifeProfile { + if (override) { + if (isPaperCacheLifeProfile(override)) { + return override; + } + const legacy = LEGACY_PROFILE_ALIASES[override]; + if (legacy) { + return legacy; + } + console.warn(`[cache-life] Unknown profile override "${override}" — resolving from tag "${tag}" instead`); + } + return resolveFromTag(tag); +} + +/** Human-readable summary for `/api/cache-info` and debugging. */ +export const paperCacheLifeProfileDocs: Record< + PaperCacheLifeProfile, + { label: string; usedFor: string; stale: string; revalidate: string; expire: string } +> = { + catalog: { + label: "Catalog", + usedFor: "Products, categories, collections, listings, homepage featured", + stale: "5 min", + revalidate: "1 hour", + expire: "1 day", + }, + menus: { + label: "Menus", + usedFor: "Header navigation, footer menu", + stale: "5 min", + revalidate: "1 hour", + expire: "1 day", + }, + channels: { + label: "Channels", + usedFor: "Footer channel selector metadata", + stale: "5 min", + revalidate: "1 day", + expire: "1 week", + }, + listingTtl: { + label: "Listing TTL", + usedFor: "Search-engine listing providers. No Saleor webhook tag — the index lags the catalog.", + stale: "1 min", + revalidate: "2 min", + expire: "10 min", + }, +}; diff --git a/apps/web/src/lib/saleor/cache/manifest.test.ts b/apps/web/src/lib/saleor/cache/manifest.test.ts new file mode 100644 index 0000000..04361da --- /dev/null +++ b/apps/web/src/lib/saleor/cache/manifest.test.ts @@ -0,0 +1,348 @@ +import { describe, it, expect } from "vitest"; +import { + CACHE_PROFILES, + CACHE_PROFILE_LIST, + buildCatchAllTag, + buildTag, + buildStorefrontManifestIdentity, + resolveCacheLifeProfileForTag, + resolveManualRevalidateTag, + resolveRevalidateProfileForTag, + resolveCacheProfileForMenuSlug, + resolveStorefrontManifestEnvironment, + isKnownStorefrontMenuSlug, + isChannelLocaleScopedTagProfile, + isChannelScopedTagProfile, + extractMenuSlugFromWebhookPayload, + extractPageSlugFromWebhookPayload, + buildMenuRevalidationTags, + planFullPurgeTagEntries, + planMenuRevalidation, + planPageRevalidation, + planStorefrontContentRevalidation, +} from "./manifest"; +import { PAPER_CACHE_LIFE_PROFILE_NAMES, paperCacheLifeProfiles } from "./life-profiles"; + +describe("buildTag", () => { + it("resolves slug placeholders", () => { + expect(buildTag(CACHE_PROFILES.products, "blue-shirt")).toBe("product:blue-shirt"); + expect(buildTag(CACHE_PROFILES.products, { slug: "blue-shirt" })).toBe("product:blue-shirt"); + }); + + it("resolves channel placeholders", () => { + expect(buildTag(CACHE_PROFILES.navigation, { channel: "default-channel" })).toBe( + "navigation:default-channel", + ); + expect(buildTag(CACHE_PROFILES.footerMenu, { channel: "us" })).toBe("footer-menu:us"); + }); + + it("resolves channel+slug listing patterns", () => { + expect(buildTag(CACHE_PROFILES.listingAll, { channel: "us" })).toBe("listing:all:us"); + expect(buildTag(CACHE_PROFILES.listingCategory, { channel: "us", slug: "shoes" })).toBe( + "listing:category:us:shoes", + ); + expect(buildTag(CACHE_PROFILES.listingCollection, { channel: "uk", slug: "summer" })).toBe( + "listing:collection:uk:summer", + ); + }); + + it("throws when required placeholders are missing", () => { + expect(() => buildTag(CACHE_PROFILES.navigation)).toThrow(/Unresolved tag/); + expect(() => buildTag(CACHE_PROFILES.navigation, {})).toThrow(/Provide: \{channel\}/); + expect(() => buildTag(CACHE_PROFILES.products, { channel: "us" })).toThrow(/Provide: \{slug\}/); + }); +}); + +describe("buildCatchAllTag", () => { + it("resolves the channel catch-all for listing profiles", () => { + expect(buildCatchAllTag(CACHE_PROFILES.listingCategory, "us")).toBe("listing:category-any:us"); + expect(buildCatchAllTag(CACHE_PROFILES.listingCollection, "uk")).toBe("listing:collection-any:uk"); + }); + + it("throws for profiles without a sharedTagPattern", () => { + expect(() => buildCatchAllTag(CACHE_PROFILES.products, "us")).toThrow(/no sharedTagPattern/); + }); +}); + +describe("resolveCacheLifeProfileForTag", () => { + it("maps known tags to Paper cacheLife tiers", () => { + expect(resolveCacheLifeProfileForTag("navigation:default-channel")).toBe("menus"); + expect(resolveCacheLifeProfileForTag("footer-menu:us")).toBe("menus"); + expect(resolveCacheLifeProfileForTag("product:blue-shirt")).toBe("catalog"); + expect(resolveCacheLifeProfileForTag("page:about-us")).toBe("catalog"); + expect(resolveCacheLifeProfileForTag("storefront-content:default-channel:en-US")).toBe("menus"); + expect(resolveCacheLifeProfileForTag("channels")).toBe("channels"); + }); + + it("maps sharded listing tags and their catch-alls to the catalog tier", () => { + expect(resolveCacheLifeProfileForTag("listing:all:us")).toBe("catalog"); + expect(resolveCacheLifeProfileForTag("listing:category:us:shoes")).toBe("catalog"); + expect(resolveCacheLifeProfileForTag("listing:collection:us:summer")).toBe("catalog"); + expect(resolveCacheLifeProfileForTag("listing:category-any:us")).toBe("catalog"); + expect(resolveCacheLifeProfileForTag("listing:collection-any:us")).toBe("catalog"); + }); + + it("falls back to catalog for unknown tags", () => { + expect(resolveCacheLifeProfileForTag("unknown-tag")).toBe("catalog"); + }); +}); + +describe("resolveManualRevalidateTag", () => { + it("expands profile id + channel into a concrete tag", () => { + expect(resolveManualRevalidateTag("navigation", "default-channel")).toBe("navigation:default-channel"); + expect(resolveManualRevalidateTag("footer-menu", "us")).toBe("footer-menu:us"); + }); + + it("leaves fully qualified tags unchanged", () => { + expect(resolveManualRevalidateTag("navigation:default-channel", "us")).toBe("navigation:default-channel"); + }); +}); + +describe("cache manifest ↔ cacheLife tiers", () => { + it("maps every manifest profile to a registered next.config tier", () => { + for (const profile of Object.values(CACHE_PROFILES)) { + expect(PAPER_CACHE_LIFE_PROFILE_NAMES).toContain(profile.cacheProfile); + expect(paperCacheLifeProfiles[profile.cacheProfile]).toBeDefined(); + } + }); +}); + +describe("resolveRevalidateProfileForTag", () => { + it("accepts legacy built-in profile names for manual revalidation", () => { + expect(resolveRevalidateProfileForTag("navigation:us", "hours")).toBe("menus"); + expect(resolveRevalidateProfileForTag("product:foo", "minutes")).toBe("catalog"); + expect(resolveRevalidateProfileForTag("channels", "days")).toBe("channels"); + }); + + it("falls back to tag resolution for unknown overrides", () => { + expect(resolveRevalidateProfileForTag("product:foo", "bogus")).toBe("catalog"); + }); +}); + +describe("menu revalidation helpers", () => { + it("maps storefront menu slugs to cache profiles", () => { + expect(isKnownStorefrontMenuSlug("navbar")).toBe(true); + expect(isKnownStorefrontMenuSlug("footer")).toBe(true); + expect(isKnownStorefrontMenuSlug("sidebar")).toBe(false); + expect(resolveCacheProfileForMenuSlug("navbar")).toBe(CACHE_PROFILES.navigation); + expect(resolveCacheProfileForMenuSlug("footer")).toBe(CACHE_PROFILES.footerMenu); + expect(resolveCacheProfileForMenuSlug("sidebar")).toBeNull(); + }); + + it("extracts menu slug from menu and menuItem webhook payloads", () => { + expect(extractMenuSlugFromWebhookPayload({ menu: { slug: "navbar" } })).toBe("navbar"); + expect(extractMenuSlugFromWebhookPayload({ menuItem: { menu: { slug: "footer" } } })).toBe("footer"); + expect(extractMenuSlugFromWebhookPayload({ menu: { slug: "" } })).toBeNull(); + expect(extractMenuSlugFromWebhookPayload({ product: { slug: "shirt" } })).toBeNull(); + }); + + it("builds channel-scoped tags for all storefront channels", () => { + expect(buildMenuRevalidationTags("navbar", ["us", "uk"])).toEqual([ + { tag: "navigation:us", profile: "menus" }, + { tag: "navigation:uk", profile: "menus" }, + ]); + expect(buildMenuRevalidationTags("footer", ["default-channel"])).toEqual([ + { tag: "footer-menu:default-channel", profile: "menus" }, + ]); + expect(buildMenuRevalidationTags("unknown", ["us"])).toEqual([]); + }); + + it("plans menu revalidation outcomes", () => { + expect(planMenuRevalidation(undefined, ["us"])).toEqual({ + action: "skip", + reason: "missing_slug", + }); + expect(planMenuRevalidation("sidebar", ["us"])).toEqual({ + action: "skip", + reason: "unknown_menu", + }); + expect(planMenuRevalidation("navbar", [])).toEqual({ + action: "error", + reason: "no_channels", + }); + expect(planMenuRevalidation("navbar", ["us", "uk"])).toEqual({ + action: "revalidate", + menuSlug: "navbar", + tags: [ + { tag: "navigation:us", profile: "menus" }, + { tag: "navigation:uk", profile: "menus" }, + ], + }); + }); +}); + +describe("page revalidation helpers", () => { + it("extracts page slug from page webhook payloads", () => { + expect(extractPageSlugFromWebhookPayload({ page: { slug: "about-us" } })).toBe("about-us"); + expect(extractPageSlugFromWebhookPayload({ page: { slug: "" } })).toBeNull(); + expect(extractPageSlugFromWebhookPayload({ product: { slug: "shirt" } })).toBeNull(); + }); + + it("plans tag + channel paths for CMS pages", () => { + expect(planPageRevalidation("about-us", ["us", "uk"], null)).toEqual({ + action: "revalidate", + slug: "about-us", + tag: "page:about-us", + profile: "catalog", + paths: ["/en/us/pages/about-us", "/en/uk/pages/about-us"], + }); + expect(planPageRevalidation(undefined, ["us"])).toEqual({ + action: "skip", + reason: "missing_slug", + }); + expect(planPageRevalidation("about-us", [], "default-channel")).toEqual({ + action: "revalidate", + slug: "about-us", + tag: "page:about-us", + profile: "catalog", + paths: ["/en/default-channel/pages/about-us"], + }); + expect(planPageRevalidation("about-us", [], null)).toEqual({ + action: "error", + reason: "no_channels", + }); + }); +}); + +describe("storefront content revalidation helpers", () => { + it("skips non-storefront editorial page slugs", () => { + expect(planStorefrontContentRevalidation("about-us", ["us"])).toEqual({ + action: "skip", + reason: "not_storefront_singleton", + }); + }); + + it("revalidates all channels for global PageType slug", () => { + expect(planStorefrontContentRevalidation("storefront-homepage", ["us", "uk"], null)).toEqual({ + action: "revalidate", + tags: [ + { tag: "storefront-content:us:en-US", profile: "menus" }, + { tag: "storefront-content:uk:en-US", profile: "menus" }, + ], + paths: ["/en/us", "/en/uk"], + }); + }); + + it("revalidates a single channel for {pageType}-{channel} slug", () => { + expect(planStorefrontContentRevalidation("storefront-homepage-us", ["us", "uk"], null)).toEqual({ + action: "revalidate", + tags: [{ tag: "storefront-content:us:en-US", profile: "menus" }], + paths: ["/en/us"], + }); + }); +}); + +describe("full purge tag planning", () => { + it("treats storefront-content as channel×locale, not channel-only", () => { + expect(isChannelScopedTagProfile(CACHE_PROFILES.storefrontContent)).toBe(false); + expect(isChannelLocaleScopedTagProfile(CACHE_PROFILES.storefrontContent)).toBe(true); + expect(isChannelScopedTagProfile(CACHE_PROFILES.navigation)).toBe(true); + expect(isChannelLocaleScopedTagProfile(CACHE_PROFILES.navigation)).toBe(false); + }); + + it("expands enumerable tags without throwing on locale placeholders", () => { + const tags = planFullPurgeTagEntries(["us", "uk"]).map((e) => e.tag); + + expect(tags).toContain("channels"); + expect(tags).toContain("navigation:us"); + expect(tags).toContain("navigation:uk"); + expect(tags).toContain("footer-menu:us"); + expect(tags).toContain("footer-menu:uk"); + expect(tags).toContain("storefront-content:us:en-US"); + expect(tags).toContain("storefront-content:uk:en-US"); + expect(tags).toContain("products"); + expect(tags).toContain("categories"); + expect(tags).toContain("collections"); + expect(tags).toContain("pages"); + // "Revalidate all" must clear cached listing grids too, or the Dashboard button + // appears to work while the PLP keeps serving the old grid. Per-slug grids are + // covered by the channel catch-alls every entry also carries. + expect(tags).toContain("listing:all:us"); + expect(tags).toContain("listing:all:uk"); + expect(tags).toContain("listing:category-any:us"); + expect(tags).toContain("listing:category-any:uk"); + expect(tags).toContain("listing:collection-any:us"); + expect(tags).toContain("listing:collection-any:uk"); + expect(tags.some((t) => t.includes("{locale}"))).toBe(false); + expect(tags.some((t) => t.startsWith("product:"))).toBe(false); + }); + + it("includes shared catalog tags even when no channels are configured", () => { + expect(planFullPurgeTagEntries([]).map((e) => e.tag)).toEqual([ + "products", + "categories", + "collections", + "pages", + "channels", + ]); + }); +}); + +describe("shared catalog tags", () => { + it("defines sharedTag on every slug-scoped catalog profile", () => { + expect(CACHE_PROFILES.products.sharedTag).toBe("products"); + expect(CACHE_PROFILES.categories.sharedTag).toBe("categories"); + expect(CACHE_PROFILES.collections.sharedTag).toBe("collections"); + expect(CACHE_PROFILES.pages.sharedTag).toBe("pages"); + expect(CACHE_PROFILE_LIST.filter((p) => p.id === "navigation")[0]?.sharedTag).toBeUndefined(); + }); + + it("maps shared tags to the catalog cacheLife tier", () => { + expect(resolveCacheLifeProfileForTag("products")).toBe("catalog"); + expect(resolveCacheLifeProfileForTag("categories")).toBe("catalog"); + expect(resolveCacheLifeProfileForTag("collections")).toBe("catalog"); + expect(resolveCacheLifeProfileForTag("pages")).toBe("catalog"); + }); +}); + +describe("manifest v6 identity", () => { + it("resolves environment from explicit override, then Vercel, then NODE_ENV", () => { + expect( + resolveStorefrontManifestEnvironment({ + PAPER_STOREFRONT_ENVIRONMENT: "staging", + VERCEL_ENV: "production", + }), + ).toBe("staging"); + expect(resolveStorefrontManifestEnvironment({ VERCEL_ENV: "preview" })).toBe("preview"); + expect(resolveStorefrontManifestEnvironment({ NODE_ENV: "development" })).toBe("development"); + }); + + it("does not fall through when an explicit environment override is invalid", () => { + expect( + resolveStorefrontManifestEnvironment({ + PAPER_STOREFRONT_ENVIRONMENT: "prod", + VERCEL_ENV: "production", + }), + ).toBeUndefined(); + }); + + it("builds identity from Saleor URL and deploy metadata", () => { + expect( + buildStorefrontManifestIdentity({ + NEXT_PUBLIC_SALEOR_API_URL: "https://demo.saleor.cloud/graphql/", + VERCEL_ENV: "production", + VERCEL_DEPLOYMENT_ID: "dpl_abc", + VERCEL_GIT_COMMIT_SHA: "deadbeef", + VERCEL_GIT_COMMIT_REF: "main", + }), + ).toEqual({ + saleorApiUrl: "https://demo.saleor.cloud/graphql/", + environment: "production", + buildId: "dpl_abc", + commit: "deadbeef", + branch: "main", + }); + }); + + it("canonicalizes Saleor API URL with a trailing slash", () => { + expect( + buildStorefrontManifestIdentity({ + NEXT_PUBLIC_SALEOR_API_URL: "https://demo.saleor.cloud/graphql", + }), + ).toEqual({ saleorApiUrl: "https://demo.saleor.cloud/graphql/" }); + }); + + it("omits identity when Saleor URL is unset", () => { + expect(buildStorefrontManifestIdentity({})).toBeUndefined(); + }); +}); diff --git a/apps/web/src/lib/saleor/cache/manifest.ts b/apps/web/src/lib/saleor/cache/manifest.ts new file mode 100644 index 0000000..a42cda1 --- /dev/null +++ b/apps/web/src/lib/saleor/cache/manifest.ts @@ -0,0 +1,747 @@ +import { cacheLife, cacheTag } from "next/cache"; +import { extensionCacheProfiles } from "../extensions"; +import { getStaticStorefrontChannelSlugs } from "@/config/channels"; +import { getDefaultLocaleSlug, getLocaleBcp47List, getStorefrontLocaleSlugs } from "@/config/locale"; +import { + DEFAULT_PAPER_CACHE_LIFE_PROFILE, + type PaperCacheLifeProfile, + paperCacheLifeProfileDocs, + resolveRevalidateCacheLifeProfile, +} from "./life-profiles"; +import { + isStorefrontContentPageSlug, + resolveStorefrontContentChannelsForPageSlug, +} from "@/lib/content/constants"; + +// ============================================================================ +// Cache Profile Definitions — single source of truth +// +// **cacheLife profile names** live in src/lib/saleor/cache/life-profiles.ts (with docs). +// This file maps Saleor cache *tags* to those profiles and builds invalidation paths. +// +// Imported by: +// - Cached functions (applyCacheProfile → cacheLife + cacheTag) +// - Revalidation endpoint (revalidateTag tag + profile) +// - /api/cache-info (manifest for dashboard) +// ============================================================================ + +const UNRESOLVED_PLACEHOLDER = /\{(slug|channel|locale)\}/; + +export type CacheLifeProfile = PaperCacheLifeProfile; + +export interface CacheProfile { + readonly id: string; + readonly label: string; + /** Paper cacheLife tier — see src/lib/saleor/cache/life-profiles.ts */ + readonly cacheProfile: CacheLifeProfile; + /** Tag pattern — use {slug} and/or {channel} placeholders */ + readonly tagPattern: string; + /** Path pattern — use {channel} and {slug} as placeholders, or null for non-path caches */ + readonly pathPattern: string | null; + /** + * Catch-all tag applied alongside the entity tag (slug-scoped profiles). + * Full purge (`?all=1`) revalidates this so every product/category/… entry + * is busted without enumerating slugs. + */ + readonly sharedTag?: string; + /** + * Channel-scoped catch-all applied alongside channel+slug tags (listing grids). + * Full purge enumerates it per channel, and webhook events whose payload does + * not name the affected slugs fall back to it — one channel's grids, never + * every channel's. + */ + readonly sharedTagPattern?: string; +} + +export type CacheTagParams = { + slug?: string; + channel?: string; + /** BCP 47 locale — storefront content cache key (Saleor translations not wired yet). */ + locale?: string; +}; + +const profiles = { + products: { + id: "products", + label: "Product Pages", + cacheProfile: "catalog", + tagPattern: "product:{slug}", + pathPattern: "/{locale}/{channel}/products/{slug}", + sharedTag: "products", + }, + categories: { + id: "categories", + label: "Category Pages", + cacheProfile: "catalog", + tagPattern: "category:{slug}", + pathPattern: "/{locale}/{channel}/categories/{slug}", + sharedTag: "categories", + }, + collections: { + id: "collections", + label: "Collection Pages", + cacheProfile: "catalog", + tagPattern: "collection:{slug}", + pathPattern: "/{locale}/{channel}/collections/{slug}", + sharedTag: "collections", + }, + pages: { + id: "pages", + label: "CMS Pages", + cacheProfile: "catalog", + tagPattern: "page:{slug}", + pathPattern: "/{locale}/{channel}/pages/{slug}", + sharedTag: "pages", + }, + /** + * Listing grids (PLP, category, collection) for the *cacheable* views only — + * see `isCacheableListingQuery` in src/lib/listing/cacheability.ts. + * + * Sharded by surface and slug: cache entries are keyed by (slug ×) sort × + * locale × channel, and the tags follow the key so one product edit busts + * only the grids it can appear in — its category grid, its collections' + * grids, and the all-products grid — instead of every cached grid in the + * channel. Category/collection grids also carry a channel catch-all + * (`sharedTagPattern`) used by full purge and by product events whose + * payload doesn't name the affected grids (unenriched webhooks). + * + * Only product events that can change a listing card revalidate these + * (`affectsListing` in src/lib/saleor/invalidation/webhook-events.ts) — stock and metadata + * churn must not, or the cache never stays warm. + */ + listingAll: { + id: "listing-all", + label: "All-Products Listing", + cacheProfile: "catalog", + tagPattern: "listing:all:{channel}", + pathPattern: null, + }, + listingCategory: { + id: "listing-category", + label: "Category Listings", + cacheProfile: "catalog", + tagPattern: "listing:category:{channel}:{slug}", + pathPattern: null, + sharedTagPattern: "listing:category-any:{channel}", + }, + listingCollection: { + id: "listing-collection", + label: "Collection Listings", + cacheProfile: "catalog", + tagPattern: "listing:collection:{channel}:{slug}", + pathPattern: null, + sharedTagPattern: "listing:collection-any:{channel}", + }, + navigation: { + id: "navigation", + label: "Navigation Menus", + cacheProfile: "menus", + tagPattern: "navigation:{channel}", + pathPattern: null, + }, + footerMenu: { + id: "footer-menu", + label: "Footer Menu", + cacheProfile: "menus", + tagPattern: "footer-menu:{channel}", + pathPattern: null, + }, + channels: { + id: "channels", + label: "Channel List", + cacheProfile: "channels", + tagPattern: "channels", + pathPattern: null, + }, + storefrontContent: { + id: "storefront-content", + label: "Storefront Content", + cacheProfile: "menus", + tagPattern: "storefront-content:{channel}:{locale}", + pathPattern: "/{locale}/{channel}", + }, +} as const satisfies Record; + +export const CACHE_PROFILES = profiles; + +export const CACHE_PROFILE_LIST: readonly CacheProfile[] = [ + ...Object.values(profiles), + ...Object.values(extensionCacheProfiles), +]; + +/** Saleor menu slugs used by cached layout components — keep in sync with saleor-paper-app storefront-menus.ts */ +export const NAVBAR_MENU_SLUG = "navbar" as const; +export const FOOTER_MENU_SLUG = "footer" as const; + +/** Saleor menu slugs fetched by the storefront → cache profile for invalidation. */ +export const STOREFRONT_MENU_SLUGS = { + [NAVBAR_MENU_SLUG]: profiles.navigation, + [FOOTER_MENU_SLUG]: profiles.footerMenu, +} as const satisfies Record; + +export type StorefrontMenuSlug = keyof typeof STOREFRONT_MENU_SLUGS; + +export function resolveCacheProfileForMenuSlug(menuSlug: string): CacheProfile | null { + if (!isKnownStorefrontMenuSlug(menuSlug)) return null; + return STOREFRONT_MENU_SLUGS[menuSlug]; +} + +export function isKnownStorefrontMenuSlug(menuSlug: string): menuSlug is StorefrontMenuSlug { + return menuSlug in STOREFRONT_MENU_SLUGS; +} + +/** Extract menu slug from a Saleor menu or menu-item webhook payload. */ +export function extractMenuSlugFromWebhookPayload(payload: unknown): string | null { + if (!payload || typeof payload !== "object") return null; + + const data = payload as Record; + + if (data.menu && typeof data.menu === "object") { + const slug = (data.menu as Record).slug; + if (typeof slug === "string" && slug.length > 0) return slug; + } + + if (data.menuItem && typeof data.menuItem === "object") { + const menu = (data.menuItem as Record).menu; + if (menu && typeof menu === "object") { + const slug = (menu as Record).slug; + if (typeof slug === "string" && slug.length > 0) return slug; + } + } + + return null; +} + +/** Extract page slug from a Saleor page webhook payload. */ +export function extractPageSlugFromWebhookPayload(payload: unknown): string | null { + if (!payload || typeof payload !== "object") return null; + + const data = payload as Record; + + if (data.page && typeof data.page === "object") { + const slug = (data.page as Record).slug; + if (typeof slug === "string" && slug.length > 0) return slug; + } + + return null; +} + +/** Build channel-scoped menu tags for every storefront channel. */ +export function buildMenuRevalidationTags( + menuSlug: string, + channels: readonly string[], +): Array<{ tag: string; profile: CacheLifeProfile }> { + const profile = resolveCacheProfileForMenuSlug(menuSlug); + if (!profile || channels.length === 0) return []; + + return channels.map((channel) => ({ + tag: buildTag(profile, { channel }), + profile: profile.cacheProfile, + })); +} + +export type MenuRevalidationPlan = + | { action: "revalidate"; menuSlug: string; tags: Array<{ tag: string; profile: CacheLifeProfile }> } + | { action: "skip"; reason: "missing_slug" | "unknown_menu" } + | { action: "error"; reason: "no_channels" }; + +/** Pure planner for menu webhook invalidation — keeps route handler thin and testable. */ +export function planMenuRevalidation( + menuSlug: string | undefined, + channels: readonly string[], +): MenuRevalidationPlan { + if (!menuSlug) return { action: "skip", reason: "missing_slug" }; + if (channels.length === 0) return { action: "error", reason: "no_channels" }; + + const tags = buildMenuRevalidationTags(menuSlug, channels); + if (tags.length === 0) return { action: "skip", reason: "unknown_menu" }; + + return { action: "revalidate", menuSlug, tags }; +} + +export type PageRevalidationPlan = + | { action: "revalidate"; slug: string; tag: string; profile: CacheLifeProfile; paths: string[] } + | { action: "skip"; reason: "missing_slug" } + | { action: "error"; reason: "no_channels" }; + +/** Plan CMS page invalidation — tag is slug-scoped; paths are per storefront channel. */ +export function planPageRevalidation( + slug: string | undefined, + channels: readonly string[], + fallbackChannel?: string | null, +): PageRevalidationPlan { + if (!slug) return { action: "skip", reason: "missing_slug" }; + + const channelList = channels.length > 0 ? channels : fallbackChannel ? [fallbackChannel] : []; + if (channelList.length === 0) return { action: "error", reason: "no_channels" }; + + const paths = channelList.flatMap((channel) => + buildPathsForAllLocales(CACHE_PROFILES.pages, { channel, slug }), + ); + + return { + action: "revalidate", + slug, + tag: buildTag(CACHE_PROFILES.pages, slug), + profile: CACHE_PROFILES.pages.cacheProfile, + paths, + }; +} + +export type StorefrontContentRevalidationPlan = + | { + action: "revalidate"; + tags: Array<{ tag: string; profile: CacheLifeProfile }>; + paths: string[]; + } + | { action: "skip"; reason: "not_storefront_singleton" | "no_channels" }; + +/** + * Plan invalidation for Saleor `storefront-*` singleton pages (`default`, `default-{channel}`). + * Merges with editorial CMS page revalidation in the webhook handler. + */ +export function planStorefrontContentRevalidation( + pageSlug: string | undefined, + channels: readonly string[], + fallbackChannel?: string | null, +): StorefrontContentRevalidationPlan { + if (!pageSlug || !isStorefrontContentPageSlug(pageSlug)) { + return { action: "skip", reason: "not_storefront_singleton" }; + } + + const channelList = channels.length > 0 ? channels : fallbackChannel ? [fallbackChannel] : []; + if (channelList.length === 0) return { action: "skip", reason: "no_channels" }; + + const targetChannels = resolveStorefrontContentChannelsForPageSlug(pageSlug, channelList); + if (targetChannels.length === 0) { + return { action: "skip", reason: "not_storefront_singleton" }; + } + + const profile = CACHE_PROFILES.storefrontContent; + + return { + action: "revalidate", + tags: targetChannels.flatMap((channel) => + buildStorefrontContentCacheTags(channel).map((tag) => ({ + tag, + profile: profile.cacheProfile, + })), + ), + paths: targetChannels.flatMap((channel) => buildPathsForAllLocales(profile, { channel })), + }; +} + +/** All locale cache tags for storefront marketing copy on a channel. */ +export function buildStorefrontContentCacheTags(channel: string): string[] { + return getLocaleBcp47List().map((locale) => + buildTag(CACHE_PROFILES.storefrontContent, { channel, locale }), + ); +} + +function normalizeTagParams(params?: string | CacheTagParams): CacheTagParams { + if (typeof params === "string") { + return { slug: params }; + } + return params ?? {}; +} + +export function tagPatternHasPlaceholders(pattern: string): boolean { + return pattern.includes("{slug}") || pattern.includes("{channel}") || pattern.includes("{locale}"); +} + +export function isGlobalTagProfile(profile: CacheProfile): boolean { + return !tagPatternHasPlaceholders(profile.tagPattern); +} + +/** + * Profiles tagged per channel only (e.g. navigation:{channel}, footer-menu:{channel}). + * Excludes channel+locale profiles (storefront-content) and slug-scoped catalog tags. + */ +export function isChannelScopedTagProfile(profile: CacheProfile): boolean { + return ( + profile.tagPattern.includes("{channel}") && + !profile.tagPattern.includes("{slug}") && + !profile.tagPattern.includes("{locale}") + ); +} + +/** Profiles tagged per channel × locale (e.g. storefront-content:{channel}:{locale}). */ +export function isChannelLocaleScopedTagProfile(profile: CacheProfile): boolean { + return ( + profile.tagPattern.includes("{channel}") && + profile.tagPattern.includes("{locale}") && + !profile.tagPattern.includes("{slug}") + ); +} + +export function getChannelScopedTagProfiles(): CacheProfile[] { + return CACHE_PROFILE_LIST.filter(isChannelScopedTagProfile); +} + +export function getChannelLocaleScopedTagProfiles(): CacheProfile[] { + return CACHE_PROFILE_LIST.filter(isChannelLocaleScopedTagProfile); +} + +/** + * Enumerable tags for a full purge (`?all=1`). + * + * Covers global, channel-scoped, channel×locale, and shared catalog tags + * (`products`, `categories`, …). Per-slug tags are not enumerated — shared + * tags bust every `"use cache"` entry that carries them. + */ +export function planFullPurgeTagEntries( + channels: readonly string[], +): Array<{ tag: string; profile: CacheLifeProfile }> { + const entries: Array<{ tag: string; profile: CacheLifeProfile }> = []; + + for (const profile of CACHE_PROFILE_LIST) { + if (profile.sharedTag) { + entries.push({ tag: profile.sharedTag, profile: profile.cacheProfile }); + } + + // Channel-scoped catch-alls (listing grids) — the per-slug tags can't be + // enumerated, but every entry also carries the catch-all. + if (profile.sharedTagPattern) { + for (const channel of channels) { + entries.push({ + tag: buildCatchAllTag(profile, channel), + profile: profile.cacheProfile, + }); + } + } + + if (isGlobalTagProfile(profile)) { + entries.push({ tag: buildTag(profile), profile: profile.cacheProfile }); + continue; + } + + if (isChannelScopedTagProfile(profile)) { + for (const channel of channels) { + entries.push({ + tag: buildTag(profile, { channel }), + profile: profile.cacheProfile, + }); + } + continue; + } + + if (isChannelLocaleScopedTagProfile(profile)) { + for (const channel of channels) { + for (const locale of getLocaleBcp47List()) { + entries.push({ + tag: buildTag(profile, { channel, locale }), + profile: profile.cacheProfile, + }); + } + } + } + } + + return entries; +} + +function tagPatternToRegExp(pattern: string): RegExp { + const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp( + `^${escaped + .replace("\\{slug\\}", "[^:]+") + .replace("\\{channel\\}", "[^:]+") + .replace("\\{locale\\}", "[^:]+")}$`, + ); +} + +/** + * Resolve the cacheLife profile for a concrete tag string (manual revalidation). + * Falls back to catalog tier for unknown tags. + */ +export function resolveCacheLifeProfileForTag(tag: string): CacheLifeProfile { + return resolveRevalidateCacheLifeProfile(tag, null, resolveCacheLifeProfileForTagFromManifest); +} + +function resolveCacheLifeProfileForTagFromManifest(tag: string): CacheLifeProfile { + for (const profile of CACHE_PROFILE_LIST) { + if (profile.sharedTag === tag) return profile.cacheProfile; + if (profile.sharedTagPattern && tagPatternToRegExp(profile.sharedTagPattern).test(tag)) { + return profile.cacheProfile; + } + if (isGlobalTagProfile(profile)) { + if (tag === profile.tagPattern) return profile.cacheProfile; + continue; + } + if (tagPatternToRegExp(profile.tagPattern).test(tag)) { + return profile.cacheProfile; + } + } + return DEFAULT_PAPER_CACHE_LIFE_PROFILE; +} + +/** @internal Exported for revalidate route profile override resolution. */ +export function resolveRevalidateProfileForTag( + tag: string, + profileOverride: string | null | undefined, +): CacheLifeProfile { + return resolveRevalidateCacheLifeProfile(tag, profileOverride, resolveCacheLifeProfileForTagFromManifest); +} + +/** + * Resolve a manual revalidation tag from profile id/shorthand + optional channel. + * + * @example resolveManualRevalidateTag("navigation", "default-channel") → "navigation:default-channel" + */ +export function resolveManualRevalidateTag(tag: string, channel?: string | null): string { + if (!channel || UNRESOLVED_PLACEHOLDER.test(tag)) { + return tag; + } + + for (const profile of CACHE_PROFILE_LIST) { + if (!isChannelScopedTagProfile(profile)) continue; + + const shorthand = profile.tagPattern.replace(":{channel}", ""); + if (tag === profile.id || tag === shorthand) { + return buildTag(profile, { channel }); + } + } + + return tag; +} + +// ============================================================================ +// Helpers for "use cache" functions +// ============================================================================ + +/** + * Apply cacheLife + cacheTag for a profile inside a "use cache" function body. + * Pass `slug` and/or `channel` when the profile's tagPattern contains placeholders. + * Slug-scoped profiles also receive `sharedTag` (and channel+slug profiles their + * channel catch-all) so full purge can bust the whole set without enumerating slugs. + * + * Profile timings are defined in src/lib/saleor/cache/life-profiles.ts (registered in next.config.js). + */ +/** + * TTL-only listing cache. Search-engine providers have no Saleor tag to bust, + * so this applies `listingTtl` and no `cacheTag`. Call from inside `"use cache"`. + */ +export function applyListingTtl(): void { + applyCacheLife("listingTtl"); +} + +export function applyCacheProfile(profile: CacheProfile, params?: string | CacheTagParams) { + applyCacheLife(profile.cacheProfile); + const tags = [buildTag(profile, params)]; + if (profile.sharedTag) { + tags.push(profile.sharedTag); + } + if (profile.sharedTagPattern) { + tags.push(resolveTagPattern(profile, profile.sharedTagPattern, params)); + } + cacheTag(...tags); +} + +/** + * Next 16.3 generates one `cacheLife` overload per profile registered in next.config.js + * (no catch-all `string` overload), and a union argument doesn't distribute over overloads. + * Exhaustive dispatch keeps each Paper tier compile-checked against the registered profiles. + */ +function applyCacheLife(name: PaperCacheLifeProfile): void { + switch (name) { + case "catalog": + return cacheLife("catalog"); + case "menus": + return cacheLife("menus"); + case "channels": + return cacheLife("channels"); + case "listingTtl": + // Custom profile from next.config.js. The generated cacheLife overloads + // list built-ins only; the name is still the string `listingTtl` at runtime. + return cacheLife("listingTtl" as "default"); + default: { + // Adding a tier without a case above must fail typecheck here — otherwise the + // switch falls through and the entry silently inherits Next's default timings. + const unregistered: never = name; + throw new Error(`Unregistered cacheLife profile: ${String(unregistered)}`); + } + } +} + +// ============================================================================ +// Tag / path builders — used by the revalidation endpoint +// ============================================================================ + +export function buildTag(profile: CacheProfile, params?: string | CacheTagParams): string { + return resolveTagPattern(profile, profile.tagPattern, params); +} + +/** + * Channel catch-all for a channel+slug profile (`sharedTagPattern`) — the fallback + * tag when an event can't name the affected slugs, and the full-purge handle. + */ +export function buildCatchAllTag(profile: CacheProfile, channel: string): string { + if (!profile.sharedTagPattern) { + throw new Error(`[cache-manifest] Profile "${profile.id}" has no sharedTagPattern`); + } + return resolveTagPattern(profile, profile.sharedTagPattern, { channel }); +} + +function resolveTagPattern(profile: CacheProfile, pattern: string, params?: string | CacheTagParams): string { + const { slug, channel, locale } = normalizeTagParams(params); + let tag = pattern; + if (slug) tag = tag.replaceAll("{slug}", slug); + if (channel) tag = tag.replaceAll("{channel}", channel); + if (locale) tag = tag.replaceAll("{locale}", locale); + + if (UNRESOLVED_PLACEHOLDER.test(tag)) { + const missing = (["{slug}", "{channel}", "{locale}"] as const).filter((placeholder) => + tag.includes(placeholder), + ); + throw new Error( + `[cache-manifest] Unresolved tag "${tag}" for profile "${profile.id}". ` + + `Provide: ${missing.join(", ")}`, + ); + } + + return tag; +} + +export type BuildPathParams = { + channel: string; + slug?: string; + /** URL locale slug — defaults to configured default locale */ + locale?: string; +}; + +export function buildPath( + profile: CacheProfile, + channelOrParams: string | BuildPathParams, + legacySlug?: string, +): string | null { + if (!profile.pathPattern) return null; + + const params: BuildPathParams = + typeof channelOrParams === "string" ? { channel: channelOrParams, slug: legacySlug } : channelOrParams; + + const localeSlug = params.locale ?? getDefaultLocaleSlug(); + let path = profile.pathPattern.replaceAll("{locale}", localeSlug).replaceAll("{channel}", params.channel); + if (params.slug) path = path.replaceAll("{slug}", params.slug); + return path; +} + +/** Fan out a path pattern across all configured storefront locale slugs. */ +export function buildPathsForAllLocales( + profile: CacheProfile, + params: Omit, +): string[] { + return getStorefrontLocaleSlugs() + .map((locale) => buildPath(profile, { ...params, locale })) + .filter((path): path is string => path !== null); +} + +// ============================================================================ +// Manifest for /api/cache-info +// ============================================================================ + +// v7: listing tags sharded by surface/slug (listing:all|category|collection) with +// channel catch-alls — replaces the channel-wide product-listing:{channel} tag. +const MANIFEST_VERSION = 7; + +const STOREFRONT_MANIFEST_ENVIRONMENTS = ["production", "preview", "development", "staging"] as const; + +/** Manifest v6+ — which Saleor backend this deploy talks to (Paper handshake). */ +export type StorefrontManifestEnvironment = (typeof STOREFRONT_MANIFEST_ENVIRONMENTS)[number]; + +export interface StorefrontManifestIdentity { + saleorApiUrl: string; + environment?: StorefrontManifestEnvironment; + buildId?: string; + commit?: string; + branch?: string; +} + +function isStorefrontManifestEnvironment(value: string): value is StorefrontManifestEnvironment { + return (STOREFRONT_MANIFEST_ENVIRONMENTS as readonly string[]).includes(value); +} + +/** + * Map deploy hints to Paper's environment ladder. + * Prefer explicit `PAPER_STOREFRONT_ENVIRONMENT`, then Vercel, then NODE_ENV. + * + * An explicit but invalid override does **not** fall through — reporting the + * wrong ladder rung is worse for the Paper handshake than omitting it. + */ +export function resolveStorefrontManifestEnvironment( + // Next 16.3 types `ProcessEnv.NODE_ENV` as required; helpers accept partial bags for tests. + env: Partial = process.env, +): StorefrontManifestEnvironment | undefined { + const rawExplicit = env.PAPER_STOREFRONT_ENVIRONMENT?.trim(); + if (rawExplicit) { + const explicit = rawExplicit.toLowerCase(); + if (isStorefrontManifestEnvironment(explicit)) return explicit; + console.warn( + `[cache-manifest] Ignoring invalid PAPER_STOREFRONT_ENVIRONMENT="${rawExplicit}". ` + + `Expected ${STOREFRONT_MANIFEST_ENVIRONMENTS.join("|")}.`, + ); + return undefined; + } + + const vercel = env.VERCEL_ENV?.trim().toLowerCase(); + // Vercel only emits production|preview|development — never staging. + if (vercel === "production" || vercel === "preview" || vercel === "development") { + return vercel; + } + + if (env.NODE_ENV === "development") return "development"; + if (env.NODE_ENV === "production") return "production"; + return undefined; +} + +/** Canonicalize Saleor GraphQL URL for handshake equality (trailing slash). */ +export function normalizeSaleorApiUrlForManifest(url: string): string { + return url.endsWith("/") ? url : `${url}/`; +} + +/** Build the v6 identity block from env — omitted when Saleor URL is unset. */ +export function buildStorefrontManifestIdentity( + env: Partial = process.env, +): StorefrontManifestIdentity | undefined { + const rawSaleorApiUrl = env.NEXT_PUBLIC_SALEOR_API_URL?.trim(); + if (!rawSaleorApiUrl) return undefined; + + const identity: StorefrontManifestIdentity = { + saleorApiUrl: normalizeSaleorApiUrlForManifest(rawSaleorApiUrl), + }; + const environment = resolveStorefrontManifestEnvironment(env); + if (environment) identity.environment = environment; + + const buildId = env.VERCEL_DEPLOYMENT_ID?.trim(); + if (buildId) identity.buildId = buildId; + + const commit = env.VERCEL_GIT_COMMIT_SHA?.trim(); + if (commit) identity.commit = commit; + + const branch = env.VERCEL_GIT_COMMIT_REF?.trim(); + if (branch) identity.branch = branch; + + return identity; +} + +export function buildManifest() { + const identity = buildStorefrontManifestIdentity(); + + return { + version: MANIFEST_VERSION, + cacheLifeTiers: paperCacheLifeProfileDocs, + profiles: CACHE_PROFILE_LIST.map((p) => ({ + id: p.id, + label: p.label, + cacheProfile: p.cacheProfile, + tagPattern: p.tagPattern, + pathPattern: p.pathPattern, + ...(p.sharedTag ? { sharedTag: p.sharedTag } : {}), + ...(p.sharedTagPattern ? { sharedTagPattern: p.sharedTagPattern } : {}), + })), + locales: [...getStorefrontLocaleSlugs()], + defaultLocale: getDefaultLocaleSlug(), + channels: getStaticStorefrontChannelSlugs(), + menuSlugs: Object.keys(STOREFRONT_MENU_SLUGS), + ...(identity ? { identity } : {}), + }; +} diff --git a/apps/web/src/lib/saleor/cache/tag-primary.ts b/apps/web/src/lib/saleor/cache/tag-primary.ts new file mode 100644 index 0000000..d263818 --- /dev/null +++ b/apps/web/src/lib/saleor/cache/tag-primary.ts @@ -0,0 +1,17 @@ +import { cacheTag } from "next/cache"; +import { buildTag, type CacheProfile } from "./manifest"; + +/** + * When a page was fetched via a translated URL slug, also tag the entry with the + * primary slug so PRODUCT_/CATEGORY_/… webhooks (which carry the primary slug) bust + * the `"use cache"` payload. + */ +export function tagPrimaryCatalogSlug(profile: CacheProfile, urlSlug: string, primarySlug: string) { + if (urlSlug === primarySlug) return; + cacheTag(buildTag(profile, primarySlug)); +} + +/** Tag one slug even when it is the only handle (category slug → id lookups). */ +export function tagCatalogSlug(profile: CacheProfile, slug: string) { + cacheTag(buildTag(profile, slug)); +} diff --git a/apps/web/src/lib/saleor/client.ts b/apps/web/src/lib/saleor/client.ts new file mode 100644 index 0000000..1fbe632 --- /dev/null +++ b/apps/web/src/lib/saleor/client.ts @@ -0,0 +1,607 @@ +import "server-only"; + +import { io } from "next/cache"; +import packageJson from "../../../package.json"; +import { type TypedDocumentString } from "../../gql/graphql"; +import { recordResponse, takeReplay } from "./fixtures"; +import { recordSaleorCall } from "./ledger"; + +const USER_AGENT = `${packageJson.name}/${packageJson.version}`; + +// ============================================================================ +// Result Types - Explicit error handling without exceptions +// ============================================================================ + +/** + * Error layers in order of occurrence: + * 1. network - Failed to reach server (timeout, DNS, connection refused) + * 2. http - Server responded with error status (4xx, 5xx) + * 3. graphql - Query/mutation syntax or validation errors + * 4. validation - Saleor domain errors (e.g., "email already exists") + */ +export type GraphQLErrorType = "network" | "http" | "graphql" | "validation"; + +export interface GraphQLError { + type: GraphQLErrorType; + message: string; + /** HTTP status code (only for 'http' type) */ + statusCode?: number; + /** Whether the request could succeed if retried */ + isRetryable: boolean; + /** Saleor error codes from `errors[].extensions.code` (only for 'graphql' type) */ + codes?: readonly string[]; + /** Original error for debugging */ + cause?: unknown; + /** Saleor validation errors with field info (only for 'validation' type) */ + validationErrors?: ReadonlyArray<{ + field?: string | null; + message: string; + code?: string | null; + }>; +} + +/** One entry of a GraphQL `errors` array that arrived next to partial `data`. */ +export interface GraphQLPartialError { + message: string; + code?: string; + path?: readonly (string | number)[]; +} + +/** Success result with data */ +export interface GraphQLSuccess { + ok: true; + data: T; + /** + * Saleor resolved part of the query and failed the rest. The failed fields are + * `null` in `data`. `cachedQuery` throws on these; uncached reads may render them. + */ + partialErrors?: readonly GraphQLPartialError[]; +} + +/** Error result with typed error */ +export interface GraphQLFailure { + ok: false; + error: GraphQLError; +} + +/** Result type - either success with data or failure with error */ +export type GraphQLResult = GraphQLSuccess | GraphQLFailure; + +// ============================================================================ +// Helper functions +// ============================================================================ + +function networkError(message: string, cause?: unknown): GraphQLFailure { + return { + ok: false, + error: { type: "network", message, isRetryable: true, cause }, + }; +} + +function httpError(statusCode: number, message: string): GraphQLFailure { + return { + ok: false, + error: { + type: "http", + message, + statusCode, + isRetryable: statusCode >= 500 || statusCode === 429, + }, + }; +} + +function graphqlError(messages: string[], codes: string[] = []): GraphQLFailure { + return { + ok: false, + error: { + type: "graphql", + message: messages.join("\n"), + isRetryable: false, + ...(codes.length > 0 ? { codes } : {}), + }, + }; +} + +function validationError( + errors: ReadonlyArray<{ field?: string | null; message: string; code?: string | null }>, +): GraphQLFailure { + return { + ok: false, + error: { + type: "validation", + message: errors.map((e) => e.message).join(", "), + isRetryable: false, + validationErrors: errors, + }, + }; +} + +function success(data: T): GraphQLSuccess { + return { ok: true, data }; +} + +/** User-friendly message for each error type */ +export function getUserMessage(error: GraphQLError): string { + switch (error.type) { + case "network": + return "Unable to connect to the store. Please check your internet connection."; + case "http": + if (error.statusCode === 401 || error.statusCode === 403) { + return "You don't have permission to view this content."; + } + if (error.statusCode === 404) { + return "The item you're looking for doesn't exist or has been removed."; + } + return "The store is temporarily unavailable. Please try again in a moment."; + case "graphql": + return "Something went wrong loading this page."; + case "validation": + return error.message || "Please check your input and try again."; + } +} + +// ============================================================================ +// Request Queue for Rate Limiting +// ============================================================================ + +class RequestQueue { + private queue: Array<() => void> = []; + private activeRequests = 0; + private readonly maxConcurrent: number; + private readonly minDelayMs: number; + + constructor(maxConcurrent = 3, minDelayMs = 300) { + this.maxConcurrent = maxConcurrent; + this.minDelayMs = minDelayMs; + } + + async enqueue(fn: () => Promise): Promise { + await this.waitForSlot(); + this.activeRequests++; + + try { + if (this.minDelayMs <= 0) { + return await fn(); + } + const [result] = await Promise.all([fn(), sleep(this.minDelayMs)]); + return result; + } finally { + this.activeRequests--; + this.processQueue(); + } + } + + private waitForSlot(): Promise { + if (this.activeRequests < this.maxConcurrent) { + return Promise.resolve(); + } + return new Promise((resolve) => this.queue.push(resolve)); + } + + private processQueue(): void { + if (this.queue.length > 0 && this.activeRequests < this.maxConcurrent) { + const next = this.queue.shift(); + next?.(); + } + } +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function formatVariablesForLog(variables: Record): string { + const parts: string[] = []; + for (const [key, value] of Object.entries(variables)) { + if (value === undefined || value === null) continue; + const strValue = typeof value === "string" ? value : JSON.stringify(value); + const truncated = strValue.length > 30 ? strValue.slice(0, 30) + "…" : strValue; + parts.push(`${key}=${truncated}`); + } + return parts.length > 0 ? `(${parts.join(", ")})` : ""; +} + +/** + * The inter-request delay exists to survive `next build`, where `generateStaticParams` + * fans out enough parallel requests to trip Saleor's rate limiter. At runtime the + * concurrency cap already bounds pressure, so the delay only adds latency to every + * request — and on Fluid Compute you pay for that wall time. Default it off at runtime. + */ +const isBuildPhase = process.env.NEXT_PHASE === "phase-production-build"; + +const requestQueue = new RequestQueue( + parseInt(process.env.SALEOR_MAX_CONCURRENT_REQUESTS || "3", 10), + parseInt(process.env.SALEOR_MIN_REQUEST_DELAY_MS || (isBuildPhase ? "200" : "0"), 10), +); + +function getRetryConfig(overrides?: { maxRetries?: number; timeoutMs?: number }) { + const buildRetries = process.env.NEXT_BUILD_RETRIES; + const timeoutMs = parseInt(process.env.SALEOR_REQUEST_TIMEOUT_MS || "15000", 10); + const base = + buildRetries !== undefined + ? { maxRetries: parseInt(buildRetries, 10), delayMs: 500, timeoutMs } + : { maxRetries: 3, delayMs: 1000, timeoutMs }; + + return { + maxRetries: overrides?.maxRetries ?? base.maxRetries, + delayMs: base.delayMs, + timeoutMs: overrides?.timeoutMs ?? base.timeoutMs, + }; +} + +async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: number): Promise { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), timeoutMs); + + try { + return await fetch(url, { ...init, signal: controller.signal }); + } finally { + clearTimeout(timeoutId); + } +} + +// ============================================================================ +// Core Fetch with Retry +// ============================================================================ + +/** How to authenticate the request — session cookies or app token, never both. */ +export type GraphQLAuth = "none" | "session" | "app"; + +type FetchResult = GraphQLSuccess | GraphQLFailure; + +type RetryOverrides = { + maxRetries?: number; + timeoutMs?: number; + /** When set, session auth honors `timeoutMs` via AbortSignal. Default session fetches stay untimed. */ + abortSession?: boolean; +}; + +async function fetchWithRetry( + input: RequestInit, + auth: GraphQLAuth, + operationName: string, + variablesForLog?: string, + retry?: RetryOverrides, +): Promise { + const url = process.env.NEXT_PUBLIC_SALEOR_API_URL; + if (!url) { + return networkError("Missing NEXT_PUBLIC_SALEOR_API_URL env variable"); + } + + const { maxRetries, delayMs, timeoutMs } = getRetryConfig(retry); + const requestBody = typeof input.body === "string" ? input.body : undefined; + const replayed = takeReplay(operationName, requestBody); + if (replayed.status === "miss") return networkError(`${operationName}: ${replayed.message}`); + if (replayed.status === "hit") return success(replayed.response); + + for (let attempt = 0; attempt <= maxRetries; attempt++) { + try { + let response: Response; + + if (auth === "session") { + const { getServerAuthClient } = await import("@/lib/auth/server"); + const client = await getServerAuthClient(); + if (retry?.abortSession) { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), timeoutMs); + try { + response = await client.fetchWithAuth(url, { ...input, signal: controller.signal }); + } finally { + clearTimeout(timeoutId); + } + } else { + response = await client.fetchWithAuth(url, input); + } + } else { + response = await fetchWithTimeout(url, input, timeoutMs); + } + + // Retry on 429 (rate limit) or 5xx (server errors) + if ((response.status === 429 || response.status >= 500) && attempt < maxRetries) { + const retryAfter = response.headers.get("Retry-After"); + const retryDelayMs = retryAfter ? parseInt(retryAfter, 10) * 1000 : delayMs * Math.pow(2, attempt); + console.warn( + `[GraphQL] ${operationName}${variablesForLog ? ` ${variablesForLog}` : ""}: HTTP ${ + response.status + } - retrying in ${retryDelayMs}ms (attempt ${attempt + 1}/${maxRetries})`, + ); + await sleep(retryDelayMs); + continue; + } + + return success(await recordResponse(operationName, requestBody, response, auth)); + } catch (error) { + const isTimeout = error instanceof Error && error.name === "AbortError"; + if (attempt < maxRetries) { + const errorType = isTimeout ? `Timeout (>${timeoutMs}ms)` : "Network error"; + console.warn( + `[GraphQL] ${operationName}${ + variablesForLog ? ` ${variablesForLog}` : "" + }: ${errorType} - retrying (attempt ${attempt + 1}/${maxRetries})`, + ); + await sleep(delayMs * Math.pow(2, attempt)); + continue; + } + return networkError( + `${operationName}: ${isTimeout ? "Request timed out" : "Failed to connect to Saleor API"}`, + error, + ); + } + } + + return networkError(`${operationName}: Max retries exceeded`); +} + +// ============================================================================ +// GraphQL Execution +// ============================================================================ + +export type GraphQLOptions = { + headers?: HeadersInit; + /** + * Internal only. `liveQuery` / `sessionQuery` / `mutate` pass `no-cache`. + * Cached reads omit it so `"use cache"` owns freshness. There is no `revalidate`. + */ + cache?: RequestCache; + /** Set by the access-mode wrappers for the dev ledger. */ + ledgerMode?: string; + /** Override the default retry count (runtime: 3). Use `0` for best-effort side effects. */ + maxRetries?: number; + /** Override `SALEOR_REQUEST_TIMEOUT_MS`. Also applies to session auth (otherwise untimed). */ + timeoutMs?: number; +} & (Variables extends Record ? { variables?: never } : { variables: Variables }); + +type GraphQLResponseBody = { + data?: T | null; + errors?: readonly { + message?: string | null; + path?: readonly (string | number)[] | null; + extensions?: { code?: string | null } | null; + }[]; +}; + +/** Extract Saleor error codes from `errors[].extensions.code` (e.g. `ExpiredSignatureError`). */ +function extractErrorCodes(errors: GraphQLResponseBody["errors"]): string[] { + return errors?.map((e) => e.extensions?.code).filter((c): c is string => Boolean(c)) ?? []; +} + +function toPartialErrors(errors: GraphQLResponseBody["errors"]): GraphQLPartialError[] { + return (errors ?? []).map((e) => ({ + message: e.message || "Unknown GraphQL error", + ...(e.extensions?.code ? { code: e.extensions.code } : {}), + ...(e.path ? { path: e.path } : {}), + })); +} + +/** + * Internal base GraphQL executor. Returns a Result type. + */ +export async function executeGraphQL( + operation: TypedDocumentString, + options: GraphQLOptions & { auth: GraphQLAuth }, +): Promise> { + const { variables, headers, cache, auth, maxRetries, timeoutMs, ledgerMode } = options; + + // `Date.now()` during a page prerender makes the route blocking. Search and other + // live reads hit that clock here, and session auth hits it again inside + // `@saleor/auth-sdk`'s `fetchWithAuth`. `io()` moves this call into the dynamic + // stage first. Cached reads omit `cache: "no-cache"` and must not call `io()` — + // they run inside `"use cache"`. + if (cache === "no-cache") { + await io(); + } + + const started = Date.now(); + + const operationName = operation.toString().match(/(?:query|mutation)\s+(\w+)/)?.[1] || "UnknownOperation"; + const variablesForLog = variables ? formatVariablesForLog(variables) : undefined; + const finish = (result: GraphQLResult): GraphQLResult => { + recordSaleorCall({ + op: operationName, + mode: ledgerMode ?? "raw", + auth, + ok: result.ok, + ms: Date.now() - started, + }); + return result; + }; + + if (process.env.NODE_ENV === "development" && process.env.DEBUG_CACHE) { + console.log( + `[GraphQL] ${operationName} | auth: ${auth} | cache: ${cache || "default"} | mode: ${ledgerMode || "raw"}`, + ); + } + + const requestHeaders: Record = { + "Content-Type": "application/json", + "User-Agent": USER_AGENT, + ...(headers as Record | undefined), + }; + + if (auth === "app") { + const token = process.env.SALEOR_APP_TOKEN; + if (!token) { + return finish(networkError("Missing SALEOR_APP_TOKEN")); + } + requestHeaders.Authorization = `Bearer ${token}`; + } + + const input: RequestInit = { + method: "POST", + headers: requestHeaders, + body: JSON.stringify({ + query: operation.toString(), + ...(variables && { variables }), + }), + ...(cache !== undefined ? { cache } : {}), + }; + + const fetchResult = await requestQueue.enqueue(() => + fetchWithRetry(input, auth, operationName, variablesForLog, { + maxRetries, + timeoutMs, + abortSession: timeoutMs !== undefined, + }), + ); + + if (!fetchResult.ok) { + return finish(fetchResult); + } + + const response = fetchResult.data; + + if (!response.ok) { + const body = await response.text().catch(() => ""); + return finish(httpError(response.status, `HTTP ${response.status}: ${response.statusText}\n${body}`)); + } + + const body = (await response.json()) as GraphQLResponseBody; + const messages = body.errors?.map((e) => e.message).filter((m): m is string => Boolean(m)) ?? []; + + // GraphQL allows partial success — return data when Saleor included it, and keep + // the errors: a failed resolver reads as `null`, which a cached read must not keep. + if (body.data !== null && body.data !== undefined) { + if (body.errors?.length) { + const partialErrors = toPartialErrors(body.errors); + console.warn( + `[GraphQL] ${operationName}${variablesForLog ? ` ${variablesForLog}` : ""}: partial data with ${ + partialErrors.length + } error(s): ${partialErrors.map((e) => e.message).join(" | ")}`, + ); + return finish({ ...success(body.data), partialErrors }); + } + return finish(success(body.data)); + } + + if (messages.length > 0) { + return finish(graphqlError(messages, extractErrorCodes(body.errors))); + } + + return finish(graphqlError(["No data in GraphQL response"])); +} + +// ============================================================================ +// Raw GraphQL Execution (for API routes without codegen) +// ============================================================================ + +interface RawGraphQLOptions { + query: string; + variables?: Record; + headers?: HeadersInit; +} + +/** + * Execute a raw GraphQL mutation without codegen types. + * Use this for API routes (auth, etc.) that don't use codegen. + * + * @example + * const result = await executeRawGraphQL({ + * query: `mutation Register($input: AccountRegisterInput!) { ... }`, + * variables: { input: { email, password } }, + * }); + * + * if (!result.ok) { + * return NextResponse.json({ error: result.error.message }, { status: 400 }); + * } + * + * // Access mutation result + * const { accountRegister } = result.data; + * if (accountRegister.errors?.length) { + * return validationErrorResponse(accountRegister.errors); + * } + */ +export async function executeRawGraphQL(options: RawGraphQLOptions): Promise> { + const url = process.env.NEXT_PUBLIC_SALEOR_API_URL; + if (!url) { + return networkError("Missing NEXT_PUBLIC_SALEOR_API_URL env variable"); + } + + const { query, variables, headers } = options; + const operationName = query.match(/(?:query|mutation)\s+(\w+)/)?.[1] || "RawOperation"; + + try { + const response = await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT, ...headers }, + body: JSON.stringify({ query, variables }), + }); + + if (!response.ok) { + const body = await response.text().catch(() => ""); + return httpError(response.status, `HTTP ${response.status}: ${response.statusText}\n${body}`); + } + + const body = (await response.json()) as GraphQLResponseBody; + const messages = body.errors?.map((e) => e.message).filter((m): m is string => Boolean(m)) ?? []; + + if (body.data !== null && body.data !== undefined) { + return success(body.data); + } + + if (messages.length > 0) { + return graphqlError(messages, extractErrorCodes(body.errors)); + } + + return graphqlError(["No data in GraphQL response"]); + } catch (error) { + return networkError(`${operationName}: Failed to execute`, error); + } +} + +/** + * Helper to create a validation error result from Saleor mutation errors. + * Use after checking the mutation response for domain errors. + * + * @example + * const { accountRegister } = result.data; + * if (accountRegister.errors?.length) { + * return asValidationError(accountRegister.errors); + * } + */ +export function asValidationError( + errors: ReadonlyArray<{ field?: string | null; message: string; code?: string | null }>, +): GraphQLFailure { + return validationError(errors); +} + +// ============================================================================ +// Legacy exports (for gradual migration) +// ============================================================================ + +// Re-export error types for backwards compatibility during migration +export type SaleorErrorType = GraphQLErrorType; + +/** + * @deprecated Use Result pattern instead. This class is kept for gradual migration. + */ +export class SaleorError extends Error { + public readonly type: SaleorErrorType; + public readonly statusCode?: number; + public readonly isRetryable: boolean; + + constructor( + message: string, + options: { + type: SaleorErrorType; + statusCode?: number; + isRetryable?: boolean; + cause?: unknown; + }, + ) { + super(message, { cause: options.cause }); + this.name = "SaleorError"; + this.type = options.type; + this.statusCode = options.statusCode; + this.isRetryable = options.isRetryable ?? (options.type === "network" || options.type === "http"); + Object.setPrototypeOf(this, new.target.prototype); + } + + get userMessage(): string { + return getUserMessage({ + type: this.type, + message: this.message, + statusCode: this.statusCode, + isRetryable: this.isRetryable, + }); + } +} diff --git a/apps/web/src/lib/saleor/extensions.ts b/apps/web/src/lib/saleor/extensions.ts new file mode 100644 index 0000000..6304924 --- /dev/null +++ b/apps/web/src/lib/saleor/extensions.ts @@ -0,0 +1,12 @@ +import { dataExtensions } from "@/config/data-extensions"; +import type { CacheProfile } from "./cache/manifest"; + +/** + * Fork extension records, merged into the manifest, webhook map, and operation registry. + * The core directory does not contain merchant-specific profiles. + */ +export const extensionCacheProfiles = dataExtensions.profiles as Record; + +export const extensionWebhookScopes = dataExtensions.webhookScopes; + +export const extensionOperations = dataExtensions.operations; diff --git a/apps/web/src/lib/saleor/fixtures.test.ts b/apps/web/src/lib/saleor/fixtures.test.ts new file mode 100644 index 0000000..f391046 --- /dev/null +++ b/apps/web/src/lib/saleor/fixtures.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "vitest"; +import { canRecordFixture, fixtureKey } from "./fixtures"; + +describe("canRecordFixture", () => { + it("records anonymous queries only", () => { + const query = JSON.stringify({ query: "query ProductDetails { product { id } }" }); + expect(canRecordFixture("none", query)).toBe(true); + expect(fixtureKey("ProductDetails", query)).toMatch(/^ProductDetails\.[0-9a-f]{16}\.json$/); + expect(canRecordFixture("session", query)).toBe(false); + expect(canRecordFixture("app", query)).toBe(false); + }); + + it("refuses mutations so passwords and tokens are not written to disk", () => { + const mutation = JSON.stringify({ + query: + "mutation AccountRegister($input: AccountRegisterInput!) { accountRegister(input: $input) { user { id } } }", + variables: { input: { email: "a@b.c", password: "secret" } }, + }); + expect(canRecordFixture("none", mutation)).toBe(false); + expect(fixtureKey("AccountRegister", mutation)).toBeNull(); + }); + + it("does not build a fixture name from a password change", () => { + const body = JSON.stringify({ + query: + "mutation PasswordChange($oldPassword: String!, $newPassword: String!) { passwordChange(oldPassword: $oldPassword, newPassword: $newPassword) { errors { message } } }", + variables: { oldPassword: "current-secret", newPassword: "next-secret" }, + }); + expect(fixtureKey("PasswordChange", body)).toBeNull(); + }); +}); diff --git a/apps/web/src/lib/saleor/fixtures.ts b/apps/web/src/lib/saleor/fixtures.ts new file mode 100644 index 0000000..d19a6b9 --- /dev/null +++ b/apps/web/src/lib/saleor/fixtures.ts @@ -0,0 +1,153 @@ +import "server-only"; + +import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs"; +import { join } from "node:path"; + +export type FixtureMode = "record" | "replay" | "off"; + +export type SaleorFixture = { + operationName: string; + status: number; + body: unknown; +}; + +const ROOT = join(process.cwd(), "e2e/fixtures/saleor"); + +const SECRET_KEYS = new Set([ + "password", + "oldPassword", + "newPassword", + "confirmPassword", + "token", + "refreshToken", + "accessToken", + "csrfToken", + "secret", + "authorization", +]); + +export function fixtureMode(raw: string | undefined = process.env.SALEOR_FIXTURES): FixtureMode { + if (raw === "record" || raw === "replay") return raw; + return "off"; +} + +function containsSecret(value: unknown): boolean { + if (!value || typeof value !== "object") return false; + if (Array.isArray(value)) return value.some(containsSecret); + for (const [key, child] of Object.entries(value as Record)) { + if (SECRET_KEYS.has(key) || containsSecret(child)) return true; + } + return false; +} + +/** + * Text that may identify a public query fixture. + * Mutations and any body carrying a password or token return null so those + * bytes are never hashed or written to disk. + */ +function publicQueryIdentity(body: string | undefined): string | null { + if (!body) return null; + try { + const parsed = JSON.parse(body) as { query?: unknown; variables?: unknown }; + if (typeof parsed.query !== "string" || !/^\s*query\b/.test(parsed.query)) return null; + if (containsSecret(parsed.variables)) return null; + return `${parsed.query}\n${JSON.stringify(parsed.variables ?? null)}`; + } catch { + return null; + } +} + +/** Filename disambiguator. Not a password hash — secrets never reach this. */ +function fingerprint(value: string): string { + let h1 = 0x811c9dc5; + let h2 = 0x01000193; + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + h1 = Math.imul(h1 ^ code, 0x01000193); + h2 = Math.imul(h2 ^ (code + 1), 0x01000193); + } + return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0"); +} + +export function fixtureKey(operationName: string, body: string | undefined): string | null { + const identity = publicQueryIdentity(body); + if (identity === null) return null; + return `${operationName}.${fingerprint(`${operationName}\n${identity}`)}.json`; +} + +export function readFixture(operationName: string, body: string | undefined): SaleorFixture | null { + const key = fixtureKey(operationName, body); + if (!key) return null; + const path = join(ROOT, key); + if (!existsSync(path)) return null; + return JSON.parse(readFileSync(path, "utf8")) as SaleorFixture; +} + +export function writeFixture(operationName: string, body: string | undefined, fixture: SaleorFixture): void { + const key = fixtureKey(operationName, body); + if (!key) return; + mkdirSync(ROOT, { recursive: true }); + writeFileSync(join(ROOT, key), JSON.stringify(fixture, null, 2)); +} + +/** + * Public queries only. Mutations and session/app calls carry passwords, tokens, + * and customer payloads — never write those into a fixture file. + */ +export function canRecordFixture(auth: string, requestBody: string | undefined): boolean { + return auth === "none" && publicQueryIdentity(requestBody) !== null; +} + +export type ReplayResult = + | { status: "off" } + | { status: "hit"; response: Response } + | { status: "miss"; message: string }; + +/** Replay a public fixture. A miss is a result, not a throw, so callers keep the Result path. */ +export function takeReplay(operationName: string, body: string | undefined): ReplayResult { + const mode = fixtureMode(); + if (mode !== "replay") return { status: "off" }; + const key = fixtureKey(operationName, body); + if (!key) return { status: "off" }; + + const fixture = readFixture(operationName, body); + if (!fixture) { + return { + status: "miss", + message: + `No fixture for ${operationName}. Record one with SALEOR_FIXTURES=record ` + + `(e2e/fixtures/saleor/${key}).`, + }; + } + + return { + status: "hit", + response: new Response(JSON.stringify(fixture.body), { + status: fixture.status, + headers: { "Content-Type": "application/json", "x-paper-fixture": "replay" }, + }), + }; +} + +export async function recordResponse( + operationName: string, + requestBody: string | undefined, + response: Response, + auth: string, +): Promise { + if (fixtureMode() !== "record" || !canRecordFixture(auth, requestBody)) return response; + + const clone = response.clone(); + let body: unknown = null; + try { + body = await clone.json(); + } catch { + body = await clone.text(); + } + writeFixture(operationName, requestBody, { + operationName, + status: response.status, + body, + }); + return response; +} diff --git a/apps/web/src/lib/saleor/index.ts b/apps/web/src/lib/saleor/index.ts new file mode 100644 index 0000000..ddddaa7 --- /dev/null +++ b/apps/web/src/lib/saleor/index.ts @@ -0,0 +1,67 @@ +import "server-only"; + +export { cachedQuery, liveQuery, mutate, SaleorDataError, sessionQuery } from "./access"; +export { asValidationError, getUserMessage, SaleorError } from "./client"; +export type { + GraphQLError, + GraphQLFailure, + GraphQLPartialError, + GraphQLResult, + GraphQLSuccess, + SaleorErrorType, +} from "./client"; +export { applyCacheProfile as bindCacheProfile, applyListingTtl } from "./cache/manifest"; +export { + buildCatchAllTag, + buildManifest, + buildMenuRevalidationTags, + buildPathsForAllLocales, + buildPath, + buildStorefrontContentCacheTags, + buildStorefrontManifestIdentity, + buildTag, + CACHE_PROFILE_LIST, + CACHE_PROFILES, + extractMenuSlugFromWebhookPayload, + extractPageSlugFromWebhookPayload, + FOOTER_MENU_SLUG, + isChannelLocaleScopedTagProfile, + isChannelScopedTagProfile, + isGlobalTagProfile, + isKnownStorefrontMenuSlug, + NAVBAR_MENU_SLUG, + planFullPurgeTagEntries, + planMenuRevalidation, + planPageRevalidation, + planStorefrontContentRevalidation, + resolveCacheLifeProfileForTag, + resolveCacheProfileForMenuSlug, + resolveManualRevalidateTag, + resolveRevalidateProfileForTag, + resolveStorefrontManifestEnvironment, + STOREFRONT_MENU_SLUGS, +} from "./cache/manifest"; +export type { + CacheLifeProfile, + CacheProfile, + CacheTagParams, + MenuRevalidationPlan, + PageRevalidationPlan, + StorefrontContentRevalidationPlan, + StorefrontManifestEnvironment, + StorefrontManifestIdentity, + StorefrontMenuSlug, +} from "./cache/manifest"; +export { tagCatalogSlug, tagPrimaryCatalogSlug } from "./cache/tag-primary"; +export { paperCacheLifeProfiles, PAPER_CACHE_LIFE_PROFILE_NAMES } from "./cache/life-profiles"; +export type { PaperCacheLifeProfile } from "./cache/life-profiles"; +export { + bustListingAllOnProductEvent, + deliveryFingerprint, + resolveWebhookEventScope, + sanitizeLogValue, +} from "./invalidation/webhook-events"; +export type { WebhookEntity, WebhookEventScope } from "./invalidation/webhook-events"; +export { revalidateTags } from "./invalidation/revalidate-tags"; +export { recentSaleorCalls, resetSaleorLedger } from "./ledger"; +export { rawMutation } from "./raw"; diff --git a/apps/web/src/lib/saleor/invalidation/revalidate-tags.ts b/apps/web/src/lib/saleor/invalidation/revalidate-tags.ts new file mode 100644 index 0000000..e03dba8 --- /dev/null +++ b/apps/web/src/lib/saleor/invalidation/revalidate-tags.ts @@ -0,0 +1,15 @@ +import { revalidateTag } from "next/cache"; +import type { CacheLifeProfile, CacheProfile } from "../cache/manifest"; + +/** + * Revalidate multiple tags in parallel. + * Sequential revalidateTag() calls in one request only honor the first tag in some Next.js versions. + */ +export async function revalidateTags( + entries: ReadonlyArray<{ tag: string; profile: CacheLifeProfile | CacheProfile["cacheProfile"] }>, +): Promise { + if (entries.length === 0) return []; + + await Promise.all(entries.map(({ tag, profile }) => revalidateTag(tag, profile))); + return entries.map(({ tag }) => tag); +} diff --git a/apps/web/src/lib/saleor/invalidation/webhook-events.test.ts b/apps/web/src/lib/saleor/invalidation/webhook-events.test.ts new file mode 100644 index 0000000..208a2cd --- /dev/null +++ b/apps/web/src/lib/saleor/invalidation/webhook-events.test.ts @@ -0,0 +1,116 @@ +import { describe, it, expect } from "vitest"; +import { + bustListingAllOnProductEvent, + deliveryFingerprint, + resolveWebhookEventScope, + sanitizeLogValue, +} from "./webhook-events"; + +describe("resolveWebhookEventScope", () => { + it("returns null for events Paper does not act on", () => { + // The regression this guards: these used to fall through to a broad purge of + // the product listing on every locale. + expect(resolveWebhookEventScope("order_created")).toBeNull(); + expect(resolveWebhookEventScope("checkout_updated")).toBeNull(); + expect(resolveWebhookEventScope("customer_created")).toBeNull(); + expect(resolveWebhookEventScope("gift_card_created")).toBeNull(); + }); + + it("returns null for a missing header so payload inference can take over", () => { + expect(resolveWebhookEventScope(null)).toBeNull(); + expect(resolveWebhookEventScope(undefined)).toBeNull(); + expect(resolveWebhookEventScope("")).toBeNull(); + }); + + it("maps catalog events to their entity", () => { + expect(resolveWebhookEventScope("product_updated")?.entity).toBe("product"); + expect(resolveWebhookEventScope("product_variant_updated")?.entity).toBe("product"); + expect(resolveWebhookEventScope("category_updated")?.entity).toBe("category"); + expect(resolveWebhookEventScope("collection_updated")?.entity).toBe("collection"); + expect(resolveWebhookEventScope("page_updated")?.entity).toBe("page"); + expect(resolveWebhookEventScope("menu_item_updated")?.entity).toBe("menu"); + expect(resolveWebhookEventScope("channel_updated")?.entity).toBe("channel"); + }); + + it("marks events that can change a listing card", () => { + expect(resolveWebhookEventScope("product_created")?.affectsListing).toBe(true); + expect(resolveWebhookEventScope("product_updated")?.affectsListing).toBe(true); + expect(resolveWebhookEventScope("product_deleted")?.affectsListing).toBe(true); + expect(resolveWebhookEventScope("product_media_updated")?.affectsListing).toBe(true); + expect(resolveWebhookEventScope("product_variant_discounted_price_updated")?.affectsListing).toBe(true); + expect(resolveWebhookEventScope("product_variant_created")?.affectsListing).toBe(true); + expect(resolveWebhookEventScope("product_variant_updated")?.affectsListing).toBe(true); + expect(resolveWebhookEventScope("product_variant_deleted")?.affectsListing).toBe(true); + }); + + it("keeps stock and metadata churn off the listing cache", () => { + // These fire constantly on inventory sync; busting listings here would leave + // the listing cache permanently cold. + const detailOnly = [ + "product_metadata_updated", + "product_variant_metadata_updated", + "product_variant_out_of_stock", + "product_variant_back_in_stock", + "product_variant_stock_updated", + "product_variant_out_of_stock_in_channel", + "product_variant_back_in_stock_in_channel", + "product_variant_out_of_stock_for_click_and_collect", + "product_variant_back_in_stock_for_click_and_collect", + ]; + + for (const event of detailOnly) { + expect(resolveWebhookEventScope(event), event).toEqual({ + entity: "product", + affectsListing: false, + }); + } + }); + + it("normalizes header casing and whitespace", () => { + expect(resolveWebhookEventScope("PRODUCT_UPDATED")?.entity).toBe("product"); + expect(resolveWebhookEventScope(" product_updated ")?.entity).toBe("product"); + }); +}); + +describe("bustListingAllOnProductEvent", () => { + it("defaults on so existing shops keep current invalidation", () => { + expect(bustListingAllOnProductEvent(undefined)).toBe(true); + expect(bustListingAllOnProductEvent("")).toBe(true); + expect(bustListingAllOnProductEvent(" ")).toBe(true); + }); + + it("turns off for high-churn catalogs", () => { + expect(bustListingAllOnProductEvent("0")).toBe(false); + expect(bustListingAllOnProductEvent("false")).toBe(false); + expect(bustListingAllOnProductEvent("OFF")).toBe(false); + }); + + it("accepts explicit on values", () => { + expect(bustListingAllOnProductEvent("1")).toBe(true); + expect(bustListingAllOnProductEvent("true")).toBe(true); + }); + + it("fails open on garbage so a typo does not silently skip listing:all", () => { + expect(bustListingAllOnProductEvent("sometimes")).toBe(true); + }); +}); + +describe("sanitizeLogValue", () => { + it("strips newlines so a header cannot forge extra log lines", () => { + expect(sanitizeLogValue("product_updated\n[Revalidate] forged")).toBe( + "product_updated[Revalidate] forged", + ); + expect(sanitizeLogValue(null)).toBe(""); + }); +}); + +describe("deliveryFingerprint", () => { + it("is stable for the same body so duplicate deliveries are greppable", () => { + const body = JSON.stringify({ product: { slug: "blue-hoodie" } }); + expect(deliveryFingerprint(body)).toBe(deliveryFingerprint(body)); + }); + + it("differs for different bodies", () => { + expect(deliveryFingerprint('{"a":1}')).not.toBe(deliveryFingerprint('{"a":2}')); + }); +}); diff --git a/apps/web/src/lib/saleor/invalidation/webhook-events.ts b/apps/web/src/lib/saleor/invalidation/webhook-events.ts new file mode 100644 index 0000000..794e2d3 --- /dev/null +++ b/apps/web/src/lib/saleor/invalidation/webhook-events.ts @@ -0,0 +1,142 @@ +/** + * Saleor webhook event → invalidation scope. + * + * Saleor sends the event type in the `saleor-event` header (lowercase snake_case, + * e.g. `product_updated`) on every delivery. Paper drives invalidation from that + * header rather than guessing from payload shape, so an event we do not act on + * (orders, checkouts, customers, …) is skipped instead of triggering a broad purge. + * + * `affectsListing` separates events that can change how a product appears in a grid + * (created/deleted/renamed/repriced/new media, plus variant CRUD — channel listing + * price and priceRange live on the variant) from the high-frequency churn that cannot + * (stock movements, metadata writes). Inventory sync must not cost a listing cache + * entry. + * + * Event names verified against saleor/webhook/event_types.py (WebhookEventAsyncType). + */ + +import { createHash } from "crypto"; +import { extensionWebhookScopes } from "../extensions"; + +/** Entities Paper caches and can therefore invalidate. */ +export type WebhookEntity = "product" | "category" | "collection" | "page" | "menu" | "channel"; + +export interface WebhookEventScope { + entity: WebhookEntity; + /** Event can add, remove, or reshape a listing card → bust the listing tag. */ + affectsListing: boolean; +} + +const PRODUCT_LISTING: WebhookEventScope = { entity: "product", affectsListing: true }; +const PRODUCT_DETAIL_ONLY: WebhookEventScope = { entity: "product", affectsListing: false }; + +/** + * Events Paper acts on. Anything absent here is deliberately ignored — adding an entry + * is how you opt a new event into invalidation. + */ +const WEBHOOK_EVENT_SCOPES: Readonly> = { + // Listing membership or card content changed. + product_created: PRODUCT_LISTING, + product_updated: PRODUCT_LISTING, + product_deleted: PRODUCT_LISTING, + product_media_created: PRODUCT_LISTING, + product_media_updated: PRODUCT_LISTING, + product_media_deleted: PRODUCT_LISTING, + product_variant_discounted_price_updated: PRODUCT_LISTING, + // Variant CRUD can change the card's priceRange. Saleor does not reliably also + // emit product_updated for a channel-listing price edit. + product_variant_created: PRODUCT_LISTING, + product_variant_updated: PRODUCT_LISTING, + product_variant_deleted: PRODUCT_LISTING, + + // PDP-only: cannot change a listing card, and fires far more often. + product_metadata_updated: PRODUCT_DETAIL_ONLY, + product_variant_metadata_updated: PRODUCT_DETAIL_ONLY, + product_variant_out_of_stock: PRODUCT_DETAIL_ONLY, + product_variant_back_in_stock: PRODUCT_DETAIL_ONLY, + product_variant_stock_updated: PRODUCT_DETAIL_ONLY, + product_variant_out_of_stock_in_channel: PRODUCT_DETAIL_ONLY, + product_variant_back_in_stock_in_channel: PRODUCT_DETAIL_ONLY, + product_variant_out_of_stock_for_click_and_collect: PRODUCT_DETAIL_ONLY, + product_variant_back_in_stock_for_click_and_collect: PRODUCT_DETAIL_ONLY, + + category_created: { entity: "category", affectsListing: true }, + category_updated: { entity: "category", affectsListing: true }, + category_deleted: { entity: "category", affectsListing: true }, + + collection_created: { entity: "collection", affectsListing: true }, + collection_updated: { entity: "collection", affectsListing: true }, + collection_deleted: { entity: "collection", affectsListing: true }, + collection_metadata_updated: { entity: "collection", affectsListing: false }, + + page_created: { entity: "page", affectsListing: false }, + page_updated: { entity: "page", affectsListing: false }, + page_deleted: { entity: "page", affectsListing: false }, + + menu_created: { entity: "menu", affectsListing: false }, + menu_updated: { entity: "menu", affectsListing: false }, + menu_deleted: { entity: "menu", affectsListing: false }, + menu_item_created: { entity: "menu", affectsListing: false }, + menu_item_updated: { entity: "menu", affectsListing: false }, + menu_item_deleted: { entity: "menu", affectsListing: false }, + + channel_created: { entity: "channel", affectsListing: false }, + channel_updated: { entity: "channel", affectsListing: false }, + channel_deleted: { entity: "channel", affectsListing: false }, + channel_status_changed: { entity: "channel", affectsListing: false }, + channel_metadata_updated: { entity: "channel", affectsListing: false }, + ...extensionWebhookScopes, +}; + +/** + * Resolve the `saleor-event` header to an invalidation scope. + * Returns null for events Paper does not act on, and for a missing header + * (manual/direct POSTs fall back to payload-shape inference). + */ +export function resolveWebhookEventScope(eventHeader: string | null | undefined): WebhookEventScope | null { + if (!eventHeader) return null; + return WEBHOOK_EVENT_SCOPES[eventHeader.trim().toLowerCase()] ?? null; +} + +/** + * High-churn catalogs (unique SKUs that turn over quickly) fire listing-affecting + * product events constantly. Busting `listing:all:{channel}` on every sale keeps + * the all-products grid permanently cold. Category/collection shards still bust. + * + * Default is on (current Paper behavior). Set `PAPER_BUST_LISTING_ALL_ON_PRODUCT_EVENT=0` + * when the all-products first page changing every few minutes is not worth a + * regeneration — the `catalog` cacheLife backstop (1 h) is then the freshness path. + */ +export function bustListingAllOnProductEvent( + raw: string | undefined = process.env.PAPER_BUST_LISTING_ALL_ON_PRODUCT_EVENT, +): boolean { + if (raw === undefined || raw.trim() === "") return true; + const normalized = raw.trim().toLowerCase(); + if (["0", "false", "no", "off"].includes(normalized)) return false; + if (["1", "true", "yes", "on"].includes(normalized)) return true; + console.warn( + `[revalidate] Ignoring invalid PAPER_BUST_LISTING_ALL_ON_PRODUCT_EVENT="${raw.replace(/[\r\n]/g, "")}". ` + + `Expected 0/1 (or true/false). Defaulting to on.`, + ); + return true; +} + +/** Header values are attacker-influenced; keep them on one log line. */ +export function sanitizeLogValue(value: string | null | undefined): string { + return value?.replace(/[\r\n]/g, "") ?? ""; +} + +/** + * Short fingerprint of a delivery body. + * + * Paper's docs warn against running direct Saleor webhooks alongside saleor-paper-app, + * because both deliver the same events and every invalidation is paid for twice. That + * misconfiguration is invisible in aggregate metrics but obvious in the logs: the same + * fingerprint arriving twice within seconds is a duplicate subscription, not two edits. + * + * Not used to *drop* deliveries — functions are multi-instance, so dedup here would be + * unreliable in exactly the way that silently loses invalidations. + */ +export function deliveryFingerprint(rawBody: string): string { + return createHash("sha1").update(rawBody).digest("hex").slice(0, 12); +} diff --git a/apps/web/src/lib/saleor/ledger.ts b/apps/web/src/lib/saleor/ledger.ts new file mode 100644 index 0000000..5a134d3 --- /dev/null +++ b/apps/web/src/lib/saleor/ledger.ts @@ -0,0 +1,42 @@ +import "server-only"; + +export type SaleorLedgerEntry = { + op: string; + mode: string; + auth: string; + ok: boolean; + ms: number; + at: string; +}; + +const MAX_ENTRIES = 200; + +type LedgerState = { + entries: SaleorLedgerEntry[]; +}; + +const state: LedgerState = { entries: [] }; + +export function saleorLedgerEnabled(): boolean { + return process.env.NODE_ENV === "development" || process.env.PAPER_SALEOR_LEDGER === "1"; +} + +export function recordSaleorCall(entry: Omit): void { + if (!saleorLedgerEnabled()) return; + + const full: SaleorLedgerEntry = { ...entry, at: new Date().toISOString() }; + state.entries.push(full); + if (state.entries.length > MAX_ENTRIES) { + state.entries.splice(0, state.entries.length - MAX_ENTRIES); + } + + console.log(`[paper:saleor] op=${full.op} mode=${full.mode} auth=${full.auth} ok=${full.ok} ms=${full.ms}`); +} + +export function recentSaleorCalls(): readonly SaleorLedgerEntry[] { + return state.entries; +} + +export function resetSaleorLedger(): void { + state.entries.length = 0; +} diff --git a/apps/web/src/lib/saleor/operations.ts b/apps/web/src/lib/saleor/operations.ts new file mode 100644 index 0000000..611ba7f --- /dev/null +++ b/apps/web/src/lib/saleor/operations.ts @@ -0,0 +1,157 @@ +import { extensionOperations } from "./extensions"; + +/** + * One entry per Saleor operation Paper ships. + * + * `cached` operations may also be read with `liveQuery` (filtered listings). + * The reverse is rejected: a session read or a mutation cannot be cached. + */ + +export type OperationAccess = "cached" | "live" | "session" | "mutate"; +export type OperationAuth = "none" | "session" | "app"; +export type CacheScope = "channel-locale" | "locale" | "global"; + +export type OperationSpec = { + access: OperationAccess; + auth: OperationAuth; + scope?: CacheScope; +}; + +const cached = (scope: CacheScope, auth: OperationAuth = "none"): OperationSpec => ({ + access: "cached", + auth, + scope, +}); +const live = (auth: OperationAuth = "none"): OperationSpec => ({ access: "live", auth }); +const session = (): OperationSpec => ({ access: "session", auth: "session" }); +const mutate = (auth: OperationAuth = "session"): OperationSpec => ({ access: "mutate", auth }); + +const CORE_OPERATIONS = { + // Storefront catalog — cached, and readable live for the uncached long tail. + ProductDetails: cached("channel-locale"), + ProductVariantForPdp: cached("channel-locale"), + ProductVariantsForPdp: cached("channel-locale"), + ProductList: cached("channel-locale"), + ProductListPaginated: cached("channel-locale"), + ProductListByCategory: cached("channel-locale"), + ProductListByCategoryProducts: cached("channel-locale"), + ProductListByCollection: cached("channel-locale"), + ProductListByCollectionProducts: cached("channel-locale"), + PageGetBySlug: cached("locale"), + MenuGetBySlug: cached("channel-locale"), + StorefrontContentPages: cached("channel-locale"), + CategoriesBySlug: cached("global"), + ChannelsList: cached("global", "app"), + + // Storefront session reads. + CurrentUser: session(), + CurrentUserProfile: session(), + CurrentUserOrderList: session(), + CurrentUserOrdersPaginated: session(), + OrderByNumber: session(), + + // Storefront cart and account mutations. + CheckoutFind: live(), + CheckoutCreate: mutate(), + CheckoutAddLine: mutate(), + CheckoutDeleteLines: mutate(), + CheckoutLinesUpdate: mutate(), + CheckoutCustomerDetach: mutate(), + AccountUpdate: mutate(), + PasswordChange: mutate(), + AccountAddressCreate: mutate(), + AccountAddressUpdate: mutate(), + AccountAddressDelete: mutate(), + AccountSetDefaultAddress: mutate(), + AccountRequestDeletion: mutate(), + + // Checkout surface (operation names are the GraphQL names, not the TS exports). + checkout: live(), + checkoutCommerceContext: live(), + channel: live(), + addressValidationRules: live(), + order: live(), + ordersByNumber: live("app"), + user: session(), + checkoutLinesUpdate: mutate(), + checkoutLineDelete: mutate(), + checkoutEmailUpdate: mutate(), + checkoutMetadataUpdate: mutate(), + checkoutCustomerAttach: mutate(), + checkoutCustomerDetach: mutate(), + checkoutCreate: mutate(), + checkoutLinesAdd: mutate(), + checkoutShippingAddressUpdate: mutate(), + checkoutBillingAddressUpdate: mutate(), + checkoutDeliveryMethodUpdate: mutate(), + checkoutAddPromoCode: mutate(), + checkoutRemovePromoCode: mutate(), + checkoutComplete: mutate(), + deliveryOptionsCalculate: mutate(), + paymentGatewaysInitialize: mutate(), + transactionInitialize: mutate(), + transactionProcess: mutate(), + userRegister: mutate("none"), + requestPasswordReset: mutate("none"), + userAddressDelete: mutate(), + userAddressUpdate: mutate(), + userAddressCreate: mutate(), + userSetDefaultAddress: mutate(), +} as const satisfies Record; + +export type CoreOperationName = keyof typeof CORE_OPERATIONS; + +export function getOperation(name: string): OperationSpec | undefined { + const extension = extensionOperations[name]; + if (extension) return extension; + return CORE_OPERATIONS[name as CoreOperationName]; +} + +export function listCoreOperations(): Readonly> { + return CORE_OPERATIONS; +} + +export function operationNameFromDocument(operation: { toString(): string }): string { + const name = operation.toString().match(/(?:query|mutation|subscription)\s+(\w+)/)?.[1]; + if (!name) { + throw new Error( + "[saleor] Could not read an operation name. Name the query or mutation in the .graphql document.", + ); + } + return name; +} + +/** + * Reject the calls that poison the cache. A cached catalog query may still be + * read live (filter permutations). A session read or a mutation may not be cached. + */ +export function resolveOperationCall(name: string, via: OperationAccess): OperationSpec { + const spec = getOperation(name); + if (!spec) { + throw new Error( + `[saleor] "${name}" is not in the operation registry. Add it to src/lib/saleor/operations.ts ` + + `(core) or src/config/data-extensions.ts (fork). See rules/data-access.md.`, + ); + } + + const allowed = + via === "cached" + ? spec.access === "cached" + : via === "live" + ? spec.access === "live" || spec.access === "cached" + : spec.access === via; + + if (!allowed) { + throw new Error( + `[saleor] "${name}" is registered as ${spec.access}/${spec.auth}. ` + + `Do not call it via ${via}. ` + + (spec.access === "mutate" + ? "Use mutate() from a server action." + : spec.access === "session" + ? 'Use sessionQuery() — session reads must not enter "use cache".' + : 'Use cachedQuery() inside "use cache", or liveQuery() for an uncached read.'), + ); + } + + return spec; +} diff --git a/apps/web/src/lib/saleor/raw.ts b/apps/web/src/lib/saleor/raw.ts new file mode 100644 index 0000000..a6aeb8c --- /dev/null +++ b/apps/web/src/lib/saleor/raw.ts @@ -0,0 +1,28 @@ +import "server-only"; + +import { executeRawGraphQL, type GraphQLResult } from "./client"; +import { recordSaleorCall } from "./ledger"; + +type RawOptions = { + query: string; + variables?: Record; + headers?: HeadersInit; +}; + +/** + * Untyped mutation for the auth BFF routes that predate codegen documents. + * Prefer `mutate()` with a `.graphql` document everywhere else. + */ +export async function rawMutation(options: RawOptions): Promise> { + const started = Date.now(); + const name = options.query.match(/(?:query|mutation)\s+(\w+)/)?.[1] || "RawOperation"; + const result = await executeRawGraphQL(options); + recordSaleorCall({ + op: name, + mode: "raw", + auth: "none", + ok: result.ok, + ms: Date.now() - started, + }); + return result; +} diff --git a/apps/web/src/lib/seo/config.ts b/apps/web/src/lib/seo/config.ts new file mode 100644 index 0000000..2296d71 --- /dev/null +++ b/apps/web/src/lib/seo/config.ts @@ -0,0 +1,63 @@ +/** + * SEO Configuration + * + * Centralized SEO settings for the storefront. + * Branding values are imported from @/config/brand. + * + * To disable SEO features entirely, you can: + * 1. Remove imports of this module + * 2. Set individual features to undefined/null + */ + +import { brandConfig } from "@/config/brand"; + +export const seoConfig = { + /** Site name used in titles and OG tags */ + siteName: brandConfig.siteName, + + /** Default site description */ + description: brandConfig.tagline, + + /** Twitter/X handle (without @) - set to null to disable */ + twitterHandle: brandConfig.social.twitter, + + /** Organization name for structured data */ + organizationName: brandConfig.organizationName, + + /** Default brand name for products without a brand */ + defaultBrand: brandConfig.defaultBrand, + + /** Title template - %s will be replaced with page title */ + titleTemplate: brandConfig.titleTemplate, + + /** Separator used in compound titles */ + titleSeparator: " | ", + + /** Pages to exclude from search engine indexing */ + noIndexPaths: ["/checkout", "/order", "/cart", "/api/", "/login", "/orders"], + + /** Enable/disable JSON-LD structured data */ + enableJsonLd: true, + + /** Enable/disable OpenGraph tags */ + enableOpenGraph: true, + + /** Enable/disable Twitter cards */ + enableTwitterCards: true, +} as const; + +/** + * Get the base URL for the storefront + * Falls back to localhost for development + */ +export function getBaseUrl(): string { + return process.env.NEXT_PUBLIC_STOREFRONT_URL || "http://localhost:3000"; +} + +/** + * Get the metadata base URL object + * Used by Next.js for resolving relative URLs in metadata + */ +export function getMetadataBase(): URL { + return new URL(getBaseUrl()); +} diff --git a/apps/web/src/lib/seo/hreflang.test.ts b/apps/web/src/lib/seo/hreflang.test.ts new file mode 100644 index 0000000..bf57791 --- /dev/null +++ b/apps/web/src/lib/seo/hreflang.test.ts @@ -0,0 +1,52 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { buildLocaleHreflangAlternates } from "./hreflang"; + +describe("buildLocaleHreflangAlternates", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("builds language-only hreflang keys when locale×channel pairs are unset", () => { + vi.stubEnv("NEXT_PUBLIC_STOREFRONT_LOCALES", "en,pl"); + vi.stubEnv("NEXT_PUBLIC_DEFAULT_CHANNEL", "default-channel"); + vi.stubEnv("STOREFRONT_CHANNELS", "default-channel"); + + expect(buildLocaleHreflangAlternates("default-channel", "/products/hoodie")).toEqual({ + en: "/en/default-channel/products/hoodie", + pl: "/pl/default-channel/products/hoodie", + "x-default": "/en/default-channel/products/hoodie", + }); + }); + + it("uses paired channels and region-aware keys when LOCALE_CHANNELS is configured", () => { + vi.stubEnv("NEXT_PUBLIC_STOREFRONT_LOCALES", "en,pl,ja"); + vi.stubEnv("NEXT_PUBLIC_DEFAULT_CHANNEL", "default-channel"); + vi.stubEnv("STOREFRONT_CHANNELS", "default-channel,channel-pln,japan"); + vi.stubEnv("NEXT_PUBLIC_STOREFRONT_LOCALE_CHANNELS", "en:default-channel,pl:channel-pln,ja:japan"); + + expect(buildLocaleHreflangAlternates("default-channel", "/products/hoodie")).toEqual({ + "en-US": "/en/default-channel/products/hoodie", + "pl-PL": "/pl/channel-pln/products/hoodie", + "ja-JP": "/ja/japan/products/hoodie", + "x-default": "/en/default-channel/products/hoodie", + }); + }); + + it("uses per-locale path suffixes for translated catalog slugs", () => { + vi.stubEnv("NEXT_PUBLIC_STOREFRONT_LOCALES", "en,pl"); + vi.stubEnv("NEXT_PUBLIC_DEFAULT_LOCALE", "en"); + vi.stubEnv("NEXT_PUBLIC_DEFAULT_CHANNEL", "default-channel"); + vi.stubEnv("STOREFRONT_CHANNELS", "default-channel"); + + expect( + buildLocaleHreflangAlternates("default-channel", { + en: "/products/hoodie", + pl: "/products/bluza", + }), + ).toEqual({ + en: "/en/default-channel/products/hoodie", + pl: "/pl/default-channel/products/bluza", + "x-default": "/en/default-channel/products/hoodie", + }); + }); +}); diff --git a/apps/web/src/lib/seo/hreflang.ts b/apps/web/src/lib/seo/hreflang.ts new file mode 100644 index 0000000..08d38aa --- /dev/null +++ b/apps/web/src/lib/seo/hreflang.ts @@ -0,0 +1,79 @@ +import { getDefaultLocaleSlug, getLocaleDefinition, getStorefrontLocaleSlugs } from "@/config/locale"; +import { getConfiguredLocaleChannelPairs } from "@/config/locale-channel"; +import { getStaticStorefrontChannelSlugs } from "@/config/channels"; +import { buildStorefrontPath } from "@/lib/storefront-path"; + +type LocaleChannelTarget = { locale: string; channel: string }; + +/** Same suffix for every locale, or a per-locale suffix map (translated catalog slugs). */ +export type HreflangPathInput = string | Record; + +function getHreflangTargets(fallbackChannel: string): LocaleChannelTarget[] { + const pairs = getConfiguredLocaleChannelPairs(); + if (pairs) { + return pairs.map(({ locale, channel }) => ({ locale, channel })); + } + + return getStorefrontLocaleSlugs().map((locale) => ({ locale, channel: fallbackChannel })); +} + +function getXDefaultTarget(fallbackChannel: string): LocaleChannelTarget { + const pairs = getConfiguredLocaleChannelPairs(); + const defaultLocale = getDefaultLocaleSlug(); + + if (pairs) { + const defaultPair = pairs.find((pair) => pair.locale === defaultLocale) ?? pairs[0]; + if (defaultPair) return defaultPair; + } + + const defaultChannel = getStaticStorefrontChannelSlugs()[0] ?? fallbackChannel; + return { locale: defaultLocale, channel: defaultChannel }; +} + +function resolvePathSuffix(pathInput: HreflangPathInput, locale: string, fallbackSuffix: string): string { + if (typeof pathInput === "string") return pathInput; + return pathInput[locale] ?? pathInput[getDefaultLocaleSlug()] ?? fallbackSuffix; +} + +/** + * hreflang language key for a locale. + * + * - Locale×channel pairs configured → BCP 47 region form (`ja-JP`): each alternate is a + * language+market URL, so a region-aware code matches Google's guidance. + * - No pairs (any locale × any channel) → language-only (`ja`): the same language may + * exist on multiple markets; claiming `ja-JP` for one channel would over-assert. + */ +function getHreflangLanguageKey(locale: string, regionAware: boolean): string | null { + const definition = getLocaleDefinition(locale); + if (!definition) return null; + return regionAware ? definition.bcp47 : definition.htmlLang; +} + +/** + * hreflang alternates for browse URLs. + * Pass a single path suffix, or a per-locale map when catalog slugs are translated (ADR 0004). + * When `NEXT_PUBLIC_STOREFRONT_LOCALE_CHANNELS` is set, each locale uses its paired channel + * and hreflang keys are region-aware (`ja-JP`); otherwise keys stay language-only (`ja`). + * Includes `x-default` pointing at default locale + its channel. + */ +export function buildLocaleHreflangAlternates( + channel: string, + pathSuffix: HreflangPathInput, +): Record { + const languages: Record = {}; + const fallbackSuffix = typeof pathSuffix === "string" ? pathSuffix : (Object.values(pathSuffix)[0] ?? ""); + const regionAware = getConfiguredLocaleChannelPairs() !== null; + + for (const { locale, channel: targetChannel } of getHreflangTargets(channel)) { + const languageKey = getHreflangLanguageKey(locale, regionAware); + if (!languageKey) continue; + const suffix = resolvePathSuffix(pathSuffix, locale, fallbackSuffix); + languages[languageKey] = buildStorefrontPath(locale, targetChannel, suffix); + } + + const xDefault = getXDefaultTarget(channel); + const xDefaultSuffix = resolvePathSuffix(pathSuffix, xDefault.locale, fallbackSuffix); + languages["x-default"] = buildStorefrontPath(xDefault.locale, xDefault.channel, xDefaultSuffix); + + return languages; +} diff --git a/apps/web/src/lib/seo/index.ts b/apps/web/src/lib/seo/index.ts new file mode 100644 index 0000000..8088597 --- /dev/null +++ b/apps/web/src/lib/seo/index.ts @@ -0,0 +1,69 @@ +/** + * SEO Module + * + * Centralized SEO utilities for the Saleor storefront. + * + * ## Quick Start + * + * 1. Root layout metadata: + * ```tsx + * // src/app/layout.tsx + * export { rootMetadata as metadata } from "@/lib/seo"; + * ``` + * + * 2. Page metadata: + * ```tsx + * import { buildPageMetadata } from "@/lib/seo"; + * + * export async function generateMetadata() { + * return buildPageMetadata({ + * title: "Page Title", + * description: "Page description", + * image: "/image.jpg", + * }); + * } + * ``` + * + * 3. Product JSON-LD: + * ```tsx + * import { buildProductJsonLd, jsonLdScriptProps } from "@/lib/seo"; + * + * const jsonLd = buildProductJsonLd({ + * name: product.name, + * price: { amount: 29.99, currency: "USD" }, + * }); + * + * ", + "data:text/html;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+", +] as const; + +/** Protocol-relative and slash-normalization bypasses — never valid internal paths. */ +const UNSAFE_PROTOCOL_RELATIVE_HREFS = ["//evil.com", "/\\evil.com"] as const; + +/** Nav validators must reject scheme attacks and protocol-relative bypasses. */ +const UNSAFE_NAV_HREFS = [...UNSAFE_HREFS, ...UNSAFE_PROTOCOL_RELATIVE_HREFS] as const; + +describe("safe-href", () => { + it("accepts http and https URLs only for external hrefs", () => { + expect(isSafeExternalHref("https://unsplash.com/@user")).toBe(true); + expect(isSafeExternalHref("http://example.com")).toBe(true); + expect(isSafeExternalHref("/relative")).toBe(false); + }); + + it("accepts internal paths but not protocol-relative URLs", () => { + expect(isSafeInternalHref("/products")).toBe(true); + expect(isSafeInternalHref("/categories/apparel")).toBe(true); + expect(isSafeInternalHref("https://example.com")).toBe(false); + expect(isSafeInternalHref("products")).toBe(false); + }); + + it("accepts mailto links", () => { + expect(isSafeMailtoHref("mailto:support@example.com")).toBe(true); + }); + + it("combines safe nav href rules", () => { + expect(isSafeNavHref("https://saleor.io")).toBe(true); + expect(isSafeNavHref("/products")).toBe(true); + expect(isSafeNavHref("mailto:hello@example.com")).toBe(true); + }); + + it.each(UNSAFE_HREFS)("isSafeExternalHref rejects %s", (href) => { + expect(isSafeExternalHref(href)).toBe(false); + }); + + it.each(UNSAFE_HREFS)("isSafeInternalHref rejects %s", (href) => { + expect(isSafeInternalHref(href)).toBe(false); + }); + + it.each(UNSAFE_PROTOCOL_RELATIVE_HREFS)("isSafeInternalHref rejects %s", (href) => { + expect(isSafeInternalHref(href)).toBe(false); + }); + + it.each(UNSAFE_HREFS)("isSafeMailtoHref rejects %s", (href) => { + expect(isSafeMailtoHref(href)).toBe(false); + }); + + it.each(UNSAFE_NAV_HREFS)("isSafeNavHref rejects %s", (href) => { + expect(isSafeNavHref(href)).toBe(false); + }); + + it.each(UNSAFE_NAV_HREFS)("sanitizeNavHref rejects %s", (href) => { + expect(sanitizeNavHref(href)).toBeNull(); + }); + + it("sanitizeNavHref trims safe values and drops empty input", () => { + expect(sanitizeNavHref(" /sale ")).toBe("/sale"); + expect(sanitizeNavHref("")).toBeNull(); + expect(sanitizeNavHref(null)).toBeNull(); + expect(sanitizeNavHref(undefined)).toBeNull(); + }); +}); diff --git a/apps/web/src/lib/url/safe-href.ts b/apps/web/src/lib/url/safe-href.ts new file mode 100644 index 0000000..5ab38b5 --- /dev/null +++ b/apps/web/src/lib/url/safe-href.ts @@ -0,0 +1,52 @@ +/** + * Shared href safety for CMS / menu / Saleor attribute input. + * Blocks javascript:, data:, and other dangerous schemes before they reach ``. + */ + +/** Absolute http(s) only — for external-only surfaces (e.g. photo credits). */ +export function isSafeExternalHref(href: string): boolean { + try { + const url = new URL(href); + return url.protocol === "http:" || url.protocol === "https:"; + } catch { + return false; + } +} + +/** Storefront-relative paths: `/…` but not protocol-relative (`//…`, `/\…`). */ +export function isSafeInternalHref(href: string): boolean { + const trimmed = href.trim(); + if (!trimmed.startsWith("/")) { + return false; + } + // Browsers normalize backslashes to slashes, so `/\evil.com` and `//evil.com` + // are both treated as protocol-relative external URLs — reject them. + return trimmed[1] !== "/" && trimmed[1] !== "\\"; +} + +export function isSafeMailtoHref(href: string): boolean { + try { + const url = new URL(href); + return url.protocol === "mailto:"; + } catch { + return false; + } +} + +/** Safe for nav/CTA anchors: http(s), mailto, or internal path. */ +export function isSafeNavHref(href: string): boolean { + const trimmed = href.trim(); + if (!trimmed) { + return false; + } + return isSafeExternalHref(trimmed) || isSafeMailtoHref(trimmed) || isSafeInternalHref(trimmed); +} + +/** Returns a trimmed safe href or null when the value must not be linked. */ +export function sanitizeNavHref(href: string | null | undefined): string | null { + const trimmed = href?.trim(); + if (!trimmed || !isSafeNavHref(trimmed)) { + return null; + } + return trimmed; +} diff --git a/apps/web/src/lib/utils.test.ts b/apps/web/src/lib/utils.test.ts new file mode 100644 index 0000000..8af4f39 --- /dev/null +++ b/apps/web/src/lib/utils.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { cn } from "./utils"; + +describe("cn", () => { + it("keeps semantic type size when merged with text color utilities", () => { + expect(cn("text-display text-foreground")).toBe("text-display text-foreground"); + expect(cn("text-h1 text-foreground")).toBe("text-h1 text-foreground"); + expect(cn("text-h2 text-muted-foreground")).toBe("text-h2 text-muted-foreground"); + }); + + it("still deduplicates conflicting font-size utilities", () => { + expect(cn("text-h1 text-h2")).toBe("text-h2"); + }); +}); diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts new file mode 100644 index 0000000..5816a1c --- /dev/null +++ b/apps/web/src/lib/utils.ts @@ -0,0 +1,82 @@ +import { ProductsPerPage } from "@/app/config"; +import { clsx, type ClassValue } from "clsx"; +import { extendTailwindMerge } from "tailwind-merge"; +import { formatPrice, formatDate as formatLocaleDate } from "@/config/locale"; + +/** Custom semantic type tokens from tailwind.config.cjs — must be registered so twMerge + * does not treat `text-display` + `text-foreground` as conflicting `text-*` utilities. */ +const twMerge = extendTailwindMerge({ + extend: { + classGroups: { + "font-size": [{ text: ["display", "h1", "h2", "h3", "lead", "eyebrow"] }], + "text-color": [{ text: ["bestseller"] }], + "border-color": [{ border: ["bestseller"] }], + }, + }, +}); + +/** Merge class names with clsx and tailwind-merge for proper Tailwind class deduplication */ +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} + +/** @deprecated Use formatDate from @/config/locale instead */ +export const formatDate = formatLocaleDate; + +/** @deprecated Use formatPrice from @/config/locale instead */ +export const formatMoney = formatPrice; + +export const formatMoneyRange = ( + range: { + start?: { amount: number; currency: string } | null; + stop?: { amount: number; currency: string } | null; + } | null, + locale?: string, +) => { + const { start, stop } = range || {}; + const startMoney = start && formatMoney(start.amount, start.currency, locale); + const stopMoney = stop && formatMoney(stop.amount, stop.currency, locale); + + if (startMoney === stopMoney) { + return startMoney; + } + + return `${startMoney} - ${stopMoney}`; +}; + +export function getHrefForVariant({ + productSlug, + variantId, +}: { + productSlug: string; + variantId?: string; +}): string { + const pathname = `/products/${encodeURIComponent(productSlug)}`; + + if (!variantId) { + return pathname; + } + + const query = new URLSearchParams({ variant: variantId }); + return `${pathname}?${query.toString()}`; +} + +export type PaginatedListVariables = { + first?: number; + after?: string | null; + last?: number; + before?: string | null; +}; + +export const getPaginatedListVariables = ({ + params, +}: { + params: { [key: string]: unknown }; +}): PaginatedListVariables => { + const cursor = typeof params?.cursor === "string" ? params?.cursor : null; + const direction = params?.direction === "prev" ? "prev" : "next"; + + return direction === "prev" + ? { last: ProductsPerPage, before: cursor } + : { first: ProductsPerPage, after: cursor }; +}; diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts new file mode 100644 index 0000000..25120f1 --- /dev/null +++ b/apps/web/src/middleware.ts @@ -0,0 +1,133 @@ +import { type NextRequest, NextResponse } from "next/server"; +import { DefaultChannelSlug } from "@/app/config"; +import { isSaleorConnected } from "@/lib/saleor-connection"; +import { getStaticStorefrontChannelSlugs, isAllowedStorefrontChannel } from "@/config/channels"; +import { getDefaultLocaleSlug, isLocaleSlug, isStorefrontLocaleSlug } from "@/config/locale"; +import { BROWSE_LOCALE_COOKIE, getBrowseLocaleCookieOptions } from "@/lib/browse-locale"; +import { buildStorefrontPath } from "@/lib/storefront-path"; + +const RESERVED_ROOT_SEGMENTS = new Set([ + "api", + "checkout", + "order", + "_next", + "favicon.ico", + "robots.txt", + "sitemap.xml", +]); + +function isChannelSlug(segment: string): boolean { + const allowed = getStaticStorefrontChannelSlugs(); + return isAllowedStorefrontChannel(segment, allowed); +} + +function withBrowseLocaleCookie(request: NextRequest, response: NextResponse, locale: string): NextResponse { + if (!isStorefrontLocaleSlug(locale)) { + return response; + } + + // Skip Set-Cookie when the value is already correct — re-setting on every HTML response + // marks responses as uncacheable at shared CDNs even when nothing changed. + const current = request.cookies.get(BROWSE_LOCALE_COOKIE)?.value; + if (current === locale) { + return response; + } + + response.cookies.set(BROWSE_LOCALE_COOKIE, locale, getBrowseLocaleCookieOptions()); + return response; +} + +export function middleware(request: NextRequest) { + const { pathname } = request.nextUrl; + + if ( + pathname.startsWith("/_next") || + pathname.startsWith("/api") || + pathname.includes(".") // static files + ) { + return NextResponse.next(); + } + + const segments = pathname.split("/").filter(Boolean); + + // No Saleor store yet: `/` says how to connect one; every other page goes there. + if (!isSaleorConnected) { + if (segments.length === 0) return NextResponse.next(); + const url = request.nextUrl.clone(); + url.pathname = "/"; + url.search = ""; + return NextResponse.redirect(url, 307); + } + const defaultLocale = getDefaultLocaleSlug(); + const defaultChannel = DefaultChannelSlug ?? getStaticStorefrontChannelSlugs()[0]; + + // Root → default browse home + if (segments.length === 0) { + if (!defaultChannel) { + return NextResponse.next(); + } + const url = request.nextUrl.clone(); + url.pathname = buildStorefrontPath(defaultLocale, defaultChannel); + return withBrowseLocaleCookie(request, NextResponse.redirect(url, 308), defaultLocale); + } + + const [first, second, ...rest] = segments; + + if (RESERVED_ROOT_SEGMENTS.has(first)) { + return NextResponse.next(); + } + + // Disabled locale slug (defined but not in NEXT_PUBLIC_STOREFRONT_LOCALES) → canonical default locale + if (isLocaleSlug(first) && !isStorefrontLocaleSlug(first)) { + if (second && isChannelSlug(second)) { + const url = request.nextUrl.clone(); + const suffix = rest.length > 0 ? `/${rest.join("/")}` : ""; + url.pathname = buildStorefrontPath(defaultLocale, second, suffix); + return withBrowseLocaleCookie(request, NextResponse.redirect(url, 308), defaultLocale); + } + return NextResponse.next(); + } + + // Canonical format: /{locale}/{channel}/… + if (isStorefrontLocaleSlug(first)) { + if (second && isChannelSlug(second)) { + return withBrowseLocaleCookie(request, NextResponse.next(), first); + } + + // /{locale} only → add default channel + if (!second && defaultChannel) { + const url = request.nextUrl.clone(); + url.pathname = buildStorefrontPath(first, defaultChannel); + return withBrowseLocaleCookie(request, NextResponse.redirect(url, 308), first); + } + + return NextResponse.next(); + } + + // Legacy: /{channel}/… → /{defaultLocale}/{channel}/… + if (isChannelSlug(first)) { + const url = request.nextUrl.clone(); + const suffix = [second, ...rest].filter(Boolean).join("/"); + url.pathname = buildStorefrontPath(defaultLocale, first, suffix ? `/${suffix}` : ""); + return withBrowseLocaleCookie(request, NextResponse.redirect(url, 308), defaultLocale); + } + + return NextResponse.next(); +} + +export const config = { + /** + * Vercel bills an Edge Middleware invocation for every matched request, including the + * ones this function immediately no-ops on. Excluding them here means they are never + * invoked at all: API routes, the checkout surface, all `_next` internals, and any + * path ending in a file extension (public/ assets, fonts, icons — this also covers + * favicon.ico, robots.txt and sitemap.xml). + * + * Prefixes are anchored with `/` or `$` so they exclude `/api/…` without also + * excluding a channel or locale slug that merely starts with those letters. + * + * The equivalent guards at the top of `middleware()` stay as a backstop for runtimes + * that apply the matcher differently (self-hosted, `next start`). + */ + matcher: ["/((?!api/|api$|checkout/|checkout$|order/|order$|_next/|.*\\.[\\w]+$).*)"], +}; diff --git a/apps/web/src/session-bridge/README.md b/apps/web/src/session-bridge/README.md new file mode 100644 index 0000000..11b0436 --- /dev/null +++ b/apps/web/src/session-bridge/README.md @@ -0,0 +1,25 @@ +# `@paper/session-bridge` + +Shared contract between the **storefront** surface (browse, cart) and the **checkout** surface (transactional flow). + +## Rules + +- **Storefront** may import `@paper/session-bridge` and must not import `@/checkout/*` UI or hooks. +- **Checkout** may import `@/checkout/*` and `@paper/session-bridge`; it must not import catalog/PDP/cached data layers. +- No React in this folder — safe for server cart code and client checkout. + +## Contents + +| Module | Purpose | +| ------------------ | -------------------------------------------------------------------------------------------- | +| `cookies.ts` | `checkoutId-{channel}` cookie name | +| `checkout-url.ts` | `buildCheckoutPath`, `buildOrderConfirmationPath` (`/order/{token}`), `buildOrderStatusPath` | +| `search-params.ts` | URL param map, `getQueryParams`, `createQueryString` | + +## Checkout v2 + +Active checkout: `/checkout?checkout=`. Guest order status: `/order/{key}` (HMAC after pay; Saleor id from email is redacted). The HMAC URL is frozen; the page re-fetches the order on each visit. Legacy `/checkout/complete?order=` redirects. See [`rules/paper-surfaces.md`](../skills/saleor-paper-storefront/rules/paper-surfaces.md) and [`checkout-guest-order.md`](../skills/saleor-paper-storefront/rules/checkout-guest-order.md). + +## Hosted checkout (optional) + +Set `NEXT_PUBLIC_CHECKOUT_URL=https://checkout.example.com` so `buildCheckoutUrl` returns absolute links. Optional middleware can block non-checkout / non-`/order` routes on a checkout-only deploy. diff --git a/apps/web/src/session-bridge/checkout-url.test.ts b/apps/web/src/session-bridge/checkout-url.test.ts new file mode 100644 index 0000000..767fddb --- /dev/null +++ b/apps/web/src/session-bridge/checkout-url.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it } from "vitest"; + +import { + buildCheckoutPath, + buildCheckoutUrl, + buildOrderConfirmationPath, + buildOrderConfirmationUrl, + buildOrderStatusPath, +} from "./checkout-url"; + +describe("buildCheckoutPath", () => { + it("builds checkout session path", () => { + expect(buildCheckoutPath({ checkoutId: "abc" })).toBe("/checkout?checkout=abc"); + }); + + it("includes step when provided", () => { + expect(buildCheckoutPath({ checkoutId: "abc", step: "payment" })).toBe( + "/checkout?checkout=abc&step=payment", + ); + }); + + it("includes browse locale when provided", () => { + expect(buildCheckoutPath({ checkoutId: "abc", browseLocale: "pl" })).toBe( + "/checkout?checkout=abc&locale=pl", + ); + }); +}); + +describe("buildOrderConfirmationPath", () => { + it("builds the guest order path from a signed token", () => { + expect(buildOrderConfirmationPath({ token: "ov1.abc.def" })).toBe("/order/ov1.abc.def"); + }); + + it("forwards browse locale so confirmation matches checkout", () => { + expect(buildOrderConfirmationPath({ token: "ov1.abc.def", browseLocale: "pl" })).toBe( + "/order/ov1.abc.def?locale=pl", + ); + }); +}); + +describe("buildOrderStatusPath", () => { + it("encodes a Saleor order id for the email landing", () => { + expect(buildOrderStatusPath("T3JkZXI6MQ==")).toBe("/order/T3JkZXI6MQ%3D%3D"); + }); + + it("appends browse locale when provided", () => { + expect(buildOrderStatusPath("T3JkZXI6MQ==", "ja")).toBe("/order/T3JkZXI6MQ%3D%3D?locale=ja"); + }); +}); + +describe("buildCheckoutUrl", () => { + it("returns relative path when CHECKOUT_URL is unset", () => { + const prev = process.env.NEXT_PUBLIC_CHECKOUT_URL; + delete process.env.NEXT_PUBLIC_CHECKOUT_URL; + expect(buildCheckoutUrl({ checkoutId: "x" })).toBe("/checkout?checkout=x"); + process.env.NEXT_PUBLIC_CHECKOUT_URL = prev; + }); + + it("returns absolute URL when CHECKOUT_URL is set", () => { + const prev = process.env.NEXT_PUBLIC_CHECKOUT_URL; + process.env.NEXT_PUBLIC_CHECKOUT_URL = "https://checkout.example.com"; + expect(buildCheckoutUrl({ checkoutId: "x" })).toBe("https://checkout.example.com/checkout?checkout=x"); + process.env.NEXT_PUBLIC_CHECKOUT_URL = prev; + }); +}); + +describe("buildOrderConfirmationUrl", () => { + it("returns relative path when CHECKOUT_URL is unset", () => { + const prev = process.env.NEXT_PUBLIC_CHECKOUT_URL; + delete process.env.NEXT_PUBLIC_CHECKOUT_URL; + expect(buildOrderConfirmationUrl({ token: "ov1.abc.def" })).toBe("/order/ov1.abc.def"); + process.env.NEXT_PUBLIC_CHECKOUT_URL = prev; + }); +}); diff --git a/apps/web/src/session-bridge/checkout-url.ts b/apps/web/src/session-bridge/checkout-url.ts new file mode 100644 index 0000000..0109ce5 --- /dev/null +++ b/apps/web/src/session-bridge/checkout-url.ts @@ -0,0 +1,94 @@ +export type BuildCheckoutPathOptions = { + checkoutId: string; + step?: string; + /** Browse locale slug from `/{locale}/{channel}/…` — synced to checkout via `?locale=`. */ + browseLocale?: string; +}; + +export type BuildOrderConfirmationPathOptions = { + /** Signed guest-order token (`ov1.…`), or a Saleor order id for the email landing. */ + token: string; + /** Browse locale slug — `/order` is locale-less, so confirmation must carry `?locale=`. */ + browseLocale?: string | null; +}; + +/** Query keys as they appear in the browser URL (not internal mapped names). */ +const urlQueryKeys = { + checkout: "checkout", + order: "order", + step: "step", + locale: "locale", +} as const; + +/** Locale-less guest / confirmation order page. */ +export function buildOrderStatusPath(key: string, browseLocale?: string | null): string { + const path = `/order/${encodeURIComponent(key)}`; + if (!browseLocale) { + return path; + } + return `${path}?${urlQueryKeys.locale}=${encodeURIComponent(browseLocale)}`; +} + +/** + * Relative checkout path (same-origin Paper deploy). + */ +export function buildCheckoutPath({ checkoutId, step, browseLocale }: BuildCheckoutPathOptions): string { + const params = new URLSearchParams(); + params.set(urlQueryKeys.checkout, checkoutId); + + if (step) { + params.set(urlQueryKeys.step, step); + } + + if (browseLocale) { + params.set(urlQueryKeys.locale, browseLocale); + } + + return `/checkout?${params.toString()}`; +} + +/** + * Post-pay and email order page (`/order/{token}`). + */ +export function buildOrderConfirmationPath({ + token, + browseLocale, +}: BuildOrderConfirmationPathOptions): string { + return buildOrderStatusPath(token, browseLocale); +} + +/** + * Origin for checkout links. Empty NEXT_PUBLIC_CHECKOUT_URL → same deploy (relative paths). + */ +export function getCheckoutOrigin(): string | undefined { + const configured = process.env.NEXT_PUBLIC_CHECKOUT_URL?.replace(/\/$/, ""); + return configured || undefined; +} + +/** + * Absolute or relative checkout URL for cart → checkout handoff. + */ +export function buildCheckoutUrl(options: BuildCheckoutPathOptions): string { + const path = buildCheckoutPath(options); + const origin = getCheckoutOrigin(); + + if (!origin) { + return path; + } + + return `${origin}${path}`; +} + +/** + * Absolute or relative order confirmation URL. + */ +export function buildOrderConfirmationUrl(options: BuildOrderConfirmationPathOptions): string { + const path = buildOrderConfirmationPath(options); + const origin = getCheckoutOrigin(); + + if (!origin) { + return path; + } + + return `${origin}${path}`; +} diff --git a/apps/web/src/session-bridge/cookies.ts b/apps/web/src/session-bridge/cookies.ts new file mode 100644 index 0000000..405b986 --- /dev/null +++ b/apps/web/src/session-bridge/cookies.ts @@ -0,0 +1,4 @@ +/** Server and client agree on this cookie name per Saleor channel. */ +export function checkoutIdCookieName(channel: string): string { + return `checkoutId-${channel}`; +} diff --git a/apps/web/src/session-bridge/index.ts b/apps/web/src/session-bridge/index.ts new file mode 100644 index 0000000..0f91f98 --- /dev/null +++ b/apps/web/src/session-bridge/index.ts @@ -0,0 +1,21 @@ +export { checkoutIdCookieName } from "./cookies"; +export { + buildCheckoutPath, + buildCheckoutUrl, + buildOrderConfirmationPath, + buildOrderConfirmationUrl, + buildOrderStatusPath, + getCheckoutOrigin, +} from "./checkout-url"; +export type { BuildCheckoutPathOptions, BuildOrderConfirmationPathOptions } from "./checkout-url"; +export { + checkoutSearchParamKeys, + createQueryString, + extractCheckoutIdFromParams, + getQueryParams, +} from "./search-params"; +export type { CheckoutQueryParams } from "./search-params"; +export type { ParamBasicValue } from "./types"; + +/** @deprecated Use CheckoutQueryParams */ +export type QueryParams = import("./search-params").CheckoutQueryParams; diff --git a/apps/web/src/session-bridge/search-params.ts b/apps/web/src/session-bridge/search-params.ts new file mode 100644 index 0000000..6ea5144 --- /dev/null +++ b/apps/web/src/session-bridge/search-params.ts @@ -0,0 +1,98 @@ +import type { ReadonlyURLSearchParams } from "next/navigation"; + +import type { ParamBasicValue } from "./types"; + +/** + * Maps public URL param names to internal names. + * URL uses shorter/external names; app code uses descriptive names. + */ +export const checkoutSearchParamKeys = { + redirectUrl: "redirectUrl", + checkout: "checkoutId", + order: "orderId", + confirm: "accountConfirm", + token: "passwordResetToken", + email: "passwordResetEmail", + saleorApiUrl: "saleorApiUrl", + transaction: "transaction", + processingPayment: "processingPayment", + redirectResult: "redirectResult", + resultCode: "resultCode", + type: "type", + payment_intent: "paymentIntent", + payment_intent_client_secret: "paymentIntentClientSecret", + redirect_status: "redirectStatus", + step: "step", +} as const; + +type UnmappedQueryParam = keyof typeof checkoutSearchParamKeys; + +type QueryParam = (typeof checkoutSearchParamKeys)[UnmappedQueryParam]; + +export type CheckoutQueryParams = Record & { + countryCode?: string; + channel?: string; + saleorApiUrl?: string; +}; + +/** + * Read checkout-related query params from Next.js search params (mapped names). + */ +export function getQueryParams(searchParams: ReadonlyURLSearchParams): CheckoutQueryParams { + const result: Record = {}; + + for (const [key, value] of searchParams.entries()) { + if (key in checkoutSearchParamKeys) { + const mappedKey = checkoutSearchParamKeys[key as UnmappedQueryParam]; + result[mappedKey] = value; + } + } + + return result as CheckoutQueryParams; +} + +/** + * Build a query string with internal keys translated back to URL keys. + */ +export function createQueryString( + currentParams: ReadonlyURLSearchParams, + updates: Record, +): string { + const params = new URLSearchParams(currentParams.toString()); + + const internalToUrlKey = Object.entries(checkoutSearchParamKeys).reduce( + (acc, [urlKey, internalKey]) => { + acc[internalKey] = urlKey; + return acc; + }, + {} as Record, + ); + + for (const [internalKey, value] of Object.entries(updates)) { + const urlKey = internalToUrlKey[internalKey]; + if (!urlKey) continue; + + if (value === null) { + params.delete(urlKey); + } else { + params.set(urlKey, value); + } + } + + return params.toString(); +} + +/** + * Checkout session id from mapped params. Null on order confirmation (`order` param). + */ +export function extractCheckoutIdFromParams(params: CheckoutQueryParams): string | null { + if (params.orderId) { + return null; + } + + if (typeof params.checkoutId !== "string") { + return null; + } + + return params.checkoutId; +} diff --git a/apps/web/src/session-bridge/types.ts b/apps/web/src/session-bridge/types.ts new file mode 100644 index 0000000..97d26c3 --- /dev/null +++ b/apps/web/src/session-bridge/types.ts @@ -0,0 +1,2 @@ +/** Value that may be missing from the URL. */ +export type ParamBasicValue = string | undefined; diff --git a/apps/web/src/styles/README.md b/apps/web/src/styles/README.md new file mode 100644 index 0000000..e3ac4fe --- /dev/null +++ b/apps/web/src/styles/README.md @@ -0,0 +1,269 @@ +# Design tokens (`brand.css`) + +**`src/styles/brand.css` is the single source of truth for visual design.** + +Tailwind is how you apply tokens in components. `tailwind.config.cjs` maps CSS variables to utility classes — wire it once, don't edit it for rebrands. + +``` +brand.css → tailwind.config.cjs → className in components + ↑ + edit here to rebrand +``` + +Copy and metadata (site name, tagline) live in `src/config/brand.ts`. + +--- + +## Rebrand checklist + +| Change | File | +| ------------------------------------- | ------------------------------------------------------------- | +| Colors, radius, inverted footer tones | `src/styles/brand.css` | +| Typography scale (fluid sizes) | `src/styles/brand.css` + `tailwind.config.cjs` (see below) | +| Site name, tagline, copyright, social | `src/config/brand.ts` | +| Logo | `public/logo.svg`, `public/logo-dark.svg` (inverted surfaces) | +| Favicons | `public/favicon*` | +| OG image hex colors | `src/lib/seo/og-brand-colors.ts` (sync with `brand.css`) | + +**Light-only UI:** Storefront pages use the light theme only (no `.dark` class). Browser tab favicons in `src/lib/seo/metadata.ts` still follow `prefers-color-scheme` so icons stay readable on dark browser chrome — that is intentional and not an in-app dark mode. + +--- + +## Canonical Tailwind workflow + +### 1. Edit tokens + +```css +/* src/styles/brand.css */ +:root { + --primary: oklch(0.45 0.2 250); /* example: blue CTAs */ + --foreground: oklch(0.15 0.02 250); + --background: oklch(0.98 0.005 90); + --radius: 0.25rem; +} +``` + +### 2. Use semantic Tailwind classes + +Prefer classes that resolve to a `var(--*)` from `brand.css` (mapped in `tailwind.config.cjs`). For brand colors and surfaces, this is the default path in this repo. + +| Intent | Classes | +| ------------------ | -------------------------------------------------------- | +| Page background | `bg-background` | +| Primary text | `text-foreground` | +| Secondary text | `text-muted-foreground` | +| Cards, menus | `bg-card` | +| Subtle panels | `bg-muted`, `bg-secondary` | +| Hover / active row | `bg-accent` | +| CTAs | `bg-primary text-primary-foreground hover:bg-primary/90` | +| Borders | `border-border`, `divide-border` | +| Sale / error | `bg-destructive text-destructive-foreground` | +| Corners | `rounded-md`, `rounded-lg` (from `--radius`) | + +Layout and spacing stay normal Tailwind (`gap-4`, `grid-cols-2`, etc.). For **page width and section rhythm**, prefer the canonical width/spacing tokens over magic strings — see [Layout width & rhythm](#8-layout-width--rhythm). + +### 3. Inverted surfaces (footer) + +Footer uses `bg-foreground text-background`. Text on that dark band uses **inverse** tokens (not `muted-foreground`, which is for light surfaces): + +| Intent | Classes | +| --------------- | ---------------------------------------------- | +| Column headings | `text-inverse` | +| Links | `text-inverse-subtle hover:text-inverse` | +| Copyright | `text-inverse-muted hover:text-inverse-subtle` | +| Divider | `border-inverse` | + +### 4. Use UI primitives for repeated patterns + +```tsx +import { Button } from "@/ui/components/ui/button"; + +; +``` + +Prefer `Button`, `Input`, `Badge` over hand-rolled color classes. + +For primary-styled links (`` / ``), use `buttonClassName({ asLink: true })` from `button.tsx`. Disabled links use `aria-disabled` — the default variant switches to `bg-muted text-muted-foreground` (solid, not opacity fade). Outline-style disabled links can use `ariaDisabledClassName`. + +**Note:** Layout, spacing, and other non-brand utilities are still plain Tailwind. If you need a color that should change when `brand.css` changes, add or use a token — don't hardcode hex/rgb in components. + +### 5. Sale labels + +Use `sale-label.tsx` for all sale / discount UI — don't hand-roll `text-destructive` sale styles. + +```tsx +import { SaleBadge, DiscountPercentLabel } from "@/ui/components/ui/sale-label"; + + {/* "Sale" chip on card / PDP */} + {/* inline, next to price */} + {/* variant option overlay */} +``` + +| Component | Use for | +| --------------------------- | -------------------------------------------- | +| `SaleBadge` | Product on sale (image corner, PDP category) | +| `DiscountPercentLabel` | `-X%` next to price or on variant options | +| `Badge variant="secondary"` | Stock, status (not sale) | + +Sale color is always `--destructive` (mapped to `text-destructive` / `border-destructive`). + +### 6. Border radius + +`--radius` (default `0.5rem`) drives `rounded-sm` / `rounded-md` / `rounded-lg` / `rounded-xl` in Tailwind. Use this hierarchy: + +| Surface | Class | Notes | +| ------------------------------- | -------------- | ------------------------------------- | +| Buttons, inputs, nav controls | `rounded-md` | From `Button`, `Input` | +| Marketing / empty-state CTAs | `rounded-lg` | Optional; links via `buttonClassName` | +| Product cards, media containers | `rounded-xl` | PLP cards, gallery frames | +| Pills (badges, swatch overlays) | `rounded-full` | `SaleBadge`, discount pills | + +Don't mix arbitrarily on the same component type. + +### 7. Typography + +Headings and marketing copy use **semantic type tokens** — same pattern as colors (`--foreground` → `text-foreground`). + +``` +brand.css (--text-h1, …) → tailwind.config.cjs (text-h1 utility) → className + ↑ + weight / tracking / line-height defined here +``` + +| Token class | Use for | Approx. size (mobile → desktop) | +| -------------- | ----------------------------------- | ------------------------------- | +| `text-display` | Homepage hero only | 44px → 72px | +| `text-h1` | Page titles, PDP name, cart H1 | 32px → 48px | +| `text-h2` | Section headings | 24px → 36px | +| `text-h3` | Card/column titles | 18px → 24px | +| `text-lead` | Hero subheads, intro paragraphs | 17px → 20px | +| `text-eyebrow` | Brand labels, overlines (uppercase) | 12px fixed | + +Sizes use `clamp()` in `rem` so they respect user font-size settings and scale fluidly — no `md:text-4xl` breakpoint stacks on headings. + +**Pair with layout utilities:** + +```tsx +

…

+

…

+

Brand

+``` + +**Default Tailwind still works** (`text-sm`, `text-lg`, `text-2xl`, …) for misc UI — PDP price, breadcrumbs, cart line items. Use semantic tokens for **roles** (page title, section head), not every text node. + +**Adding or changing a token** — update all three: + +1. `src/styles/brand.css` — `--text-*` size variable (if fluid) +2. `tailwind.config.cjs` — `theme.extend.fontSize` entry (size + weight/tracking/leading) +3. `src/lib/utils.ts` — register the name in `extendTailwindMerge` so `cn("text-h1 text-foreground")` does not drop the size class + +**`cn()` + colors:** Custom `text-*` size utilities share a prefix with `text-foreground`. Always merge heading classes through `cn()` — the merge config is already set up for `display`, `h1`, `h2`, `h3`, `lead`, `eyebrow`. + +**Future:** On Tailwind v4, type tokens can move into `@theme` in `brand.css` and collapse the split between CSS variables and `tailwind.config.cjs`. + +**Typography theme examples (optional):** The default is Direction C (Geist everywhere). An **editorial** example (Fraunces display + Geist body) ships under [`config/themes/`](../../config/themes/README.md) — try with `pnpm run dev:theme-editorial` or merge `config/themes/typography-editorial.env.example` into `.env.local`. + +**Dev server / Tailwind config:** After changing `tailwind.config.cjs` (new `fontSize` tokens, plugins, etc.), restart the dev server. If utilities like `text-display` appear in HTML but render at body size, clear the webpack cache: `rm -rf .next` and restart. Tailwind JIT reads config at startup; stale `.next` can serve CSS from before the change. + +### 8. Layout width & rhythm + +**Page width is a design decision, not a fixed default.** Paper does not assume a particular desktop width — a page can be edge-to-edge (`container-full`) or constrained (`container-content`). The named tokens make that choice explicit and reviewable instead of scattering `max-w-7xl` / `max-w-none` across files. + +**Canonical container classes** (bundle centering + responsive gutters + a width token): + +| Class | Width | Use for | +| ---------------------- | --------------------------------- | --------------------------------------------------- | +| `container-prose` | `--container-prose` (48rem) | Long-form copy, legal, FAQ — readable measure | +| `container-content` | `--container-content` (80rem) | Default storefront body (replaces bare `max-w-7xl`) | +| `container-wide` | `--container-wide` (96rem) | Editorial marketing bands | +| `container-super-wide` | `--container-super-wide` (160rem) | Immersive PDP — full-bleed with ultrawide cap | +| `container-full` | `--container-full` (100%) | True edge-to-edge at every viewport width | + +```tsx +{ + /* canonical body container — was: mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 */ +} +
…
; + +{ + /* full-width desktop band with a readable inner column */ +} +
+
+
…copy stays readable even full-bleed…
+
+
; +``` + +Need just the width (no gutter/centering)? Use `max-w-content` / `max-w-wide` / `max-w-super-wide`. Plain Tailwind (`mx-auto max-w-7xl px-4 …`) still works — these are additive, never enforced. + +**Immersive full-bleed:** prefer `container-super-wide` over `container-full` — identical below 2560px CSS width, caps on ultrawide (3440+) and very wide 4K. Use `container-full` only when content must touch the bezel at any resolution. See `skills/.../ui-design-system.md` § Full-bleed nuance. + +> Full-width does NOT mean full-measure text. Keep line length readable (~60–80ch) by nesting a `container-prose` (or `max-w-prose`) inside wide/full bands. + +**Section rhythm** — vertical spacing between full-bleed bands uses fluid `clamp()` tokens so cadence stays consistent and scales smoothly (no breakpoint jumps): + +| Class | Approx (mobile → desktop) | Use for | +| --------------- | ------------------------- | -------------------------------- | +| `py-section-sm` | 40 → 64px | Compact bands, announcement rows | +| `py-section-md` | 64 → 112px | Standard marketing sections | +| `py-section-lg` | 80 → 144px | Hero-adjacent / feature bands | + +Works with any spacing utility (`gap-section-md`, `mt-section-sm`, …). + +### 9. Elevation & motion + +| Token class | Role | +| ----------------- | ----------------------------------------- | +| `shadow-card` | Resting cards, subtle separation | +| `shadow-elevated` | Dropdowns, popovers, hovered cards | +| `shadow-overlay` | Sheets, modals, floating bars | +| `duration-fast` | 150ms — micro-interactions (hover, focus) | +| `duration-base` | 250ms — most transitions | +| `duration-slow` | 400ms — larger reveals | +| `ease-standard` | Default easing | +| `ease-emphasized` | Entrances / attention | + +Always guard non-trivial motion with `motion-reduce:` (or `prefers-reduced-motion`). + +--- + +## Token reference + +| Token | Role | +| --------------------------------------------------------- | --------------------------------------------------------- | +| `--background` | Page background | +| `--foreground` | Primary text | +| `--muted-foreground` | Secondary text | +| `--card` | Elevated surfaces | +| `--muted` | Subtle backgrounds, skeletons | +| `--primary` | CTAs | +| `--destructive` | Errors, sale labels (`SaleBadge`, `DiscountPercentLabel`) | +| `--border` | Dividers | +| `--radius` | Border radius scale | +| `--text-display` … `--text-lead`, `--text-eyebrow` | Fluid type scale + fixed eyebrow (see Typography) | +| `--container-prose/content/wide/full` | Named page widths (see Layout width & rhythm) | +| `--section-space-sm/md/lg` | Fluid section vertical rhythm (`py-section-*`) | +| `--shadow-card/elevated/overlay` | Elevation scale (`shadow-*`) | +| `--duration-fast/base/slow`, `--ease-standard/emphasized` | Motion durations + easings | +| `--inverse*` | Text/borders on inverse surfaces (`bg-foreground`) | + +Colors use **OKLCH**: `oklch(lightness chroma hue)` — lightness 0–1, hue 0–360. + +--- + +## Why OKLCH? + +Perceptually uniform lightness, predictable mixing, easier contrast tuning than hex. + +--- + +## Related files + +| File | Role | +| ---------------------- | ------------------------------------------------------- | +| `src/styles/brand.css` | Design tokens | +| `tailwind.config.cjs` | Maps tokens → Tailwind utilities | +| `src/lib/utils.ts` | `cn()` / tailwind-merge (typography token registration) | +| `src/app/globals.css` | Imports `brand.css`, base styles | +| `src/config/brand.ts` | Site name, tagline, SEO copy | diff --git a/apps/web/src/styles/brand.css b/apps/web/src/styles/brand.css new file mode 100644 index 0000000..5a1b987 --- /dev/null +++ b/apps/web/src/styles/brand.css @@ -0,0 +1,174 @@ +/** + * ======================================== + * SALEOR STOREFRONT - DESIGN TOKENS + * ======================================== + * + * Single source of truth for visual design. Edit this file to rebrand. + * Tailwind consumes these via tailwind.config.cjs (see src/styles/README.md). + * + * Color format: OKLCH (perceptually uniform, good for programmatic tweaks) + * + * @see src/styles/README.md — canonical workflow for Tailwind developers + */ + +/* ============================================ + * Light theme (only) + * ============================================ */ +:root { + /* --- Color tokens — BARE OKLCH CHANNELS (no oklch() wrapper) --- + * IMPORTANT: these hold raw `L C H` components, NOT a finished color. Tailwind wraps + * them as `oklch(var(--token) / )` (see tailwind.config.cjs), which is what + * makes opacity modifiers work everywhere — `bg-foreground/40`, `text-background/80`, + * gradient scrims, etc. (A bare `var(--background)` color silently drops the `/NN`.) + * + * Consequence: never use `var(--token)` directly as a color in CSS/SVG/inline styles — + * it isn't a color on its own. Wrap it: `color: oklch(var(--foreground))`. In JSX prefer + * a Tailwind utility (`text-foreground`) over inline `var()`. + * + * Cool, neutral palette: crisp near-white page with soft grey panels. */ + --background: 0.99 0 0; /* Page background - crisp near-white */ + --card: 1 0 0; /* Cards, dropdowns, modals */ + --popover: 1 0 0; + --secondary: 0.965 0 0; /* Soft grey panels (hero/editorial image tiles) */ + --muted: 0.95 0 0; + --accent: 0.95 0 0; + + /* --- Foregrounds (text on light surfaces) --- */ + --foreground: 0.12 0 0; + --card-foreground: 0.12 0 0; + --popover-foreground: 0.12 0 0; + --secondary-foreground: 0.12 0 0; + --muted-foreground: 0.45 0 0; + --accent-foreground: 0.12 0 0; + + /* --- Primary (CTAs, key actions) --- */ + --primary: 0.12 0 0; + --primary-foreground: 0.98 0 0; + + /* --- Semantic --- */ + --destructive: 0.55 0.2 25; + --destructive-foreground: 0.98 0 0; + --success: 0.55 0.15 145; + --success-foreground: 0.98 0 0; + --bestseller: 0.56 0.084 68; /* Bronze outline (~#8B6B3D) — bestseller badge */ + + /* --- Interactive --- */ + --border: 0.915 0 0; + --input: 0.915 0 0; + --ring: 0.12 0 0; + + /* --- Inverse surfaces (dark bands: bg-foreground text-background) --- */ + --inverse: 0.82 0 0; + --inverse-subtle: 0.65 0 0; + --inverse-muted: 0.55 0 0; + --border-inverse: 0.28 0 0; + + /* --- Typography: fluid type scale (rem + clamp) --- + * Sized in rem so it respects the user's browser font size (a11y). + * clamp() scales smoothly between mobile and desktop — no breakpoint jumps. + * Weight / tracking / line-height are baked into the Tailwind fontSize tokens + * (see tailwind.config.cjs → theme.extend.fontSize): text-display/h1/h2/h3/lead. + * + * --font-display: heading family (Geist by default; Fraunces when data-typography=editorial). */ + --font-display: var(--font-geist-sans), system-ui, sans-serif; + --text-display: clamp(2.75rem, 1.9rem + 4.2vw, 4.5rem); /* 44 → 72px */ + --text-h1: clamp(2rem, 1.5rem + 2.4vw, 3rem); /* 32 → 48px */ + --text-h2: clamp(1.5rem, 1.25rem + 1.2vw, 2.25rem); /* 24 → 36px */ + --text-h3: clamp(1.125rem, 1.05rem + 0.4vw, 1.5rem); /* 18 → 24px */ + --text-lead: clamp(1.0625rem, 1rem + 0.3vw, 1.25rem); /* 17 → 20px */ + --text-eyebrow: 0.75rem; /* 12px fixed — overlines, brand labels */ + + /* --- Layout / shape --- + * Corner styles are split out so the whole UI can be re-shaped from one place. + * To experiment with a different look in dev, change these here — every button, + * input, card and tile follows. E.g. set --radius-button: 9999px for pill buttons + * site-wide, or --radius-card: 0 for hard-edged tiles. No component edits needed. */ + --radius: 0.5rem; /* base scale → rounded-sm/md/lg/xl */ + --radius-button: calc(var(--radius) - 2px); /* buttons + token-backed link CTAs */ + --radius-card: calc(var(--radius) + 4px); /* cards, tiles, image panels */ + + /* --- Container widths --- + * Named page-width tokens. `content` is the canonical storefront body width + * (formerly the bare `max-w-7xl` magic string). Page width is a DESIGN DECISION: + * full-bleed (`full`) is fully supported — Paper does not assume a fixed desktop + * width. Even inside wide/full layouts, keep text measure readable (see README). */ + --container-prose: 48rem; /* ~75ch reading measure — long-form copy, legal, FAQ */ + --container-content: 80rem; /* 1280px — default storefront body width (was max-w-7xl) */ + --container-wide: 96rem; /* 1536px — immersive / editorial layouts */ + /* 160rem (2560px) — full-bleed feel on typical desktops; caps ultrawide / very wide 4K. + * Identical to container-full below ~2560px CSS width; above that, content centers with + * side margins. Use for immersive PDP and editorial bands. True edge-to-edge at any + * resolution → container-full. See ui-design-system.md § Page width. */ + --container-super-wide: 160rem; + --container-full: 100%; /* edge-to-edge content at every viewport width */ + + /* Header/nav column width. Defaults to the main content width so the nav lines + * up with page bodies (the current look). A brand can take the nav edge-to-edge + * by setting this to var(--container-full) (or var(--container-wide)) — the header + * bar AND the mega-menu panel follow, no component edits. Always reversible: + * restore var(--container-content) for the default. */ + --container-nav: var(--container-full); + + /* --- Chrome heights (single source of truth for sticky/offset math) --- + * Everything that needs to reason about "how tall is the fixed chrome?" reads + * these instead of hardcoding magic numbers. Keep the announcement bar a known, + * single-line height so the sum is deterministic; consumers always subtract the + * MAX chrome (bar present), so a dismissed/absent bar only leaves harmless extra + * space — it can never clip content. See `gallery-layout.ts`, `main-chrome.tsx`. */ + --header-height: 4rem; /* matches header h-16 */ + --announcement-bar-height: 2.5rem; /* single-line announcement bar */ + --chrome-offset: calc(var(--header-height) + var(--announcement-bar-height)); + /* PDP-local vertical budget above/below the immersive image (breadcrumb, page + * padding, gallery gap, controls row) — stable, not chrome-dependent. */ + --pdp-immersive-reserved: 9.5rem; + + /* --- Section rhythm (fluid vertical spacing for full-bleed bands) --- + * Use as py-section-* / gap-section-*. Keeps the cadence between marketing + * sections consistent instead of ad-hoc `py-16 md:py-24 lg:py-28` per section. */ + --section-space-sm: clamp(2.5rem, 1.7rem + 3vw, 4rem); /* 40 → 64px */ + --section-space-md: clamp(4rem, 2.6rem + 5vw, 7rem); /* 64 → 112px */ + --section-space-lg: clamp(5rem, 3rem + 7vw, 9rem); /* 80 → 144px */ + + /* --- Elevation (use shadow-card / shadow-elevated / shadow-overlay) --- */ + --shadow-card: 0 1px 2px 0 oklch(0.12 0 0 / 0.05); + --shadow-elevated: 0 4px 16px -2px oklch(0.12 0 0 / 0.1); + --shadow-overlay: 0 12px 40px -4px oklch(0.12 0 0 / 0.18); + + /* --- Motion --- + * Standard durations / easings (use duration-fast|base|slow, ease-standard|emphasized). + * Always pair non-trivial motion with a prefers-reduced-motion guard in components. */ + --duration-fast: 150ms; + --duration-base: 250ms; + --duration-slow: 400ms; + --ease-standard: cubic-bezier(0.4, 0, 0.2, 1); + --ease-emphasized: cubic-bezier(0.2, 0, 0, 1); + + /* --- Skeleton --- */ + --skeleton-delay: 300ms; +} + +/* Dismissible announcement bar — hide without layout shift. + * Set on by the dismiss island (`announcement-bar-dismiss.tsx`) on click. Zeroes + * --announcement-bar-height so chrome math reclaims the space. The server omits the bar + * when the dismiss cookie matches (see `announcement-bar-slot.tsx`). */ +html[data-announcement-dismissed] [data-announcement-bar] { + display: none; +} + +/* Direction A — Editorial Adventure (example theme: Fraunces display + Geist body). + * Enable via NEXT_PUBLIC_TYPOGRAPHY_THEME=editorial — see config/themes/README.md */ +html[data-typography="editorial"] { + --font-display: var(--font-fraunces), Georgia, "Times New Roman", serif; +} + +/* ============================================ + * Delayed skeleton — invisible until --skeleton-delay + * ============================================ */ +@keyframes skeleton-fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} diff --git a/apps/web/src/templates/AGENTS.md b/apps/web/src/templates/AGENTS.md new file mode 100644 index 0000000..80d7ef3 --- /dev/null +++ b/apps/web/src/templates/AGENTS.md @@ -0,0 +1,16 @@ +# Templates + +This directory is fork-owned. Paper upgrades do not overwrite it. + +A PDP template arranges `product` (`ProductView`) and `slots` (gallery, buy box, breadcrumbs, attributes). A PLP template arranges `surface` and `slots` (header, results, empty). Neither fetches, caches, or reads the request. + +Read `skills/saleor-paper-storefront/rules/ui-templates.md` before adding or changing a layout. Listing backends are `rules/plp-listing.md`. + +- A new PDP layout is a file in `src/templates/pdp/`, registered in `src/templates/pdp/registry.ts`. +- Select it with `ACTIVE_PDP_TEMPLATE` and `ACTIVE_PDP_GALLERY` in `src/config/template-selection.ts`. `ACTIVE_PDP_GALLERY` must equal the template's `gallery` field; a mismatch fails `pnpm typecheck`. +- Place `slots.gallery` and `slots.buyBox` exactly once. +- Do not edit the product route, `gallery-layout.ts`, or `src/lib/storefront` for a layout change. +- Do not import `@/gql`, `@/lib/saleor`, or loaders from a template. Do not read `searchParams`, cookies, or headers there. +- A missing PDP field goes in `src/graphql/extensions/ProductDetailsExtension.graphql` and `mapProductExtensions` in `src/config/storefront-view.ts`. +- A new PLP layout is a file in `src/templates/plp/`, registered in `src/templates/plp/registry.ts`. Select it with `ACTIVE_PLP_TEMPLATE` and `ACTIVE_PLP_FACETS` (must equal the template's `facets`; a mismatch fails `pnpm typecheck`). +- A new listing backend is a provider. Do not edit listing routes or `src/lib/listing/policy.ts` for a layout or a backend. diff --git a/apps/web/src/templates/pdp/columns.tsx b/apps/web/src/templates/pdp/columns.tsx new file mode 100644 index 0000000..24aa19c --- /dev/null +++ b/apps/web/src/templates/pdp/columns.tsx @@ -0,0 +1,7 @@ +import { definePresetTemplate } from "@/templates/pdp/product-layout"; + +/** + * Thumbnails on the left of the hero, buy box on the right. + * The thumbnail column is inside the `columns` gallery island. + */ +export const columnsPdp = definePresetTemplate("columns"); diff --git a/apps/web/src/templates/pdp/immersive.tsx b/apps/web/src/templates/pdp/immersive.tsx new file mode 100644 index 0000000..eec8db3 --- /dev/null +++ b/apps/web/src/templates/pdp/immersive.tsx @@ -0,0 +1,4 @@ +import { definePresetTemplate } from "@/templates/pdp/product-layout"; + +/** Wide gallery, sticky buy box, specs under the images. The default Paper PDP. */ +export const immersivePdp = definePresetTemplate("immersive"); diff --git a/apps/web/src/templates/pdp/mosaic.tsx b/apps/web/src/templates/pdp/mosaic.tsx new file mode 100644 index 0000000..314dd8b --- /dev/null +++ b/apps/web/src/templates/pdp/mosaic.tsx @@ -0,0 +1,4 @@ +import { definePresetTemplate } from "@/templates/pdp/product-layout"; + +/** Editorial image grid with a narrow sticky buy box. */ +export const mosaicPdp = definePresetTemplate("mosaic"); diff --git a/apps/web/src/templates/pdp/product-layout.tsx b/apps/web/src/templates/pdp/product-layout.tsx new file mode 100644 index 0000000..0b86b45 --- /dev/null +++ b/apps/web/src/templates/pdp/product-layout.tsx @@ -0,0 +1,59 @@ +import type { ReactNode } from "react"; + +import { definePdpTemplate, type PdpTemplate, type PdpTemplateProps } from "@/lib/storefront/templates"; +import type { PdpGalleryLayout } from "@/lib/storefront/contract/gallery"; +import { BestsellerBadge } from "@/ui/components/ui/sale-label"; +import { PDP_LAYOUT_CLASSES, type PdpLayoutClasses } from "@/ui/components/pdp/gallery-layout"; +import { ProductRouteSkeleton } from "@/ui/components/pdp/product-route-skeleton"; + +/** Shared chrome for the built-in presets. A custom template can ignore this and arrange slots itself. */ +export function PdpPresetLayout({ + product, + slots, + layout, +}: PdpTemplateProps & { layout: PdpLayoutClasses }): ReactNode { + return ( +
+
+
{slots.breadcrumbs}
+ +
+
{slots.gallery}
+ +
+ {product.isBestseller && ( +
+ +
+ )} + +

{product.name}

+ + {slots.buyBox} + + {layout.attributesPlacement === "info" &&
{slots.attributes}
} +
+ + {layout.attributesPlacement === "gallery" && layout.attributesGalleryBlock && ( +
{slots.attributes}
+ )} +
+
+
+ ); +} + +export function definePresetTemplate( + gallery: G, +): PdpTemplate & { gallery: G } { + const layout = PDP_LAYOUT_CLASSES[gallery]; + function Layout(props: PdpTemplateProps) { + return ; + } + return definePdpTemplate({ + id: gallery, + gallery, + Layout, + Skeleton: ProductRouteSkeleton, + }); +} diff --git a/apps/web/src/templates/pdp/registry.ts b/apps/web/src/templates/pdp/registry.ts new file mode 100644 index 0000000..d8ca86d --- /dev/null +++ b/apps/web/src/templates/pdp/registry.ts @@ -0,0 +1,38 @@ +import { ACTIVE_PDP_GALLERY, ACTIVE_PDP_TEMPLATE } from "@/config/template-selection"; +import type { PdpTemplate } from "@/lib/storefront/templates"; +import { columnsPdp } from "@/templates/pdp/columns"; +import { immersivePdp } from "@/templates/pdp/immersive"; +import { mosaicPdp } from "@/templates/pdp/mosaic"; +import { standardPdp } from "@/templates/pdp/standard"; + +/** + * Fork-owned PDP registry. Add a template here, then point + * `ACTIVE_PDP_TEMPLATE` at it in `src/config/template-selection.ts`. + */ +export const PDP_TEMPLATES = { + immersive: immersivePdp, + standard: standardPdp, + mosaic: mosaicPdp, + columns: columnsPdp, +} as const satisfies Record; + +const activeId: keyof typeof PDP_TEMPLATES = ACTIVE_PDP_TEMPLATE; + +/** + * Compile-time selection check. A type error on this line means `ACTIVE_PDP_GALLERY` + * is not the active template's `gallery`. Set both in src/config/template-selection.ts. + * (A template typed as plain `PdpTemplate` widens `gallery`; the runtime check below still holds.) + */ +const activeGallery: (typeof PDP_TEMPLATES)[typeof ACTIVE_PDP_TEMPLATE]["gallery"] = ACTIVE_PDP_GALLERY; + +export function activePdpTemplate(): PdpTemplate { + const template = PDP_TEMPLATES[activeId]; + // The template's own classes and the gallery island read different constants. + // A mismatch renders the columns shell with the immersive filmstrip. + if (template.gallery !== activeGallery) { + throw new Error( + `ACTIVE_PDP_TEMPLATE "${activeId}" uses gallery "${template.gallery}", but ACTIVE_PDP_GALLERY is "${ACTIVE_PDP_GALLERY}". Set both in src/config/template-selection.ts.`, + ); + } + return template; +} diff --git a/apps/web/src/templates/pdp/standard.tsx b/apps/web/src/templates/pdp/standard.tsx new file mode 100644 index 0000000..5db84bb --- /dev/null +++ b/apps/web/src/templates/pdp/standard.tsx @@ -0,0 +1,4 @@ +import { definePresetTemplate } from "@/templates/pdp/product-layout"; + +/** Classic split: gallery and buy box side by side, specs under the buy box. */ +export const standardPdp = definePresetTemplate("standard"); diff --git a/apps/web/src/templates/plp/bar.tsx b/apps/web/src/templates/plp/bar.tsx new file mode 100644 index 0000000..69ee8d7 --- /dev/null +++ b/apps/web/src/templates/plp/bar.tsx @@ -0,0 +1,14 @@ +import { ProductsGridSkeleton } from "@/ui/components/plp/products-grid-skeleton"; +import { definePlpTemplate } from "@/lib/storefront/templates"; +import { PlpPresetLayout } from "@/templates/plp/preset-layout"; + +function BarSkeleton() { + return ; +} + +export const barPlp = definePlpTemplate({ + id: "bar", + facets: "bar", + Layout: PlpPresetLayout, + Skeleton: BarSkeleton, +}); diff --git a/apps/web/src/templates/plp/preset-layout.tsx b/apps/web/src/templates/plp/preset-layout.tsx new file mode 100644 index 0000000..8e069dc --- /dev/null +++ b/apps/web/src/templates/plp/preset-layout.tsx @@ -0,0 +1,12 @@ +import type { PlpTemplateProps } from "@/lib/storefront/templates"; + +/** Shared chrome for the built-in PLP presets. Facet placement lives on the results island. */ +export function PlpPresetLayout({ surface, slots }: PlpTemplateProps) { + return ( +
+ {slots.header} + {slots.results} + {slots.empty} +
+ ); +} diff --git a/apps/web/src/templates/plp/registry.ts b/apps/web/src/templates/plp/registry.ts new file mode 100644 index 0000000..c202ede --- /dev/null +++ b/apps/web/src/templates/plp/registry.ts @@ -0,0 +1,31 @@ +import { ACTIVE_PLP_FACETS, ACTIVE_PLP_TEMPLATE } from "@/config/template-selection"; +import type { PlpTemplate } from "@/lib/storefront/templates"; +import { barPlp } from "@/templates/plp/bar"; +import { sidebarPlp } from "@/templates/plp/sidebar"; + +/** + * Fork-owned PLP registry. Add a template here, then point + * `ACTIVE_PLP_TEMPLATE` at it in `src/config/template-selection.ts`. + */ +export const PLP_TEMPLATES = { + bar: barPlp, + sidebar: sidebarPlp, +} as const satisfies Record; + +const activeId: keyof typeof PLP_TEMPLATES = ACTIVE_PLP_TEMPLATE; + +/** + * Compile-time selection check. A type error on this line means `ACTIVE_PLP_FACETS` + * is not the active template's `facets`. Set both in src/config/template-selection.ts. + */ +const activeFacets: (typeof PLP_TEMPLATES)[typeof ACTIVE_PLP_TEMPLATE]["facets"] = ACTIVE_PLP_FACETS; + +export function activePlpTemplate(): PlpTemplate { + const template = PLP_TEMPLATES[activeId]; + if (template.facets !== activeFacets) { + throw new Error( + `ACTIVE_PLP_TEMPLATE "${activeId}" uses facets "${template.facets}", but ACTIVE_PLP_FACETS is "${ACTIVE_PLP_FACETS}". Set both in src/config/template-selection.ts.`, + ); + } + return template; +} diff --git a/apps/web/src/templates/plp/sidebar.tsx b/apps/web/src/templates/plp/sidebar.tsx new file mode 100644 index 0000000..500a598 --- /dev/null +++ b/apps/web/src/templates/plp/sidebar.tsx @@ -0,0 +1,14 @@ +import { ProductsGridSkeleton } from "@/ui/components/plp/products-grid-skeleton"; +import { definePlpTemplate } from "@/lib/storefront/templates"; +import { PlpPresetLayout } from "@/templates/plp/preset-layout"; + +function SidebarSkeleton() { + return ; +} + +export const sidebarPlp = definePlpTemplate({ + id: "sidebar", + facets: "sidebar", + Layout: PlpPresetLayout, + Skeleton: SidebarSkeleton, +}); diff --git a/apps/web/src/ui/atoms/link-with-channel.tsx b/apps/web/src/ui/atoms/link-with-channel.tsx new file mode 100644 index 0000000..76cb853 --- /dev/null +++ b/apps/web/src/ui/atoms/link-with-channel.tsx @@ -0,0 +1,24 @@ +"use client"; +import Link from "next/link"; +import { useParams } from "next/navigation"; +import { type ComponentProps } from "react"; +import { buildStorefrontPath } from "@/lib/storefront-path"; + +export const LinkWithChannel = ({ + href, + ...props +}: Omit, "href"> & { href: string }) => { + const { locale, channel } = useParams<{ locale?: string; channel?: string }>(); + + if (!href.startsWith("/")) { + return ; + } + + // During hydration/recovery there can be a transient moment where params + // are unavailable. Avoid generating malformed URLs in that case. + if (!locale || !channel) { + return ; + } + + return ; +}; diff --git a/apps/web/src/ui/atoms/loader.tsx b/apps/web/src/ui/atoms/loader.tsx new file mode 100644 index 0000000..6fe63fd --- /dev/null +++ b/apps/web/src/ui/atoms/loader.tsx @@ -0,0 +1,25 @@ +export function Loader() { + return ( +
+
+ + Loading... +
+
+ ); +} diff --git a/apps/web/src/ui/atoms/nav-href-link.tsx b/apps/web/src/ui/atoms/nav-href-link.tsx new file mode 100644 index 0000000..15887bb --- /dev/null +++ b/apps/web/src/ui/atoms/nav-href-link.tsx @@ -0,0 +1,53 @@ +import type { ComponentProps, ReactNode } from "react"; +import { isExternalMenuHref } from "@/lib/menus/menu-item-utils"; +import { isSafeNavHref } from "@/lib/url/safe-href"; +import { cn } from "@/lib/utils"; +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; + +export interface NavHrefLinkProps extends Omit, "href"> { + href: string; + children: ReactNode; +} + +/** + * Channel-aware link for CMS/menu hrefs. + * Renders a plain anchor for safe external/mailto URLs, `LinkWithChannel` for internal paths, + * and non-interactive content when the href fails validation. + * + * Next Link navigation props (`prefetch`, `replace`, `scroll`) stay on the internal + * `Link` only — spreading them onto `
` prints a React DOM warning (boolean `prefetch`). + */ +export function NavHrefLink({ + href, + children, + className, + prefetch, + replace, + scroll, + ...props +}: NavHrefLinkProps) { + if (!isSafeNavHref(href)) { + return {children}; + } + + if (isExternalMenuHref(href)) { + return ( + + {children} + + ); + } + + return ( + + {children} + + ); +} diff --git a/apps/web/src/ui/atoms/product-image-wrapper.tsx b/apps/web/src/ui/atoms/product-image-wrapper.tsx new file mode 100644 index 0000000..95e15fd --- /dev/null +++ b/apps/web/src/ui/atoms/product-image-wrapper.tsx @@ -0,0 +1,26 @@ +import NextImage, { type ImageProps } from "next/image"; +import clsx from "clsx"; + +interface ProductImageWrapperProps extends ImageProps { + containerClassName?: string; +} + +export const ProductImageWrapper = ({ + containerClassName, + className, + fill = true, + ...props +}: ProductImageWrapperProps) => { + return ( +
+ +
+ ); +}; diff --git a/apps/web/src/ui/atoms/saleor-image.tsx b/apps/web/src/ui/atoms/saleor-image.tsx new file mode 100644 index 0000000..3275268 --- /dev/null +++ b/apps/web/src/ui/atoms/saleor-image.tsx @@ -0,0 +1,82 @@ +import NextImage from "next/image"; +import { preload } from "react-dom"; +import { cn } from "@/lib/utils"; +import { PAPER_IMAGE_PIPELINE, PRODUCT_IMAGE_QUALITY } from "@/lib/images"; + +export interface SaleorImageProps { + /** Largest requested rung — also the `src` fallback for browsers ignoring `srcSet`. */ + src: string; + /** + * Built by `buildSaleorSrcSet()` from aliased Saleor thumbnail fields. When absent + * (local asset, CMS upload, single rung) the component falls back to `next/image`. + */ + srcSet?: string; + alt: string; + sizes: string; + className?: string; + /** LCP candidate: eager, high fetch priority, and a preload hint. */ + priority?: boolean; + /** Overrides the `priority`-derived default — e.g. eager-load a carousel's first slide. */ + loading?: "eager" | "lazy"; + draggable?: boolean; + /** Only consulted on the `next/image` path — Saleor rungs are pre-encoded. */ + quality?: number; +} + +/** + * Fill-positioned catalog image that prefers Saleor's CDN over Vercel's optimizer. + * + * Saleor has already produced a correctly-sized, CloudFront-cached WebP for each rung + * we request, so sending those through `/_next/image` pays for a transformation that + * re-derives a file we already have. When a rung set is available this renders a plain + * `` against the CDN; otherwise it defers to `next/image`. + * + * See the `ui-images` rule for the decision table and the Saleor thumbnail mechanics. + */ +export function SaleorImage({ + src, + srcSet, + alt, + sizes, + className, + priority = false, + loading, + draggable, + quality = PRODUCT_IMAGE_QUALITY, +}: SaleorImageProps) { + if (PAPER_IMAGE_PIPELINE === "vercel" || !srcSet) { + return ( + + ); + } + + // next/image emits this for `priority`; the plain path has to ask for it. + if (priority) { + preload(src, { as: "image", imageSrcSet: srcSet, imageSizes: sizes, fetchPriority: "high" }); + } + + return ( + // eslint-disable-next-line @next/next/no-img-element -- deliberate: Saleor serves a CDN-cached WebP per rung, so next/image would bill a transformation to re-encode an already-optimal file. + {alt} + ); +} diff --git a/apps/web/src/ui/atoms/storefront-hard-link.tsx b/apps/web/src/ui/atoms/storefront-hard-link.tsx new file mode 100644 index 0000000..17e6c08 --- /dev/null +++ b/apps/web/src/ui/atoms/storefront-hard-link.tsx @@ -0,0 +1,30 @@ +"use client"; + +import { type ReactNode, type MouseEvent } from "react"; + +type StorefrontHardLinkProps = { + href: string; + className?: string; + children: ReactNode; +}; + +/** + * Same-root storefront navigation that must bypass the App Router cache. + * Plain `` inside a root layout is still client-navigated by Next.js; + * auth routes (login after logout) can restore a cached “already signed in → home” + * payload and feel like the link does nothing. + */ +export function StorefrontHardLink({ href, className, children }: StorefrontHardLinkProps) { + return ( + ) => { + event.preventDefault(); + window.location.assign(href); + }} + > + {children} + + ); +} diff --git a/apps/web/src/ui/components/account/account-action-result.ts b/apps/web/src/ui/components/account/account-action-result.ts new file mode 100644 index 0000000..1a922d6 --- /dev/null +++ b/apps/web/src/ui/components/account/account-action-result.ts @@ -0,0 +1,30 @@ +import type { useTranslations } from "next-intl"; + +/** Keys under `account.errors` returned by account server actions for client-side translation. */ +export type AccountActionErrorKey = + | "passwordMinLength" + | "passwordsMismatch" + | "updateProfileFailed" + | "changePasswordFailed" + | "createAddressFailed" + | "updateAddressFailed" + | "deleteAddressFailed" + | "setDefaultAddressFailed" + | "deleteAccountFailed"; + +export type AccountActionResult = + | { success: true } + | { success: false; errorKey: AccountActionErrorKey } + | { success: false; error: string }; + +type AccountTranslator = ReturnType>; + +export function resolveAccountActionError( + t: AccountTranslator, + result: Extract, +): string { + if ("errorKey" in result) { + return t(`errors.${result.errorKey}`); + } + return result.error; +} diff --git a/apps/web/src/ui/components/account/account-context.tsx b/apps/web/src/ui/components/account/account-context.tsx new file mode 100644 index 0000000..6c0b597 --- /dev/null +++ b/apps/web/src/ui/components/account/account-context.tsx @@ -0,0 +1,18 @@ +"use client"; + +import { createContext, use } from "react"; +import { type AccountUser } from "@/app/(storefront)/[locale]/[channel]/(main)/account/get-current-user"; + +const AccountContext = createContext(null); + +export function AccountProvider({ user, children }: { user: AccountUser; children: React.ReactNode }) { + return {children}; +} + +export function useAccountUser(): AccountUser { + const user = use(AccountContext); + if (!user) { + throw new Error("useAccountUser must be used within an AccountProvider"); + } + return user; +} diff --git a/apps/web/src/ui/components/account/account-login.tsx b/apps/web/src/ui/components/account/account-login.tsx new file mode 100644 index 0000000..5e2fdb2 --- /dev/null +++ b/apps/web/src/ui/components/account/account-login.tsx @@ -0,0 +1,29 @@ +import { Suspense } from "react"; +import { LoginForm } from "@/ui/components/login-form"; + +function LoginFormSkeleton() { + return ( +
+
+
+
+
+
+
+
+
+
+
+
+
+ ); +} + +/** Login UI for /account when the user is signed out or the session is invalid. */ +export function AccountLogin() { + return ( + }> + + + ); +} diff --git a/apps/web/src/ui/components/account/account-nav.tsx b/apps/web/src/ui/components/account/account-nav.tsx new file mode 100644 index 0000000..3705b9a --- /dev/null +++ b/apps/web/src/ui/components/account/account-nav.tsx @@ -0,0 +1,110 @@ +"use client"; + +import { usePathname, useParams } from "next/navigation"; +import Image from "next/image"; +import { useTranslations } from "next-intl"; +import { LayoutGrid, Receipt, MapPin, Settings, ArrowLeft } from "lucide-react"; +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; +import { cn } from "@/lib/utils"; +import { LogoutButton } from "@/lib/auth/logout-button"; +import { useAccountUser } from "@/ui/components/account/account-context"; +import { accountRoutes } from "@/ui/components/account/routes"; +import { stripStorefrontPrefix } from "@/lib/storefront-path"; + +const navItems: ReadonlyArray<{ + href: string; + labelKey: "overview" | "orders" | "addresses" | "settings"; + icon: typeof LayoutGrid; + exact?: boolean; +}> = [ + { href: accountRoutes.overview, labelKey: "overview", icon: LayoutGrid, exact: true }, + { href: accountRoutes.orders, labelKey: "orders", icon: Receipt }, + { href: accountRoutes.addresses, labelKey: "addresses", icon: MapPin }, + { href: accountRoutes.settings, labelKey: "settings", icon: Settings }, +]; + +export function AccountNav() { + const t = useTranslations("account.nav"); + const user = useAccountUser(); + const pathname = usePathname(); + const { locale, channel } = useParams<{ locale?: string; channel?: string }>(); + + const isActive = (href: string, exact?: boolean) => { + const accountPath = locale && channel ? stripStorefrontPrefix(pathname, locale, channel) : pathname; + if (exact) return accountPath === href; + return accountPath.startsWith(href); + }; + + const initials = + user.firstName && user.lastName + ? `${user.firstName[0]}${user.lastName[0]}` + : user.email.slice(0, 2).toUpperCase(); + + return ( +
+ + ‹ + {t("backToStore")} + + +
+ {user.avatar ? ( + {user.avatar.alt + ) : ( +
+ {initials} +
+ )} +

+ {user.firstName} {user.lastName} +

+

{user.email}

+
+ + + +
+ + + {t("signOut")} + +
+
+ ); +} diff --git a/apps/web/src/ui/components/account/account-overview-default-address.tsx b/apps/web/src/ui/components/account/account-overview-default-address.tsx new file mode 100644 index 0000000..efe5301 --- /dev/null +++ b/apps/web/src/ui/components/account/account-overview-default-address.tsx @@ -0,0 +1,36 @@ +"use client"; + +import { ChevronRight } from "lucide-react"; +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; +import { AccountAddressCard } from "@/ui/components/account/address-card"; +import { accountRoutes } from "@/ui/components/account/routes"; +import { useAccountUser } from "@/ui/components/account/account-context"; + +export function AccountOverviewDefaultAddress() { + const user = useAccountUser(); + const defaultAddress = + user.addresses.find((a) => a.id === user.defaultShippingAddress?.id) ?? user.addresses[0] ?? null; + + return ( +
+
+

Default Address

+ + Manage + + +
+ + {defaultAddress ? ( + + ) : ( +
+ No addresses saved yet. +
+ )} +
+ ); +} diff --git a/apps/web/src/ui/components/account/account-overview-welcome.tsx b/apps/web/src/ui/components/account/account-overview-welcome.tsx new file mode 100644 index 0000000..4c987f9 --- /dev/null +++ b/apps/web/src/ui/components/account/account-overview-welcome.tsx @@ -0,0 +1,17 @@ +"use client"; + +import { useTranslations } from "next-intl"; +import { useAccountUser } from "@/ui/components/account/account-context"; + +export function AccountOverviewWelcome() { + const t = useTranslations("account.overview"); + const user = useAccountUser(); + const displayName = user.firstName || user.email.split("@")[0] || ""; + + return ( +
+

{t("welcome", { name: displayName })}

+

{t("subtitle")}

+
+ ); +} diff --git a/apps/web/src/ui/components/account/account-skeleton.tsx b/apps/web/src/ui/components/account/account-skeleton.tsx new file mode 100644 index 0000000..bc3e732 --- /dev/null +++ b/apps/web/src/ui/components/account/account-skeleton.tsx @@ -0,0 +1,127 @@ +/** + * Mirrors the sidebar + overview layout to prevent CLS. + * animate-skeleton-delayed (defined in tailwind config) adds 300ms + * visibility delay to avoid flash on fast loads. + */ +export function AccountSkeleton() { + return ( +
+
+ + +
+ {[1, 2, 3, 4].map((i) => ( +
+ ))} +
+ +
+
+
+
+
+ +
+
+
+
+
+
+ {[1, 2, 3].map((i) => ( +
+
+
+
+
+
+
+
+
+
+
+
+
+ ))} +
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ); +} + +export function RecentOrdersSectionSkeleton() { + return ( +
+
+
+ {[1, 2, 3].map((i) => ( +
+ ))} +
+
+ ); +} + +export function AccountOrdersListSkeleton() { + return ( +
+
+
+
+
+
+ {[1, 2, 3, 4].map((i) => ( +
+ ))} +
+
+ ); +} + +export function AccountOrderDetailSkeleton() { + return ( +
+
+
+
+
+
+
+
+
+
+
+
+
+ ); +} diff --git a/apps/web/src/ui/components/account/account-unavailable.tsx b/apps/web/src/ui/components/account/account-unavailable.tsx new file mode 100644 index 0000000..77fa939 --- /dev/null +++ b/apps/web/src/ui/components/account/account-unavailable.tsx @@ -0,0 +1,16 @@ +import { getTranslations } from "next-intl/server"; +import { AuthFormSection } from "@/ui/components/auth/auth-form-section"; + +/** Session cookies exist but profile could not be loaded — not the same as signed out. */ +export async function AccountUnavailable({ locale }: { locale: string }) { + const t = await getTranslations({ locale, namespace: "account.unavailable" }); + + return ( + +
+

{t("title")}

+

{t("body")}

+
+
+ ); +} diff --git a/apps/web/src/ui/components/account/address-actions.tsx b/apps/web/src/ui/components/account/address-actions.tsx new file mode 100644 index 0000000..6e323a5 --- /dev/null +++ b/apps/web/src/ui/components/account/address-actions.tsx @@ -0,0 +1,96 @@ +"use client"; + +import { useState, useTransition } from "react"; +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { Trash2 } from "lucide-react"; +import { Button } from "@/ui/components/ui/button"; +import { + deleteAddress, + setDefaultAddress, +} from "@/app/(storefront)/[locale]/[channel]/(main)/account/actions"; + +type DeleteProps = { + addressId: string; +}; + +export function DeleteAddressButton({ addressId }: DeleteProps) { + const t = useTranslations("account"); + const router = useRouter(); + const [isPending, startTransition] = useTransition(); + const [showConfirm, setShowConfirm] = useState(false); + + function handleDelete() { + startTransition(async () => { + const formData = new FormData(); + formData.set("id", addressId); + const result = await deleteAddress(formData); + if (result.success) { + setShowConfirm(false); + router.refresh(); + } + }); + } + + if (showConfirm) { + return ( +
+ + +
+ ); + } + + return ( + + ); +} + +type SetDefaultProps = { + addressId: string; + type: "SHIPPING" | "BILLING"; +}; + +export function SetDefaultAddressButton({ addressId, type }: SetDefaultProps) { + const t = useTranslations("account.addresses"); + const tCommon = useTranslations("account.common"); + const router = useRouter(); + const [isPending, startTransition] = useTransition(); + + function handleSetDefault() { + startTransition(async () => { + const formData = new FormData(); + formData.set("id", addressId); + formData.set("type", type); + const result = await setDefaultAddress(formData); + if (result.success) { + router.refresh(); + } + }); + } + + const label = type === "SHIPPING" ? t("makeDefaultShipping") : t("makeDefaultBilling"); + + return ( + + ); +} diff --git a/apps/web/src/ui/components/account/address-card.tsx b/apps/web/src/ui/components/account/address-card.tsx new file mode 100644 index 0000000..ebbc8d5 --- /dev/null +++ b/apps/web/src/ui/components/account/address-card.tsx @@ -0,0 +1,65 @@ +"use client"; + +import { useTranslations } from "next-intl"; +import { type AddressDetailsFragment } from "@/gql/graphql"; +import { cn } from "@/lib/utils"; + +type Props = { + address: AddressDetailsFragment; + isDefaultShipping?: boolean; + isDefaultBilling?: boolean; + className?: string; + children?: React.ReactNode; + footer?: React.ReactNode; +}; + +export function AccountAddressCard({ + address, + isDefaultShipping, + isDefaultBilling, + className, + children, + footer, +}: Props) { + const t = useTranslations("account.addresses"); + + return ( +
+
+
+
+ + {address.firstName} {address.lastName} + + {isDefaultShipping && ( + + {t("defaultShipping")} + + )} + {isDefaultBilling && ( + + {t("defaultBilling")} + + )} +
+

{address.streetAddress1}

+ {address.streetAddress2 && ( +

{address.streetAddress2}

+ )} +

+ {address.city} + {address.countryArea && `, ${address.countryArea}`} {address.postalCode} +

+

{address.country.country}

+ {address.phone &&

{address.phone}

} +
+ {children &&
{children}
} +
+ {footer && ( +
+ {footer} +
+ )} +
+ ); +} diff --git a/apps/web/src/ui/components/account/address-form-dialog.tsx b/apps/web/src/ui/components/account/address-form-dialog.tsx new file mode 100644 index 0000000..8b9ce79 --- /dev/null +++ b/apps/web/src/ui/components/account/address-form-dialog.tsx @@ -0,0 +1,215 @@ +"use client"; + +import { useState, useTransition, useCallback } from "react"; +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { Plus, Pencil } from "lucide-react"; +import { type AddressDetailsFragment } from "@/gql/graphql"; +import { Button } from "@/ui/components/ui/button"; +import { Input } from "@/ui/components/ui/input"; +import { Label } from "@/ui/components/ui/label"; +import { + Sheet, + SheetContent, + SheetHeader, + SheetTitle, + SheetDescription, + SheetCloseButton, +} from "@/ui/components/ui/sheet"; +import { createAddress, updateAddress } from "@/app/(storefront)/[locale]/[channel]/(main)/account/actions"; +import { resolveAccountActionError } from "@/ui/components/account/account-action-result"; + +type Props = { + address?: AddressDetailsFragment; +}; + +export function AddressFormDialog({ address }: Props) { + const t = useTranslations("account"); + const router = useRouter(); + const [open, setOpen] = useState(false); + const [isPending, startTransition] = useTransition(); + const [error, setError] = useState(""); + + const isEditing = !!address; + + const handleSubmit = useCallback( + (formData: FormData) => { + setError(""); + const action = isEditing ? updateAddress : createAddress; + + startTransition(async () => { + const result = await action(formData); + if (!result.success) { + setError(resolveAccountActionError(t, result)); + } else { + setOpen(false); + router.refresh(); + } + }); + }, + [isEditing, router, startTransition, t], + ); + + return ( + <> + {isEditing ? ( + + ) : ( + + )} + + + + {isEditing ? t("addresses.editAddress") : t("addresses.addNewAddress")} + + {isEditing ? t("addresses.editAddressDescription") : t("addresses.addAddressDescription")} + + + + + + {isEditing && } + + {error && ( +

+ {error} +

+ )} + +
+
+ + +
+
+ + +
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+ + +
+ +
+ +
+ +
+
+ + ); +} diff --git a/apps/web/src/ui/components/account/addresses-page.tsx b/apps/web/src/ui/components/account/addresses-page.tsx new file mode 100644 index 0000000..0b1e77c --- /dev/null +++ b/apps/web/src/ui/components/account/addresses-page.tsx @@ -0,0 +1,67 @@ +"use client"; + +import { useTranslations } from "next-intl"; +import { AccountAddressCard } from "@/ui/components/account/address-card"; +import { AddressFormDialog } from "@/ui/components/account/address-form-dialog"; +import { DeleteAddressButton, SetDefaultAddressButton } from "@/ui/components/account/address-actions"; +import { useAccountUser } from "@/ui/components/account/account-context"; + +export function AddressesPage() { + const t = useTranslations("account.addresses"); + const user = useAccountUser(); + const { addresses } = user; + const defaultShippingId = user.defaultShippingAddress?.id; + const defaultBillingId = user.defaultBillingAddress?.id; + + return ( +
+
+
+

{t("title")}

+

{t("subtitle")}

+
+ +
+ + {addresses.length === 0 ? ( +
+

{t("empty")}

+
+ +
+
+ ) : ( +
+ {addresses.map((address) => { + const isDefaultShipping = address.id === defaultShippingId; + const isDefaultBilling = address.id === defaultBillingId; + + const showDefaultLinks = !isDefaultShipping || !isDefaultBilling; + + return ( + + {!isDefaultShipping && ( + + )} + {!isDefaultBilling && } + + ) : undefined + } + > + + + + ); + })} +
+ )} +
+ ); +} diff --git a/apps/web/src/ui/components/account/change-password-form.tsx b/apps/web/src/ui/components/account/change-password-form.tsx new file mode 100644 index 0000000..3d8affc --- /dev/null +++ b/apps/web/src/ui/components/account/change-password-form.tsx @@ -0,0 +1,154 @@ +"use client"; + +import { useState, useTransition, useRef, useCallback } from "react"; +import { useTranslations } from "next-intl"; +import { Lock, Eye, EyeOff } from "lucide-react"; +import { Button } from "@/ui/components/ui/button"; +import { Input } from "@/ui/components/ui/input"; +import { Label } from "@/ui/components/ui/label"; +import { changePassword } from "@/app/(storefront)/[locale]/[channel]/(main)/account/actions"; +import { resolveAccountActionError } from "@/ui/components/account/account-action-result"; + +export function ChangePasswordForm() { + const t = useTranslations("account"); + const [isOpen, setIsOpen] = useState(false); + const [isPending, startTransition] = useTransition(); + const [error, setError] = useState(""); + const [success, setSuccess] = useState(false); + const [showOld, setShowOld] = useState(false); + const [showNew, setShowNew] = useState(false); + const formRef = useRef(null); + + const handleSubmit = useCallback( + (formData: FormData) => { + setError(""); + setSuccess(false); + + startTransition(async () => { + const result = await changePassword(formData); + if (!result.success) { + setError(resolveAccountActionError(t, result)); + } else { + setSuccess(true); + setIsOpen(false); + formRef.current?.reset(); + } + }); + }, + [startTransition, t], + ); + + if (!isOpen) { + return ( +
+
+

{t("fields.password")}

+

••••••••

+
+
+ {success && ( + + {t("common.updated")} + + )} + +
+
+ ); + } + + return ( +
+

{t("fields.password")}

+ {error && ( +

+ {error} +

+ )} + +
+ +
+ + + +
+
+ +
+ +
+ + + +
+
+ +
+ +
+ + +
+
+ +
+ + +
+
+ ); +} diff --git a/apps/web/src/ui/components/account/delete-account-section.tsx b/apps/web/src/ui/components/account/delete-account-section.tsx new file mode 100644 index 0000000..0f77c1f --- /dev/null +++ b/apps/web/src/ui/components/account/delete-account-section.tsx @@ -0,0 +1,83 @@ +"use client"; + +import { useState, useTransition } from "react"; +import { useParams } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { AlertTriangle } from "lucide-react"; +import { Button } from "@/ui/components/ui/button"; +import { requestAccountDeletion } from "@/app/(storefront)/[locale]/[channel]/(main)/account/actions"; +import { resolveAccountActionError } from "@/ui/components/account/account-action-result"; +import { buildStorefrontPath } from "@/lib/storefront-path"; + +export function DeleteAccountSection() { + const t = useTranslations("account.deleteAccount"); + const tAccount = useTranslations("account"); + const tCommon = useTranslations("account.common"); + const params = useParams<{ locale: string; channel: string }>(); + const [showConfirm, setShowConfirm] = useState(false); + const [isPending, startTransition] = useTransition(); + const [error, setError] = useState(""); + const [sent, setSent] = useState(false); + + function handleDelete() { + setError(""); + startTransition(async () => { + const formData = new FormData(); + formData.set( + "redirectUrl", + `${window.location.origin}${buildStorefrontPath(params.locale, params.channel)}`, + ); + formData.set("channel", params.channel); + const result = await requestAccountDeletion(formData); + if (!result.success) { + setError(resolveAccountActionError(tAccount, result)); + } else { + setSent(true); + } + }); + } + + if (sent) { + return ( +
+

{t("emailSent")}

+
+ ); + } + + return ( +
+
+

{t("title")}

+

{t("description")}

+
+ + {error && ( +

+ {error} +

+ )} + + {!showConfirm ? ( + + ) : ( +
+ +
+

{t("confirmBody")}

+
+ + +
+
+
+ )} +
+ ); +} diff --git a/apps/web/src/ui/components/account/edit-name-form.tsx b/apps/web/src/ui/components/account/edit-name-form.tsx new file mode 100644 index 0000000..8205022 --- /dev/null +++ b/apps/web/src/ui/components/account/edit-name-form.tsx @@ -0,0 +1,108 @@ +"use client"; + +import { useState, useTransition, useCallback } from "react"; +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { Button } from "@/ui/components/ui/button"; +import { Input } from "@/ui/components/ui/input"; +import { Label } from "@/ui/components/ui/label"; +import { updateProfile } from "@/app/(storefront)/[locale]/[channel]/(main)/account/actions"; +import { resolveAccountActionError } from "@/ui/components/account/account-action-result"; + +type Props = { + firstName: string; + lastName: string; +}; + +export function EditNameForm({ firstName, lastName }: Props) { + const t = useTranslations("account"); + const router = useRouter(); + const [isEditing, setIsEditing] = useState(false); + const [isPending, startTransition] = useTransition(); + const [error, setError] = useState(""); + const [success, setSuccess] = useState(false); + + const handleSubmit = useCallback( + (formData: FormData) => { + setError(""); + setSuccess(false); + + startTransition(async () => { + const result = await updateProfile(formData); + if (!result.success) { + setError(resolveAccountActionError(t, result)); + } else { + setSuccess(true); + setIsEditing(false); + router.refresh(); + } + }); + }, + [router, startTransition, t], + ); + + if (!isEditing) { + return ( +
+
+

{t("fields.name")}

+

+ {firstName || lastName ? `${firstName} ${lastName}`.trim() : t("common.notSet")} +

+
+
+ {success && ( + + {t("common.updated")} + + )} + +
+
+ ); + } + + return ( +
+ {error && ( +

+ {error} +

+ )} +
+
+ + +
+
+ + +
+
+
+ + +
+
+ ); +} diff --git a/apps/web/src/ui/components/account/form-utils.ts b/apps/web/src/ui/components/account/form-utils.ts new file mode 100644 index 0000000..37c7d7a --- /dev/null +++ b/apps/web/src/ui/components/account/form-utils.ts @@ -0,0 +1,21 @@ +/** + * Safely extract a string field from FormData. + * Throws if the field is missing or is a File. + */ +export function getFormString(fd: FormData, key: string): string { + const val = fd.get(key); + if (typeof val !== "string") { + throw new Error(`Missing or invalid form field: ${key}`); + } + return val; +} + +/** + * Extract an optional string field from FormData. + * Returns undefined if empty or missing. + */ +export function getFormStringOptional(fd: FormData, key: string): string | undefined { + const val = fd.get(key); + if (typeof val !== "string" || val === "") return undefined; + return val; +} diff --git a/apps/web/src/ui/components/account/order-row-labels.ts b/apps/web/src/ui/components/account/order-row-labels.ts new file mode 100644 index 0000000..a712bcc --- /dev/null +++ b/apps/web/src/ui/components/account/order-row-labels.ts @@ -0,0 +1,29 @@ +import type { OrderDetailsFragment } from "@/gql/graphql"; +import { getCustomerOrderStatusLabel } from "./order-status-labels"; + +export type OrderRowLabels = { + orderNumber: string; + itemCount: string; + statusLabel: string; +}; + +type OrderStatusLabelKey = "UNFULFILLED" | "UNCONFIRMED" | "PARTIALLY_FULFILLED" | "FULFILLED"; + +type AccountOrderTranslator = ( + key: "orders.orderNumber" | "common.itemCount", + values?: { number?: string; count?: number }, +) => string; + +export function buildOrderRowLabels( + t: AccountOrderTranslator, + tStatus: (key: OrderStatusLabelKey) => string, + order: OrderDetailsFragment, +): OrderRowLabels { + const itemCount = order.lines.reduce((sum, l) => sum + l.quantity, 0); + + return { + orderNumber: t("orders.orderNumber", { number: order.number }), + itemCount: t("common.itemCount", { count: itemCount }), + statusLabel: getCustomerOrderStatusLabel(tStatus, order.status, order.statusDisplay), + }; +} diff --git a/apps/web/src/ui/components/account/order-row.tsx b/apps/web/src/ui/components/account/order-row.tsx new file mode 100644 index 0000000..b1bc158 --- /dev/null +++ b/apps/web/src/ui/components/account/order-row.tsx @@ -0,0 +1,76 @@ +import Image from "next/image"; +import { ArrowRight } from "lucide-react"; +import { type OrderDetailsFragment } from "@/gql/graphql"; +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; +import { formatDate, formatMoney } from "@/lib/utils"; +import { resolveLocaleFromSlug } from "@/config/locale"; +import { orderStatusStyle, defaultStatusStyle } from "./order-status-config"; +import { type OrderRowLabels } from "./order-row-labels"; +import { accountRoutes } from "./routes"; + +type Props = { + order: OrderDetailsFragment; + localeSlug: string; + labels: OrderRowLabels; +}; + +export function OrderRow({ order, localeSlug, labels }: Props) { + const intlLocale = resolveLocaleFromSlug(localeSlug).bcp47; + + const thumbnails = order.lines + .filter((l) => l.variant?.product.thumbnail) + .map((l) => l.variant!.product.thumbnail!) + .slice(0, 3); + + const style = orderStatusStyle[order.status] ?? defaultStatusStyle; + const StatusIcon = style.icon; + + return ( + +
+ {thumbnails.map((thumb, i) => ( +
+ {thumb.alt +
+ ))} + {thumbnails.length === 0 && ( +
+ # +
+ )} +
+ +
+

{labels.orderNumber}

+

+ + {" · "} + {labels.itemCount} +

+
+ +
+ + + {labels.statusLabel} + + + {formatMoney(order.total.gross.amount, order.total.gross.currency, intlLocale)} + + +
+
+ ); +} diff --git a/apps/web/src/ui/components/account/order-status-badge.tsx b/apps/web/src/ui/components/account/order-status-badge.tsx new file mode 100644 index 0000000..e14895e --- /dev/null +++ b/apps/web/src/ui/components/account/order-status-badge.tsx @@ -0,0 +1,29 @@ +import { Circle } from "lucide-react"; +import { getTranslations } from "next-intl/server"; +import { type OrderStatus } from "@/gql/graphql"; +import { orderStatusBadgeStyle } from "./order-status-config"; +import { getCustomerOrderStatusLabel } from "./order-status-labels"; + +type Props = { + status: OrderStatus; + statusDisplay: string; + localeSlug: string; +}; + +export async function OrderStatusBadge({ status, statusDisplay, localeSlug }: Props) { + const tStatus = await getTranslations({ locale: localeSlug, namespace: "account.orderStatus" }); + const config = orderStatusBadgeStyle[status] ?? { + icon: Circle, + badgeClassName: "text-muted-foreground bg-secondary border-border", + }; + const Icon = config.icon; + + return ( + + + {getCustomerOrderStatusLabel(tStatus, status, statusDisplay)} + + ); +} diff --git a/apps/web/src/ui/components/account/order-status-config.ts b/apps/web/src/ui/components/account/order-status-config.ts new file mode 100644 index 0000000..96ec47f --- /dev/null +++ b/apps/web/src/ui/components/account/order-status-config.ts @@ -0,0 +1,60 @@ +import { CheckCircle2, Clock, RotateCcw, XCircle, Circle, PackageCheck, type LucideIcon } from "lucide-react"; +import { OrderStatus } from "@/gql/graphql"; + +type StatusConfig = { icon: LucideIcon; className: string }; + +export const orderStatusStyle: Record = { + [OrderStatus.Fulfilled]: { icon: CheckCircle2, className: "text-green-700" }, + [OrderStatus.PartiallyFulfilled]: { icon: PackageCheck, className: "text-blue-700" }, + [OrderStatus.Unfulfilled]: { icon: Clock, className: "text-amber-600" }, + [OrderStatus.Canceled]: { icon: XCircle, className: "text-red-600" }, + [OrderStatus.Returned]: { icon: RotateCcw, className: "text-muted-foreground" }, + [OrderStatus.PartiallyReturned]: { icon: RotateCcw, className: "text-amber-600" }, + [OrderStatus.Draft]: { icon: Circle, className: "text-muted-foreground" }, + [OrderStatus.Unconfirmed]: { icon: Circle, className: "text-muted-foreground" }, + [OrderStatus.Expired]: { icon: XCircle, className: "text-muted-foreground" }, +}; + +export const orderStatusBadgeStyle: Record = { + [OrderStatus.Fulfilled]: { + ...orderStatusStyle[OrderStatus.Fulfilled], + badgeClassName: "text-green-700 bg-green-50 border-green-200", + }, + [OrderStatus.PartiallyFulfilled]: { + ...orderStatusStyle[OrderStatus.PartiallyFulfilled], + badgeClassName: "text-blue-700 bg-blue-50 border-blue-200", + }, + [OrderStatus.Unfulfilled]: { + ...orderStatusStyle[OrderStatus.Unfulfilled], + badgeClassName: "text-amber-700 bg-amber-50 border-amber-200", + }, + [OrderStatus.Canceled]: { + ...orderStatusStyle[OrderStatus.Canceled], + badgeClassName: "text-red-700 bg-red-50 border-red-200", + }, + [OrderStatus.Returned]: { + ...orderStatusStyle[OrderStatus.Returned], + badgeClassName: "text-muted-foreground bg-secondary border-border", + }, + [OrderStatus.PartiallyReturned]: { + ...orderStatusStyle[OrderStatus.PartiallyReturned], + badgeClassName: "text-amber-700 bg-amber-50 border-amber-200", + }, + [OrderStatus.Draft]: { + ...orderStatusStyle[OrderStatus.Draft], + badgeClassName: "text-muted-foreground bg-secondary border-border", + }, + [OrderStatus.Unconfirmed]: { + ...orderStatusStyle[OrderStatus.Unconfirmed], + badgeClassName: "text-muted-foreground bg-secondary border-border", + }, + [OrderStatus.Expired]: { + ...orderStatusStyle[OrderStatus.Expired], + badgeClassName: "text-muted-foreground bg-secondary border-border", + }, +}; + +export const defaultStatusStyle: StatusConfig = { + icon: Circle, + className: "text-muted-foreground", +}; diff --git a/apps/web/src/ui/components/account/order-status-labels.ts b/apps/web/src/ui/components/account/order-status-labels.ts new file mode 100644 index 0000000..81a12b2 --- /dev/null +++ b/apps/web/src/ui/components/account/order-status-labels.ts @@ -0,0 +1,2 @@ +export { getCustomerOrderStatusLabel } from "@/lib/order-status"; +export type { CustomerOrderStatusKey as OrderStatusLabelKey } from "@/lib/order-status"; diff --git a/apps/web/src/ui/components/account/order-timeline.tsx b/apps/web/src/ui/components/account/order-timeline.tsx new file mode 100644 index 0000000..d97871d --- /dev/null +++ b/apps/web/src/ui/components/account/order-timeline.tsx @@ -0,0 +1,102 @@ +import { type OrderFullDetailsFragment } from "@/gql/graphql"; +import { getTranslations } from "next-intl/server"; +import { resolveLocaleFromSlug } from "@/config/locale"; +import { formatDate } from "@/lib/utils"; + +type Props = { + order: OrderFullDetailsFragment; + localeSlug: string; +}; + +type TimelineEvent = { + label: string; + description: string; + date: Date; + isCurrent: boolean; +}; + +export async function OrderTimeline({ order, localeSlug }: Props) { + const intlLocale = resolveLocaleFromSlug(localeSlug).bcp47; + const t = await getTranslations({ locale: localeSlug, namespace: "account.fulfillment" }); + const tDetail = await getTranslations({ locale: localeSlug, namespace: "account.orderDetail" }); + + const events: TimelineEvent[] = []; + + events.push({ + label: t("orderConfirmed"), + description: t("orderConfirmedDescription"), + date: new Date(order.created), + isCurrent: false, + }); + + for (const fulfillment of order.fulfillments) { + const statusKey = fulfillment.status; + const label = t(statusKey); + const baseDescription = t(`${statusKey}Description`); + const itemCount = fulfillment.lines?.reduce((sum, l) => sum + l.quantity, 0) ?? 0; + const description = + itemCount > 0 + ? t("descriptionWithItems", { description: baseDescription, count: itemCount }) + : baseDescription; + + events.push({ + label, + description, + date: new Date(fulfillment.created), + isCurrent: false, + }); + + if (fulfillment.trackingNumber) { + events.push({ + label: t("trackingUpdated"), + description: t("trackingNumber", { number: fulfillment.trackingNumber }), + date: new Date(fulfillment.created), + isCurrent: false, + }); + } + } + + events.sort((a, b) => b.date.getTime() - a.date.getTime()); + + if (events.length > 0) { + events[0].isCurrent = true; + } + + if (events.length === 0) return null; + + return ( +
+
+

{tDetail("timeline")}

+
+
+
    + {events.map((event, i) => ( +
  1. + +

    + {event.label} +

    + {event.description && ( +

    {event.description}

    + )} +

    + +

    +
  2. + ))} +
+
+
+ ); +} diff --git a/apps/web/src/ui/components/account/recent-orders-section.tsx b/apps/web/src/ui/components/account/recent-orders-section.tsx new file mode 100644 index 0000000..4382f16 --- /dev/null +++ b/apps/web/src/ui/components/account/recent-orders-section.tsx @@ -0,0 +1,68 @@ +import { ChevronRight } from "lucide-react"; +import { getTranslations } from "next-intl/server"; +import { getCurrentUserOrders } from "@/lib/account/get-orders"; +import { hasAuthSession } from "@/lib/auth/has-auth-session"; +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; +import { OrderRow } from "@/ui/components/account/order-row"; +import { buildOrderRowLabels } from "@/ui/components/account/order-row-labels"; +import { accountRoutes } from "@/ui/components/account/routes"; + +export async function RecentOrdersSection({ localeSlug }: { localeSlug: string }) { + if (!(await hasAuthSession())) { + return null; + } + + const t = await getTranslations({ locale: localeSlug, namespace: "account.overview" }); + const tErrors = await getTranslations({ locale: localeSlug, namespace: "account.errors" }); + const tOrder = await getTranslations({ locale: localeSlug, namespace: "account" }); + const tStatus = await getTranslations({ locale: localeSlug, namespace: "account.orderStatus" }); + + const result = await getCurrentUserOrders(localeSlug, 3); + + if (!result.ok) { + return ( +
+

{t("recentOrders")}

+
+ {tErrors("loadRecentOrdersFailed")} +
+
+ ); + } + + const orders = result.data.me?.orders?.edges ?? []; + + return ( +
+
+

{t("recentOrders")}

+ {orders.length > 0 && ( + + {t("viewAll")} + + + )} +
+ + {orders.length === 0 ? ( +
+ {t("noOrdersYet")} +
+ ) : ( +
+ {orders.map(({ node: order }) => ( + + ))} +
+ )} +
+ ); +} diff --git a/apps/web/src/ui/components/account/routes.ts b/apps/web/src/ui/components/account/routes.ts new file mode 100644 index 0000000..e99d4d1 --- /dev/null +++ b/apps/web/src/ui/components/account/routes.ts @@ -0,0 +1,7 @@ +export const accountRoutes = { + overview: "/account", + orders: "/account/orders", + orderDetail: (number: string) => `/account/orders/${number}`, + addresses: "/account/addresses", + settings: "/account/settings", +} as const; diff --git a/apps/web/src/ui/components/account/settings-page.tsx b/apps/web/src/ui/components/account/settings-page.tsx new file mode 100644 index 0000000..d2154d6 --- /dev/null +++ b/apps/web/src/ui/components/account/settings-page.tsx @@ -0,0 +1,65 @@ +"use client"; + +import { useParams } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { Mail, Calendar } from "lucide-react"; +import { resolveLocaleFromSlug } from "@/config/locale"; +import { EditNameForm } from "@/ui/components/account/edit-name-form"; +import { ChangePasswordForm } from "@/ui/components/account/change-password-form"; +import { DeleteAccountSection } from "@/ui/components/account/delete-account-section"; +import { useAccountUser } from "@/ui/components/account/account-context"; + +export function AccountSettingsPage() { + const t = useTranslations("account.settings"); + const tFields = useTranslations("account.fields"); + const params = useParams<{ locale: string }>(); + const user = useAccountUser(); + const intlLocale = resolveLocaleFromSlug(params.locale).bcp47; + + const memberSince = new Date(user.dateJoined).toLocaleDateString(intlLocale, { + month: "long", + year: "numeric", + }); + + return ( +
+
+

{t("title")}

+

{t("subtitle")}

+
+ +
+
+
+
+

{tFields("email")}

+
+ +

{user.email}

+
+
+
+
+ +
+ +
+ +
+ +
+ +
+
+ + {t("memberSince", { date: memberSince })} +
+
+
+ +
+ +
+
+ ); +} diff --git a/apps/web/src/ui/components/analytics-mount.tsx b/apps/web/src/ui/components/analytics-mount.tsx new file mode 100644 index 0000000..49e3913 --- /dev/null +++ b/apps/web/src/ui/components/analytics-mount.tsx @@ -0,0 +1,29 @@ +import { Suspense } from "react"; +import { analyticsConsentMode } from "@/lib/analytics/consent"; +import { gaMeasurementId } from "@/lib/analytics/ga4"; +import { AnalyticsPathnameViews } from "@/ui/components/analytics-pathname-views"; +import { AnalyticsRuntime } from "@/ui/components/analytics-runtime"; +import { GoogleAnalytics } from "@/ui/components/google-analytics"; + +/** + * Root-layout mount: merchant tag when a measurement id is set, plus the + * always-on runtime. Pathname-driven page views sit in Suspense so fallback + * CMS/catalog params (`pages/[slug]`, …) can still prerender. First-touch and + * `window.paperAnalytics` stay outside that hole. + * https://nextjs.org/docs/messages/blocking-prerender-client-hook + */ +export function AnalyticsMount() { + const measurementId = gaMeasurementId(); + + return ( + <> + {measurementId ? ( + + ) : null} + + + + + + ); +} diff --git a/apps/web/src/ui/components/analytics-pathname-views.tsx b/apps/web/src/ui/components/analytics-pathname-views.tsx new file mode 100644 index 0000000..bf0e411 --- /dev/null +++ b/apps/web/src/ui/components/analytics-pathname-views.tsx @@ -0,0 +1,21 @@ +"use client"; + +import { useEffect } from "react"; +import { usePathname } from "next/navigation"; +import { sendRedactedPageView } from "@/lib/analytics/browser"; + +/** + * Redacted merchant-tag page views on pathname change (not `?step=`). + * Must stay inside `` — `usePathname` suspends on fallback params. + * https://nextjs.org/docs/messages/blocking-prerender-client-hook + */ +export function AnalyticsPathnameViews() { + const pathname = usePathname(); + + useEffect(() => { + if (!pathname) return; + sendRedactedPageView(); + }, [pathname]); + + return null; +} diff --git a/apps/web/src/ui/components/analytics-runtime.tsx b/apps/web/src/ui/components/analytics-runtime.tsx new file mode 100644 index 0000000..dd05381 --- /dev/null +++ b/apps/web/src/ui/components/analytics-runtime.tsx @@ -0,0 +1,28 @@ +"use client"; + +import { useEffect } from "react"; +import { + applyCampaignFromSnapshot, + applyConsentToGtag, + bindPaperAnalyticsApi, + persistFirstTouch, +} from "@/lib/analytics/browser"; + +if (typeof window !== "undefined") { + bindPaperAnalyticsApi(); +} + +/** + * Consent API + first-touch. No navigation hooks — stays in the static shell + * so a fork banner can call `window.paperAnalytics` before pathname resolves. + */ +export function AnalyticsRuntime() { + useEffect(() => { + bindPaperAnalyticsApi(); + persistFirstTouch(); + applyConsentToGtag(); + applyCampaignFromSnapshot(); + }, []); + + return null; +} diff --git a/apps/web/src/ui/components/auth/auth-form-section.tsx b/apps/web/src/ui/components/auth/auth-form-section.tsx new file mode 100644 index 0000000..62079de --- /dev/null +++ b/apps/web/src/ui/components/auth/auth-form-section.tsx @@ -0,0 +1,6 @@ +import type { ReactNode } from "react"; + +/** Shared page shell for standalone auth forms (login, signup, signed-out /account). */ +export function AuthFormSection({ children }: { children: ReactNode }) { + return
{children}
; +} diff --git a/apps/web/src/ui/components/auth/confirm-account-mode.tsx b/apps/web/src/ui/components/auth/confirm-account-mode.tsx new file mode 100644 index 0000000..0759d11 --- /dev/null +++ b/apps/web/src/ui/components/auth/confirm-account-mode.tsx @@ -0,0 +1,281 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import Link from "next/link"; +import { useTranslations } from "next-intl"; +import { CheckCircle, Eye, EyeOff, Lock, Mail } from "lucide-react"; +import { confirmAccountWithBffDeduped } from "@/lib/auth/confirm-account-client"; +import { buildStorefrontPath } from "@/lib/storefront-path"; +import { Button, buttonClassName } from "@/ui/components/ui/button"; +import { Input } from "@/ui/components/ui/input"; +import { Label } from "@/ui/components/ui/label"; + +type ConfirmState = "form" | "success" | "error"; + +type ConfirmErrorKey = + | "invalidConfirmToken" + | "confirmFailed" + | "passwordRequired" + | "invalidCredentials" + | "resetLinkFailed" + | "generic"; + +type Props = { + email: string; + token: string; + locale: string; + channel: string; + /** Called after a successful confirmation (e.g. refresh checkout session). */ + onConfirmed?: () => void | Promise; + signInHref?: string; + continueShoppingHref?: string; +}; + +export function ConfirmAccountMode({ + email, + token, + locale, + channel, + onConfirmed, + signInHref, + continueShoppingHref, +}: Props) { + const t = useTranslations("account"); + const [state, setState] = useState("form"); + const [password, setPassword] = useState(""); + const [showPassword, setShowPassword] = useState(false); + const [isSubmitting, setIsSubmitting] = useState(false); + const [isResettingPassword, setIsResettingPassword] = useState(false); + const [resetEmailSent, setResetEmailSent] = useState(false); + const [resetMessage, setResetMessage] = useState(""); + const [errorKey, setErrorKey] = useState(null); + const onConfirmedRef = useRef(onConfirmed); + + const loginHref = signInHref ?? buildStorefrontPath(locale, channel, "/login"); + const storeHref = continueShoppingHref ?? buildStorefrontPath(locale, channel); + + useEffect(() => { + onConfirmedRef.current = onConfirmed; + }, [onConfirmed]); + + async function handleConfirm(event: React.FormEvent) { + event.preventDefault(); + setErrorKey(null); + + if (!password) { + setErrorKey("passwordRequired"); + return; + } + + setIsSubmitting(true); + + try { + const result = await confirmAccountWithBffDeduped(email, token, password); + + if (result.errors?.length) { + const err = result.errors[0]; + const message = err.message?.toLowerCase() ?? ""; + const code = err.code ?? ""; + + if (code === "INVALID_TOKEN" || message.includes("token")) { + setErrorKey("invalidConfirmToken"); + setState("error"); + return; + } + + if (code === "INVALID_CREDENTIALS" || code === "INVALID_PASSWORD" || message.includes("password")) { + setErrorKey("invalidCredentials"); + return; + } + + setErrorKey("confirmFailed"); + return; + } + + if (result.success) { + setState("success"); + await onConfirmedRef.current?.(); + return; + } + + setErrorKey("confirmFailed"); + setState("error"); + } catch { + setErrorKey("generic"); + } finally { + setIsSubmitting(false); + } + } + + async function handleForgotPassword() { + setErrorKey(null); + setResetMessage(""); + setIsResettingPassword(true); + + try { + const response = await fetch("/api/auth/reset-password", { + method: "POST", + headers: { "Content-Type": "application/json" }, + credentials: "same-origin", + body: JSON.stringify({ + email, + channel, + redirectUrl: new URL(loginHref, window.location.origin).toString(), + }), + }); + + const data = (await response.json()) as { errors?: Array<{ message: string }>; success?: boolean }; + + if (!response.ok || data.errors?.length) { + setErrorKey("resetLinkFailed"); + return; + } + + setResetEmailSent(true); + setResetMessage(t("login.resetSent", { email })); + } catch { + setErrorKey("generic"); + } finally { + setIsResettingPassword(false); + } + } + + const errorMessage = errorKey ? t(`errors.${errorKey}`) : ""; + + if (state === "success") { + return ( +
+
+
+
+ +
+

{t("confirm.successTitle")}

+

{t("confirm.successBody", { email })}

+ + {t("confirm.signIn")} + + + {t("confirm.continueShopping")} + +
+
+
+ ); + } + + if (state === "error") { + return ( +
+
+
+
+ +
+

{t("confirm.errorTitle")}

+

+ {errorMessage} +

+ + + {t("confirm.continueShopping")} + +
+
+
+ ); + } + + return ( +
+
+
+

{t("confirm.title")}

+

{t("confirm.body", { email })}

+
+ +
+ {errorKey && ( +
+ {errorMessage} +
+ )} + + {resetMessage && ( +
+ {resetMessage} +
+ )} + +
+ +
+ + setPassword(event.target.value)} + className="h-12 pl-10 pr-10" + required + /> + +
+
+ +
+ +
+ + +
+
+
+ ); +} diff --git a/apps/web/src/ui/components/auth/login-mode.tsx b/apps/web/src/ui/components/auth/login-mode.tsx new file mode 100644 index 0000000..d9409b2 --- /dev/null +++ b/apps/web/src/ui/components/auth/login-mode.tsx @@ -0,0 +1,216 @@ +"use client"; + +import { useState } from "react"; +import Link from "next/link"; +import { useParams, useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { Mail, Lock, Eye, EyeOff } from "lucide-react"; +import { loginWithBff, syncAuthSurfacesAfterSignIn } from "@/lib/auth"; +import { buildStorefrontPath } from "@/lib/storefront-path"; +import { Button } from "@/ui/components/ui/button"; +import { Input } from "@/ui/components/ui/input"; +import { Label } from "@/ui/components/ui/label"; + +const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + +export function LoginMode() { + const t = useTranslations("account"); + const params = useParams<{ locale: string; channel: string }>(); + const router = useRouter(); + + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [showPassword, setShowPassword] = useState(false); + const [isSubmitting, setIsSubmitting] = useState(false); + const [error, setError] = useState(""); + const [resetMessage, setResetMessage] = useState(""); + const [resetEmailSent, setResetEmailSent] = useState(false); + + const handleLogin = async (e: React.FormEvent) => { + e.preventDefault(); + setError(""); + + if (!email || !EMAIL_RE.test(email)) { + setError(t("errors.invalidEmail")); + return; + } + + if (!password) { + setError(t("errors.passwordRequired")); + return; + } + + setIsSubmitting(true); + + try { + const result = await loginWithBff(email, password); + + if (result.errors?.length) { + const err = result.errors[0]; + const isInvalidCredentials = + err.code === "INVALID_CREDENTIALS" || + err.code === "INVALID_PASSWORD" || + err.message?.toLowerCase().includes("invalid") || + err.message?.toLowerCase().includes("credentials"); + const isRateLimited = err.code === "RATE_LIMITED"; + setError( + isRateLimited + ? t("errors.rateLimited") + : isInvalidCredentials + ? t("errors.invalidCredentials") + : t("errors.signInFailed"), + ); + return; + } + + if (result.ok) { + await syncAuthSurfacesAfterSignIn(params.channel, router, { + redirectTo: buildStorefrontPath(params.locale, params.channel), + }); + return; + } + + setError(t("errors.signInFailed")); + } catch { + setError(t("errors.generic")); + } finally { + setIsSubmitting(false); + } + }; + + const handleForgotPassword = async () => { + setError(""); + setResetMessage(""); + + if (!email || !EMAIL_RE.test(email)) { + setError(t("errors.invalidEmailFirst")); + return; + } + + setIsSubmitting(true); + + try { + const loginPath = buildStorefrontPath(params.locale, params.channel, "/login"); + const response = await fetch("/api/auth/reset-password", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + email, + channel: params.channel, + redirectUrl: `${window.location.origin}${loginPath}`, + }), + }); + + const data = (await response.json()) as { + errors?: Array<{ message: string }>; + success?: boolean; + }; + + if (data.errors?.length) { + setError(t("errors.resetLinkFailed")); + return; + } + + setResetEmailSent(true); + setResetMessage(t("login.resetSent", { email })); + } catch { + setError(t("errors.generic")); + } finally { + setIsSubmitting(false); + } + }; + + return ( +
+
+
+

{t("login.title")}

+

+ {t("login.noAccount")}{" "} + + {t("login.signUp")} + +

+
+ +
+ {error && ( +
+ {error} +
+ )} + + {resetMessage && ( +
+ {resetMessage} +
+ )} + +
+ +
+ + setEmail(e.target.value)} + className="h-12 pl-10" + required + /> +
+
+ +
+ +
+ + setPassword(e.target.value)} + className="h-12 pl-10 pr-10" + required + /> + +
+
+ +
+ +
+ + +
+
+
+ ); +} diff --git a/apps/web/src/ui/components/auth/set-password-mode.tsx b/apps/web/src/ui/components/auth/set-password-mode.tsx new file mode 100644 index 0000000..04a9c54 --- /dev/null +++ b/apps/web/src/ui/components/auth/set-password-mode.tsx @@ -0,0 +1,182 @@ +"use client"; + +import { useState } from "react"; +import Link from "next/link"; +import { useParams, useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { Lock, Eye, EyeOff, CheckCircle } from "lucide-react"; +import { setPasswordWithBff, syncAuthSurfacesAfterSignIn } from "@/lib/auth"; +import { buildStorefrontPath } from "@/lib/storefront-path"; +import { Button } from "@/ui/components/ui/button"; +import { Input } from "@/ui/components/ui/input"; +import { Label } from "@/ui/components/ui/label"; + +type Props = { + email: string; + token: string; +}; + +export function SetPasswordMode({ email, token }: Props) { + const t = useTranslations("account"); + const router = useRouter(); + const params = useParams<{ locale: string; channel: string }>(); + + const [password, setPassword] = useState(""); + const [confirmPassword, setConfirmPassword] = useState(""); + const [showPassword, setShowPassword] = useState(false); + const [showConfirmPassword, setShowConfirmPassword] = useState(false); + const [isSubmitting, setIsSubmitting] = useState(false); + const [error, setError] = useState(""); + const [success, setSuccess] = useState(false); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setError(""); + + if (!password) { + setError(t("errors.newPasswordRequired")); + return; + } + + if (password.length < 8) { + setError(t("errors.passwordMinLength")); + return; + } + + if (password !== confirmPassword) { + setError(t("errors.passwordsMismatch")); + return; + } + + setIsSubmitting(true); + + try { + const data = await setPasswordWithBff(email, token, password); + + if (data.errors?.length) { + const err = data.errors[0]; + if (err.code === "INVALID_TOKEN" || err.message?.includes("token")) { + setError(t("errors.invalidResetToken")); + } else { + setError(t("errors.setPasswordFailed")); + } + return; + } + + if (data.success) { + setSuccess(true); + await syncAuthSurfacesAfterSignIn(params.channel, router, { skipRefresh: true }); + setTimeout(() => { + window.location.assign(buildStorefrontPath(params.locale, params.channel)); + }, 2000); + } + } catch { + setError(t("errors.generic")); + } finally { + setIsSubmitting(false); + } + }; + + if (success) { + return ( +
+
+
+
+ +
+

{t("setPassword.successTitle")}

+

{t("setPassword.successBody")}

+

{t("setPassword.redirecting")}

+
+
+
+ ); + } + + return ( +
+
+
+

{t("setPassword.title")}

+

{t("setPassword.subtitle", { email })}

+
+ +
+ {error && ( +
+ {error} +
+ )} + +
+ +
+ + setPassword(e.target.value)} + className="h-12 pl-10 pr-10" + required + /> + +
+
+ +
+ +
+ + setConfirmPassword(e.target.value)} + className="h-12 pl-10 pr-10" + required + /> + +
+
+ + + +
+ + {t("setPassword.backToSignIn")} + +
+
+
+
+ ); +} diff --git a/apps/web/src/ui/components/breadcrumbs.tsx b/apps/web/src/ui/components/breadcrumbs.tsx new file mode 100644 index 0000000..63b1330 --- /dev/null +++ b/apps/web/src/ui/components/breadcrumbs.tsx @@ -0,0 +1,68 @@ +import Link from "next/link"; +import { ChevronRight } from "lucide-react"; +import { cn } from "@/lib/utils"; + +export interface BreadcrumbItem { + label: string; + href?: string; +} + +export type BreadcrumbsSurface = "default" | "pill"; + +export interface BreadcrumbsProps { + items: BreadcrumbItem[]; + ariaLabel: string; + /** `pill` places crumbs on a compact surface for busy backgrounds (default: white). */ + surface?: BreadcrumbsSurface; + className?: string; +} + +/** + * Functional chrome breadcrumbs — code-owned i18n labels (ADR 0002). + * Use `surface="pill"` on photo heroes; `default` on solid page backgrounds. + */ +export function Breadcrumbs({ items, ariaLabel, surface = "default", className }: BreadcrumbsProps) { + const isPill = surface === "pill"; + const crumbClass = isPill ? "text-foreground" : "text-muted-foreground"; + const currentClass = "font-medium text-foreground"; + const linkClass = isPill + ? "text-foreground transition-opacity hover:opacity-70" + : "text-muted-foreground transition-colors hover:text-foreground"; + + return ( + + ); +} diff --git a/apps/web/src/ui/components/cart/cart-button.tsx b/apps/web/src/ui/components/cart/cart-button.tsx new file mode 100644 index 0000000..00693ba --- /dev/null +++ b/apps/web/src/ui/components/cart/cart-button.tsx @@ -0,0 +1,35 @@ +"use client"; + +import { ShoppingBagIcon } from "lucide-react"; +import { useTranslations } from "next-intl"; +import { useCart } from "./cart-context"; + +interface CartButtonProps { + itemCount: number; +} + +export function CartButton({ itemCount }: CartButtonProps) { + const { openCart } = useCart(); + const t = useTranslations("nav"); + + return ( + + ); +} diff --git a/apps/web/src/ui/components/cart/cart-context.tsx b/apps/web/src/ui/components/cart/cart-context.tsx new file mode 100644 index 0000000..e511c32 --- /dev/null +++ b/apps/web/src/ui/components/cart/cart-context.tsx @@ -0,0 +1,41 @@ +"use client"; + +import { createContext, useContext, useState, useCallback, type ReactNode } from "react"; + +interface CartContextType { + isOpen: boolean; + openCart: () => void; + closeCart: () => void; + toggleCart: () => void; +} + +const CartContext = createContext(undefined); + +export function CartProvider({ children }: { children: ReactNode }) { + const [isOpen, setIsOpen] = useState(false); + + const openCart = useCallback(() => setIsOpen(true), []); + const closeCart = useCallback(() => setIsOpen(false), []); + const toggleCart = useCallback(() => setIsOpen((prev) => !prev), []); + + return ( + + {children} + + ); +} + +export function useCart() { + const context = useContext(CartContext); + if (!context) { + throw new Error("useCart must be used within a CartProvider"); + } + return context; +} diff --git a/apps/web/src/ui/components/cart/cart-drawer-wrapper.tsx b/apps/web/src/ui/components/cart/cart-drawer-wrapper.tsx new file mode 100644 index 0000000..f98ceea --- /dev/null +++ b/apps/web/src/ui/components/cart/cart-drawer-wrapper.tsx @@ -0,0 +1,34 @@ +import { cookies } from "next/headers"; +import { io } from "next/cache"; +import { deleteCartLine, updateCartLineQuantity } from "@/app/actions"; +import type { CartContent, StorefrontPolicies } from "@/lib/content"; +import * as Checkout from "@/lib/checkout"; +import { CartDrawer } from "./cart-drawer"; + +interface CartDrawerWrapperProps { + channel: string; + localeSlug: string; + cart: CartContent; + policies: StorefrontPolicies; +} + +export async function CartDrawerWrapper({ channel, localeSlug, cart, policies }: CartDrawerWrapperProps) { + await cookies(); + await io(); + + const checkoutId = await Checkout.getIdFromCookies(channel); + const checkout = checkoutId ? await Checkout.find(checkoutId, localeSlug) : null; + + return ( + + ); +} diff --git a/apps/web/src/ui/components/cart/cart-drawer.tsx b/apps/web/src/ui/components/cart/cart-drawer.tsx new file mode 100644 index 0000000..bbeaac2 --- /dev/null +++ b/apps/web/src/ui/components/cart/cart-drawer.tsx @@ -0,0 +1,443 @@ +"use client"; + +import { useState } from "react"; +import { useTranslations } from "next-intl"; +import Image from "next/image"; +import Link from "next/link"; +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; +import { Minus, Plus, Trash2, ShoppingBag, ArrowRight, Truck, RotateCcw } from "lucide-react"; +import { Button, buttonClassName } from "@/ui/components/ui/button"; +import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetCloseButton } from "@/ui/components/ui/sheet"; +import { useCart } from "./cart-context"; +import type { DeleteCartLine, UpdateCartLineQuantity } from "./cart-mutations"; +import { bumpChromeVersion } from "@/lib/chrome-sync"; +import { cn } from "@/lib/utils"; +import { formatMoney } from "@/lib/utils"; +import { localeConfig, resolveLocaleFromSlug } from "@/config/locale"; +import { hasDiscount } from "@/lib/pricing"; +import { CART_THUMBNAIL_IMAGE_SIZES, PRODUCT_IMAGE_QUALITY } from "@/lib/images"; +import { buildCheckoutPath } from "@paper/session-bridge"; +import type { CartContent, StorefrontPolicies } from "@/lib/content"; +import { formatContentLabel } from "@/lib/content/format-label"; + +interface CartLine { + id: string; + quantity: number; + totalPrice: { + gross: { + amount: number; + currency: string; + }; + }; + variant: { + id: string; + name: string; + product: { + id: string; + name: string; + slug: string; + thumbnail?: { + url: string; + alt?: string | null; + } | null; + }; + pricing?: { + price?: { + gross: { + amount: number; + currency: string; + }; + } | null; + priceUndiscounted?: { + gross: { + amount: number; + currency: string; + }; + } | null; + } | null; + attributes?: Array<{ + attribute: { + name?: string | null; + slug?: string | null; + }; + values: Array<{ + name?: string | null; + value?: string | null; + }>; + }>; + }; +} + +import { getColorHex, isColorAttribute } from "@/lib/colors"; + +interface VariantAttribute { + name: string; + value: string; + colorHex?: string; + isColor: boolean; +} + +function getVariantDetails(variant: CartLine["variant"]): VariantAttribute[] { + const attributes = variant.attributes || []; + const result: VariantAttribute[] = []; + + for (const attr of attributes) { + const slug = attr.attribute.slug || ""; + const name = attr.attribute.name || slug; + const value = attr.values[0]; + + if (!value?.name) continue; + + const isColor = isColorAttribute(slug); + + result.push({ + name, + value: value.name, + colorHex: isColor ? getColorHex(value) : undefined, + isColor, + }); + } + + // Sort: color first, then others + return result.sort((a, b) => { + if (a.isColor && !b.isColor) return -1; + if (!a.isColor && b.isColor) return 1; + return 0; + }); +} + +interface CartDrawerProps { + checkoutId: string | null; + lines: CartLine[]; + totalPrice: { + gross: { + amount: number; + currency: string; + }; + } | null; + localeSlug: string; + cart: CartContent; + policies: StorefrontPolicies; + deleteCartLine: DeleteCartLine; + updateCartLineQuantity: UpdateCartLineQuantity; +} + +export function CartDrawer({ + checkoutId, + lines, + totalPrice, + localeSlug, + cart, + policies, + deleteCartLine, + updateCartLineQuantity, +}: CartDrawerProps) { + const { isOpen, closeCart } = useCart(); + const [isCartBusy, setIsCartBusy] = useState(false); + // Functional drawer chrome (totals, buttons, a11y labels) — code-owned i18n (ADR 0002). + const t = useTranslations("cart.drawer"); + + const itemCount = lines.reduce((sum, line) => sum + line.quantity, 0); + const subtotal = totalPrice?.gross.amount ?? 0; + const currency = totalPrice?.gross.currency ?? localeConfig.fallbackCurrency; + const intlLocale = resolveLocaleFromSlug(localeSlug).bcp47; + + const runCartMutation = (mutation: () => Promise) => { + setIsCartBusy(true); + void mutation().finally(() => { + // This tab re-renders via `refresh()` inside the action; other tabs + // sync their cart chrome on next focus. + bumpChromeVersion(); + setIsCartBusy(false); + }); + }; + + const handleRemove = (lineId: string) => { + if (!checkoutId) return; + runCartMutation(() => deleteCartLine(checkoutId, lineId)); + }; + + const handleUpdateQuantity = (lineId: string, newQuantity: number) => { + if (!checkoutId || newQuantity < 1) return; + runCartMutation(() => updateCartLineQuantity(checkoutId, lineId, newQuantity)); + }; + + const checkoutHref = checkoutId + ? buildCheckoutPath({ checkoutId, step: "contact", browseLocale: localeSlug }) + : "/checkout"; + const { drawer } = cart; + + // Single source of truth: the same threshold drives the progress bar, the summary + // shipping row, and the trust signal — and matches the announcement bar copy. + const freeShippingThreshold = policies.shipping.freeShippingThreshold; + const freeShippingEnabled = freeShippingThreshold != null; + const qualifiesForFreeShipping = freeShippingEnabled && subtotal >= freeShippingThreshold; + const progressToFreeShipping = + freeShippingEnabled && freeShippingThreshold > 0 + ? Math.min((subtotal / freeShippingThreshold) * 100, 100) + : 100; + const amountToFreeShipping = freeShippingEnabled ? Math.max(freeShippingThreshold - subtotal, 0) : 0; + const returnsLabel = formatContentLabel(cart.trust.returnsLabel, { + returnsWindowDays: policies.returns.windowDays, + }); + + return ( + !open && closeCart()}> + + {/* Header */} + +
+ + {drawer.title} + ({t("itemCount", { count: itemCount })}) +
+ +
+ + {/* Free Shipping Progress */} + {lines.length > 0 && freeShippingEnabled && ( +
+
+ + {amountToFreeShipping > 0 ? ( + + {formatContentLabel(drawer.addForFreeShipping, { + amount: formatMoney(amountToFreeShipping, currency, intlLocale), + })} + + ) : ( + {drawer.freeShippingQualified} + )} +
+
+
+
+
+ )} + + {/* Cart Items */} +
+ {lines.length === 0 ? ( +
+
+ +
+

{cart.empty.title}

+

{cart.empty.body}

+ + {cart.empty.ctaLabel} + +
+ ) : ( +
    + {lines.map((line) => { + const variantAttributes = getVariantDetails(line.variant); + const isDiscounted = hasDiscount( + line.variant.pricing?.price?.gross.amount, + line.variant.pricing?.priceUndiscounted?.gross.amount, + ); + + return ( +
  • +
    + {/* Product Image */} + + {line.variant.product.thumbnail?.url && ( + {line.variant.product.thumbnail.alt + )} + + + {/* Product Details */} +
    +
    +
    + + {line.variant.product.name} + + {/* Variant attributes: Color swatch + values separated by | */} + {variantAttributes.length > 0 ? ( +
    + {variantAttributes.map((attr, index) => ( + + {index > 0 && |} + {attr.colorHex && ( + + )} + {/* Show "Size X" for size attributes, just value for colors */} + {attr.isColor ? attr.value : `${attr.name} ${attr.value}`} + + ))} +
    + ) : line.variant.name && line.variant.name !== line.variant.id ? ( +

    {line.variant.name}

    + ) : null} +
    + +
    + + {/* Quantity & Price */} +
    + {/* Quantity Selector */} +
    + + {line.quantity} + +
    + + {/* Price */} +
    + + {formatMoney( + line.totalPrice.gross.amount, + line.totalPrice.gross.currency, + intlLocale, + )} + + {isDiscounted && line.variant.pricing?.priceUndiscounted && ( + + {formatMoney( + line.variant.pricing.priceUndiscounted.gross.amount * line.quantity, + line.variant.pricing.priceUndiscounted.gross.currency, + intlLocale, + )} + + )} +
    +
    +
    +
    +
  • + ); + })} +
+ )} +
+ + {/* Footer */} + {lines.length > 0 && ( +
+ {/* Order Summary */} +
+
+ {t("subtotal")} + {formatMoney(subtotal, currency, intlLocale)} +
+
+ {t("shipping")} + {qualifiesForFreeShipping ? t("shippingFree") : t("shippingCalculated")} +
+
+ {t("total")} + {formatMoney(subtotal, currency, intlLocale)} +
+
+ + {/* Actions */} +
+ { + if (isCartBusy) { + event.preventDefault(); + return; + } + closeCart(); + }} + aria-disabled={isCartBusy} + className={buttonClassName({ + asLink: true, + size: "lg", + className: "group h-12 w-full", + })} + > + {t("checkout")} + + + + {t("continueShopping")} + +
+ + {/* Trust Signals */} +
+ {freeShippingEnabled && ( + + + {cart.trust.freeShippingPrefix} {formatMoney(freeShippingThreshold, currency, intlLocale)} + + )} + + + {returnsLabel} + +
+
+ )} + + + ); +} diff --git a/apps/web/src/ui/components/cart/cart-mutations.ts b/apps/web/src/ui/components/cart/cart-mutations.ts new file mode 100644 index 0000000..43bbf08 --- /dev/null +++ b/apps/web/src/ui/components/cart/cart-mutations.ts @@ -0,0 +1,3 @@ +export type DeleteCartLine = (checkoutId: string, lineId: string) => Promise; + +export type UpdateCartLineQuantity = (checkoutId: string, lineId: string, quantity: number) => Promise; diff --git a/apps/web/src/ui/components/cart/index.ts b/apps/web/src/ui/components/cart/index.ts new file mode 100644 index 0000000..9b74f9f --- /dev/null +++ b/apps/web/src/ui/components/cart/index.ts @@ -0,0 +1,4 @@ +export { CartProvider, useCart } from "./cart-context"; +export { CartDrawer } from "./cart-drawer"; +export { CartDrawerWrapper } from "./cart-drawer-wrapper"; +export { CartButton } from "./cart-button"; diff --git a/apps/web/src/ui/components/channel-select.tsx b/apps/web/src/ui/components/channel-select.tsx new file mode 100644 index 0000000..59db5c5 --- /dev/null +++ b/apps/web/src/ui/components/channel-select.tsx @@ -0,0 +1,41 @@ +"use client"; + +import { useStorefrontRegionNavigation } from "@/hooks/use-storefront-region-navigation"; +import type { ChannelSelectOption } from "@/config/channels"; +import { cn } from "@/lib/utils"; + +export const ChannelSelect = ({ + channels, + variant = "default", + className, +}: { + channels: ChannelSelectOption[]; + variant?: "default" | "inverted"; + className?: string; +}) => { + const { channel, navigateToChannel } = useStorefrontRegionNavigation(); + + return ( + + ); +}; diff --git a/apps/web/src/ui/components/copyright-text.tsx b/apps/web/src/ui/components/copyright-text.tsx new file mode 100644 index 0000000..a34a476 --- /dev/null +++ b/apps/web/src/ui/components/copyright-text.tsx @@ -0,0 +1,18 @@ +"use client"; + +import { use } from "react"; +import { io } from "next/cache"; +import { getCopyrightText } from "@/config/brand"; + +/** + * Copyright line with the current year. Render it inside ``. + * + * `new Date()` during a prerender is sync IO. Under Cache Components it aborts the + * prerender mid-tree, and the request-time resume of the surrounding boundary then + * fails ("Couldn't find all resumable slots") and falls back to client rendering. + * `io()` turns the read into a small dynamic hole instead. + */ +export function CopyrightText() { + use(io()); + return <>{getCopyrightText()}; +} diff --git a/apps/web/src/ui/components/dev/graphql-monitor.tsx b/apps/web/src/ui/components/dev/graphql-monitor.tsx new file mode 100644 index 0000000..d3990f5 --- /dev/null +++ b/apps/web/src/ui/components/dev/graphql-monitor.tsx @@ -0,0 +1,683 @@ +"use client"; + +import { useEffect, useState, useRef, useCallback } from "react"; +import { Activity, AlertTriangle, X, ChevronDown, ChevronUp } from "lucide-react"; + +/** + * GraphQL Request Monitor for Development + * + * Shows a floating widget that tracks: + * - Total request count + * - Requests per second (detects loops!) + * - Errors + * - Most frequent operations + * + * Alerts when request rate exceeds threshold (likely infinite loop). + */ + +type RequestSource = "storefront" | "checkout"; + +interface RequestLog { + operation: string; + timestamp: number; + duration?: number; + error?: string; + errorCode?: string; + variables?: Record; + source?: RequestSource; + isRetry?: boolean; + retryCount?: number; +} + +interface ErrorLog { + operation: string; + error: string; + errorCode?: string; + timestamp: number; + variables?: Record; +} + +interface OperationStats { + count: number; + errors: number; + retries: number; + avgDuration: number; + lastSeen: number; +} + +interface SourceStats { + total: number; + errors: number; +} + +// Global store for request logs (persists across re-renders) +const requestLogs: RequestLog[] = []; +const errorLogs: ErrorLog[] = []; +const operationStats = new Map(); +const sourceStats: Record = { + storefront: { total: 0, errors: 0 }, + checkout: { total: 0, errors: 0 }, +}; +let totalRequests = 0; +let totalErrors = 0; +let totalRetries = 0; + +// Track recent failed operations for retry detection +const recentFailedOps = new Map(); +const RETRY_WINDOW_MS = 5000; // Consider it a retry if same operation fails within 5s + +// Thresholds for alerts +const RATE_ALERT_THRESHOLD = 5; // requests/second +const WINDOW_SIZE_MS = 5000; // 5 second window for rate calculation + +// Dev testing: simulate random failures +let simulateFailureRate = 0; // 0 = disabled, 0.5 = 50% failure rate +export function setSimulateFailureRate(rate: number) { + simulateFailureRate = Math.max(0, Math.min(1, rate)); +} +export function getSimulateFailureRate() { + return simulateFailureRate; +} + +/** + * Call this from your GraphQL client to log requests. + * Works with any client (urql, Apollo, fetch). + */ +export function logGraphQLRequest(log: RequestLog) { + if (process.env.NODE_ENV !== "development") return; + + // Detect if this is a retry (same operation failed recently) + const recentFailed = recentFailedOps.get(log.operation); + const now = log.timestamp; + let isRetry = false; + let retryCount = 0; + + if (recentFailed && now - recentFailed.timestamp < RETRY_WINDOW_MS) { + isRetry = true; + retryCount = recentFailed.count + 1; + totalRetries++; + } + + // Update recent failed ops tracking + if (log.error) { + recentFailedOps.set(log.operation, { + timestamp: now, + count: isRetry ? retryCount : 1, + }); + } else { + // Success clears the retry tracking for this operation + recentFailedOps.delete(log.operation); + } + + // Add retry info to log + const enrichedLog: RequestLog = { + ...log, + isRetry, + retryCount: isRetry ? retryCount : undefined, + }; + + requestLogs.push(enrichedLog); + totalRequests++; + + if (log.error) { + totalErrors++; + // Track error details + errorLogs.push({ + operation: log.operation, + error: log.error, + errorCode: log.errorCode, + timestamp: log.timestamp, + variables: log.variables, + }); + // Keep only last 50 errors + if (errorLogs.length > 50) { + errorLogs.shift(); + } + } + + // Track by source + if (log.source) { + sourceStats[log.source].total++; + if (log.error) sourceStats[log.source].errors++; + } + + // Keep only last 1000 logs + if (requestLogs.length > 1000) { + requestLogs.shift(); + } + + // Update operation stats + const stats = operationStats.get(log.operation) || { + count: 0, + errors: 0, + retries: 0, + avgDuration: 0, + lastSeen: 0, + }; + stats.count++; + if (log.error) stats.errors++; + if (isRetry) stats.retries++; + if (log.duration) { + stats.avgDuration = (stats.avgDuration * (stats.count - 1) + log.duration) / stats.count; + } + stats.lastSeen = log.timestamp; + operationStats.set(log.operation, stats); + + // Dispatch custom event for React components to listen to + window.dispatchEvent(new CustomEvent("graphql-request", { detail: enrichedLog })); +} + +type FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise; + +/** + * Helper to wrap fetch for automatic logging + * @param originalFetch - The fetch function to wrap + * @param source - Tag requests with their source ("storefront" or "checkout") + */ +export function createMonitoredFetch(originalFetch: FetchFn, source?: RequestSource): FetchFn { + return async (input, init) => { + const body = init?.body; + let operation = "unknown"; + let variables: Record | undefined; + + // Parse GraphQL operation name from body + if (typeof body === "string") { + try { + const parsed = JSON.parse(body) as { query?: string; variables?: Record }; + const match = parsed.query?.match(/(?:query|mutation)\s+(\w+)/); + operation = match?.[1] || "anonymous"; + variables = parsed.variables; + } catch { + // Not JSON, ignore + } + } + + // Dev testing: simulate random failures + if (simulateFailureRate > 0 && Math.random() < simulateFailureRate) { + const error = "Simulated network failure (dev testing)"; + logGraphQLRequest({ + operation, + timestamp: Date.now(), + duration: 50, + error, + variables, + source, + }); + throw new Error(error); + } + + const start = performance.now(); + let error: string | undefined; + let errorCode: string | undefined; + let wasAborted = false; + + try { + const response = await originalFetch(input, init); + + // Check for GraphQL errors in response + if (response.headers.get("content-type")?.includes("application/json")) { + const clone = response.clone(); + try { + const json = (await clone.json()) as { + errors?: Array<{ message: string }>; + data?: Record }>; + }; + // Top-level GraphQL errors + if (json.errors?.length) { + error = json.errors[0].message; + } + // Saleor mutation errors (in data.mutationName.errors) + if (json.data) { + for (const val of Object.values(json.data)) { + if (val?.errors?.length) { + error = val.errors[0].message || error; + errorCode = val.errors[0].code; + break; + } + } + } + } catch { + // Ignore parse errors + } + } + + return response; + } catch (e) { + // Don't log abort signals as errors - these are expected in React Strict Mode + // or when components unmount during fetch + const isAbort = + (e instanceof DOMException && e.name === "AbortError") || + (e instanceof Error && e.message.includes("abort")); + + if (isAbort) { + wasAborted = true; + throw e; + } + + error = e instanceof Error ? e.message : "Network error"; + throw e; + } finally { + // Skip logging aborted requests - they're expected in dev (React Strict Mode) + if (!wasAborted) { + const duration = performance.now() - start; + logGraphQLRequest({ + operation, + timestamp: Date.now(), + duration, + error, + errorCode, + variables, + source, + }); + } + } + }; +} + +export function GraphQLMonitor() { + const [isOpen, setIsOpen] = useState(false); + const [isExpanded, setIsExpanded] = useState(false); + const [stats, setStats] = useState({ + total: 0, + errors: 0, + retries: 0, + rate: 0, + storefront: { total: 0, errors: 0 }, + checkout: { total: 0, errors: 0 }, + operations: [] as [string, OperationStats][], + recentErrors: [] as ErrorLog[], + recentRequests: [] as RequestLog[], + }); + const [showErrors, setShowErrors] = useState(false); + const [showRequests, setShowRequests] = useState(false); + const [expandedError, setExpandedError] = useState(null); + const [expandedRequest, setExpandedRequest] = useState(null); + const [alert, setAlert] = useState(null); + const lastAlertRef = useRef(0); + + // Calculate request rate over sliding window + const calculateRate = useCallback(() => { + const now = Date.now(); + const windowStart = now - WINDOW_SIZE_MS; + const recentRequests = requestLogs.filter((log) => log.timestamp > windowStart); + return recentRequests.length / (WINDOW_SIZE_MS / 1000); + }, []); + + // Update stats periodically + useEffect(() => { + if (process.env.NODE_ENV !== "development") return; + + const updateStats = () => { + const rate = calculateRate(); + const sortedOps = Array.from(operationStats.entries()).sort((a, b) => b[1].count - a[1].count); + + setStats({ + total: totalRequests, + errors: totalErrors, + retries: totalRetries, + rate, + storefront: { ...sourceStats.storefront }, + checkout: { ...sourceStats.checkout }, + operations: sortedOps.slice(0, 10), + recentErrors: [...errorLogs].reverse().slice(0, 10), + recentRequests: [...requestLogs].reverse().slice(0, 20), + }); + + // Alert on high request rate (likely infinite loop!) + const now = Date.now(); + if (rate > RATE_ALERT_THRESHOLD && now - lastAlertRef.current > 10000) { + lastAlertRef.current = now; + const topOp = sortedOps[0]; + setAlert( + `⚠️ High request rate: ${rate.toFixed(1)}/sec!\n` + + `Most frequent: ${topOp?.[0]} (${topOp?.[1].count} calls)\n` + + `Possible infinite loop detected!`, + ); + setIsOpen(true); + } + }; + + // Listen for new requests + const handleRequest = () => updateStats(); + window.addEventListener("graphql-request", handleRequest); + + // Periodic update for rate decay + const interval = setInterval(updateStats, 1000); + + return () => { + window.removeEventListener("graphql-request", handleRequest); + clearInterval(interval); + }; + }, [calculateRate]); + + // Don't render in production + if (process.env.NODE_ENV !== "development") return null; + + // Minimized state - just show icon + if (!isOpen) { + return ( + + ); + } + + return ( +
+ {/* Header */} +
+
+ + GraphQL Monitor +
+
+ + +
+
+ + {/* Alert banner */} + {alert && ( +
+ +
{alert}
+ +
+ )} + + {/* Stats */} +
+
+
Requests
+
{stats.total}
+
+
+
Errors
+
0 ? "text-red-400" : ""}`}>{stats.errors}
+
+
+
Retries
+
0 ? "text-yellow-400" : ""}`}> + {stats.retries} +
+
+
+
Rate
+
RATE_ALERT_THRESHOLD ? "text-red-400" : ""}`}> + {stats.rate.toFixed(1)}/s +
+
+
+ + {/* Errors section (clickable) */} + {stats.errors > 0 && ( + + )} + + {/* Recent errors list */} + {showErrors && stats.recentErrors.length > 0 && !expandedError && ( +
+ {stats.recentErrors.map((err, i) => ( + + ))} +
+ )} + + {/* Expanded error detail */} + {expandedError && ( +
+
+ {expandedError.operation} + +
+
+ {expandedError.errorCode && ( +
+
Error Code
+
+ {expandedError.errorCode} +
+
+ )} +
+
Message
+
+ {expandedError.error} +
+
+ {expandedError.variables && Object.keys(expandedError.variables).length > 0 && ( +
+
Variables
+
+									{JSON.stringify(expandedError.variables, null, 2)}
+								
+
+ )} +
+ {new Date(expandedError.timestamp).toLocaleString()} +
+
+
+ )} + + {/* Recent requests toggle */} + + + {/* Recent requests list */} + {showRequests && !expandedRequest && ( +
+ {stats.recentRequests.map((req, i) => ( + + ))} + {stats.recentRequests.length === 0 && ( +
No requests yet
+ )} +
+ )} + + {/* Expanded request detail */} + {expandedRequest && ( +
+
+ + {expandedRequest.operation} + + +
+
+
+ {expandedRequest.duration && ( +
+ Duration: + {expandedRequest.duration.toFixed(0)}ms +
+ )} +
+ Status: + + {expandedRequest.error ? "Error" : "Success"} + +
+ {expandedRequest.isRetry && ( +
+ Retry: + #{expandedRequest.retryCount} +
+ )} +
+ {expandedRequest.error && ( +
+
Error
+
+ {expandedRequest.errorCode && ( + + {expandedRequest.errorCode} + + )} + {expandedRequest.error} +
+
+ )} + {expandedRequest.variables && Object.keys(expandedRequest.variables).length > 0 && ( +
+
Variables
+
+									{JSON.stringify(expandedRequest.variables, null, 2)}
+								
+
+ )} +
+ {new Date(expandedRequest.timestamp).toLocaleString()} +
+
+
+ )} + + {/* Operations list (expanded) */} + {isExpanded && ( +
+
Top Operations
+ {stats.operations.map(([name, opStats]) => ( +
+
+
{name}
+
+ {opStats.avgDuration > 0 && `${opStats.avgDuration.toFixed(0)}ms avg`} +
+
+
+
100 ? "text-yellow-400" : ""}>{opStats.count}
+ {opStats.errors > 0 &&
{opStats.errors} err
} + {opStats.retries > 0 &&
{opStats.retries} retry
} +
+
+ ))} + {stats.operations.length === 0 && ( +
No requests yet
+ )} +
+ )} + + {/* Footer */} +
+ Dev mode only +
+ +
+
+
+ ); +} diff --git a/apps/web/src/ui/components/error-content.tsx b/apps/web/src/ui/components/error-content.tsx new file mode 100644 index 0000000..413bb14 --- /dev/null +++ b/apps/web/src/ui/components/error-content.tsx @@ -0,0 +1,72 @@ +"use client"; + +import { useEffect } from "react"; +import Link from "next/link"; +import { AlertCircle, RefreshCw, Home, ArrowLeft } from "lucide-react"; +import { buttonClassName } from "@/ui/components/ui/button"; + +export interface ErrorContentProps { + error: Error & { digest?: string }; + reset: () => void; +} + +/** + * Shared error UI for per-root-group `error.tsx` boundaries. + * Displays user-friendly messages based on error type; technical details are logged only. + */ +export function ErrorContent({ error, reset }: ErrorContentProps) { + useEffect(() => { + console.error("[Error Page]", error); + }, [error]); + + const saleorError = error as Error & { isRetryable?: boolean; userMessage?: string; type?: string }; + const isRetryable = saleorError.isRetryable ?? true; + const userMessage = saleorError.userMessage ?? "Something went wrong loading this page."; + const errorType = saleorError.type ?? "unknown"; + + return ( +
+
+
+ +
+ +

+ {errorType === "network" ? "Connection Error" : "Something Went Wrong"} +

+ +

{userMessage}

+ +
+ {isRetryable && ( + + )} + + + + Go Home + +
+ + + + {error.digest &&

Error ID: {error.digest}

} +
+
+ ); +} diff --git a/apps/web/src/ui/components/footer-attribution.tsx b/apps/web/src/ui/components/footer-attribution.tsx new file mode 100644 index 0000000..b0cba90 --- /dev/null +++ b/apps/web/src/ui/components/footer-attribution.tsx @@ -0,0 +1,23 @@ +const attributionLinkClass = "text-inverse-subtle transition-colors hover:text-inverse"; + +/** Paper storefront attribution — remove or edit when forking for a custom brand. */ +export function FooterAttribution() { + return ( +

+ Powered by{" "} + + Saleor + {" "} + and{" "} + + Paper + + . Built for humans and AI. +

+ ); +} diff --git a/apps/web/src/ui/components/footer-menu-columns.tsx b/apps/web/src/ui/components/footer-menu-columns.tsx new file mode 100644 index 0000000..5834c4c --- /dev/null +++ b/apps/web/src/ui/components/footer-menu-columns.tsx @@ -0,0 +1,106 @@ +import Link from "next/link"; +import type { MenuItem } from "@/lib/menus/get-menu-data"; +import { getMenuItemHref, getMenuItemLabel } from "@/lib/menus/menu-item-utils"; +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; +import { NavHrefLink } from "@/ui/atoms/nav-href-link"; + +const defaultFooterLinks = { + support: [ + { label: "Contact Us", href: "/contact" }, + { label: "FAQs", href: "/faq" }, + { label: "Shipping", href: "/shipping" }, + { label: "Returns", href: "/returns" }, + ], + company: [ + { label: "About", href: "/about" }, + { label: "Sustainability", href: "/sustainability" }, + { label: "Careers", href: "/careers" }, + { label: "Press", href: "/press" }, + ], +}; + +function FooterMenuChildLink({ child }: { child: MenuItem }) { + const href = getMenuItemHref(child); + const label = getMenuItemLabel(child); + if (!href || !label) return null; + + if (child.category || child.collection || child.page) { + return ( + + {label} + + ); + } + + return ( + + {label} + + ); +} + +export function FooterMenuColumns({ items }: { items: MenuItem[] }) { + if (items.length === 0) { + return ( + <> +
+

Support

+
    + {defaultFooterLinks.support.map((link) => ( +
  • + + {link.label} + +
  • + ))} +
+
+
+

Company

+
    + {defaultFooterLinks.company.map((link) => ( +
  • + + {link.label} + +
  • + ))} +
+
+ + ); + } + + return ( + <> + {items.map((item) => ( +
+

{item.name}

+
    + {item.children?.map((child) => ( +
  • + +
  • + ))} +
+
+ ))} + + ); +} diff --git a/apps/web/src/ui/components/footer-photo-credits.tsx b/apps/web/src/ui/components/footer-photo-credits.tsx new file mode 100644 index 0000000..7e6086b --- /dev/null +++ b/apps/web/src/ui/components/footer-photo-credits.tsx @@ -0,0 +1,47 @@ +import type { HomepagePhotoCredit } from "@/lib/content/types"; + +const linkClassName = + "text-inverse-subtle underline-offset-2 transition-colors hover:text-inverse hover:underline"; + +function PhotoCreditLink({ name, href }: HomepagePhotoCredit) { + return ( + + {name} + + ); +} + +function formatCreditList(credits: readonly HomepagePhotoCredit[]) { + if (credits.length === 1) { + return ( + <> + Lifestyle photography by + + ); + } + + return ( + <> + Lifestyle photography by{" "} + {credits.map((credit, index) => { + const isLast = index === credits.length - 1; + const isSecondToLast = index === credits.length - 2; + + return ( + + + {!isLast ? (isSecondToLast ? " and " : ", ") : null} + + ); + })} + + ); +} + +export function FooterPhotoCredits({ credits }: { credits: readonly HomepagePhotoCredit[] }) { + if (credits.length === 0) { + return null; + } + + return

{formatCreditList(credits)}

; +} diff --git a/apps/web/src/ui/components/footer.tsx b/apps/web/src/ui/components/footer.tsx new file mode 100644 index 0000000..7164fb4 --- /dev/null +++ b/apps/web/src/ui/components/footer.tsx @@ -0,0 +1,97 @@ +import { Suspense } from "react"; +import Link from "next/link"; +import { StorefrontRegionPicker } from "./storefront-region-picker"; +import { + getStaticStorefrontChannelSlugs, + needsAsyncChannelDiscovery, + shouldFetchChannelMetadata, + toChannelSelectOptions, +} from "@/config/channels"; +import { getCachedChannelsList } from "@/lib/channels/get-channels-data"; +import { getStorefrontChannelSlugs } from "@/lib/channel-slugs"; +import { getFooterMenuItems } from "@/lib/menus/get-menu-data"; +import { getStorefrontContent } from "@/lib/content/server"; +import { getStorefrontLocaleOptions } from "@/lib/locale-display"; +import { FooterMenuColumns } from "./footer-menu-columns"; +import { CopyrightText } from "./copyright-text"; +import { FooterAttribution } from "./footer-attribution"; +import { FooterPhotoCredits } from "./footer-photo-credits"; +import { brandConfig } from "@/config/brand"; +import { Logo } from "./shared/logo"; + +import { buildStorefrontPath } from "@/lib/storefront-path"; + +export async function Footer({ locale, channel }: { locale: string; channel: string }) { + const resolvedSlugs = needsAsyncChannelDiscovery() + ? await getStorefrontChannelSlugs() + : getStaticStorefrontChannelSlugs(); + + const [menuItems, channels, content] = await Promise.all([ + getFooterMenuItems(channel, locale), + shouldFetchChannelMetadata(resolvedSlugs) ? getCachedChannelsList() : Promise.resolve(null), + getStorefrontContent(channel, locale), + ]); + + const footerMenuItems = menuItems ?? []; + const localeOptions = getStorefrontLocaleOptions(); + const selectorChannels = + channels?.channels && resolvedSlugs.length > 0 + ? toChannelSelectOptions(channels.channels, resolvedSlugs) + : []; + + return ( +
+ {/* Extra bottom padding on mobile to account for sticky add-to-cart bar */} +
+
+ {/* Brand */} +
+ + + +

{brandConfig.tagline}

+
+ + +
+ + {/* Language + market — hidden when only one option on each axis */} + {(localeOptions.length > 1 || selectorChannels.length > 1) && ( +
+ +
+ )} + + {/* Bottom bar */} +
+
+

+ {/* The year is read at request time; the shell keeps the line's height. */} + + + +

+ + +
+
+ + Privacy Policy + + + Terms of Service + +
+
+
+
+ ); +} diff --git a/apps/web/src/ui/components/google-analytics.tsx b/apps/web/src/ui/components/google-analytics.tsx new file mode 100644 index 0000000..c2b0f49 --- /dev/null +++ b/apps/web/src/ui/components/google-analytics.tsx @@ -0,0 +1,36 @@ +import Script from "next/script"; +import type { AnalyticsConsentMode } from "@/lib/analytics/consent"; + +/** + * Optional merchant tag. The default-consent stub is a blocking inline script + * so it runs before `gtag.js` (`afterInteractive`). Automatic page views are + * off — `AnalyticsPathnameViews` sends a redacted `page_view` after storage is allowed. + * + * Ads consents stay denied; Paper core has no ad pixels. + */ +export function GoogleAnalytics({ + measurementId, + consentMode, +}: { + measurementId: string; + consentMode: AnalyticsConsentMode; +}) { + const analyticsDefault = consentMode === "implied" ? "granted" : "denied"; + + return ( + <> + + + ); +} diff --git a/apps/web/src/ui/components/locale-select.tsx b/apps/web/src/ui/components/locale-select.tsx new file mode 100644 index 0000000..c3bd62d --- /dev/null +++ b/apps/web/src/ui/components/locale-select.tsx @@ -0,0 +1,41 @@ +"use client"; + +import { useStorefrontRegionNavigation } from "@/hooks/use-storefront-region-navigation"; +import type { LocaleSelectOption } from "@/lib/locale-display"; +import { cn } from "@/lib/utils"; + +export const LocaleSelect = ({ + locales, + variant = "default", + className, +}: { + locales: LocaleSelectOption[]; + variant?: "default" | "inverted"; + className?: string; +}) => { + const { locale, navigateToLocale } = useStorefrontRegionNavigation(); + + return ( + + ); +}; diff --git a/apps/web/src/ui/components/login-form.tsx b/apps/web/src/ui/components/login-form.tsx new file mode 100644 index 0000000..c9a768f --- /dev/null +++ b/apps/web/src/ui/components/login-form.tsx @@ -0,0 +1,17 @@ +"use client"; + +import { useSearchParams } from "next/navigation"; +import { getEmailAndTokenFromSearchParams } from "@/lib/auth/account-confirmation-url"; +import { LoginMode } from "./auth/login-mode"; +import { SetPasswordMode } from "./auth/set-password-mode"; + +export function LoginForm() { + const searchParams = useSearchParams(); + const credentials = getEmailAndTokenFromSearchParams(searchParams); + + if (credentials) { + return ; + } + + return ; +} diff --git a/apps/web/src/ui/components/logo.tsx b/apps/web/src/ui/components/logo.tsx new file mode 100644 index 0000000..cfc425e --- /dev/null +++ b/apps/web/src/ui/components/logo.tsx @@ -0,0 +1,14 @@ +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; +import { Logo as SharedLogo } from "./shared/logo"; + +/** + * Site logo with link to homepage. + * Always renders as a link - no client-side pathname detection needed. + */ +export const Logo = () => { + return ( + + + + ); +}; diff --git a/apps/web/src/ui/components/nav/components/cart-nav-item.tsx b/apps/web/src/ui/components/nav/components/cart-nav-item.tsx new file mode 100644 index 0000000..19d09f0 --- /dev/null +++ b/apps/web/src/ui/components/nav/components/cart-nav-item.tsx @@ -0,0 +1,11 @@ +import * as Checkout from "@/lib/checkout"; +import { CartButton } from "@/ui/components/cart"; + +export const CartNavItem = async ({ channel, localeSlug }: { channel: string; localeSlug: string }) => { + const checkoutId = await Checkout.getIdFromCookies(channel); + const checkout = checkoutId ? await Checkout.find(checkoutId, localeSlug) : null; + + const lineCount = checkout ? checkout.lines.reduce((result, line) => result + line.quantity, 0) : 0; + + return ; +}; diff --git a/apps/web/src/ui/components/nav/components/mega-menu-desktop.tsx b/apps/web/src/ui/components/nav/components/mega-menu-desktop.tsx new file mode 100644 index 0000000..d16f2eb --- /dev/null +++ b/apps/web/src/ui/components/nav/components/mega-menu-desktop.tsx @@ -0,0 +1,310 @@ +"use client"; + +import { useEffect, useState, type MouseEvent, type PointerEvent as ReactPointerEvent } from "react"; +import { useParams, useRouter } from "next/navigation"; +import { type NavMenuItem, hasNavMenuChildren, isExternalNavHref } from "@/lib/menus/serialize-menu-for-nav"; +import { formatContentLabel } from "@/lib/content/format-label"; +import type { NavChromeContent } from "@/lib/content/types"; +import { buildStorefrontPath } from "@/lib/storefront-path"; +import { + NavigationMenu, + NavigationMenuContent, + NavigationMenuItem, + NavigationMenuLink, + NavigationMenuList, + NavigationMenuTrigger, +} from "@/ui/components/ui/navigation-menu"; +import { cn } from "@/lib/utils"; +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; +import useSelectedPathname from "@/hooks/use-selected-pathname"; +import { MegaMenuCloseContext, MegaMenuColumnHeader, MegaMenuLeafLink } from "./mega-menu-link"; + +const STOREFRONT_HEADER_NAV_SELECTOR = "#storefront-header nav"; + +/** Equal-width columns in a single row; right panel reserved for future featured content. */ +const MEGA_MENU_NAV_COLUMN_CLASS = "min-w-0 flex-1"; + +function MegaMenuColumn({ item }: { item: NavMenuItem }) { + const children = item.children ?? []; + + if (children.length === 0) { + if (!item.href) { + return null; + } + + return ( +
+ +
+ ); + } + + return ( +
+ +
    + {children.map((child) => ( + + ))} +
+
+ ); +} + +const megaMenuTriggerClassName = + "inline-flex items-baseline justify-start h-auto rounded-none border-b-2 border-transparent bg-transparent px-0 py-1 text-sm font-medium text-muted-foreground no-underline hover:bg-transparent hover:text-foreground focus:bg-transparent data-[state=open]:border-foreground data-[state=open]:bg-transparent data-[state=open]:text-foreground"; + +const megaMenuDropdownTriggerClassName = cn( + megaMenuTriggerClassName, + "[&>svg]:ml-0.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:shrink-0 [&>svg]:self-center [&>svg]:relative [&>svg]:top-0 [&>svg]:text-muted-foreground [&>svg]:transition-transform [&>svg]:duration-200 group-data-[state=open]:[&>svg]:rotate-180 group-data-[state=open]:[&>svg]:text-foreground", +); + +function MegaMenuTriggerLabel({ item, onClose }: { item: NavMenuItem; onClose: () => void }) { + const router = useRouter(); + const params = useParams<{ locale?: string; channel?: string }>(); + + const navigate = () => { + if (!item.href) { + return; + } + + onClose(); + + if (isExternalNavHref(item.href)) { + window.location.assign(item.href); + return; + } + + if (!params.locale || !params.channel) { + window.location.assign(item.href); + return; + } + + router.push(buildStorefrontPath(params.locale, params.channel, item.href)); + }; + + const getPointerType = (event: ReactPointerEvent | MouseEvent) => { + if ("pointerType" in event) { + return event.pointerType; + } + + const nativeEvent = event.nativeEvent; + return "pointerType" in nativeEvent ? (nativeEvent as PointerEvent).pointerType : "mouse"; + }; + + const isMousePointer = (event: ReactPointerEvent | MouseEvent) => getPointerType(event) === "mouse"; + + return ( + { + // On touch, let the trigger open the mega menu instead of navigating. + if (isMousePointer(event)) { + event.stopPropagation(); + } + }} + onClick={(event) => { + if (!isMousePointer(event)) { + return; + } + event.stopPropagation(); + event.preventDefault(); + navigate(); + }} + onKeyDown={(event) => { + if (event.key !== "Enter" && event.key !== " ") { + return; + } + event.stopPropagation(); + event.preventDefault(); + navigate(); + }} + > + {item.label} + + ); +} + +function MegaMenuPanel({ + item, + nav, + onClose, +}: { + item: NavMenuItem; + nav: NavChromeContent; + onClose: () => void; +}) { + const children = item.children ?? []; + + return ( +
+
+
+
+
+ {children.map((child) => ( + + ))} +
+ {item.href ? ( +
+ + {formatContentLabel(nav.viewAllLabel, { label: item.label })} + +
+ ) : null} +
+ {/* Reserved for featured products, callouts, or editorial content */} + +
+
+ ); +} + +function MegaMenuTopItem({ + item, + nav, + onClose, +}: { + item: NavMenuItem; + nav: NavChromeContent; + onClose: () => void; +}) { + const pathname = useSelectedPathname(); + + if (hasNavMenuChildren(item)) { + const isActive = Boolean(item.href && !isExternalNavHref(item.href) && pathname === item.href); + + return ( + + + {item.href ? : item.label} + + + + + + ); + } + + if (!item.href) { + return null; + } + + const isActive = !isExternalNavHref(item.href) && pathname === item.href; + const linkClassName = cn(megaMenuTriggerClassName, isActive && "border-foreground text-foreground"); + + if (isExternalNavHref(item.href)) { + return ( + + + + {item.label} + + + + ); + } + + return ( + + + + {item.label} + + + + ); +} + +export function MegaMenuDesktop({ items, nav }: { items: NavMenuItem[]; nav: NavChromeContent }) { + const pathname = useSelectedPathname(); + + // Remount on route change so open menu state resets without an effect. + return ; +} + +function MegaMenuDesktopMenu({ + items, + nav, + pathname, +}: { + items: NavMenuItem[]; + nav: NavChromeContent; + pathname: string; +}) { + const [openItem, setOpenItem] = useState(""); + const closeMenu = () => setOpenItem(""); + + useEffect(() => { + if (!openItem) { + return; + } + + const onPointerDown = (event: PointerEvent) => { + const target = event.target; + if (!(target instanceof Element)) { + return; + } + + if (target.closest("[data-slot=mega-menu-panel]")) { + return; + } + + if (target.closest(`${STOREFRONT_HEADER_NAV_SELECTOR} button`)) { + return; + } + + closeMenu(); + }; + + document.addEventListener("pointerdown", onPointerDown); + return () => document.removeEventListener("pointerdown", onPointerDown); + }, [openItem]); + + const allProductsClassName = cn( + megaMenuTriggerClassName, + pathname === "/products" && "border-foreground text-foreground", + ); + + return ( + + + + + + + {/* Default (auto) prefetch — not `prefetch={true}`. This link is on every + browse page; a full prefetch would resolve `/products` searchParams + (and the listing) on every view. */} + {nav.allProductsLabel} + + + + {items.map((item) => ( + + ))} + + + + ); +} diff --git a/apps/web/src/ui/components/nav/components/mega-menu-link.tsx b/apps/web/src/ui/components/nav/components/mega-menu-link.tsx new file mode 100644 index 0000000..29e2c37 --- /dev/null +++ b/apps/web/src/ui/components/nav/components/mega-menu-link.tsx @@ -0,0 +1,75 @@ +"use client"; + +import { createContext, useContext } from "react"; +import clsx from "clsx"; +import { type NavMenuItem, isExternalNavHref } from "@/lib/menus/serialize-menu-for-nav"; +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; +import useSelectedPathname from "@/hooks/use-selected-pathname"; + +const MegaMenuCloseContext = createContext<(() => void) | undefined>(undefined); + +function useMegaMenuClose() { + return useContext(MegaMenuCloseContext) ?? (() => undefined); +} + +const leafLinkClassName = + "block text-sm text-muted-foreground no-underline transition-colors hover:text-foreground"; + +export function MegaMenuLeafLink({ item }: { item: NavMenuItem }) { + const pathname = useSelectedPathname(); + const closeMenu = useMegaMenuClose(); + + if (!item.href) { + return null; + } + + if (isExternalNavHref(item.href)) { + return ( +
  • + + {item.label} + +
  • + ); + } + + const isActive = pathname === item.href; + + return ( +
  • + + {item.label} + +
  • + ); +} + +export function MegaMenuColumnHeader({ item }: { item: NavMenuItem }) { + const className = + "mb-0 block text-sm font-semibold tracking-tight text-foreground no-underline transition-colors hover:text-foreground/80"; + const closeMenu = useMegaMenuClose(); + + if (item.href && !isExternalNavHref(item.href)) { + return ( + + {item.label} + + ); + } + + if (item.href) { + return ( + + {item.label} + + ); + } + + return

    {item.label}

    ; +} + +export { MegaMenuCloseContext }; diff --git a/apps/web/src/ui/components/nav/components/mobile-menu.tsx b/apps/web/src/ui/components/nav/components/mobile-menu.tsx new file mode 100644 index 0000000..e795a4c --- /dev/null +++ b/apps/web/src/ui/components/nav/components/mobile-menu.tsx @@ -0,0 +1,70 @@ +"use client"; + +import { type ReactNode, useState, createContext, useContext } from "react"; +import { Menu } from "lucide-react"; +import { useTranslations } from "next-intl"; +import { Logo } from "../../logo"; +import { + Sheet, + SheetContent, + SheetHeader, + SheetTitle, + SheetTrigger, + SheetCloseButton, +} from "@/ui/components/ui/sheet"; + +// Context to allow children to close the menu +const MobileMenuContext = createContext<{ close: () => void } | null>(null); + +export const useMobileMenuClose = () => { + const context = useContext(MobileMenuContext); + return context?.close ?? (() => {}); +}; + +type Props = { + children: ReactNode; +}; + +export const MobileMenu = ({ children }: Props) => { + const [isOpen, setIsOpen] = useState(false); + const t = useTranslations("nav.mobileMenu"); + + const close = () => setIsOpen(false); + + return ( + + + + + + {t("title")} + + + + + + + + ); +}; diff --git a/apps/web/src/ui/components/nav/components/mobile-nav-links.tsx b/apps/web/src/ui/components/nav/components/mobile-nav-links.tsx new file mode 100644 index 0000000..f9c920c --- /dev/null +++ b/apps/web/src/ui/components/nav/components/mobile-nav-links.tsx @@ -0,0 +1,174 @@ +"use client"; + +import clsx from "clsx"; +import { type NavMenuItem, hasNavMenuChildren, isExternalNavHref } from "@/lib/menus/serialize-menu-for-nav"; +import { formatContentLabel } from "@/lib/content/format-label"; +import type { NavChromeContent } from "@/lib/content/types"; +import { + Accordion, + AccordionContent, + AccordionItemWrapper, + AccordionTrigger, +} from "@/ui/components/ui/accordion"; +import { LinkWithChannel } from "@/ui/atoms/link-with-channel"; +import useSelectedPathname from "@/hooks/use-selected-pathname"; + +function MobileNavLeafLink({ item }: { item: NavMenuItem }) { + const pathname = useSelectedPathname(); + + if (!item.href) { + return null; + } + + const className = clsx( + "block rounded-md py-1.5 text-sm transition-colors", + pathname === item.href && !isExternalNavHref(item.href) + ? "font-medium text-foreground" + : "text-muted-foreground hover:text-foreground", + ); + + if (isExternalNavHref(item.href)) { + return ( + + {item.label} + + ); + } + + return ( + + {item.label} + + ); +} + +/** L2 category — section heading when it has children, otherwise a direct sub-link. */ +function MobileNavSectionHeading({ item, hasChildren }: { item: NavMenuItem; hasChildren: boolean }) { + const pathname = useSelectedPathname(); + const className = clsx( + "block text-sm font-semibold tracking-tight", + hasChildren ? "text-foreground" : "transition-colors hover:text-foreground", + !hasChildren && pathname === item.href ? "text-foreground" : !hasChildren && "text-foreground/90", + hasChildren && item.href && "hover:underline", + ); + + if (!item.href) { + return

    {item.label}

    ; + } + + if (isExternalNavHref(item.href)) { + return ( + + {item.label} + + ); + } + + return ( + + {item.label} + + ); +} + +function MobileNavSection({ item }: { item: NavMenuItem }) { + const grandchildren = item.children ?? []; + const hasGrandchildren = grandchildren.length > 0; + + return ( +
    + + {hasGrandchildren ? ( +
      + {grandchildren.map((grandchild) => ( +
    • + +
    • + ))} +
    + ) : null} +
    + ); +} + +function MobileNavGroup({ item, nav }: { item: NavMenuItem; nav: NavChromeContent }) { + const children = item.children ?? []; + + return ( + + + + {item.label} + + +
    + {children.map((child) => ( + + ))} +
    + {item.href ? ( +
    + + {formatContentLabel(nav.viewAllLabel, { label: item.label })} + +
    + ) : null} +
    +
    +
    + ); +} + +function MobileNavTopLink({ item }: { item: NavMenuItem }) { + const pathname = useSelectedPathname(); + + if (!item.href) { + return null; + } + + const className = clsx( + "block text-base font-medium transition-colors", + pathname === item.href && !isExternalNavHref(item.href) + ? "text-foreground" + : "text-muted-foreground hover:text-foreground", + ); + + if (isExternalNavHref(item.href)) { + return ( + + {item.label} + + ); + } + + return ( + + {item.label} + + ); +} + +export function MobileNavLinks({ items, nav }: { items: NavMenuItem[]; nav: NavChromeContent }) { + return ( + <> +
  • + +
  • + {items.map((item) => { + if (hasNavMenuChildren(item)) { + return ( +
  • + +
  • + ); + } + + return ( +
  • + +
  • + ); + })} + + ); +} diff --git a/apps/web/src/ui/components/nav/components/nav-links-desktop.tsx b/apps/web/src/ui/components/nav/components/nav-links-desktop.tsx new file mode 100644 index 0000000..c06f2ba --- /dev/null +++ b/apps/web/src/ui/components/nav/components/nav-links-desktop.tsx @@ -0,0 +1,21 @@ +import dynamic from "next/dynamic"; +import type { NavMenuItem } from "@/lib/menus/serialize-menu-for-nav"; +import type { NavChromeContent } from "@/lib/content/types"; + +function NavLinksDesktopSkeleton() { + return ( + + ); +} + +const MegaMenuDesktop = dynamic(() => import("./mega-menu-desktop").then((mod) => mod.MegaMenuDesktop), { + loading: () => , +}); + +export function NavLinksDesktop({ items, nav }: { items: NavMenuItem[]; nav: NavChromeContent }) { + return ; +} diff --git a/apps/web/src/ui/components/nav/components/search-bar.tsx b/apps/web/src/ui/components/nav/components/search-bar.tsx new file mode 100644 index 0000000..0937b13 --- /dev/null +++ b/apps/web/src/ui/components/nav/components/search-bar.tsx @@ -0,0 +1,47 @@ +import { redirect } from "next/navigation"; +import { SearchIcon } from "lucide-react"; +import { buildStorefrontPath } from "@/lib/storefront-path"; + +export const SearchBar = ({ + locale, + channel, + placeholder, + srOnlyLabel, +}: { + locale: string; + channel: string; + placeholder: string; + srOnlyLabel: string; +}) => { + async function onSubmit(formData: FormData) { + "use server"; + const search = formData.get("search") as string; + if (search && search.trim().length > 0) { + redirect(`${buildStorefrontPath(locale, channel, "/search")}?query=${encodeURIComponent(search)}`); + } + } + + return ( +
    + +
    + ); +}; diff --git a/apps/web/src/ui/components/nav/components/user-menu/components/user-avatar.tsx b/apps/web/src/ui/components/nav/components/user-menu/components/user-avatar.tsx new file mode 100644 index 0000000..f335f5d --- /dev/null +++ b/apps/web/src/ui/components/nav/components/user-menu/components/user-avatar.tsx @@ -0,0 +1,35 @@ +import Image from "next/image"; +import { type UserDetailsFragment } from "@/gql/graphql"; + +type Props = { + user: UserDetailsFragment; +}; + +export const UserAvatar = ({ user }: Props) => { + const label = + user.firstName && user.lastName + ? `${user.firstName.slice(0, 1)}${user.lastName.slice(0, 1)}` + : user.email.slice(0, 2); + + if (user.avatar) { + return ( + + ); + } + + return ( + + ); +}; diff --git a/apps/web/src/ui/components/nav/components/user-menu/components/user-info.tsx b/apps/web/src/ui/components/nav/components/user-menu/components/user-info.tsx new file mode 100644 index 0000000..0d6478c --- /dev/null +++ b/apps/web/src/ui/components/nav/components/user-menu/components/user-info.tsx @@ -0,0 +1,18 @@ +import { type UserDetailsFragment } from "@/gql/graphql"; + +type Props = { + user: UserDetailsFragment; +}; + +export const UserInfo = ({ user }: Props) => { + const userName = user.firstName && user.lastName ? `${user.firstName} ${user.lastName}` : null; + + return ( +
    + {userName ? ( + {userName} + ) : null} + {user.email} +
    + ); +}; diff --git a/apps/web/src/ui/components/nav/components/user-menu/header-chrome-sync.tsx b/apps/web/src/ui/components/nav/components/user-menu/header-chrome-sync.tsx new file mode 100644 index 0000000..66f1342 --- /dev/null +++ b/apps/web/src/ui/components/nav/components/user-menu/header-chrome-sync.tsx @@ -0,0 +1,71 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { startTransition, useEffect, type ReactNode } from "react"; + +import { CHROME_LOCAL_BUMP_EVENT, CHROME_VERSION_KEY, readChromeVersion } from "@/lib/chrome-sync"; + +/** + * Refreshes header auth/cart chrome when *another tab* changed session or cart + * state (login, logout, cart mutation, order placed). + * + * Same-tab freshness never needs this component: the served document renders + * the cookie-gated chrome holes with current cookies, and mutations refresh + * the router themselves (server actions call `refresh()` from `next/cache`; + * auth boundaries hard-navigate). Cross-tab, mutators call + * `bumpChromeVersion()`; this listens for the version change and re-renders + * once when the tab is (or becomes) visible. + * + * Deliberately does **no work on mount and no server round-trip per focus**. + * The previous design invalidated the whole locale/channel layout (a sitewide + * shared-cache purge) via a Server Action on every hard load and tab refocus — + * a per-visitor Vercel cost multiplier that also busted caches shared by all + * users. See the `paper-vercel-cost` rule. + */ +export function HeaderChromeSync({ children }: { children: ReactNode }) { + const router = useRouter(); + + useEffect(() => { + let lastSyncedVersion = readChromeVersion(); + + const syncIfStale = () => { + // Hidden tabs wait for refocus — N background tabs must not all + // re-render on one bump. + if (document.visibilityState !== "visible") return; + const version = readChromeVersion(); + if (version === lastSyncedVersion) return; + lastSyncedVersion = version; + startTransition(() => { + router.refresh(); + }); + }; + + const syncOnStorage = (event: StorageEvent) => { + // `key === null` means storage was cleared wholesale. + if (event.key !== null && event.key !== CHROME_VERSION_KEY) return; + syncIfStale(); + }; + + // This tab's own bump: adopt the version without refreshing — the acting + // tab is already fresh (server action `refresh()` / hard navigation), and + // `storage` events never fire in the tab that wrote. + const adoptOwnBump = () => { + lastSyncedVersion = readChromeVersion(); + }; + + // pageshow covers bfcache restores, where effects don't re-run but the + // restored DOM may predate a mutation in another tab. + window.addEventListener("storage", syncOnStorage); + window.addEventListener(CHROME_LOCAL_BUMP_EVENT, adoptOwnBump); + window.addEventListener("pageshow", syncIfStale); + document.addEventListener("visibilitychange", syncIfStale); + return () => { + window.removeEventListener("storage", syncOnStorage); + window.removeEventListener(CHROME_LOCAL_BUMP_EVENT, adoptOwnBump); + window.removeEventListener("pageshow", syncIfStale); + document.removeEventListener("visibilitychange", syncIfStale); + }; + }, [router]); + + return children; +} diff --git a/apps/web/src/ui/components/nav/components/user-menu/user-menu-container.tsx b/apps/web/src/ui/components/nav/components/user-menu/user-menu-container.tsx new file mode 100644 index 0000000..77eb52d --- /dev/null +++ b/apps/web/src/ui/components/nav/components/user-menu/user-menu-container.tsx @@ -0,0 +1,3 @@ +export function UserMenuSkeleton() { + return