Skip to content

feat(core): content-references HTTP API (relation defs + entry edges) - #1535

Merged
ascorbic merged 7 commits into
emdash-cms:mainfrom
MA2153:content-references-api
Jul 9, 2026
Merged

ascorbic merged 7 commits into
emdash-cms:mainfrom
MA2153:content-references-api

Conversation

@MA2153

@MA2153 MA2153 commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds the HTTP API layer over the content-references repository — the third bottom-up slice after the schema (migration 043) and RelationRepository. Two surfaces:

  • Relation-definition CRUD under /_emdash/api/relations — manage relationship types (editor-readable via schema:read, admin-writable via schema:manage), treated as schema-like structural config.
  • Content-entry reference edges under /_emdash/api/content/:collection/:id/references/:relation/{children,parents} — attach/read directed references on a specific entry, ownership-aware like the taxonomy edge endpoint.

This is the trust boundary: Zod at the route, and the write-path invariants (relation-exists, collection-agreement, directed storage) the repository deliberately skipped. References are stored only in _emdash_content_references, keyed by translation_group — no ec_* column.

The final commit hardens the slice against a code review:

  • Create-path failures map precisely instead of flattening to 500 — bad translationOf → NOT_FOUND, name/locale collisions → CONFLICT, missing collections → COLLECTION_NOT_FOUND.
  • Edge reads resolve entries in one batched IN query (chunked) instead of N+1 per edge.
  • Edge reads are cursor-paginated (?cursor/?limit, default 50, max 100) returning nextCursor; the backlink (parents) side is genuinely unbounded, so this matters. Bad cursors → INVALID_CURSOR.
  • Each resolved entry ref carries the locale of the variant returned, so the variant fallback is explicit rather than a silent wrong-locale substitution.
  • content:edit_own is gated before the existence lookup on POST children to close an existence-oracle.
  • Empty PATCH relation bodies are rejected with VALIDATION_ERROR.

Closes #

Type of change

Approved feature Discussion: #386

Part of the planned content-references effort tracked under the schema (#1367) and repository (#1444) slices.

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes — repo-wide typecheck has 5 pre-existing failures in packages/plugin-cli / src/plugins/* from an unbuilt @emdash-cms/plugin-types (build-order, unrelated to this PR); 0 new errors introduced by these changes.
  • pnpm lint passes — pnpm lint:json is clean for all files in this PR; the only remaining diagnostics are pre-existing in unrelated demo/template astro.config.mjs files.
  • pnpm test passes (targeted): relation/reference handler, route, and repository suites — 60 tests green.
  • pnpm format has been run
  • I have added/updated tests for my changes
  • User-visible strings in the admin UI are wrapped for translation — n/a, no admin UI in this slice; server error messages are English-only and mapped to localized strings client-side by code.
  • I have added a changeset (emdash, minor)
  • New features link to an approved Discussion: Complete the reference field: collection picker in schema editor + content picker in content editor #386

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 4.8 (Claude Code)

Screenshots / test output

Test Files  4 passed (4)
     Tests  60 passed (60)

@changeset-bot

changeset-bot Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1af449e

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 16 packages
Name Type
emdash Minor
@emdash-cms/cloudflare Minor
@emdash-cms/sandbox-workerd Patch
@emdash-cms/fixture-perf-site Patch
@emdash-cms/perf-demo-site Patch
@emdash-cms/cache-demo-site Patch
@emdash-cms/do-demo-site Patch
@emdash-cms/do-solo-demo-site Patch
@emdash-cms/admin Minor
@emdash-cms/auth Minor
@emdash-cms/blocks Minor
@emdash-cms/gutenberg-to-portable-text Minor
@emdash-cms/x402 Minor
create-emdash Minor
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@github-actions

github-actions Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

@github-actions

Copy link
Copy Markdown
Contributor

Scope check

This PR changes 1,516 lines across 13 files. Large PRs are harder to review and more likely to be closed without review.

If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs.

See CONTRIBUTING.md for contribution guidelines.

@github-actions github-actions Bot added the review/needs-review No maintainer or bot review yet label Jun 18, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@1535

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@1535

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@1535

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@1535

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@1535

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@1535

emdash

npm i https://pkg.pr.new/emdash@1535

create-emdash

npm i https://pkg.pr.new/create-emdash@1535

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@1535

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@1535

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@1535

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@1535

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@1535

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@1535

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@1535

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@1535

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@1535

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@1535

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@1535

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@1535

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@1535

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@1535

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@1535

commit: 1af449e

Adds relation-definition routes and handlers (list/create/get/update/delete/translations)
and content-entry reference edge routes for children and parents, with edge-read
hardening and error handling.
@MA2153
MA2153 force-pushed the content-references-api branch from 96936ca to b17ee59 Compare June 18, 2026 23:55
# Conflicts:
#	packages/core/src/database/repositories/content.ts
@ascorbic ascorbic added this to the 1.0 milestone Jul 9, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 9, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a well-scoped, architecture-faithful slice: it puts Zod validation and collection-agreement/ownership invariants at the HTTP boundary, keeps the repository focused on storage, adds batched group resolution to avoid N+1 reads, and includes solid dialect-agnostic tests. It matches the prior taxonomy edge pattern and respects draft-visibility rules.

I read the full diff, the changed routes/handlers/repository code, and cross-checked against packages/core/src/api/errors.ts, packages/core/src/api/openapi/document.ts, the taxonomy edge route, and RBAC permissions. No security or data-loss issues jumped out. The remaining items are completeness/consistency rather than blockers:

  • New relation/reference catch-all error codes (RELATION_*_ERROR, REFERENCES_*_ERROR) are not added to the central ErrorCode enum, so TypeScript consumers won't see them in the typed union.
  • The new public endpoints are missing from the generated OpenAPI document, even though analogous taxonomy endpoints are fully documented.
  • ContentRepository.findManyByIdOrSlug doesn't tolerate a missing content table the way findTranslationsForGroups does; if a referenced child collection is later dropped (schema deletion doesn't currently cascade to relation definitions), the POST children write path will 500 instead of returning a structured NOT_FOUND/COLLECTION_NOT_FOUND.

A couple of ordering/style notes are minor: the children route checks content:edit_own before requireDb, which differs from sibling routes; and createRelationBody still requires parentCollection/childCollection when translationOf is supplied even though the handler ignores them.

Overall the implementation is clean and the test coverage is good; the gaps above are polish.


Findings

  • [suggestion] packages/core/src/api/handlers/relations.ts:82

    Catch-all error codes introduced here (RELATION_CREATE_ERROR, etc.) are not added to the central ErrorCode enum in packages/core/src/api/errors.ts. Adding them keeps the typed union complete so clients can switch on them exhaustively.

  • [suggestion] packages/core/src/api/handlers/relations.ts:170

    New REFERENCES_GET_ERROR / REFERENCES_SET_ERROR codes are also missing from ErrorCode. The handlers here use raw strings instead of the enum, which is consistent with some older handlers but still leaves the canonical enum incomplete for this domain.

  • [suggestion] packages/core/src/api/openapi/document.ts:2323

    The new /_emdash/api/relations and /_emdash/api/content/{collection}/{id}/references/{relation}/{children,parents} endpoints are not included in the generated OpenAPI document. Taxonomy endpoints are documented in taxonomyPaths, so relations should get a matching relationPaths spread here and a new Relations tag to keep the spec complete.

  • [needs fixing] packages/core/src/database/repositories/content.ts:1120

    findTranslationsForGroups handles a missing collection table by returning [], but findManyByIdOrSlug has no such guard. If a relation's child collection is dropped after the relation is created, POST .../references/:relation/children will throw and 500 instead of returning a structured error. Consider wrapping the batch queries here and returning an empty map when isMissingTableError(error) is true, mirroring the read path.

  • [suggestion] packages/core/src/astro/routes/api/content/[collection]/[id]/references/[relation]/children.ts:59

    The route checks content:edit_own before requireDb. Sibling routes (taxonomy terms, single content) call requireDb first. While the end result is acceptable, reordering to match the established pattern makes DB-unconfigured errors surface consistently for all authenticated callers.

@MA2153
MA2153 marked this pull request as draft July 9, 2026 12:02
…plete relation error enum

findManyByIdOrSlug now returns an empty map on a missing content table
(mirroring findTranslationsForGroups), so setting references on a relation
whose child collection was dropped returns a structured NOT_FOUND instead
of a 500. Adds the RELATION_*/REFERENCES_* codes to the ErrorCode enum so
the typed union is complete for this domain.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@github-actions github-actions Bot removed the review/needs-review No maintainer or bot review yet label Jul 9, 2026
@MA2153

MA2153 commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in 0aa217d6.

Findings 1 & 2 (relation/reference error codes) — Added a Relations (content references) block to the ErrorCode enum in api/errors.ts with all eight codes (RELATION_LIST/CREATE/GET/UPDATE/DELETE/TRANSLATIONS_ERROR, REFERENCES_GET_ERROR, REFERENCES_SET_ERROR). All end in _ERROR, so they keep the 500 default mapping — no mapErrorStatus change. Handlers keep their raw-string literals as you noted is acceptable; the union is now complete.

Finding 4 (missing child-table guard) — Confirmed reachable: deleteCollection drops the content table but doesn't cascade to relation defs. Wrapped the batch queries in findManyByIdOrSlug to return an empty map on isMissingTableError, mirroring findTranslationsForGroups. POST …/references/:relation/children against a dropped child collection now returns a structured NOT_FOUND instead of a 500. Added a failing-first integration test (a child collection dropped after the relation is created yields NOT_FOUND, not a 500).

Finding 3 (OpenAPI docs) — Deferred out of this PR's scope.

Finding 5 (requireDb vs authz ordering) — Leaving as-is. Both GET and POST already check the permission first, and the POST has an explicit comment justifying auth-before-lookup. Moving requireDb above the perm check would make an unauthenticated caller against an unconfigured DB get a 500 instead of a 403 — the current order is marginally better on info-leak, so the consistency change is net-negative here.

@MA2153
MA2153 marked this pull request as ready for review July 9, 2026 12:07
@github-actions github-actions Bot added the review/needs-rereview New commits since the last review label Jul 9, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of PR #1535 (content-references HTTP API).

The author has addressed the prior review's most concrete gaps: the new RELATION_*/REFERENCES_* codes are now in the central ErrorCode enum, and ContentRepository.findManyByIdOrSlug tolerates a missing child collection table so POST .../references/:relation/children returns NOT_FOUND instead of 500 after a collection is dropped.

The approach remains sound: Zod at the route, invariants (relation existence, collection agreement, ownership) in the handler, batched group resolution for reads, cursor pagination on both forward and backlink edges, and explicit locale on resolved refs. Test coverage for the happy paths, auth/ownership, draft visibility, and cursor edge cases is solid.

Still open:

  • Parent-collection missing table still 500s. The new reference handlers resolve the anchor entry with content.findByIdOrSlug(collection, entryId). If the parent collection is dropped after the relation was created, this throws; the handler catch maps it to REFERENCES_GET_ERROR/REFERENCES_SET_ERROR (500). The symmetric child-side lookup was fixed; the parent side should be treated the same way (ideally by adding the same isMissingTableError guard to findByIdOrSlug that now exists on the new batch methods).
  • OpenAPI still omits the new endpoints. The public relation-definition and reference-edge routes are not documented in packages/core/src/api/openapi/document.ts, despite the taxonomy endpoints that inspired this slice being fully covered.
  • Schema still requires ignored fields for translations. createRelationBody requires parentCollection/childCollection even when translationOf is supplied, but the handler ignores those fields and inherits them from the source relation. Making them conditional would avoid confusing validation failures.

No security or data-loss concerns. The remaining items are completeness/consistency polish.


Findings

  • [needs fixing] packages/core/src/api/handlers/relations.ts:324

    Anchor entry lookup via content.findByIdOrSlug(collection, entryId) will throw if the parent collection's ec_* table no longer exists (e.g., the collection was deleted after the relation was created). The handler catch turns that into a REFERENCES_GET_ERROR/REFERENCES_SET_ERROR 500. The child-side batch lookup was already hardened in this PR; the parent lookup needs the same treatment. Either wrap/catch isMissingTableError here or add the guard to ContentRepository.findByIdOrSlug so it returns null, matching findTranslationsForGroups and findManyByIdOrSlug.

    A fix should include a reproducing test that drops ec_post and verifies the reference endpoints return NOT_FOUND instead of 500, mirroring the existing ec_page drop test.

  • [needs fixing] packages/core/src/api/handlers/relations.ts:444

    Same missing-table issue as the children path: content.findByIdOrSlug(collection, entryId) for the parents endpoint can throw no such table when the child-side collection has been dropped, leading to a 500 instead of a structured NOT_FOUND. Consistent handling with the child lookup is needed.

  • [suggestion] packages/core/src/api/openapi/document.ts:2323

    The PR exposes several new public endpoints (/_emdash/api/relations, /_emdash/api/relations/{id}, /_emdash/api/relations/{id}/translations, and /_emdash/api/content/{collection}/{id}/references/{relation}/{children,parents}) but they are still missing from the generated OpenAPI document. Taxonomy endpoints have a matching taxonomyPaths block that is spread at this line; relations should get an equivalent relationPaths block and a Relations tag to keep the spec complete.

  • [suggestion] packages/core/src/api/schemas/relations.ts:18

    createRelationBody still requires parentCollection and childCollection even when translationOf is provided, but the handler ignores those fields and inherits them from the source relation. This forces callers to supply valid collection slugs that are then discarded. Consider making those fields optional when translationOf is set, or documenting the requirement, so the schema matches the actual handler semantics.

@MA2153
MA2153 marked this pull request as draft July 9, 2026 12:28
…es; relax translation relation schema

findByIdOrSlug now returns null on a missing content table (matching
findManyByIdOrSlug and findTranslationsForGroups), so the reference
children/parents endpoints return NOT_FOUND instead of 500 when the anchor
entry's collection was dropped after the relation was created.

createRelationBody no longer requires parentCollection/childCollection when
translationOf is set — a translation inherits its structural fields from the
source relation, so those values were previously required only to be ignored.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@MA2153

MA2153 commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in 1af449ec.

Findings 1 & 2 (parent/child anchor collection dropped → 500) — Hardened the shared _findByIdOrSlug to return null on isMissingTableError, matching its sibling methods findManyByIdOrSlug and findTranslationsForGroups. This covers all three anchor lookups (children GET, children SET, parents GET) and also the route-level ownership lookup in children.ts, which a handler-only guard would have missed. Added a reproducing test that drops ec_post (and ec_page for the parents side) and asserts NOT_FOUND rather than 500. Confirmed no existing test relied on the throw.

Finding 4 (schema requires ignored fields for translations) — createRelationBody now makes parentCollection/childCollection optional with a refine that requires them only when translationOf is absent. Threaded through CreateRelationInput (both now optional), with a narrowing guard in handleRelationCreate and an explicit else-branch in RelationRepository.create that throws if a base relation omits them (the columns are NOT NULL). Added repo tests for both the omit-on-translation success path and the missing-on-base failure path.

Note: name has the same characteristic — it's required by the schema but inherited from the source when translationOf is set. I left it as-is to keep this change scoped to the fields you flagged; happy to relax it too if you'd like consistency.

Finding 3 (OpenAPI docs) — Still deferred out of this PR's scope.

@MA2153
MA2153 marked this pull request as ready for review July 9, 2026 12:34

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of PR #1535. The author has addressed the prior review's concrete blockers: the new reference handlers now surface NOT_FOUND (not 500) when a content table is dropped, because ContentRepository.findByIdOrSlug was hardened to catch isMissingTableError and return null; the test suite adds the symmetric parent-collection drop case; and createRelationBody no longer requires parentCollection/childCollection when translationOf is supplied.

The implementation remains sound: Zod validation at the route, collection-agreement and ownership checks in the handler, batched group resolution for reads, cursor pagination on both forward and backlink edges, and explicit locale on resolved refs. I read the updated handler, routes, schemas, repository changes, and tests statically; I did not run the test suite or linter.

One prior suggestion is still open: the public OpenAPI document does not yet cover the new relation-definition or reference-edge endpoints, despite the taxonomy surface that inspired this slice being documented. No new security, data-integrity, or convention issues were introduced by this revision.


Findings

  • [suggestion] packages/core/src/api/openapi/document.ts:2323

    The PR exposes several new public endpoints (/_emdash/api/relations, /_emdash/api/relations/{id}, /_emdash/api/relations/{id}/translations, /_emdash/api/content/{collection}/{id}/references/{relation}/children, and /_emdash/api/content/{collection}/{id}/references/{relation}/parents) but they are still missing from the generated OpenAPI document. Taxonomy endpoints have a matching taxonomyPaths block that is spread at this line, and a Taxonomies tag; relations should get an equivalent relationPaths block and a Relations tag to keep the public spec complete.

    		...taxonomyPaths,
    		...relationPaths,
    

    and add { name: "Relations", description: "Content reference relation definitions and entry edges" } to the tags array at the bottom of the document.

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-rereview New commits since the last review labels Jul 9, 2026

@ascorbic ascorbic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@ascorbic
ascorbic merged commit 0360900 into emdash-cms:main Jul 9, 2026
46 of 47 checks passed
@emdashbot emdashbot Bot mentioned this pull request Jul 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core bot:review Trigger an emdashbot code review on this PR cla: signed review/awaiting-author Reviewed; waiting on the author to respond size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants