Skip to content

fix(cms): send select + populate on all API client collection reads - #23

Merged
Ardnived merged 6 commits into
mainfrom
fix/api-client-select-populate
Jun 13, 2026
Merged

Ardnived merged 6 commits into
mainfrom
fix/api-client-select-populate

Conversation

@Ardnived

Copy link
Copy Markdown
Contributor

Summary

The meditation preview (and every page) broke after SahajCloud PR #294 (feat(api): require select + populate for API client reads) added a beforeOperation hook (validateClientQueryParamsHook) that rejects any clients-authenticated collection read with HTTP 400 when it:

  1. omits a non-empty select, or
  2. uses effective depth > 1 without a non-empty populate.

WeMeditateWeb authenticates as a clients API key and was issuing every query with depth: 2 and no select/populate, so all collection reads now 400 — including the meditation preview's server-side getDocumentById. PR #420 confirmed the only accepted format is PayloadCMS's qs-esm bracket notation, which is exactly what @payloadcms/sdk emits when select/populate are passed as objects.

What changed

All edits are in server/cms-client.ts:

  • Added precise, schema-typed select/populate field-set constants (PAGE_SELECT, PAGE_LIST_SELECT, MEDITATION_SELECT, SONG_SELECT, IMAGE_POPULATE, SONG_POPULATE). Each is satisfies-typed against the generated *Select interfaces (PagesSelect, MeditationsSelect, …), so a CMS schema change pulled via pnpm types:cms surfaces as a compile error rather than a silent runtime 400. Upload url selections also include filename (Payload returns url: null otherwise).
  • Wired select + populate into all four affected collection reads: getPageBySlug, getDocumentById (the preview path — shapes carried per-collection in COLLECTION_BY_ID_CONFIG), getPagesByTags, getSongsByTags.

Not affected: getWebConfig — it's a findGlobal; the hook is a collection hook and never fires for globals.

Why typed literals instead of a query builder

The only consumer of select/populate is these ~4 server-side SDK calls; the SDK already serializes typed objects to the correct bracket notation. The live-preview path (useLivePreview in PagePreview) exposes no select/populate options and isn't gated by the hook anyway (it's a cookie-auth browser fetch, not a clients request). A leaf-path builder would discard the compile-time type safety the literals provide.

Test plan

  • pnpm exec tsc --noEmit — clean
  • pnpm test:run — 89/89 pass
  • Manual: pnpm dev, load a meditation/page and the preview route, confirm [PayloadCMS] … → 200 (not 400)

Note (from PR #420): bracket-notation requests were reportedly still 400ing in production at that time (suspected deployment lag / CF Workers URL mangling). If reads still 400 after deploy, check wrangler tail sahajcloud for the diagnostic WARN log — that would be a backend issue, not this client change.

🤖 Generated with Claude Code

SahajCloud PR #294 added a beforeOperation hook that rejects any
`clients`-authenticated collection read with HTTP 400 when it omits
`select`, or uses depth > 1 without `populate`. WeMeditateWeb sent every
query with depth: 2 and no select/populate, so all collection reads
(including the meditation preview's getDocumentById) started 400ing.

Add precise, schema-typed select/populate field sets to the four affected
queries in cms-client.ts (getPageBySlug, getDocumentById, getPagesByTags,
getSongsByTags). Constants are `satisfies`-typed against the generated
*Select interfaces so a CMS schema change surfaces as a compile error
rather than a silent 400. getWebConfig is unaffected (findGlobal; the hook
only fires on collection reads).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented May 29, 2026 •

Copy link
Copy Markdown

Deploying wemeditate-design with  Cloudflare Pages  Cloudflare Pages

Latest commit: da3a535
Status: ✅  Deploy successful!
Preview URL: https://c16f73e8.wm-design.pages.dev
Branch Preview URL: https://fix-api-client-select-popula.wm-design.pages.dev

View logs

Ardnived and others added 5 commits May 30, 2026 18:48
The latest `pnpm types:cms` pull reworked the schema (meditation/lecture tag
collections replaced by a new taxonomy, several collections added). Two things
broke against the app's slice of the schema:

- `MeditationTag` no longer exists — drop its import/re-export in cms-types.
- The regenerated file now ends with a `declare module 'payload'` augmentation
  that fails to compile here (TS2664): this Workers frontend uses
  @payloadcms/sdk (typed via `new PayloadSDK<Config>()`), not the `payload`
  package. Strip it, and add scripts/strip-payload-augmentation.mjs so the
  `types:cms` script removes it on every future pull.

tsc clean; 87 tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`pnpm lint` failed because ESLint v9 ignores the legacy .eslintrc.json and
requires eslint.config.js. Migrate to a flat config using the installed
toolchain (typescript-eslint, eslint-plugin-react, eslint-config-prettier),
porting the legacy ruleset's lenient, warning-based intent.

- Prettier wired via eslint-config-prettier only (no prettier-as-lint-rule);
  the codebase isn't Prettier-formatted, so enforcing it is out of scope.
- Allow the documented `interface XSvgProps extends ComponentProps<'svg'> {}`
  pattern; keep no-explicit-any / no-unescaped-entities as warnings.
- Remove dead .eslintrc.json and .eslintignore. The jsx-a11y / react-hooks /
  import / unused-imports plugins are no longer installed, so their rules are
  intentionally omitted (documented in eslint.config.js).

`pnpm lint` now exits 0 (0 errors, 99 warnings).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Pre-existing working-tree edit to the shared .mcp.json, committed while
clearing the working tree. Leaves cloudflare-docs and puppeteer configured.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Resolves the eslint.config.js add/add conflict in favor of main's flat config:
main independently completed the ESLint v9 migration and pairs it with a new
.prettierrc.json (matching the codebase's no-semi/single-quote style) plus the
legacy jsx-sort-props / padding-line rules. That supersedes this branch's
earlier version of the same file. All other paths auto-merged (.prettierrc.json,
meditation-player components/template, .serena/project.yml).

Verified on the merged tree: tsc clean, 87 tests pass, `pnpm lint` exits 0.
main's meditation-player changes compile against this branch's regenerated
payload-types with no field-level breakage.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Ardnived
Ardnived merged commit c3b761e into main Jun 13, 2026
1 check passed
@Ardnived
Ardnived deleted the fix/api-client-select-populate branch June 13, 2026 05:59
Ardnived added a commit that referenced this pull request Jun 14, 2026
The CMS query-validation hook (PR #23) rejects collection reads without
select/populate with HTTP 400 — which is why discoverFromCms found nothing and
the content-page/meditation specs skipped (the key itself is valid, not 403).
Add a qs serializer and mirror cms-client's select/populate shapes so the
discovery queries are accepted and the specs run against the preview.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Ardnived added a commit that referenced this pull request Jun 15, 2026
…#28)

* ci: add GitHub Actions CI with smoke tests against the Cloudflare preview

The repo had no CI — the only automated PR check was the Cloudflare
git-integration preview deploy, so a PR could break page rendering and
nothing caught it before merge. This app has no database: every page is
rendered server-side from the production PayloadCMS, so the highest-value
check is a smoke test against the deployed preview confirming the Worker
loads real content and hasn't regressed.

Adds one pull_request workflow with two jobs:
- gate: lint + typecheck + unit tests (closes the no-CI gap; no prod build,
  Cloudflare builds the preview).
- smoke: discover the per-PR Cloudflare preview URL from the GitHub API,
  wait until healthy, then run fetch-based Vitest specs against it. Skips
  gracefully when no preview is posted.

Smoke specs are content-discovering (crawl the preview homepage for real
featuredPages links; optionally query the CMS for sample ids when
SAHAJCLOUD_API_KEY is set) and cover the always-present surfaces: homepage,
linked content pages, a non-English locale, the /en/ canonical redirect, the
404 page, and meditation full/embed routes.

- scripts/get-cloudflare-preview-url.mjs: GitHub-API preview URL discovery
  (deployment environment_url -> commit statuses -> check runs), plain ESM.
- vitest.smoke.config.ts + tests/smoke/: fetch-based suite + helpers.
- package.json: add typecheck + test:smoke scripts.
- vitest.config.ts: exclude tests/smoke from the unit run.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* ci: make Cloudflare preview discovery project-aware (target the web app, not Ladle)

The repo's Cloudflare git integration deploys the Ladle design system
(wm-design.pages.dev), not the Vike web app — and it's the only preview posted
on PRs today. The first CI run proved the discovery mechanism works (it found
the URL via the cloudflare bot PR comment and the "Cloudflare Pages" check-run
output.summary — there are no GitHub deployments or commit statuses), but it
grabbed the Ladle deployment and smoke-tested a static component playground.

Make discovery project-aware:
- Primary source is now the bot PR comment, the only surface that names the
  project ("Deploying <project> with Cloudflare Pages"); deployments, commit
  statuses, and check-run output remain fallbacks.
- Select the candidate matching CF_PROJECT_MATCH (set the CF_PREVIEW_PROJECT
  repo variable to the web-app preview project once it exists); always exclude
  the known Ladle project (wm-design / wemeditate-design).
- Until a target is configured, check quickly and skip (30s) instead of polling
  the full 12-minute build window, so the smoke job stays green and fast.

Workflow: pass PR_NUMBER + CF_PROJECT_MATCH, add pull-requests/issues read perms.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* ci: retrigger Cloudflare preview builds (Ladle + Web)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* ci: smoke-test both Cloudflare previews (web Worker + Ladle Pages)

Both previews are now enabled and are distinguishable by URL host:
  - web   → Workers Builds, …-wemeditate-web.<acct>.workers.dev
  - ladle → Pages,          …wm-design.pages.dev

- Workflow: replace the single smoke job with a 2-target matrix (web, ladle),
  each discovering its own preview via CF_PROJECT_MATCH (wemeditate-web / wm-design).
- Discovery: accept ANY HTTP response as "reachable" (renamed waitHealthy →
  waitReachable) so a 500 page is caught by the smoke specs instead of failing
  discovery before they run.
- Ladle: new fetch-based spec (tests/smoke/ladle) — asserts the app shell and a
  non-empty /meta.json story manifest. No Playwright needed for the static SPA.
- Web: move specs to tests/smoke/web; fix conventions verified against the live
  Worker (locale roots have no trailing slash: /es not /es/; default locale is
  stripped: /en → 301 → /index); discover a real CMS page via the API instead of
  crawling homepage anchors (which may be hydrated client-side).
- Scripts: test:smoke → web specs; add test:smoke:ladle.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(layout): degrade gracefully when WebConfig is incomplete

The homepage (and every renderable page) returned a 500 on the deployed
preview. Root cause: LayoutDefault.assertSettingsConfigured() threw when the
WebConfig was incomplete (e.g. empty/missing featuredPages — which getWebConfig
does not normalize, unlike classPages/knowledgePages/infoPages). That throw ran
OUTSIDE the Sentry error boundary, so it surfaced as an unhandled SSR error →
500 on any page that successfully fetched settings. (A thrown 404 bypasses this
path, which is why /about 404'd cleanly while / and /es 500'd.)

Note /es ≡ / here: getWebConfig() takes no locale, so this was never about
missing localized content.

Fix: drop the hard assert and null-guard every settings access
(featuredPages/knowledge/info/classPages ?? []). Incomplete config now renders
gracefully with whatever nav is available instead of crashing; genuinely-missing
pages are still 404s via the data hooks; true CMS/service errors still 500.

Add LayoutDefault.test.tsx covering the incomplete-config regression.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(smoke): log why CMS discovery finds nothing (diagnose silent skips)

discoverFromCms now logs the CMS response (HTTP status / "0 docs") so a skipped
content-page or meditation spec is diagnosable in CI — distinguishing an
unauthorized key (403) from genuinely-missing published content.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(smoke): send select/populate so CMS discovery queries are accepted

The CMS query-validation hook (PR #23) rejects collection reads without
select/populate with HTTP 400 — which is why discoverFromCms found nothing and
the content-page/meditation specs skipped (the key itself is valid, not 403).
Add a qs serializer and mirror cms-client's select/populate shapes so the
discovery queries are accepted and the specs run against the preview.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(cms): send select/populate/locale on getWebConfig

getWebConfig was the only API-client read missing select/populate — and it reads
at depth 2, which the backend requires populate for (see the note in cms-client).
The global itself returned 200, but its page relationships (homePage, featuredPages,
classPages, knowledgePages, infoPages) came back without title/slug, so the deployed
homepage rendered an empty <h1> and ~9 dead `/undefined` nav links. It also passed no
locale, so localized slug/title couldn't resolve.

- Add WEB_CONFIG_SELECT + WEB_CONFIG_POPULATE (pages → PAGE_SELECT, images) and pass
  them plus `locale` to findGlobal; key the cache by locale.
- Thread `locale` through all five getWebConfig callers.

Smoke: add expectNoBrokenLinks() and assert the homepage has no /undefined|/null
nav hrefs, so an under-populated read fails loudly instead of false-passing.

Note: verified via CI/deploy — the production CMS rejects the API key from a local
machine (403), so this can't be reproduced against cloud.sydevelopers.com locally.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(cms): drop unresolved page refs in getWebConfig + warn to Sentry

A published page populates in the WebConfig relationships; an unpublished/trashed
one comes back as a bare id (and renders a dead `/undefined` nav link). Add a
graceful fallback: partitionPublishedPages() keeps only populated pages with a
slug and drops the rest, so the layout never renders broken nav. When anything is
dropped, log a Sentry warning (level: warning) listing the unresolved refs by
group, so the underlying CMS data gap stays visible instead of silently hidden.

Also covers homePage returned as a bare id. Unit-tested in cms-client.test.ts.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant