Content, Search & Events (content.ts)
Reference for global content operations — versioning, structure management, global search, query-param filtering, real-time events, and GraphQL.
On this page
The Content API manages the structural and cross-collection aspects of SveltyCMS. It handles content versioning, global search, real-time event streams (SSE), and serves as the gateway for the GraphQL API.
⚡ Quick Reference
| Feature | HTTP Endpoint | Method | Permission Required |
|---|---|---|---|
| Get Version | /api/content/version |
GET |
Public |
| Get Structure | /api/content-structure |
GET |
collection:read |
| Global Search | /api/search |
GET |
collection:read |
| SSE Events | /api/content/events |
GET |
collection:read |
| SSE (alias) | /api/events |
GET |
collection:read |
| GraphQL API | /api/graphql |
POST |
collection:write |
Permission ids in this table are the namespaced API route vocabulary, authorized fail-closed against ENDPOINT_PERMISSIONS in src/routes/api/[...path]/+server.ts (the graphql entry maps GET ⇒ collection:read, everything else ⇒ collection:write). Admin UI tiles resolve through their own map (src/routes/(app)/config/config-tile-permissions.ts), which points at real PERMISSION_CATALOG ids (system:admin for admin-only pages) — the two contracts are separate.
1. Structure & Versioning
Content Versioning
SveltyCMS maintains a global version counter that increments on every structural or content change. Use this to trigger cache invalidation in external apps.
Endpoint: GET /api/content/version
Content Structure
Retrieve or modify the tree-like structure of your collections and folders.
- GET: Returns the full hierarchy of content nodes.
- POST: Used for reordering nodes (action:
reorderContentStructure) or force-refreshing the collection registry (action:refresh).
2. Global Search
Search across multiple collections simultaneously using the unified search engine.
Endpoint: GET /api/search?q=query_text
Parameters:
type: Comma-separated list of collections (default: all).status: filter by status (default:published).page/limit: Standard pagination.
2b. Collection List Query Params (SSR + entry-list) {#2b-collection-list-query-params-ssr—entry-list}
Per-collection view mode lists are driven by URL query parameters on the admin collection route
(/(app)/[language]/[...collection]). The page loader parses params, whitelists field names
against the collection schema, then loads via LocalCMS.collections.find (or CollectionsNamespace.find) (L1/L2 SWR).
| Param | Purpose | Client source |
|---|---|---|
search |
In-collection text search (searchable schema fields + system ids; LIKE/$regex) |
TableFilter / globalSearchValue |
page / pageSize |
Pagination | TablePagination |
sort / order |
Sort field + asc | desc |
Header click |
filter_{fieldName} |
Per-column filter value | createSmartFilter / SmartFilterRow |
edit |
Entry id for edit-mode load (full multilingual row) | Mode / URL |
Parsing & security
// +page.server.ts
import { parseCollectionListQuery } from "@utils/collection-query-filters.server";
const listQuery = parseCollectionListQuery(url.searchParams, currentCollection);
// listQuery.filter → only schema-allowed keys (whitelist)
// listQuery.queryHash → stable hash for cache keys
await locals.cms.collections.find(String(currentCollection._id), {
collection: currentCollection,
page: listQuery.page,
pageSize: listQuery.pageSize,
sort: listQuery.sort,
filter: listQuery.filter, // { field: { contains: "value" } }
search: listQuery.search,
language,
user: typedUser,
tenantId,
});
| Rule | Detail |
|---|---|
| Never trust client field names | whitelistFilterParams drops unknown keys before the DB layer |
| Operator shape | Adapter-agnostic { contains: string } today; range ops can extend without changing URL prefixes |
| Tenant isolation | CollectionsNamespace.find injects tenantId into the final filter when multi-tenant is enabled |
| Cache | Keys include query:{hash} so each filter/search combination is a distinct L1/L2 entry; mutations call invalidateCollection(id) |
Global search vs column filters
| Mode | Scope | Param | Backend |
|---|---|---|---|
| Global search (cross-collection) | Many collections | GET /api/search?q= |
Unified search engine |
| In-collection search | One collection list | ?search= |
QueryBuilder .search() on schema fields |
| Column filters | One field | ?filter_{name}= |
QueryBuilder .where({ field: { contains } }) |
UI: entry-list · Platform: collection-filtering · Cache: cache-system
3. Real-Time Events (SSE)
SveltyCMS broadcasts structural content changes using Server-Sent Events (SSE). Authenticated admin sessions connect to receive normalized update payloads; the CMS admin UI uses this to refresh the content tree without a full page reload.
Primary endpoint: GET /api/content/events
Alias: GET /api/events
Permission: collection:read (session cookie required)
Wire format
Internal eventBus events (e.g. content:update) are normalized before streaming:
{
"type": "content_update",
"event": "content:update",
"version": 1718457600000,
"tenantId": "all",
"timestamp": 1718457600123
}
Tenant-scoped subscribers only receive events where tenantId matches their context, or where tenantId is "all" (broadcast).
Client integration
The built-in admin client (content-sse.svelte.ts) listens for type: "content_update" and calls contentSystem.refresh(), which fetches the latest structure from GET /api/content-structure?action=getStructure and syncs the reactive store.
const events = new EventSource("/api/content/events", { withCredentials: true });
events.onmessage = (e) => {
const data = JSON.parse(e.data);
if (data.type === "content_update") {
// Refetch structure or invalidate SvelteKit loaders
console.log(`Content tree changed (v${data.version})`);
}
};
4. GraphQL API
While GraphQL is the primary mechanism for structured querying, we have separated its reference into its own dedicated documentation page.
For comprehensive details on schema definitions, mutations, queries, and subscriptions, please see:
5. HTTP Write Bridge (http-bridge.ts)
HTTP collection write endpoints (POST /api/collections/{id}, PATCH /api/collections/{id}/{entryId}) and the write lane pass incoming payloads through src/services/sdk/namespaces/collections/http-bridge.ts before delegating to LocalCMS.collections:
Write Payload Unwrapping (unwrapWritePayload)
Historical admin list/edit forms wrapped write payloads in { data: Record<string, unknown>, tenantId?: string }. To preserve compatibility with external API consumers sending flat payloads while safely handling legacy wrappers, unwrapWritePayload:
- Inspects top-level payload keys.
- If and only if
datais an object and no other keys exist (besides optionaltenantId), unwraps and returnsraw.data. - If extra keys exist (e.g. custom top-level fields or real collection fields named
data), the payload is preserved as-is without data loss.
Optimistic Locking (extractExpectedVersion)
To prevent concurrent overwrite anomalies in collaborative editorial workflows, SveltyCMS enforces version checks:
- Inspects
If-Matchheader first (standard HTTP ETag semantics). - If absent, inspects body field
expectedVersion(and strips it from the payload to prevent accidental schema column persistence). - If absent, checks query parameter
?expectedVersion=. - Passes the extracted version token to
cms.collections.update/cms.drafts.promoteDraft. If the existing record’s_versiondoes not match, a409 Conflictis returned.
Draft Promotion (promoteStagedDraft / isPublishWrite)
When an editor performs a publish action (status is publish or published via isPublishWrite):
promoteStagedDraftverifies whether the current user has a staged draft incontent_drafts.- If a staged draft exists, it is promoted directly to the live row via
cms.drafts.promoteDraftwith optimistic version validation, ensuring in-progress form edits match the staged draft. - If no draft exists (
null), the operation continues normally writing the submitted payload.
Minimal Return Acknowledgments (minimalWriteAck, RFC 7240)
For high-frequency write operations, callers can specify the standard RFC 7240 Prefer: return=minimal header:
prefersMinimalReturn(event)detects the header.- Instead of re-reading and serializing the complete document entity over the wire,
minimalWriteAckresponds with status200 OK(or201 Created) containing only{"_id":"<id>"}and headerPreference-Applied: return=minimal. - Saves serialization CPU time and payload bandwidth on bulk/batch write paths.
Related Documents
- Collections Reference (collections.ts)
- entry-list / createSmartFilter
- Cache System (L1/L2, SWR, prefix invalidation)
- Data Operations — content import/sync must invalidate collection caches
- Media Management (media.ts)
- System Reference (system.ts)