Relatude.DB.CMS 1.1.1.9-alpha

This is a prerelease version of Relatude.DB.CMS.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Relatude.DB.CMS --version 1.1.1.9-alpha
                    
NuGet\Install-Package Relatude.DB.CMS -Version 1.1.1.9-alpha
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Relatude.DB.CMS" Version="1.1.1.9-alpha" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Relatude.DB.CMS" Version="1.1.1.9-alpha" />
                    
Directory.Packages.props
<PackageReference Include="Relatude.DB.CMS" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Relatude.DB.CMS --version 1.1.1.9-alpha
                    
#r "nuget: Relatude.DB.CMS, 1.1.1.9-alpha"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Relatude.DB.CMS@1.1.1.9-alpha
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Relatude.DB.CMS&version=1.1.1.9-alpha&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Relatude.DB.CMS&version=1.1.1.9-alpha&prerelease
                    
Install as a Cake Tool

Relatude.CMS

A .NET 8 content backend layered on Relatude.DB, an in-process object-oriented graph database (NuGet Relatude.DB.Server). You model your domain as C# interfaces (the engine generates the implementing classes), declare relationships as small marker classes, and read/write through a NodeStore. Provides the base content model (IItem, IPage, ISite, ITemplate), pluggable content rendering (MVC, Razor Pages or any IResult), and DB access plumbing.

Using an AI coding agent? This package ships a Claude Code skill (relatude-cms) with the same guidance below. The commerce layer is documented in Relatude.Ecom (relatude-ecom skill), which builds on this one.

Host setup (Program.cs)

Relatude.DB runs in-process inside an ASP.NET Core app:

var builder = WebApplication.CreateBuilder(args);
builder.AddRelatudeCMS()          // Relatude.DB, CMS settings, analytics and content routing
    .AddMvcRendering()           // MVC views and controllers; AddRazorPagesRendering() adds Razor Pages
    .AddRendering(o => o.RenderRazorView<IArticle>());  // code defaults: what renders a type without a template
builder.AddRelatudeDB(o => o.OnDatamodelInit = (dm, _) => dm.AddCmsContentModel());  // optional, before or after: one ServerOptions

var app = builder.Build();
app.UseRelatudeCMS();             // starts the engine (admin UI at /relatude.db) and the analytics middleware
app.MapRelatudeCMS();         // content URLs to what renders them, see Content rendering
app.Run();

The schema (datamodel) is managed through the admin UI at /relatude.db, where you point a datamodel source at the assembly/types holding your model interfaces, or registered in code: builder.AddRelatudeDB(o => o.OnDatamodelInit = (dm, _) => dm.AddCmsContentModel()).

Getting a NodeStore

NodeStore (namespace Relatude.DB.Nodes) is the entire data API. In a request, inject RelatudeCmsContext (Relatude.DB.CMS.Web, scoped): .Db is the store as the visitor (the signed-in user's read access, the request's culture, published content only), .Admin the store as the master admin for trusted code, and beside them User, UserId, CultureCode, Url, Node, Content, Render and GetUrl(node). Code with no request injects IRelatudeDBAccessor (Relatude.CMS.Engine) and uses .Database, or reads RelatudeDBRuntime.Database where there is no DI. Authentication is the host's; the CMS reads the signed-in user's node id from the NameIdentifier claim (which CmsPrincipal.For(user, scheme) writes), else finds the user by the Email claim (a sign-in for a user the store does not have, such as a cookie from before the database was seeded again, reads as anonymous), and a page the visitor may not read redirects to login, or answers 403 once signed in (AddRelatudeCMS(o => o.LoginRedirect = false) turns that off). Convention: methods that touch data take NodeStore db as a parameter rather than capturing it.

Modeling: interfaces, not classes

An entity is an interface extending IItem (and usually IPage for routable content):

public interface IPage : IItem {
    string MetaTitle { get; set; }
    string MetaDescription { get; set; }
    Reference<ITemplate> Template { get; set; }     // the page's template, or none
}

IItem gives every node Guid Id, string Name, NodeMeta Meta (Meta.Address is the URL slug). IPage adds SEO metadata, a Template reference, and its place in the page tree: Parent and Children, the ends of RTree, which the URL manager (named among its URL parents) and the CMS interface's content tree follow. A page type declares no Parent or Children of its own: the datamodel refuses a property declared twice in a hierarchy. A type's icon, which the CMS interface shows it with, is [Node(Icon = "lucide:house")]: a name of Relatude.DB's icon library or SVG source; the CMS's own types have Fluent colour icons (IPage, ITemplate, ICMSUser, ICmsUserGroup, IDonation), which a site's types inherit unless they set their own. Other base types: ISite, ITemplate and its kinds (see Content rendering), ICountry, ICMSUser, ICmsUserGroup.

Relations are declared as classes deriving from OneToMany<,>, ManyToMany<,>, OneToOne<,>, OneOne<>, or ManyMany<>, with nested marker classes naming each end. The CMS's page tree is one:

public class RTree : OneToMany<IPage, IPage> {
    public class Parent : One { }     // exposed on IPage as RTree.Parent Parent
    public class Children : Many { }  // exposed on IPage as RTree.Children Children
}

OneToMany<TOne,TMany> exposes One/Many; ManyToMany<TFrom,TTo> exposes ManyFrom/ManyTo; OneToOne<,> exposes OneFrom/OneTo. Attributes (Relatude.DB.Nodes) tune mapping: [Node(...)] on the interface, [Exclude], and per-type property attributes ([StringProperty], [IntegerProperty(Indexed=true, UniqueValues=true)], [DecimalProperty], [GuidProperty], …). Embedded value maps use [EmbeddedMapProperty(KeyProperty = ...)].

Relation ends are objects, not plain collections:

if (page.Parent.IsSet()) { … }            // One: has value? / Many: Count() > 0
var parent = page.Parent.Get();             // One → T (throws if not set; guard first)
page.Parent.TryGet(out var parent);         // safe variant
foreach (var child in node.Children.Get())  // Many → IEnumerable<T>

In queries prefer Include(...) over lazy .Get() to avoid N+1.

CRUD through NodeStore

var page = db.Create<IPage>();             // in-memory, NOT yet persisted
db.Insert(page);                            // or CreateAndInsert<IPage>(p => { ... })
db.Update(existing);                        // UpdateOrFail / UpdateIfExists / Upsert / ForceUpsert
db.Delete(node);                            // also Delete(Guid id) / Delete(IEnumerable<Guid>)
var p = db.Get<IPage>(id);                  // throws if missing
db.TryGet<IPage>(id, out var page2);        // safe
bool exists = db.Exists<IPage>(id);

Relations are set/cleared as their own operations (property-selector lambda):

db.SetRelation(page, p => p.Template, templateId);  // one-end: replaces
db.AddRelation(template, t => t.Pages, page);        // add to many-end
db.RemoveRelation(template, t => t.Pages, page);     // remove one link
db.ClearAndSetRelation(node, x => x.Many, newSet);   // replace whole set

Write methods accept flushToDisk (default false) and have …Async counterparts. Mutating a property on a loaded node still requires an Update call to persist.

Querying

db.Query<T>() returns IQueryOfNodes<T,T> — fluent and expression-based; nothing runs until a terminal call:

var results = db.Query<IPage>()
    .Where(p => p.MetaTitle != null)
    .Include(p => p.Template)            // eager-load; ThenInclude to go deeper
    .OrderBy(p => p.Name)
    .Page(0, 20)                          // pageIndex0based, pageSize (or Take/Skip)
    .Execute();                           // ResultSet<IPage>; .ToList()/.ToArray() also

var one  = db.Query<IPage>().Where(p => p.Meta.Address == slug).FirstOrDefault();
long n   = db.Query<IPage>().Count();

Also: WhereSearch/Search (BM25 + optional semantic/vector), WhereRelates/WhereNotRelates/WhereRelatesAny, WhereIn, WhereTypes, Facets(), Sum(...), SelectId(), a string-based Where("a => …") overload, and db.TryParseUrl(url, out var keys) for URL → node through the store's URL manager (what content rendering uses; db.TryGetFromAddress<T>(address, out var node) is a raw address lookup that bypasses the manager). Query context controls culture/visibility/revisions: db.Context.Culture("nb-NO").Hidden().Admin().Create(). Default queries exclude hidden nodes.

Transaction plugins (triggers)

Cross-cutting node behavior goes in a plugin. Derive NodeTransactionPlugin<T>, override OnBeforeNodeAction / lifecycle hooks, register with db.RegisterTransactionPlugin(...). Example: Relatude.Ecom's ShopTemplateSetterPlugin : NodeTransactionPlugin<IProduct> sets each product's address on upsert with transaction.UpdateAddress(key, RelatudeUrlHelper.ToUrlSlug(name)). Switch on the NodeOperation enum (Upsert, Insert*, Update*, ForceUpsert, Delete*). A write comes as a whole node (OnBeforeNodeAction) or as some of its properties (OnBeforePropertyAction), which is how the CMS API's update and the CMS interface save, so a rule about values checks both. A module registers one with TransactionPlugin<T>() (see Modules).

Content rendering (Relatude.DB.CMS.Web.Rendering)

Rendering a URL takes three steps:

  1. Resolve. ContentResolver finds the node the URL addresses through the store's URL manager (db.TryParseUrl), so base paths, domains, parent-chain URLs and cultures route the way the manager builds them. The result is a ContentMatch: the node, its template or its type's code default, and the culture the URL matched. ContentResolver takes the URL apart once per request, and a file URL is served by the same routes: MapRelatudeCMS() answers files and adjusted files (resized images, converted video) through Relatude.DB's FileHandler, range requests included, read as the visitor, so read access applies to files too. Override ContentResolver.Resolve to find content another way, such as preview links, and call Match(node) to give the node its template or code default.
  2. Select. The first answer wins: selectors added with o.Select(...), in order; for a page with a template, the template's kind; for content without one, the code default for its type, then, with o.ViewPerType(), the view named after its type.
  3. Dispatch. The adapter for the target's rendering system serves it:
Target Adapter Rendered by
RazorViewTarget(view) AddMvcRendering() RelatudeContentController, with the node as the view's model
MvcControllerTarget(controller, action, area) AddMvcRendering() the host's controller action
RazorPageTarget(page, area) AddRazorPagesRendering() the Razor Page
ResultTarget((http, match) => IResult) always mapped any IResult: Blazor SSR's RazorComponentResult, JSON, a template engine

Templates. IPage.Template is a Reference<ITemplate>. A template's kind is its node type:

Kind Renders with
ITemplate only a selector, o.Select(...)
IRazorViewTemplate RazorViewTarget(ViewName)
IMvcControllerTemplate MvcControllerTarget(Controller, Action), a blank action meaning Index
IRazorPageTemplate RazorPageTarget(PagePath)

NodeTypes lists the node type ids the template is for, their subtypes included; an empty list means every type, as the last choice. The CMS pins its type ids with [Node(Id = …)]; pin a site's own types too, since an unpinned id comes from the full name.

builder.AddRelatudeDB(options => options.OnDatamodelInit = (dm, _) => {
    dm.AddCmsContentModel();                   // IItem, IPage, ISite, ITemplate and the template kinds, and the engine's own models they build on
    dm.AddNamespace<IArticle>();               // the site's own node types
});
builder.AddRelatudeCMS()                       // after AddRelatudeDB
    .AddMvcRendering().AddRazorPagesRendering()   // MVC + Razor Pages
    .AddRendering(o => o
        .Select((http, m) => http.Request.Query["view"] == "print" ? new RazorViewTarget("Print") : null)
        .Select((http, m) => m.Content is IArticle { Body.Length: > 20_000 } ? new RazorViewTarget("ArticleLong") : null)
        .RenderRazorView<IHomePage>("Home")         // code defaults, for content without a template
        .RenderRazorView<IProduct>(p => p.InStock ? "Product" : "SoldOut")
        .RenderMvcController<ISection>("Section")
        .RenderRazorPage<ILandingPage>("Landing")
        .RenderRazorView<IPage>("Default")          // any other page
        .TemplateKind<IJsonTemplate>(t => new ResultTarget((http, m) => Results.Json(new { m.Content.Name }))));

var app = builder.Build();
app.UseRelatudeDB();
app.UseRelatudeCMS();
app.UseStaticFiles();
app.UseRouting();                             // after the static files, so a file request never looks for content
app.MapRelatudeCMS();                     // pattern "{**url}" by default
  • Code defaults say what renders content of a type and its subtypes that has no template, with no template in the database: RenderRazorView<T>(view) (no name: the type's name without its leading I, so IArticle gives Article), RenderRazorView<T>(node => view), RenderMvcController<T>(controller, action), RenderRazorPage<T>(page) (with or without the leading /), RenderResult<T>((http, node) => IResult), and Render<T>(target) / Render<T>(node => target) for anything else. They work for any IItem. Defining a type again replaces it; a per-node default returning null leaves the content unrendered. o.ViewPerType(), off by default, renders whatever is left with the view named after its type.
  • Templates render by their kind, and a page without a template gets the closest one by type. Templates and code defaults compete by distance from the page's type: the type itself, else its nearest base type. A template as close as a code default wins over it, so editors can take over a type with a template that lists it; a template listing no types is the last choice, after every code default. Two equally close templates are ambiguous, which is the usual case for layout variants (article and article-wide both for IArticle), so pages of such a type choose their template; two equally close code defaults (a type deriving from two interfaces) are ambiguous too, settled by a default for the type itself.
  • Checks. A page whose template is not for its type throws on request, as does content of a type with equally close code defaults, and so do an ambiguous page without a template and a plain template no selector rendered. Saving such pages is refused (on update; CreateAndInsert inserts empty first), through plugins a Relatude.DB IStoreInitializer service registers on every store, whatever order the setup calls come in. A check logged when the store opens, and after templates change, reports views, controller actions and Razor Pages that code defaults name but that do not exist, code defaults for types not in the datamodel, ambiguous types, the names in templates, plain templates when no selector is added, and unknown node types. A default decided per node is not checked up front.
  • Full control. Selectors decide before everything, templates included; to override one template, test m.Template (its Name or Id) in a selector. o.TemplateKind<T>(t => ...) adds a kind of the host's own, asked before the built-in ones. AddMvcRendering() and AddRazorPagesRendering() add the rendering systems a site uses; AddRendering(o => ...) holds the code defaults, selectors and kinds, and every call adds to the same options.
  • Reading the content. Bind it as a parameter, public IActionResult Index([FromContent] IArticle article) (a ContentMatch parameter gets the whole match, including TemplateByType and TypeDefault), or call HttpContext.GetContent<IArticle>() / GetContentMatch() from anywhere. Resolution and selection run once per request, lazily, whoever asks first. [FromContent] skips validation, which would read every related node.
  • Rendering is optional. Without MapRelatudeCMS() nothing is routed, and GetContent<T>() still works.
  • Explicit routes win. The content routes are catch-alls, so every explicit route of the host beats content at the same path. A URL with no content, or a page with nothing to render it, falls through to the host's MapFallback or a 404.
  • Controllers must be conventionally routed. No [Route], no [ApiController]: dynamic routes cannot reach attribute-routed actions.
  • Outbound URLs come from the store. db.GetUrl(page) goes through the same URL manager.
  • Composing with another router, such as a legacy CMS: call ContentResolver.GetRender(http) and MvcContentRouteTransformer.TrySetRouteValues(target, values) from your own transformer.

Website2 in the repository is a complete example: a page tree with articles and products, code defaults for every page type, two article templates editors choose between, selectors, and a menu built from the tree.

RelatudeUrlHelper.ToUrlSlug(name) (Relatude.CMS.Engine.Web) makes a URL slug from a name (lower case, æ/ø/å and diacritics transliterated). The store makes it unique when it is saved as an address.

The full manual is docs/manual.md in the repository (rendered as docs/manual.html).

CMS settings and analytics (Relatude.CMS.Settings, Relatude.DB.CMS.Web.Analytics)

builder.AddRelatudeCMS() registers the CMS's own settings, CmsSettings, as a Relatude.DB custom settings set: a CMS tab beside each database's settings in the admin UI, read from code as db.Settings.Get<CmsSettings>(). It is layered like every custom setting: relatude.settings/cms.json (SHARED), the admin UI's saves (THIS SERVER), then RelatudeDB:CustomSettings:cms in appsettings. Its groups are Analytics, Modules and Interface plugins (see Modules); more CMS settings go in the same class.

builder.AddRelatudeDB();
builder.AddRelatudeCMS();
var app = builder.Build();
app.UseRelatudeDB();
app.UseRelatudeCMS();            // analytics: after UseRelatudeDB, before the site's pages and static files

Analytics is off until turned on (CMS > Analytics > Record page views). Then:

  • Every page view is recorded in the custom log cms-pageviews ("Page views" under Logs in the admin UI, with graphs from its statistics): path, host, referrer host, visitor hash, visitor type (human, bot, unknown), bot name, country, region, city, position, browser, operating system, device, language and duration. A page view is a GET answered 200 with HTML. The admin UI, /-info/, the paths in ExcludedPaths and prefetches are never page views.
  • The log is the database's once it is made. It is created when it is missing - the first time analytics is on, and again if it is deleted in the admin UI. After that, changes made in the admin UI (retention, columns taken out, statistics, switches) are kept. The code only adds columns: each column in PageViewLog carries the DefinitionVersion that introduced it, and the database's storage remembers the version its log has (cms/pageviews-log.json). When the CMS is newer, the columns added since are put into the log if missing, once; a column removed afterwards stays removed. A log made before this file existed counts as version 1. To add a column, give it the next version and raise DefinitionVersion.
  • Nothing happens while the visitor waits. The middleware only queues the page view (PageViewQueue). AnalyticsWorker, a hosted service, waits LookupDelaySeconds (5) for the browser's bot check to report, looks the visitors of a batch up at once with db.Services.IPLookup (once per address and user agent; settled verdicts are kept for 10 minutes), and records the entries. A failed lookup records the page views without it and warns once per 10 minutes.
  • The bot check is added to every HTML page just before its last </body>, as the CMS's HtmlRewriter finds it (InjectBotCheck, InlineBotCheck). Only an uncompressed UTF-8 HTML 200 of at most 16 MB is held to do it; everything else streams through untouched. Call UseResponseCompression() before UseRelatudeCMS(), if at all.
  • No cookie and no address are kept (GDPR). The visitor is the daily visitor hash, SHA-256(IP + User-Agent + Language + daily salt) (DailyVisitorHash). The salt is 32 random bytes per UTC day, held in memory only and never written, so a hash cannot be traced back or linked across days. A process restart starts a new salt, so a visitor seen on both sides of it counts twice that day. The referrer is only its host, and the query string is left out unless LogQueryString is on.
  • IAnalyticsHost is the database side (settings, custom logs, the database's storage, IP lookups, reserved paths). The default is RelatudeAnalyticsHost, the default database's; tests replace it.
  • Behind a proxy, call app.UseForwardedHeaders() first, so the address hashed and looked up is the visitor's.

CMS API (Relatude.DB.CMS.Api)

The NodeStore over HTTP, for a CMS interface and its plugins: the same architecture as the Relatude.DB admin UI, one command endpoint and one event stream, with a bearer token naming the user every request runs as. The TypeScript side is @relatude/sdk (Relatude.CMS.UI/packages/sdk, db export): a typed query builder and a RelatudeStore with the NodeStore's methods. The CMS interface in Relatude.CMS.UI runs on it, signing in through auth/login or the site's cookie (auth/session).

builder.AddRelatudeCMS().AddApi(o => {
    o.VerifyLogin = (login, cms) => Task.FromResult(Members.Verify(cms.Admin, login.UserName, login.Password)?.Id);  // the site's own password check
    o.Authorize = (ctx, command) => true;      // the hook for access control per command; false answers 403
});
app.MapRelatudeCmsApi();                       // before MapRelatudeCMS()
app.MapRelatudeCmsUI();                        // the CMS itself at /relatude.cms/ (below)
  • Routes under CmsApiOptions.Path ({UIPath}/api unless set, so /relatude.cms/api): POST command with { type, payload, runId? }, GET stream (SSE), POST upload?id=&property=&name=&context= (the file as the body, into the revision the read context names, sent as JSON in context; answered with the file as the user now reads it), and POST auth/login ({ userName, password }, checked by VerifyLogin; 404 without it), auth/session (a token for the user the site's own cookie signs in, SessionTokens), auth/refresh. Errors are { error } with 400/401/403/404/500; a command stopped with command-cancel (its runId) answers 499.
  • Tokens (ICmsApiTokens, default DataProtectionCmsApiTokens) are sealed with ASP.NET Core data protection and last TokenLifetime (12 h). A token of a user deleted since is refused. Without a persisted key ring every restart signs everyone out. AllowAnonymous serves token-less callers as the anonymous visitor, read-only commands only.
  • Reads run as the user (CmsApiContext.Db/QueryContext): a payload's context ({ culture, cultureFallback, edit, hidden, links }) picks the culture and edit view (unpublished nodes too, edit-view access applied); links: "stored" reads HTML and Markdown as the store keeps them, their links to the site rdb: link tokens by id rather than URLs, so an editor writing back what it reads keeps every link by id (the CMS interface reads so). get and exists go through a query, since a read by id ignores read access. Writes are open to any signed-in user for now: they are TransactionData run by NodeStore.Execute, so the store's transaction plugins run as for C# writes. Put access rules in Authorize until the engine checks writes itself.
  • Commands: whoami (the user's id, name, email and groups, and admin: a user node of the type Admin, who may design the interface's forms), schema (each type's own and inherited properties: kind, string type, enum values, relation targets, how a property holding nodes is shown (display, Relatude.DB's DisplayMode) and an embedded one's innerTypes, and defaultValue, what a node of the type gets when the property is given nothing (null for a file and a property holding nodes), which the editor gives a new inner node; the display name property; the name property (nameProperty, Relatude.DB's [Node(NameProperty = ...)], its own or the closest base type's; the CMS's IItem names Name), which the editor shows at the top of a node's form; the type's form layout when one is designed; and the type's icon as SVG, its own or the closest base type's, made by Relatude.DB's icon library from the model's [Node(Icon = "set:name")] or SVG source), commands, query ({ query, parameters: [{ name, type, value }] }, the query language with typed parameters - decimal, datetime, guid[], …), get, exists, count, get-related, get-url, parse-url (the page a URL addresses), content-link ({ id, property?, adjustment? }: { link, url }, the stored link to a node, or to a file of it resized by the adjustment, to put in HTML; an adjustment the store cannot make, as of an SVG, is left out), content-links ({ links }: what each stored link points at as the user reads it, { link, url, kind, id, type, name, property, width, height, missing, restricted }, width and height those a picture is resized to; a deleted target is missing with the URL #, one the user may not read restricted and unnamed), node-meta ({ id }: what the store keeps beside the values - address and URL, created and changed by, revision, culture, collection, the four access groups with the one that applies and where it comes from and the one that would without the node's own, release and expiry; groups and users named where the user may read them), meta-choices (what a node's access groups and collection can be set to: the engine's groups, then the groups and collections the user reads), tree and tree-path (a one-to-many relation as the content tree: RTree unless the CMS setting Content.Tree names another; when sites (ISite) can be in it, one site's tree, the site root or the first by name, answered with sites and root, and tree-path says which site a node is in; a page with ShowInTree off (indexed) is left out, and what is below it with it, unless hidden asks for them, marked $hidden; $children counts the children shown), tree-move and tree-copy ({ id | ids, parent? | before? | after?, children? }: a node, with its branch or alone, or several (ids, together, each with its branch), into a parent, beside a sibling or to the top, where in a tree of sites only a site goes; one node moved beside itself without its children lifts them out beside it, and a copy may go into its original or beside it; a copy is of one node, has its values, access, files and the links it can share, and runs as a process, answered as its snapshot), tree-count ({ id | ids, children? }: { nodes, warnAt }, how many nodes a copy would make or a delete take), tree-count-below ({ ids }: everything below each node, the ones not shown in the tree included, the tree walked once; a process the user can cancel, answered as its snapshot, its result { counted, below }, below by node and leaving out the nodes with none), tree-delete ({ ids, children? }: with everything below them, or one node alone, its children taking its place; past 200 nodes a process, answered as { process }), tree-create ({ type, name, parent? | after? }: a node of a type the tree holds, named, placed, with an address made from its name; at the top only a site), processes, process-pause, process-resume, process-cancel, process-dismiss ({ id }; the user's processes, below), collab-join, collab-live, collab-leave, collab-send (who has a node open, and the relay of editing it together, below), file-url, file-info ({ id, property }: the file as the user reads it, its pictures asked for ahead of other conversions, what the file field asks again while converting says they are being made), timestamp; form-layout ({ type, layout }, an administrator's alone, else 403: a type's form layout, saved in the CMS settings (Forms.Layouts) for every user, or taken away with null; a field names a property by CodeName once, a width is 5 to 100 percent of the row, tabs naming the same strip share a tab strip, and a tab, a heading or a panel may have a color of the CMS interface's palette: gray, red, orange, amber, green, teal, blue, indigo, violet, pink); insert, update (only the given properties; null resets), upsert, delete, reset-property, add-to-property, multiply-property, relate, unrelate, set-relation, clear-relation, move-relation, set-relation-order, change-type, update-meta (null clears a group or collection), update-address, update-display-name, file-delete (takes the file out in the revision the context names: the value is cleared and the stored file left for the sweep of unreferenced files, as another revision, made of its source's values, or a copy may hold it), file-copy ({ id, property, from: { id, property } }: another node's file, read as the user reads it, shared where the store keeps one copy per content and stored again otherwise, no bytes through the client); and transaction ({ actions: [{ op, … }] }, all or nothing - an action may use a node an earlier one inserts). Locks, revert windows and maintenance are left out on purpose.
  • A node on the wire is { "$id", "$type", "$displayName", "$createdUtc", "$changedUtc", <CodeName>: value }, an included relation end nested as nodes, an embedded list as its inner nodes, { "$id", "$type", <CodeName>: value } (written whole: an inner node keeps a $id it is sent, a value sent as null is reset, one not sent is kept, a file in it included), and a file with pictures made by the store's file conversions, of a picture or of whatever a converter makes one of (a video's frame, a tenth of the way in): a thumbnailUrl, 480 pixels (a picture cropped to a square), and a previewUrl, the whole picture scaled down to fit 1600 by 1200 (a video's frame 1280 wide). A video's frame is made in the background, so its URLs come only once it is made, and until then converting says how far along it is ({ progress, message }). Values are parsed strictly by property type (an enum by number or name; dates ISO 8601, read as UTC), and property names are CodeNames, matched exactly. HTML comes back with its internal links as URLs, a file as { name, size, contentType, url, … }.
  • The stream sends connected, a ping every 10 s, nodes-changed ({ changes: [{ id, type, kind }] }) after a command changed nodes - filtered per user by a read-access query, deletions always - process (a process's snapshot, to its user only, at most four times a second for progress) and process-dismissed ({ id }), collab-presence and collab (below), and unauthorized when the token runs out. Changes made outside the API are not published.
  • Editing together (CmsCollaboration): every node blade of the CMS interface joins its node's room (collab-join { nodeId, connectionId, participant, live? }, on its own stream), so each knows who else has the node open (collab-presence { nodeId, version, participants: [{ id, userId, name, live }] }, after every change, under a version that rises, which the answers to collab-join/collab-live carry too: a client keeps the higher, as answer and event come in either order). One that edits together goes live (collab-live, answering first for the first live one, which brings the document) and sends its document's changes, cursors and pointer to the room's other live participants (collab-send { messages: [{ data, to? }] } → collab { nodeId, from, messages }). The server keeps no document and passes the messages (Yjs, base64) on as they came, never back to the connection they came from; participants leave with their stream. A user joins only a node they may read.
  • Revisions and cultures (CmsApiStoreCommands.Revisions.cs): revisions { id } lists a node's versions in every culture ({ id, type, culture, name, … }, id null for a node without revisions), cultures the cultures to write in, and create-revision { id, revision?, type?, culture? }, set-revision-type { id, revision?, type } (published, the culture's published version is archived), set-revision-culture, delete-revision and add-culture { code, site? } change them. A node's versions are all neutral or all in cultures (Relatude.DB keeps them so): a version in a culture made for a neutral node, or one of its versions moved into a culture, takes its other versions into that culture, and a neutral version beside versions in cultures is refused (409). The payload's context.revisions ({ nodeId: revisionId }) names the revision a command reads and writes; a node read says which it is in $revisionId, $revisionType and $culture; an insert in a context with a culture is that culture's. Each version has values of its own, and editing-together rooms are per revision (revision in every collab-* payload and event).
  • Sites (CmsApiStoreCommands.Sites.cs): a site is one of Relatude.DB's collections (ISystemCollection, which the CMS's ISite is), so one database holds several sites' content. A node is in one site or none (its meta's CollectionId), which a read says in $collection and update-meta's CollectionId changes; a site names the cultures its content is written in (CollectionsToCultures), none meaning any. sites answers { supported, types, items }: the collections the user may read, by name in the context's culture, each { id, name, type, cultures }, and the CodeNames whose changes change the answer. The payload's context.collection is the site the user works in: insert (and so tree-create) puts the node in it, a collection itself goes in its own, and an id that is no collection the user reads is refused (400); reads are not limited by it. add-culture { code, site? } also makes the culture one of the site's. The CMS interface has a site selector in every blade's header beside the language one, which offers the site's languages.
  • Skins (CmsSkins.cs; interface packages/cms/src/skins/, tokens in @relatude/ui's skins.ts): the interface's look is its design tokens (tokens.css, the --r-* custom properties every component is drawn with), and a skin is a value for each, one for the light theme and one for the dark (the size of all text too, text-scale, which every font size is multiplied by). It comes with Windows (the default, after Windows 11), Neutral, and a gallery: Windows NT, iOS, Terminal, Paper, Nord, Synthwave, Christmas and Relatude; an administrator makes more in the skin designer (Settings › Appearance), whose basic mode turns a few dials (accent, tint, wallpaper, moving background, corners, depth, font, motion, frosted menus) and whose advanced mode edits every token, pictures as SVG, the shader and the skin as JSON, and every user chooses one in their browser. A picture (a token whose name ends in -image: the wallpaper, a blade texture, the menu's illustration) is SVG source, or none, put into the stylesheet as a data: URL, drawn as an image that runs and loads nothing. A moving background is a scene the interface draws with WebGL behind the blades, which a skin chooses (scene: peaks, relatude.com's flight over faceted mountains; snow; aurora; grid; stars; christmas, mountains, a village and Santa's sleigh; or shader) and colours (scene-sky, -horizon, -land, -shade, -snow, -accent, -veil, -speed, -work-speed, the share of the speed it moves at once signed in, eased to and from at sign-in and sign-out, its particles (dust, the graph's links, snowflakes) keeping the square root of the share, so Relatude's flight all but stops past the login screen while its dust still drifts by; slowed so, Peaks leaves out its graph; and -amount); the scenes are the interface's own code, so a skin still carries only values, except scene-shader: a GLSL fragment shader after Shadertoy (mainImage), which runs on the graphics card alone and can read nothing. Users may hold scenes still (Settings › Appearance › Moving backgrounds), and asking the system for less motion does too. skins answers { default, skins: [{ key, name, description, base, light, dark }], canEdit, ai } (a skin's values over its built-in base's, token names without --r-; ai says what makes a skin from a prompt, to an administrator, or null); an administrator's skin-save { skin } (saved over the skin of its key), skin-delete { key }, skin-default { key } (a built-in or saved skin; null for Windows) and skin-generate { prompt, tokens, current }, which asks the database's AI (store.Services.AI, else the Relatude AI service on the installation's license, ICmsSkinAI) for a skin, telling it the tokens the interface sent (name, group, kind, what each is for) and the skin as it is, and answers { name, description, light, dark, dropped } unsaved. Every value is checked (CmsSkinJson.IsSafeFor, the interface's isSafeFor): a CSS value has no ; { } < > \ ! @, no url(), quotes in pairs, one line; a picture is one <svg> of at most 16000 characters without scripts, event attributes, styles, embedded or linked files, links only to its own #ids; a shader is at most 12000 characters of plain ASCII with a mainImage and no #version or #extension; so a skin writes values into the interface's stylesheet and nothing else, and a shader draws on its canvas and nothing else. Kept in CmsSettings.Skins, the database's.
  • Modules add commands with Command(…) (see Modules); other code injects CmsApiCommands and calls Register("my-command", ctx => …, readOnly: true); ctx.Payload<T>(), ctx.Db, ctx.Changed(id, typeId, kind). CmsApiEvents.Broadcast pushes events of its own.
  • Processes: work that goes on after its command. ctx.StartProcess(new CmsProcessStart(kind, title) { Description, Status, CanPause, CanCancel }, async (c, process) => { …; process.Report(done, total, status); await process.CheckpointAsync(); …; return result; }), answered as process.Snapshot(); check the payload first, so a mistake is the command's answer. A process belongs to the user, not to the token: it runs on while they are signed out, processes lists it at the next sign-in, and no other user sees or touches it. CheckpointAsync is where a pause holds the work and a cancel stops it (an OperationCanceledException; any other exception fails it, with the message). The work gets a context of its own, c: the same user, store and payload, no request (c.Http throws), cancelled with the process, its Changed nodes published at each checkpoint. CmsProcesses keeps them in memory, so a restart loses them; a finished one stays until dismissed, for a day at most. tree-copy is one: 25 nodes per transaction, a checkpoint after each batch and its files; cancelled or failing half-way, it removes the nodes it copied.
  • Limits: MaxPageSize (10 000) for Page/Take/SetRowPaging, MaxQueryLength (20 000), MaxUploadBytes (1 GB). A tree copy has no limit: past TreeCopyWarnAt (10 000 nodes; 0 never) the CMS interface warns and asks whether to go ahead.

CMS interface (MapRelatudeCmsUI)

The interface editors sign in to is not in the package. app.MapRelatudeCmsUI() gets it from services.relatude.com, keeps a copy, and serves it from the site's own address.

  • GET {ui}/ (/relatude.cms/; without the slash it redirects there, the query kept) asks services.relatude.com which release to serve, server to server, each time the CMS is opened: POST {services}/api/cmsui/latest with { apiKey, cmsVersion, installationKey, uiVersion, channel, version }, uiVersion being the release it holds and channel/version the installation's choice (below). Only a release it does not hold is downloaded (POST {services}/api/cmsui/release, naming the version the check gave, a zip checked against the SHA-256 the service named). It answers the release's index.html (no-store) with <base href="{ui}/r/{version}/"> and window.__RELATUDE_CMS__ = { api, uiPath, version, cmsVersion } put first in its head. GET {ui}/r/{version}/… serves the release's files, cached as immutable.
  • The copy it keeps. CmsUiServer holds the release it serves unpacked in memory, with the two before it for pages still open on them, and keeps its zip in the database's storage (cms/ui/release.zip, with release.json naming its version and hash), so a restart does not download it again. While the service cannot be reached the copy is served; a refusal, or no release published, is never answered with it.
  • It takes a license with the feature cms. The server's ApiKey setting (the admin UI's Settings, or RelatudeDB:ApiKey) goes with every request, to the ServicesServerUrl setting (https://services.relatude.com) unless CmsApiOptions.ServicesUrl is set. With no key the page answers 503, with a refused one 403 and the service's reason, with no release published 404, with the service unreachable and no copy kept 502, each as a short HTML page.
  • The path is configurable, as /relatude.db is: the server setting CMS > Hosting > CMS path (CmsServerSettings.UIUrlPath, file key cms-server, applied at a restart) wins over CmsApiOptions.UIPath. The API moves with it ({ui}/api) unless CmsApiOptions.Path is set.
  • A release has a version of its own, apart from the package's, a channel (release, beta or alpha) and the oldest CMS it runs on (the Relatude.DB.CMS package version, or any): Relatude.CMS.UI/publish.bat builds the interface, asks for the three and publishes it to services.relatude.com/publishcmsui. Staff change a release's channel (how a beta becomes a release), its minimum CMS and its notes in the backoffice. The service counts each opening and download, per release and per installation. Releases come from ICmsUiSource (default ServicesCmsUiSource); register another to serve them from elsewhere.
  • Which release an installation serves is the newest of its channel and the steadier ones that runs on its CMS (release takes releases, beta betas and releases, alpha everything), or the one version it holds to: the server settings CMS › Interface releases (CmsServerSettings.UIChannel, UIVersion; read at every opening), which an administrator also sets in the CMS under Settings › Updates. A version held to that cannot be had (withdrawn, or needing a newer CMS) gives way to the newest of the channel, and the tab says why; a newer release the CMS is too old for is named there too. The API's commands: ui-release (the choice, what was served, newer, problem), ui-releases (every release published, with runs on this CMS), ui-release-set { channel, version } (administrators; saves and asks the service at once).

Modules (Relatude.DB.CMS.Modules)

A module is everything one feature adds to a site, described in one class and shipped in one assembly, usually a NuGet package: model types, transaction plugins, jobs, settings per database and per server, seed data, CMS API commands, routes, rendering, views, an interface plugin, custom logs and user groups, and what it needs of other modules and of the license. The module is the package; the plugins it brings are the parts that hook into something else: transaction plugins into the store's writes, the interface plugin into the CMS interface. EventsModule/, beside Website2, has every part.

public sealed class EventsModule : CmsModule {
    public override string Name => "events";                       // letters, digits and '-': names its commands, files and switch
    public Guid? ParentPageId { get; init; }                       // an option the host sets: AddModule(new EventsModule { … })

    public override void Configure(CmsModuleBuilder module) => module
        .DependsOn<VenuesModule>()                                 // ordered after it, and only active while it is
        .Datamodel(dm => dm.AddNamespace<IEventPage>())
        .TransactionPlugin<EventPagePlugin>()
        .Job("events.close-past", "Marks the events that have ended.", (c, job) => …)
        .Settings<EventSettingsDefinition>()                       // per database or per server, as its Scope says
        .Seed(1, "Three events", c => …)
        .Seed(2, "A first registration", c => …)
        .UserGroup(managersId, "Event managers")
        .Log(EventActivity.Definition())
        .OnStoreOpened(c => …)
        .Command("events.upcoming", ctx => …, readOnly: true)
        .Endpoints(e => e.MapGet("/events.ics", …))
        .Rendering(o => o.RenderRazorView<IEventPage>("EventPage"))
        .Views()                                                   // the views compiled into the module (a Razor class library)
        .InterfacePlugin();                                        // ui/index.js, embedded in the assembly
}

builder.AddRelatudeCMS().AddApi()
    .AddModule<VenuesModule>()
    .AddModule(new EventsModule { ParentPageId = homeId });
  • Added in code, explicitly. AddModule<T>() runs Configure at once: its services and settings are added then, and the rest waits for each database's start. A module added twice is added once. Two with one name, a dependency not added, or modules building on each other in a circle stop the start (UseRelatudeCMS()). Modules run dependencies first, otherwise in the order added.
  • Each database's start goes through Relatude.DB's start-up services, so no setup call of the host's can lose it. IDatamodelInitializer adds the model types of every module that applies, after the host's OnDatamodelInit (AppliesTo; by default every database whose datamodel has the CMS content model, and never one without a module it builds on). IStoreInitializer registers its transaction plugins, runners and jobs. IStoreOpenHandler, once the store is open and on a background thread, makes missing user groups and custom logs, runs the seed steps not run yet, then the start-up work.
  • Seed data is numbered steps, each run once per database, in order. The database's storage keeps the last step run (cms/modules/{name}.json). A step that throws stops the steps after it until the next start. Change data later with a new step, and never renumber a released one. Steps run as the master admin through the store's synchronous writes, so transaction plugins see them, and should find what an earlier run made (fixed ids).
  • Commands and jobs are named after their module (events.upcoming), so a module cannot replace another's or the API's own. A command runs as the user like the API's own (ctx.Db, ctx.IsInGroup(groupId)); the CMS interface sends it with cms.store.send("events.upcoming", payload).
  • The interface plugin is an ES module whose default export is definePlugin(…), embedded in the module's assembly with the files it imports: <EmbeddedResource Include="ui\**" LogicalName="cms-ui/%(RecursiveDir)%(Filename)%(Extension)" />. The API serves them at {api}/modules/{name}/{version}/…, cached as immutable (the version is the assembly's informational version unless Version is overridden). As it starts, the CMS interface asks cms-modules and imports the interface plugins of the active modules; their bare imports resolve through its import map. A plugin can be plain JavaScript, with no build, or built with @relatude/plugin-kit.
  • Interface plugins without a module are listed in the CMS settings (CMS › Interface plugins: name, address, on or off) and loaded from the site or from another site that allows CORS. They run with the editor's access, so add only plugins you trust.
  • Turning a module off (CMS › Modules › Modules turned off: names separated by commas, applied at once) keeps its model types, transaction plugins, settings, rendering and data, so nothing stored is lost or left unguarded. Its interface plugin, its commands (403 with the reason), its routes (left out of routing) and its jobs (a run says why) go at once; its seed steps and start-up work wait for a start where it is on. A module that builds on one turned off is off too.
  • The license. RequiresLicense("feature") keeps a module inactive while the installation's license is known not to carry the feature: no API key, an invalid one, a license disabled or run out, or one without it. It is asked through ICmsLicense (Relatude Services, with the server's API key, at most every ten minutes); while the license server cannot be reached, the module is given the benefit of the doubt.
  • Where a module stands: CmsModules.StatusOf(name, store) answers Active, Disabled, Unlicensed, DependencyInactive or NotInDatabase, with the reason, and SeedVersionOf(name, store) the last seed step run. The CMS interface lists the modules under Settings › Modules, and every interface plugin under Settings › Plugins: built in, the modules', the settings' and this browser's own.
  • Pin the ids of a module's node types and relations ([Node(Id = …)], [Relation(Id = …)]) from its first release, so a rename keeps the data.

Donations (Relatude.CMS.Models.Donations)

A generic donation node model with the list/detail projection behind the WAF.Client Donations admin module (postWebAPI(session, "Donations", "List" | "Get", …)). The model namespace holds only the IDonation interface — a datamodel source scans it, so anything else in that namespace would be registered as a node type. The wire DTOs (DonationRow/DonationListResult/DonationDetail) and the pure DonationAdminProjection live in Relatude.CMS.Models.Donations.Admin. Sites extend the model with their own node interface (public interface IMyDonation : IDonation { … }) — a member may be declared in only one interface of the hierarchy.

Both namespaces are registered as datamodel sources — matching is exact, and an unregistered base interface silently drops all inherited fields from the derived type:

"DatamodelSources": [
  { "Id": "<unique guid>", "Name": "My site",   "Namespace": "MySite.Models",                 "Type": "AssemblyNameReference", "Reference": null },
  { "Id": "<unique guid>", "Name": "Donations", "Namespace": "Relatude.CMS.Models.Donations", "Type": "AssemblyNameReference", "Reference": "Relatude.DB.CMS" }
]

The admin controller stays in the host — it derives from the host framework's admin API base (e.g. WAF's BaseAdminAPIController), which this package does not reference. Routed as wafapi/Donations/{action}, the shape is:

[HttpPost]
public DonationListResult List(int pageSize = 25, int pageIndex = 0, string? sortBy = null, bool sortDesc = true,
    string? categories = null, string? statuses = null, string? paymentMethods = null, string? search = null) {
    _ = Context.Session;                             // WAF's admin gate — throws (→ 403) without a session
    var query = _cx.Database.Query<IMyDonation>()    // WhereIn(d => d.Status/…) for non-empty filters
        .OrderBy(DonationAdminProjection.SortExpression<IMyDonation>(sortBy), sortDesc);
    var page = query.Page(pageIndex, pageSize).Execute();
    return new DonationListResult { Rows = page.Values.Select(d => DonationAdminProjection.ToRow(d)).ToList(), TotalCount = page.TotalCount };
}

Get(id) is TryGet<IMyDonation> → DonationAdminProjection.ToDetail(d, formGuid: …), where the host resolves the originating form's content guid from IDonation.FormId (see DonationDetail.FormGuid — the admin client cannot query by ContentId). The host also snapshots the form's name onto IDonation.FormName when the donation is created — denormalized on purpose, since the list sorts and searches it server-side (AQL orders node properties, not values computed at projection time); a later rename therefore does not retro-rename existing donations. Category (onetime/recurring/business) and free-text search have no AQL form — when active, materialise the ordered set, filter with MatchesCategory/MatchesSearch, then page.

Notes

  • Create<T>() does not persist — follow with Insert/CreateAndInsert; call Update after mutating a loaded node.
  • Relation ends aren't Lists — use .Get() / .IsSet() / .TryGet().
  • Relation changes go through SetRelation/AddRelation/RemoveRelation, not property assignment.
  • This is a library with no entry point; engine start and schema live in the host app and the /relatude.db admin UI.
  • Relatude.DB source/API reference: https://github.com/Relatude/Relatude.DB
  • Donations: every DatamodelSources entry needs its own unique Id — the store refuses to boot without one.
  • Donations: the enum-like string values (PaymentMethod, Status, GiftType, Frequency) are matched case-sensitively by the admin module's filters — store exactly the values documented on IDonation (all lowercase, e.g. vippsrecurring).
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on Relatude.DB.CMS:

Package Downloads
Relatude.Core

Relatude .Net 10.0 Headless CMS and E-commerce solution

Relatude.DB.Ecom

Relatude E-commerce backend API for Relatude.DB. Builds on the Relatude.CMS package.

Relatude.DB.MCP

An MCP server for Relatude CMS: AI agents read and change a site's datamodel, content and templates at runtime, with the rights of the user their key is for.

Relatude.DB.Scriban

Scriban templates for Relatude CMS: page templates, emails and any other text, kept in the database or as files, evaluated at runtime.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.11.42-alpha 0 11/24/2026
1.1.11.35-alpha 63 11/22/2026
1.1.10.34-alpha 55 11/22/2026
1.1.10.32-alpha 48 11/22/2026
1.1.9.30-alpha 65 11/20/2026
1.1.8.29-alpha 75 11/18/2026
1.1.8.28-alpha 90 11/17/2026
1.1.7.25-alpha 100 11/16/2026
1.1.6.25-alpha 175 11/13/2026
1.1.2.21-alpha 133 11/9/2026
1.1.2.20-alpha 98 11/9/2026
1.1.2.14-alpha 194 11/5/2026
1.1.1.13-alpha 176 11/2/2026
1.1.1.12-alpha 111 11/1/2026
1.1.1.9-alpha 106 10/30/2026
1.1.1.8-alpha 109 10/29/2026
1.1.1.7-alpha 139 10/23/2026
1.1.1.6-alpha 103 10/21/2026
1.1.1.3-alpha 188 10/17/2026
1.0.43 275 10/5/2026
Loading failed