Skip to content

feat(api): resolve canonical webUrl per owning client region - #637

Closed
Ardnived wants to merge 7 commits into
feat/client-canonicalfrom
feat/region-canonical-url
Closed

Ardnived wants to merge 7 commits into
feat/client-canonicalfrom
feat/region-canonical-url

Conversation

@Ardnived

Copy link
Copy Markdown
Contributor

Summary

  • webUrl now resolves per region — to the client that owns it, or the nearest owning ancestor — instead of one global SAHAJATLAS_URL base pointing at a host that is noindex on three layers.
  • Region paths become queryable (where[breadcrumbs.url][equals]='/nl/amsterdam') with no new endpoint, no new stored field and no migration.
  • A blank region slug — which silently costs a whole subtree its canonical URLs — now fails at write time.

⚠️ Stacked on #635 (the canonical fields it consumes). Base is feat/client-canonical, not main. Merge #635 first.

Changes

  • src/lib/atlas/canonicalUrl.ts — the two URL shapes, plus atlas-url-contract.json, the fixture SahajCloud / SahajAtlasWeb / WeMeditateWeb all assert against byte-identically.
  • src/lib/atlas/regionTree.ts — was regionWebPaths.ts; now exposes the ancestor chain alongside the path from the same single query, since ownership resolves by walking that chain. getRegionWebPaths survives as a thin projection, so a webPath read still costs one query.
  • src/lib/atlas/regionOwners.ts — the clients read (~31 rows) + nearest-ancestor walk.
  • src/fields/publicUrlFields.ts — web base widened to take the read context. Source-compatible: the existing zero-arg thunks stay assignable.
  • src/payload.config.ts + tests/utils/testHelpers.ts — nested-docs config collapsed into one shared REGION_NESTED_DOCS_CONFIG.
  • scripts/ — backfill-region-breadcrumb-urls.ts (write, --force-gated) and audit-region-slugs.ts (read-only).

Migration

None. breadcrumbs.url already exists in the schema — it has been null only because the config never passed a generateURL. Enabling it is config, not DDL.

But it needs a one-off backfill after deploy, since breadcrumbs populate on write:

pnpm tsx scripts/backfill-region-breadcrumb-urls.ts          # dry run
pnpm tsx scripts/backfill-region-breadcrumb-urls.ts --force  # apply

It re-saves roots only and lets the plugin's own cascade visit each subtree once — re-saving all 595 regions individually would repeat the work once per ancestor.

Test Results

  • Unit: 1228 passed (99 files) — 71 new across 3 specs
  • Integration: 6 touched suites green (111 tests), including 2 new specs (25 tests)
  • Lint / typecheck / typecheck:tests: ✓ clean
  • Build: not run locally — Railway builds the preview

Two assertions were mutation-checked rather than trusted: flipping the &/? join broke the URL contract test (2 failures), and disabling the ownership memo broke the query-count test (expected 3 to be 1).

Notes for reviewer

Behaviour changes that are the point of the ticket, not regressions:

  • Four existing specs asserted the old SAHAJATLAS_URL base and were updated. One of them, client-canonical.int.spec.ts, asserted feat(access): add embed metadata and canonical ownership to Clients #633's "no webUrl changes" claim — this PR is the follow-up that makes it change, so it now asserts the opposite.
  • webPath is byte-identical throughout; ownership only decides what it is joined to.

Worth extra scrutiny:

  • The slug invariant sits in the field validate, not a collection hook. Payload generates the slug in a field beforeChange, which runs after every collection hook — so a collection hook sees an empty slug on every auto-generating create. It also grandfathers a pre-existing blank, because resaveChildren re-saves each descendant by passing its whole document back through update; rejecting outright would make the ancestors of the 16 blank regions unsaveable.
  • where[breadcrumbs.url][equals] matches descendants too (their trail contains the ancestor's URL). Add slug to the where for exactly one region. Pinned by a test either way.

Known follow-ups (not in this PR):

  • The if (!value) return true in slugField's uniqueness validator disarms Payload's required for every collection using it (Pages, Meditations, tag collections), not just Regions. Fixed here only for Regions; the factory-wide fix is a cross-collection behaviour change that deserves its own ticket and test sweep.
  • The 16 blank-slugged regions are reported, not rewritten — the right name for each is a human decision. pnpm tsx scripts/audit-region-slugs.ts.
  • usagePlugin is still configured separately in payload.config.ts and testHelpers.ts (deliberately different values, so not folded into the shared-config treatment).

Closes #634

🤖 Generated with Claude Code

Ardnived and others added 7 commits August 14, 2026 13:04
Two URL shapes, no hash: `path` appends the region path to the mount,
`query` carries it in an `atlas=` parameter joined with `?` or `&`. The
prefix (`canonicalUrlBase`) is the primitive rather than the whole URL,
because `publicUrlFields` composes `webUrl` as `base + webPath` — both
shapes can express themselves that way precisely because the path is
emitted raw and always last.

`atlas-url-contract.json` pins the contract for SahajCloud, SahajAtlasWeb
and WeMeditateWeb to assert against byte-identically.

`UrlBase` is widened to receive the same read context as `buildPath`, so a
base can vary per document. Source-compatible: the existing zero-arg
thunks stay assignable, since a function ignoring its parameter satisfies
one that receives it.

Refs #634

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`webUrl` was `SAHAJATLAS_URL + webPath` for every event and region — one
global base pointing at a host that is `noindex` on three layers, so every
canonical URL this CMS emitted named a page we had told search engines to
ignore.

It is now per-region. A client that owns a region gets the canonical for
that region, its sub-regions and its events on its own domain; anything
unowned falls back up the region tree, and finally to the We Meditate
surface. `SAHAJATLAS_URL` survives only in the two live-preview URLs.

`regionWebPaths` becomes `regionTree`, exposing the ancestor chain
alongside the path from the same single query — ownership resolves by
walking that chain, and computing it twice would be two ways for one
hierarchy to disagree. `getRegionWebPaths` stays as a thin projection, so
a `webPath` read still costs exactly one query.

Owners load lazily in a second memo rather than eagerly with the tree: the
widget's geojson feed selects `webPath` and not `webUrl`, and it should
keep paying for one query, not two.

Refs #634

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Supplying `generateURL` to the nested-docs plugin populates the
`breadcrumbs.url` sub-field that has existed in the schema all along and
been null only because the config never passed one. That makes
`where[breadcrumbs.url][equals]='/nl/amsterdam'` resolve a region in one
query — no new endpoint, no new stored field, no migration. It derives
from the same `buildRegionPath` as `webPath`, so the canonical and the
lookup cannot disagree.

Breadcrumbs populate on write, so existing rows need a resave:
`backfill-region-breadcrumb-urls.ts` re-saves roots only and lets the
plugin's own cascade visit each subtree once, rather than re-saving every
region and repeating the work per ancestor.

A blank slug makes a whole subtree's canonical URLs unbuildable, and the
slug field's uniqueness `validate` replaces Payload's `required` default
while opening with `if (!value) return true` — so an empty slug passes
today. `requireNonEmptySlug` closes that, on the *transition* rather than
the state: 16 regions are blank in the data now, and rejecting every write
carrying a blank slug would block edits to their ancestors too, since the
resave cascade passes each descendant's whole document back through
`update`. `audit-region-slugs.ts` reports those rows and what each costs.

Refs #634

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

The invariant started as a collection `beforeValidate` hook, which is the
wrong seam: Payload generates the slug from `name` in a *field*
`beforeChange` hook, and the collection hooks all run before that (field
beforeValidate → collection beforeValidate → collection beforeChange →
field beforeChange). So it saw an empty slug on every auto-generating
create and rejected writes that were fine — which is what broke region
creation across four integration suites.

Field `validate` runs after the generator, so it is the only place that
sees the value that will actually be stored. `withNonEmptySlug` wraps the
uniqueness validator the factory installs rather than replacing it, and
grandfathers via `previousValue`.

Also collapses the nested-docs registration into one shared
REGION_NESTED_DOCS_CONFIG. The test harness builds its own Payload config,
so `generateURL` configured only in payload.config.ts left the whole
integration suite reading `breadcrumbs.url: null` — a plugin configured in
one of the two behaves differently under test than in production.

Refs #634

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- environment.md / .env.example: WEMEDITATE_ATLAS_BASE_PATH, and a note that
  SAHAJATLAS_URL is deliberately not a canonical base
- api-clients.md: the two URL shapes, the two-query cost, the no-fragment and
  raw-path rules, and the breadcrumbs.url lookup's descendant-match caveat;
  corrects the "#633 is data only, nothing resolves" framing now that it does
- scripts.md: the backfill + audit scripts
- tests/COVERAGE.md: a regions row and the three new canonical subjects

Refs #634

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Per the /simplify pass:

- Both resolvers hand-rolled a `WeakMap<PayloadRequest, Promise<T>>`. They now
  use `memoizeOnRequest`, which the project already has for exactly this — and
  which is strictly better here: it evicts a failed load so a later read in the
  same request can retry, where the WeakMap cached the rejection for the
  request's lifetime.
- `getRegionOwners` is no longer exported; `getCanonicalUrlBase` is its only
  caller.
- `audit-region-slugs.ts` tallied events with one `count` per blank region.
  One `events` query over the whole affected set, tallied in memory, instead.

Adds an integration test for `backfillBreadcrumbUrls` — it proves the
roots-only resave really does reach three levels down through the plugin's
cascade, that the path lookup then resolves, and that a second pass is a no-op.
The CLI wrapper around it stays unexercised locally (bootstrapping Payload hits
drizzle's interactive push prompt against a dev DB on another branch's schema).

Refs #634

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review raised both, and both turned out to be worth proving rather than
asserting.

The grandfather clause exists so the nested-docs cascade can re-save a
descendant that is already blank. Nothing tested that end-to-end — only the
validator in isolation. `region-blank-slug-cascade` plants a blank slug
through the DB adapter (the invariant is exactly what stops the normal path
creating one) and saves its ancestor. Removing the clause makes it fail with
the real production error: "Could not publish or save changes: One or more
children are invalid."

The backfill's roots-only strategy was flagged as skipping orphans — a region
whose parent id points at a deleted row. It can't: `regions_parent_id_regions_id_fk`
is ON DELETE **set null**, so deleting a parent promotes its children to roots.
The defensive filter I first wrote was unreachable, so it is gone; the FK
behaviour it assumed is pinned by a test instead, because the strategy is only
correct for as long as that holds.

Also folds the audit script's local crumbId into the shared relationId, and
records why the backfill loop is sequential (each root cascades through its
whole subtree — concurrent roots multiply into enough writes to exhaust the
pool).

Refs #634

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app

railway-app Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-637 environment in sahajcloud

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Web Aug 14, 2026 at 8:41 pm

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-637 August 14, 2026 20:39 Destroyed
@Ardnived
Ardnived deleted the branch feat/client-canonical August 19, 2026 17:31
@Ardnived Ardnived closed this Aug 19, 2026

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-637 — c8c9593b Deployed Aug 14, 2026 by railway-app[bot]
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