Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
112 changes: 104 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -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 `<repo>-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_<ENV>
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 → <repo>-web-<env>, 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 |
10 changes: 10 additions & 0 deletions apps/web/.env.configurator.local.example
Original file line number Diff line number Diff line change
@@ -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=
168 changes: 168 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
@@ -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 <img srcset> 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
81 changes: 81 additions & 0 deletions apps/web/.gitignore
Original file line number Diff line number Diff line change
@@ -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/
Loading
Loading