Help
This is the author manual. It is itself a stored page, so logged in users can improve it at /pages?edit=/help.
The editor
The editor is /pages. The page list has a form to create or open a page by
its path, and every live and deleted page has its own editor at
/pages?edit=<path>. History, the diff and the three confirmations are the same
page, so a bookmark is a query value rather than a route:
?page=<path> shows the source and history, ?edit=<path>&cmd=delete
confirms a delete, ?edit=<path>&cmd=install confirms a seed install, and
?page=<path>&rev=<hash>&cmd=restore confirms a restore.
- Save compiles the template and stores the source and the compiled image. A page that does not compile is still stored, so you do not lose your work.
- Save and view saves, then opens the page. If it does not compile, you stay in the editor with the diagnostics instead.
- Diagnostics name the line and column in your template. A diagnostic that has a position is a link to the matching number in the line gutter.
- State is what the page's stored image amounts to: Compiled, Compiled with warnings, Compile failed, Not compiled, or Stale when the image was built by an earlier deploy. A page compiled elsewhere says Stale until it is next requested, which recompiles it.
- History lists the saved revisions of a page. Choosing one shows its stored source without compiling it; choosing two compares them line by line. A row offers Restore for every revision except the current one: the confirmation shows the change it will make, and restoring saves that source as a new revision, compiled by this build. Nothing is rewound, and a revision whose source the page already holds cannot be restored.
- Delete hides a page but keeps its template and history. Scrub
permanently removes a deleted page and its retained history; use it only when you mean it. It is
the site's own route rather than an action here, because it cannot be undone: the page's row
links to
/admin/scrub, which asks you to type the page's key to confirm, and refuses a page that has not been deleted first. - Install from seed is offered only when the release has moved a seed and the page still holds the seed it was installed from — the row says release newer. It opens the same kind of confirmation as a restore and saves the bundled source as a new revision. A page you have changed since its seed set it, or one whose seed the release moved as well, is shown with the diff and no install: the row says why. A seed is installed; a saved revision is restored.
- Apply seed updates on /admin/seed-apply is the routine way a release moves a page: it writes what the release moved, records what already matches and stops at the first page that has drifted. Restore every seed on /admin/restore is the emergency way back when the editor itself will not load: it saves the bundled source of every page the site ships with, never touches a page you made, and skips a seed that already matches.
- The assistant is available from the editor to a signed-in owner, and it can view the site as you while it works: it sees the pages a signed-in visitor sees, read-only.
Paths are canonical: /About, /about/ and /about are the
same page. A path the site's own routes already answer for, such as /admin/import or
/login, cannot be created as a page.
A page with code is a fragment
A page with C# is a fragment unless it asks to be more. Nothing wraps it for you: the page
declares the page or pages that wrap it with
IPageComposition, and the site's
layout /_layout writes the document — the doctype, html,
head, title, stylesheets, the site menu, the banner, the main landmark and
the close. A page that declares nothing is served exactly as it wrote itself, which is a bare
fragment:
<% ctx.Capabilities.GetRequired<IPageLayout>().Title = "About";
ctx.Capabilities.GetRequired<IPageComposition>().Wrap(); %>
<h1>About</h1>
<p>This page is wrapped in the site layout.</p>
Wrap() names the site layout, so the page does not hard-code a key the owner can
move. Wrap("/_other") names a page instead, and Wrap("/_other", ctx.Request)
runs that page against a request of your choosing. Calls stack outward: Wrap("/_markdown"); Wrap();
is the markdown layout first and the site layout outside it. Declare the wrap near the top of the
page: the host runs the chain after the page returns, so a guard's early return; is
still wrapped.
A page with no C# is a complete representation: its stored source is the response and it must write its own whole document. A no-code page cannot read another page, so it can never wrap or be wrapped. Add a code block — even one that only sets a title — if you want the site chrome.
A page whose blocks are only declarations — <%! ... %> and
nothing else — is a library: it has nothing to render, so it is never served and
its own URL answers “not found”. It is still checked when you save it, so code that will not
compile is reported like any other page's. A library declares its types in a namespace, and the page
API policy applies to it exactly as it does to code in a page.
A declaration-only source that declares exactly one public type implementing
IWorker — a type with a parameterless constructor and a
RunAsync(IWorkerContext) method — is a worker rather than a library.
It is compiled and checked when you save it, is never served, and is not a library: a page that names
its namespace does not compile. A worker is a program a page starts, with
ctx.Capabilities.GetRequired<IPageJobs>(); see Starting a job.
Libraries live under /_lib/ by convention — the seeded document writer is
/_lib/document — so code has a folder of its own in the page list instead of a key a
visitor might ask for. Nothing refuses a library elsewhere, and its key is never served either way.
A page uses a library by naming its namespace in a using directive, which is the whole
of the binding:
<%!
namespace Site.Document {
public static class Document {
public static void Head(IContext ctx) => ctx.Response.WriteRaw("<h1>Hi</h1>");
}
}
%>
and then, in any page that wants it:
<%! using Site.Document; %>
<% Document.Head(ctx); %>
A page is compiled with every library its using directives reach, and with the
libraries those reach in turn, so one library may build on another. Editing a library recompiles the
pages that name it, and nothing else. A diagnostic from library code names the library and the line in
it, rather than pointing at your page.
A library's static fields are one copy for each page that names it, not one copy for
the site: do not use them to share a value between pages. A library that does not compile stops the
pages that name it from compiling until it is fixed — and the editor page names the document
library too, so /admin/restore, which is the shell's own route, is the way back when the
editor will not open.
Do not write a doctype, html, head, body, a
title element or the site menu in a page with code. Start at the page's first heading and
write one h1.
A response that is not HTML, a redirect, the empty body of a HEAD response and a page
with no code are not wrapped. A page whose key has a content type of its own, such as
/site.css or /editor.js, is served as that content type and is never
wrapped.
Layout and title
The slots are IPageLayout, reached
through the page's capabilities, so a page that never wants a layout never meets one. They are this
layer's own slots:
<% IPageLayout layout = ctx.Capabilities.GetRequired<IPageLayout>();
layout.Title = "About";
layout.AddStylesheet("/about.css");
ctx.Capabilities.GetRequired<IPageComposition>().Wrap(); %>
<h1>About</h1>
<p>This page is wrapped in the site layout.</p>
Title is a string? that starts unset; the setter refuses a blank one, so
leaving it unset is the only way to have none. The wrapper decides what a missing title
means: the seeded /_layout uses the page's title when it has one and the site's
own otherwise. The host no longer refuses a page that forgot.
AddStylesheet("/about.css") links one sheet. Call it zero, one or many times. A sheet
must be a site-relative URL, and the same sheet added twice to one layer is linked once.
AddHead("<meta name="robots" content="noindex">") adds raw markup to the
document's head. Use it for a meta tag or another document-level link, not for a
stylesheet; AddStylesheet owns those.
Inside a wrapper, layout.Content
is the page it wraps, as a PageCapture:
Body beside Title, Head, Stylesheets and
AllowsScripts. It is null in the page the visitor asked for. The
wrapper folds what it wants — nothing is merged behind its back — and the merged
head is one call: Document.Head(ctx, layout, "Site", ctx.AssetUrl) uses the page's title
when the wrapper set none, and links the wrapper's own sheets and head first, with the page's after,
so the page is the last word on how it looks.
A wrapper that is itself wrapped must pass on what it wants the outer layer to see: set
layout.Title to Content.Title and add Content.Head and
Content.Stylesheets to your own slots. The host passes nothing on for you.
The chain renders inside out: the page first, then the wrapper it declared, then the wrapper's
wrapper. The whole chain shares one render budget, one fetch allowance and one body allowance, so
two layers do not get two bites. The chain is limited to four layers by
Pages:Render:MaxLayoutDepth, and a page that reaches itself again with the same request
is refused as a loop.
If the site layout named by Wrap() is missing or does not compile, that layer is
skipped, the host logs a warning and the rest of the chain still runs. A page named by
Wrap(key) that cannot be served is an error naming the key. A wrapper must have code: a
no-code page has no way to read Content, so it cannot wrap.
A wrapper does not own the response. Its ctx.Response.SetStatus,
SetContentType, SetHeader and Redirect are ignored and logged,
because the page the visitor asked for owns those; AllowScripts is the one setting it
shares, and the host unions it with the page's.
A layout is not a guard. The content has already run by the time the layout starts, so a layout can hide chrome but cannot prevent a side effect.
A minimal wrapper calls the document library the site seeds at /_lib/document and puts
the page in the middle:
<%! using Site.Document; %>
<% var layout = ctx.Capabilities.GetRequired<IPageLayout>();
IPageCatalog catalog = ctx.Capabilities.GetRequired<IPageCatalog>();
var links = new System.Collections.Generic.List<NavLink>();
foreach (ShellLink link in catalog.ShellLinks()) {
if (link.Section != ShellSection.Site) { continue; }
if (link.Audience == ShellAudience.Owner && ctx.User is null) { continue; }
links.Add(new NavLink(link.Href, link.Text));
}
Document.Head(ctx, layout, "Site", ctx.AssetUrl);
Document.Banner(ctx, "Site", links, "site-nav");
Document.OpenMain(ctx); %>
<%== layout.Content?.Body ?? "" %>
<% Document.CloseMain(ctx); Document.End(ctx); %>
The menu is the shell's own list (the catalog's ShellLinks()),
filtered for this visitor and section; the footer is the layout's own markup. The shell knows its
routes, and the layout decides what a stored page carries.
The last argument to Head is the link resolver: ctx.AssetUrl is what lets
the base sheet and the icon carry a revision hash. The library is an ordinary stored page, so you can
edit the document itself from the page list, and /admin/restore puts it back.
The seeded /_layout is the full version of that page, and you can edit or restore both
from the page list.
Including another page
EmbedAsync("/cards/post")
renders another stored page where the call is. It is a render of the whole page — its body and
every wrapper it declares — with its own key, storage and session, the visitor's identity, and
the request the call gives it. Nothing about it is a sandbox: it may write the store and start a job
like any page. It is offered every capability a page the visitor asked for is offered, except its
own response.
<% var composition = ctx.Capabilities.GetRequired<IPageComposition>();
PageFrame frame = await composition.EmbedAsync("/cards/post");
if (frame.Title is not null) { ctx.Capabilities.GetRequired<IPageLayout>().Title = frame.Title; } %>
The return value is a PageFrame: the
outermost layer's title, head, sheets and script permission. The body is not in it, because the body
is already written. A page that wants the body too calls
CaptureAsync,
which renders the same page and returns a PageCapture without writing anything:
<% PageCapture captured = await ctx.Capabilities.GetRequired<IPageComposition>().CaptureAsync("/draft");
if (captured.AllowsScripts) { ctx.Response.AllowScripts(); }
ctx.Response.WriteRaw(ctx.Capabilities.GetRequired<IMarkdownRenderer>().ToHtml(captured.Body)); %>
The input is a request. Omit it to run the embedded page against this page's own request, or pass
one to shape what it sees: ctx.Request.WithQuery("id", "7") replaces a query name,
WithAnotherQuery adds a value beside the ones a name has, and WithoutQuery
drops one. The page the visitor asked for stays on ctx.Request.Path, so the embedded
page sees its own key as ctx.Path and ctx.Path != ctx.Request.Path is how it
knows it is inside another page. A method, form, header or cookie can be shaped the same way, because
they are the page's real input; only the path is the host's.
Recursion is bounded and honest. The same page with the same request anywhere above this one is a
loop and is refused. The same page with a different request is a recursive component — a comment
tree, a directory — and is allowed, counted on the status page, and bounded by
Pages:Render:MaxEmbedDepth (four levels below the page that is running). One request may
make Pages:Render:MaxEmbeds embeds (32), so a listing cannot embed a thousand siblings.
EmbedAsync throws when the page cannot be served, and a page may catch that: the
output never reached the page's body, so nothing is half-written. What does not roll back is a side
effect the embedded page already made. An embedded page cannot redirect, because it has no response
of its own; one that tries is refused and the page that embedded it may catch it.
One render still writes once. A page that embeds a widget which saves itself spends the render's one write, so a second one — in the page or in another instance of the widget — is refused; a job, by contrast, is per call and bounded by the job queue.
Streaming a response
A page sends its body when its handler returns. To send part of it earlier, call
await ctx.Response.FlushAsync(). The first flush is the commit point: the status, content type and
headers are final, any session or antiforgery cookie already minted is written, and the response
starts. Later
writes are buffered until the next flush, and whatever is left is sent when the handler returns.
A streaming page is served alone, so it declares no wrapper and writes its own document before
the first flush. A Wrap call after the first flush throws:
<!DOCTYPE html>
<html lang="en"><head><title>Progress</title></head><body>
<% await ctx.Response.FlushAsync(); %>
<p>First</p>
<% await ctx.Response.FlushAsync(); %>
<p>Second</p>
</body></html>
Once the response is committed, ctx.Response.SetStatus, ctx.Response.SetContentType,
ctx.Response.SetHeader, ctx.Response.AllowScripts, ctx.Response.Redirect and reading
ctx.Response.AntiforgeryField throw. Read the antiforgery field and write any new session state
before the first flush: their cookies can no longer be sent afterwards.
A failure after the commit cannot become an error page. An exception is logged and the response is
truncated. A HEAD request commits but sends no body, and a streamed response has no
Content-Length.
Pages:Render:MaxBodyChars still caps what is buffered before the first flush. After the
commit the body is not charged, because it is already on its way to the visitor.
The commit is also where the render's own budget ends and the stream's two clocks start. A stream
is truncated when nothing has been flushed for Pages:Stream:SilenceSeconds (60 seconds by
default), and at the latest Pages:Stream:MaxSeconds after the commit (30 minutes by
default) however busy it is. Every flush restarts the silence clock. A page that stops to think for
longer than the silence allowance, or that wants to stay open for longer than the ceiling, is ended
and the reason is logged; the alternative would be a page nobody can reclaim.
A committed stream holds one of the site's Pages:Stream:Slots (8 by default) and hands
its render slot back, so a stream that is mostly waiting does not cost the render pool anything and
the site cannot be held open by more streams than that. When every slot is taken the first flush
throws PageStreamRefusedException before anything is committed, and the visitor gets
503; a page that would rather explain the wait catches it itself.
A server-sent-events page sets text/event-stream, adds
X-Accel-Buffering: no with ctx.Response.SetHeader, writes one event at a time and
flushes after each. Each flush is what keeps it inside the silence allowance, and the ceiling is what
ends a conversation that would otherwise never finish.
For a slow upstream, write and flush a first event before opening the fetch or waiting for a line.
The commit starts the client's Pages:Stream lifetime; the upstream body has its own
Pages:Fetch:StreamSilenceSeconds, StreamMaxSeconds and
MaxStreamBytes limits. A failure after the flush cannot change the response status, so
send an error event instead:
<%
IHttpFetch fetch = ctx.Capabilities.GetRequired<IHttpFetch>();
// No Wrap call: a page that streams writes its own document.
ctx.Response.SetContentType("text/event-stream; charset=utf-8");
ctx.Response.SetHeader("X-Accel-Buffering", "no");
ctx.Response.WriteRaw(": connected\n\n");
await ctx.Response.FlushAsync();
HttpFetchStream upstream = await fetch.StreamAsync(
new HttpFetchRequest("https://api.example.com/events"));
try {
string? line;
while ((line = await upstream.ReadLineAsync()) is not null) {
ctx.Response.WriteRaw($"data: {line}\n\n");
await ctx.Response.FlushAsync();
}
string? failure = upstream.Truncated
? "truncated"
: upstream.Failure == HttpFetchFailure.None ? null : upstream.Failure.ToString();
if (failure is not null) {
ctx.Response.WriteRaw($"event: error\ndata: {failure}\n\n");
await ctx.Response.FlushAsync();
}
} finally {
await upstream.CloseAsync();
}
%>
ReadLineAsync() returns null at end of body or after a failure; inspect
Failure and Truncated after the loop. The host closes streams a page
leaves open when the render ends or is abandoned.
Starting a job
Some work outlives the request that asked for it: a long answer, a polling loop, anything that should
keep going if the visitor closes the tab. A worker is a stored program for that, and a
job is one run of it. IPageJobs starts one, talks to it, reads what it
published and stops it:
<% IPageJobs jobs = ctx.Capabilities.GetRequired<IPageJobs>();
PageJobStart start = await jobs.StartAsync("/_work/answer", "the question");
if (!start.Started) {
ctx.Response.Write("Could not start: " + start.Refusal);
return;
} %>
<p>Started <%= start.Id %>.</p>
Every call answers with a value: start.Started and start.Refusal,
sent.Sent, and null from GetAsync when the job is unknown or
another visitor's. ListAsync() lists the jobs this visitor started, which is how a reload
finds one that is still running. SendAsync(jobId, message) queues a message for the worker,
and CancelAsync(jobId) asks it to stop at its next await.
ReadEventsAsync(jobId, after, waitSeconds) reads what the worker published. Pass the last
sequence you saw as after, and it answers the events since then, waiting up to
waitSeconds for the next one. Next is the sequence to pass back, and
Reset says the worker published more than the journal kept, so start again from
Next. A viewer that streams is a page that flushes each batch as server-sent events; see
Streaming a response.
The journal is memory, and it is bounded: it keeps the most recent events and drops the oldest, and a
restart loses every job. A worker that must not lose what it has done writes it to the starting page's
storage, which the page can read again — that state, not the journal, is the record. A job is never
offered a layout, a renderer or a page writer, and a HEAD is offered the reads and not the
ones that start, send or cancel.
A worker declares exactly one public type implementing IWorker with a parameterless
constructor. Its RunAsync(IWorkerContext context) gets the job's Id, the
starting page as Path, its own key as Worker, the owner as
User, the first message as Input, Aborted,
Capabilities, three log members, ReceiveAsync for later messages and
Publish for events:
<%!
using System.Threading.Tasks;
namespace Site.Work {
public sealed class Answer : IWorker {
public async Task RunAsync(IWorkerContext context) {
IPageStorage storage = context.Capabilities.GetRequired<IPageStorage>();
context.Publish("delta", "thinking");
await storage.SetAsync("last-question", context.Input ?? "");
while (await context.ReceiveAsync(30) is { } message) {
context.Publish("delta", message);
}
}
}
}
%>
A worker has no response: it cannot write, flush, redirect or set a status, and it is offered no
renderer, no writer and no layout. Its storage is the starting page's, so a job and the page that shows
it share one store; its fetch and catalog are the worker's own, so a credential bound to the worker stays
the worker's. It asks for those through context.Capabilities exactly as a page does.
A wait in ReceiveAsync is not silence: it pauses the job's silence clock, so a worker
waiting for its owner is bounded only by the job's ceiling. A worker that neither publishes nor receives
for Pages:Jobs:SilenceSeconds is cut, and one that runs longer than
MaxDurationSeconds is stopped, so a wedged job cannot burn the ceiling.
Stylesheets, head and scripts
The page's key chooses its initial content type from the host's extension map; an unmapped key is
HTML. ctx.Response.SetContentType("text/css; charset=utf-8") overrides it when a page needs to
send something else. The extension also chooses the response's script policy, and that policy follows
the extension even if the page changes its content type.
A page with code that loads a script calls ctx.Response.AllowScripts(). That widens the
response from script-src 'none' to script-src 'self'; it does not allow
inline scripts or event-handler attributes:
<% ctx.Response.AllowScripts(); %>
<script type="module" src="/my-script.js"></script>
A page with no code cannot call AllowScripts, so the extension policy is the only way
to let a static document load a module. The shipped .html row is
"ScriptPolicy": "none"; set it to "self" in
Pages:ContentTypes:Extensions if your static documents need same-origin scripts. Inline
script and event-handler attributes stay blocked either way.
The script itself is another stored page, or a seeded asset, served with a JavaScript content
type. Write it as a native ES module: use import/export rather than globals,
and end a side-effect-only script with export {};. Modules are already deferred, so the
script's position in the document does not matter.
ctx.AssetUrl("/my-script.js") returns the versioned URL when that page is a live
asset, and the href unchanged otherwise, so write
<script type="module" src="<%= ctx.AssetUrl("/my-script.js") %>"></script>
in a page's own markup. Rewriting rendered HTML is not something the host does.
Template syntax
Literal template text is HTML. A code block is C#, and the handler is asynchronous, so
await is an ordinary expression in a block and inside an output expression.
<% %>- C# statements. They can write with
ctx.Response.Writeorctx.Response.WriteRaw. <%= %>- Writes an HTML-escaped string, like
ctx.Response.Write. <%== %>- Writes raw HTML, like
ctx.Response.WriteRaw. Only use it for markup you built or trust. <%! %>- Declarations, such as
usingdirectives and types of the page's own. They are hoisted above the handler and keep their template order. <%# %>- A comment: a note to yourself that writes no output and never reaches the visitor. It counts
as neither code nor text, so a page of text and comments has no code and is served with the
comments removed, and a library that carries one is still a library.
<% /* … */ %>is a C# comment inside a code block instead, which makes the template code — the two are not interchangeable.
<h1>Hello</h1>
<p>You asked for <%= ctx.Path %>.</p>
<% for (int i = 1; i <= 3; i++) { %>
<p>Line <%= i.ToString() %></p>
<% } %>
An output expression must produce a string, so convert other values explicitly with
.ToString().
A page is compiled with nullable analysis on, exactly as the host's own code is, so a reference
that may be null says so. ctx.User is a PageUser?, and
ctx.Capabilities.Get<T>() returns null when this render does not offer
the capability. Bind a guard to a local and use the local, which is the form the compiler can
follow:
<% if (ctx.User is not { } user) { ctx.Response.RedirectToLogin(); return; } %>
<p>Signed in as <%= user.Name %>.</p>
A warning does not stop the page: it compiles, is stored and is served. It is still unfinished
work, the editor shows it beside your template, and the page list says Compiled with
warnings until it is fixed. A page that wants the old behaviour can write
#nullable disable in its own code.
A declaration block looks like this:
<%!
using System.Globalization;
sealed class Amount {
public static string Format(decimal value) => value.ToString("N2", CultureInfo.InvariantCulture);
}
%>
<p>Total: <% ctx.Response.Write(Amount.Format(42.5m)); %></p>
Forms use <form class="form"> with one <dl>; a label is a
<dt> and its control is the matching <dd>. A textarea goes in a
<fieldset> whose <legend> contains its label.
What a page may use
A page is C#, and the base class library is wider than a page needs. What a page may name is a
fixed list: the page contract, a short set of base types,
everything in System.Collections.Generic, System.Globalization and
System.Text.Json.Nodes, and any System.* exception. Naming anything else is
the compile error PAGE001, and a refusal names the member you wrote and the type it
belongs to, because the type is what the list holds.
What is left out is deliberate: no file, network, process, assembly or reflection access, and no
reading the host's environment. A page reaches those through a capability instead — its own
storage, the visitor's session, IHttpFetch, a job — so a page can do the work
without being handed the machine.
Three that a page often wants are in the list, and each has one job:
- Text without regard to case
StringComparer.OrdinalIgnoreCasefor a dictionary or set, andstring.Equals(a, b, StringComparison.OrdinalIgnoreCase)to compare two values.- Hashing
HashCode.Combine(a, b)to build a key of your own, andSHA256.HashData(bytes)for anything a visitor can see through.- Randomness
Randomfor variety on the page, andRandomNumberGeneratorfor anything security-shaped, such as a nonce.
Context and capabilities
The variable ctx implements IContext. It carries the request and the
response, and nothing else:
ctx.Requestis aPageRequestwith read-onlyQuery,Form,HeadersandCookiesdictionaries.QueryandFormkeep one value per name;QueryValuesandFormValueskeep every value in the order sent, so a multi-select or?tag=a&tag=bloses nothing. The shell's own cookies — the sign-in ticket, the antiforgery pair and the page session id — are not inCookies, because they are the shell's identity rather than the page's.ctx.Pathis the page's canonical key;ctx.Useris the signed-inPageUserornull;ctx.Abortedis cancelled when the visitor abandons the request.ctx.EditorPathis the editor page's key, which the owner can move (Pages:Editor:Key). Link to the editor withctx.EditorPathrather than naming it, andctx.EditorPath + "?edit=" + System.Uri.EscapeDataString(ctx.Path)is the URL that opens this page in it.ctx.Log,ctx.LogWarningandctx.LogErrorwrite to the page log, tagged with this page's key.ctx.Response.SetStatus,ctx.Response.SetContentType,ctx.Response.SetHeader,ctx.Response.Redirectandctx.Response.RedirectToLoginshape the response.ctx.Response.FlushAsync()commits the response and sends what has been written; see Streaming a response.ctx.Response.AllowScriptspermits same-origin external scripts;ctx.Response.AntiforgeryFieldcarries the hidden input a form must include.ctx.AssetUrl(href)versions a bare site-relative link when its target is a live asset, and returns the href unchanged otherwise.
ctx.Capabilities is how a page asks for an optional capability.
TryGet<T>(out T?) reports whether it is there, Get<T>() returns
null when it is not, and GetRequired<T>() throws naming the
interface. The host decides what is offered.
A capability is not a feature the product has, nor an extension someone else adds: it is what this one render offers this page, and the next render may offer something else.
IBuildInfo says which build is answering. Commit is the full git commit
hash, or null when the build did not come from a checkout:
<% if (ctx.Capabilities.GetRequired<IBuildInfo>().Commit is { } commit) { %>
<a href="https://github.com/Moosemorals/uk.osric.asp/commit/<%= commit %>"><%= commit %></a>
<% } %>
IPageStorage is the page's own key/value store. Every visitor shares it, a write is
last-write-wins, and a page cannot reach another page's keys:
<% IPageStorage storage = ctx.Capabilities.GetRequired<IPageStorage>();
PageValue<int> stored = await storage.TryGetValueAsync<int>("visits");
int visits = (stored.Found ? stored.Value : 0) + 1;
await storage.SetAsync("visits", visits); %>
<p>Visited <%= visits.ToString() %> times.</p>
IHttpFetch makes one bounded HTTP request from the host, not the browser, to any
http or https host the URL names. Failures are values rather than
exceptions:
<% IHttpFetch fetch = ctx.Capabilities.GetRequired<IHttpFetch>();
HttpFetchResponse response = await fetch.GetAsync("https://api.example.com/status");
if (response.Succeeded) { %>
<p>State: <%= response.Body %></p>
<% } else { %>
<p>Unavailable (<%= response.Failure.ToString() %>).</p>
<% } %>
StreamAsync follows the same URL, header, redirect and credential rules and counts
against the same per-render request cap. It returns an HttpFetchStream with the response
status and headers, a Failure value, and a ReadLineAsync() method that
returns decoded text lines or null. Close it with CloseAsync(); the host
also closes it when the render ends or is abandoned. Response headers use
Pages:Fetch:TimeoutSeconds (4 seconds by default); body reads have a 30-second silence
limit, a 600-second total limit and a 4 MiB byte limit. Check Failure and
Truncated after the read loop.
A request may name an operator-configured credential with
Credential = "name" on HttpFetchRequest. The host adds the header; the
page never sees the value. Use the name the operator gives you, not a token. An unknown name is an
InvalidRequest. A credential is bound to one page, or to a page and everything under it
when the operator writes its Page as /inbox/*, so a page under that prefix
may name it too; the host still sends the header only to the credential's own host.
The page API allows the uk.osric.asp.Sdk contract, the common collection, culture and
LINQ helpers, the explicit base types the contract uses, and the system exception types a page may
catch. System.IO, System.Net, System.Reflection,
System.Diagnostics, regular expressions, expression trees, interop, threading beyond
CancellationToken, Microsoft.* and host namespaces are not available.
The reference lists every type and member this build documents; the page contract is the half a page may use.
Reading the page store
IPageCatalog is a read-only view of the site's page store: list the heads under a
prefix, read a live page's template, list a page's history, and read one retained revision by its
key and hash. It never meets an image, a symbol or a write; saving is
IPageWrites, below.
<% IPageCatalog catalog = ctx.Capabilities.GetRequired<IPageCatalog>();
System.Collections.Generic.IReadOnlyList<PageEntry> pages = await catalog.ListAsync("/blog");
PageSource? page = await catalog.ReadAsync("/blog");
System.Collections.Generic.IReadOnlyList<PageRevisionInfo> history = await catalog.RevisionsAsync("/blog"); %>
<ul>
<% foreach (PageEntry entry in pages) { %>
<li><%= entry.Key %> — <%= entry.IsDeleted ? "deleted" : "live" %></li>
<% } %>
</ul>
ShellLinks() is the
other read: the links the shell knows, both its site menu and its administration menu, as values.
Each link carries its href, its label, the section it belongs to, who it is for, and how the shell
marks it current. The host returns the list; you decide what to render, in what order and how to mark
it:
<% IPageCatalog catalog = ctx.Capabilities.GetRequired<IPageCatalog>();
foreach (ShellLink link in catalog.ShellLinks()) {
if (link.Section != ShellSection.Site) { continue; }
if (link.Audience == ShellAudience.Owner && ctx.User is null) { continue; }
%><a href="<%= link.Href %>"><%= link.Text %></a><%
} %>
The list is the same for every visitor, and the audience is how you filter it with your own
ctx.User, so your menu agrees with the guard on the page it links to. There is no
IsCurrent and no rendered string: the answer is values, and the menu is yours. A worker
has no request and no visitor, so its catalog has no links.
A shell page is marked: its body carries class="shell" and its banner
says Site tools. It answers when the page store is broken, so its menu is the site's
routes rather than your pages; a page that wants a page-store menu reads ListAsync as
well and writes both itself. The seeded /_layout is the working example.
A prefix is a subtree, not a string prefix: "/blog" lists /blog and
/blog/post, never /blogroll. The listing returns every head the store
holds — live pages, tombstones, seeded assets and reserved keys — each marked with
IsDeleted, IsReserved, IsHtml and IsAsset, so a
view filters rather than re-deriving the host's rules. Each row also says what the head compiled to
in State — Compiled, Compiled with warnings, Compile failed,
Stale, Not compiled or Stored as source — so a listing says exactly what
the editor's list says. How you mark it is yours: the words make a fine
data-state attribute. A tombstone has no source: it
is listed as deleted and reads as absent, while its history stays readable.
The read is as public as the page that calls it. There is no gate in the host: an anonymous visitor gets the same answers a signed-in one does. A page that wants its listing or its source private writes the ordinary guard at the top of its own source, exactly as any private page does:
<% if (ctx.User is not { } user) { ctx.Response.RedirectToLogin(); return; } %>
The trade is worth stating plainly: a page that calls ReadAsync or
ReadRevisionAsync publishes the source it reads to whoever can reach that page, including
a template whose own guard hides its output, and including the history of a deleted page until it is
scrubbed. The seeded /pages is a guarded listing, source view and
history: the same capability with that one line at the top of its source.
The read is bounded. One listing returns at most the configured row cap (500 as shipped) and
refuses rather than truncating, and one render may pull in at most the configured source budget
(512 KiB as shipped) across the page and its layouts, which is also a refusal rather than half a
page. A listing charges nothing, because its rows are metadata and the body cap bounds what a page
can write out of them. Both limits are set under Pages:Read, and a missing or unusable
value stops the site at startup rather than being quietly replaced.
Writing the page store
IPageWrites is the store's write
capability. Every page that is not a layout is offered it, and the authority it checks is the
signed-in visitor's rather than the page's. There are two saves.
SaveAsync(template) stores this page's own source. It is bound to
ctx.Path and takes no key, so a page writes itself without naming anything:
<% PageSaveResult saved = await ctx.Capabilities.GetRequired<IPageWrites>()
.SaveAsync(ctx.Request.Form["template"]); %>
<p>Saved <code><%= saved.Hash %></code>.</p>
It answers a PageSaveResult: the new
revision's hash, and the compiler's diagnostics as
PageDiagnostic values — severity, the
template line and column when there is one, the code (PAGE001, CS1002) and its
text.
SaveAsync(key, template, expectedHash) stores any key the site's own routes do
not answer, and only while that page still has the head hash the form was drawn from. It answers a
PageEditResult: Outcome is
Saved, Stale or Unchanged, with the revision's hash and the diagnostics. A
stale answer wrote nothing, so re-read the source and show the author what changed. An expectation of
null means the form was drawn from a page with no live source, so a create cannot quietly
overwrite a page that appeared in the meantime.
<% PageEditResult saved = await ctx.Capabilities.GetRequired<IPageWrites>()
.SaveAsync("/blog/post", ctx.Request.Form["template"], expected); %>
Both saves compile before they store, exactly as the editor's does, so a template with an error is
still saved and reported, and a warning still serves. A page that saves itself reads its own current
source with IPageCatalog.ReadAsync(ctx.Path), which is also where the hash for a stale-form
check comes from.
The write needs a signed-in visitor. Reading the store is as public as the page that calls it; changing what the site serves is not, so either save refuses an anonymous render before it compiles anything, with a message saying to sign in. Guard your own form as well when you want the visitor sent to the sign-in page instead of the error page:
<% if (ctx.User is not { } user) { ctx.Response.RedirectToLogin(); return; } %>
The visitor is the authority, not the page. Any page may save any key the shell does
not answer; the editor is the first customer of the capability and the owner of none.
Pages:Editor:Key says only where the editor is served, which is the key
ctx.EditorPath gives you — link to it to offer "edit this page". Reserved keys are refused,
so a shell file is never written. The editor's own page is ordinary too: any page may save it or delete
it, and /admin/restore puts the seeded editor back if it is deleted or
broken.
A save belongs to the next request: the running page is already compiled, so the response
you are writing is still the page as it was. Save on a POST, write the answer you were
given, and let the next request serve the new source. A HEAD never writes, because it runs
the page once per validator, and one render writes once: a save, a delete, a restore or an install
spends the one action. A write that has started is never abandoned: if the page runs out of time the
revision is still stored, and the next request serves it.
A layout is offered the read and not the write, because it is markup: one that saved itself would add a revision to every page it wraps. The sample above is the whole of a bound save: show the source, save it, report the diagnostics and compare the form's hash before you overwrite a newer revision.
The rest of the capability is the editor's toolbox: Resolve says whether a key is
usable, DeleteAsync tombstones a page, RestoreRevisionAsync saves a retained
revision as a new one, InstallSeedAsync stores the source a release ships,
AdoptSeedAsync records a page as already holding it, and SeedSourceAsync
reads a seed so a confirmation can show the diff. The seeded
/pages is the worked example of those.
Markdown
IMarkdownRenderer renders Markdown to HTML. Write its result raw:
<% IMarkdownRenderer markdown = ctx.Capabilities.GetRequired<IMarkdownRenderer>(); %>
<%== markdown.ToHtml("## Today\n\n- one\n- two") %>
It understands CommonMark, heading anchors, pipe tables, auto-links, links and images. Raw HTML
in the Markdown passes through, exactly like <%== %>: the renderer is not a
sanitiser, so escape a visitor's or a fetched value with ctx.Response.Write rather than
rendering it. An image must be served by this site, because the response's policy allows images
only from the same origin. A table's header cells are written with scope="col", and
column alignment markers are ignored because the site's policy forbids inline styles.
A heading is written with an id made from its text, so you can link to a section with
#the-heading; a second heading with the same text gets -1. Heading anchors,
pipe tables and auto-links can be switched for one call with MarkdownOptions, which
belongs to the call rather than to the shared renderer:
<%== markdown.ToHtml("## Today", MarkdownOptions.Default with { HeadingAnchors = false }) %>
MarkdownOptions.Default has all three on. Raw HTML has no switch, because the
template can already write it and a renderer that looked like it removed HTML would invite you to
trust it with a visitor's text.
Diff
IDiffRenderer renders the line changes between two strings as HTML. Write its
result raw:
<% IDiffRenderer diff = ctx.Capabilities.GetRequired<IDiffRenderer>(); %>
<%== diff.ToHtml(before, after) %>
Every source line is escaped, so unlike Markdown this renderer is safe for a visitor's text, a
fetched body or page state. The result is a table.diff with one row per changed or
context line and its line numbers; added and removed rows carry a + or -
as well as their class, and the table scrolls sideways. An unchanged pair says so, and a pair too
different to align line by line says that the changed middle is shown as replacement blocks. A page
that compares two revisions reads them with IPageCatalog.ReadRevisionAsync; the
editor's history page compares two revisions for you.
Per-visitor state
IPageSession is a store of this visitor's own, separate from
IPageStorage: a page storage value is shared by everyone, and a session value belongs to
one browser. That is what a form needs when it answers with a 303 and the next render has
to say what happened.
<% IPageSession session = ctx.Capabilities.GetRequired<IPageSession>();
if (ctx.Request.Method == "POST") {
await session.SetAsync("notice", "Your note was saved.");
ctx.Response.Redirect(ctx.Path, 303);
return;
}
PageValue<string> notice = await session.TryGetValueAsync<string>("notice");
if (notice.Found) {
await session.DeleteAsync("notice");
ctx.Response.Write("<p>" + notice.Value! + "</p>");
} %>
A page writes, deletes and lists only its own keys: SetAsync,
DeleteAsync and KeysAsync are bound to this page's path. Reading is open, so
a page can show what another page left for it — TryGetValueAsync
takes the other page's path, normalised before use. AllKeysAsync() lists every
PageSessionKey (a Page and a Key) this visitor holds, because a
bare key cannot be read without knowing which page wrote it.
The store is JSON like page storage, keys follow the same rule, and the caps are per visitor
rather than per page: 8 keys and 16 KiB in total for an anonymous visitor, 32 keys and 64 KiB signed
in, with 4 KiB or 16 KiB for one value. A write past a cap throws when it is awaited. A session is
minted when the page first writes and travels in an HttpOnly, SameSite=Strict
cookie, so a page that only reads sets no cookie. It lasts 30 minutes without a visit, or 8 hours
when signed in, is cleared when the visitor signs out, and a session that belongs to an account is
never handed to an anonymous visitor.
A HEAD render may read and may not write, exactly as page storage behaves, and a
layout is offered the read and not the write. The seeded /privacy page says
what the session cookie is for.
Private pages and forms
Pages are public unless their own code checks ctx.User. Put the guard at the top and
return after redirecting:
<% if (ctx.User is not { } user) { ctx.Response.RedirectToLogin(); return; } %>
<h1>Draft</h1>
<p>Signed in as <%= user.Name %>.</p>
Every form an authenticated visitor can submit must carry the antiforgery field written raw,
because the host refuses an authenticated POST without that pair:
<form method="post" class="form">
<%== ctx.Response.AntiforgeryField %>
<dl>
<dt><label for="note">Note</label></dt>
<dd><input id="note" name="note"></dd>
</dl>
<button type="submit">Save</button>
</form>
Do not write a sign-in form, handle a password or read the authentication cookie:
/login and /logout already exist and are reserved. An unversioned page URL
is sent no-store without an ETag, whoever asked, because a page with code
can keep per-visitor state. The versioned URL of an asset is the one exception, below.
Assets and recovery
A page whose key has a known extension is served with that content type, so stylesheets, scripts
and other assets are pages like any other. The host maps .html, .js,
.mjs, .css, .json, .svg and .txt by
default; an unmapped key uses the fallback row, which is HTML by default.
A page with no C# is never compiled. Its stored source is the response, byte for
byte, on every request, and it is a complete representation: no banner, no skip link, no
/site.css, no title requirement and no layout. There is nothing to report in the editor,
because there is nothing to compile; adding the first code block is what starts a page compiling
again.
An asset is exactly a page with no code. There is no document extension list: the source is the document. A static page that wants the site chrome adds a code block, which makes it a fragment and lets it set a title.
Each extension row can also choose the response's script policy:
"Extensions": {
".html": { "ContentType": "text/html; charset=utf-8", "ScriptPolicy": "none" },
".htmlx": { "ContentType": "text/html; charset=utf-8", "ScriptPolicy": "self" }
}
The policy follows the extension and is applied before the page runs, so a page that calls
SetContentType keeps the extension's policy. none sends
script-src 'none'; self allows a same-origin external script and still
refuses inline script and event-handler attributes. The shipped .html row is
none; set it to self if your static documents need modules.
A versioned URL adds ?v= and the revision's hash:
/site.css?v=0123…. The value is the same 64-character lowercase hexadecimal hash the
editor's history shows. It names that exact revision and never falls back: an unknown, empty,
repeated, wrong-case or malformed hash is a 404, and so is a hash for a revision stored
under another path. Only GET and HEAD are answered. A versioned asset is
sent Cache-Control: public, max-age=31536000, immutable and a strong ETag,
so the browser need never revalidate; if it does, the answer is a cheap 304.
A URL without v still works. It is not cacheable, because a bare URL names whatever
the head is now. Editing an asset saves a new revision, so an old hash keeps serving the old bytes
and moving a link forward is your decision, never the host's. ctx.AssetUrl("/my.js")
does it for a link your own markup writes; the shell does it for the document head, its own views
and the seeded layout. A static page's own src cannot be versioned on its behalf: link
an unversioned asset, or write the hash by hand once.
The pages the site ships with are called seeds. They live under Pages/Seeds and are
created only when the page does not already exist, so editing a seed changes the site without being
overwritten on the next start. Every page the store holds carries a seed verdict in
the page list: in sync when it holds the shipped seed, release newer when the release
moved the seed and the page still holds the one it was installed from, edited when the page
changed and the seed did not, conflict when both changed, store newer when the
page holds the shipped bytes but has no record of installing them, and unknown when there is
no record at all. A page whose seed this release no longer ships is retired, and is an
ordinary live page. Only release newer offers an install; store newer and an
unknown page whose content already matches offer record as installed instead. The
row's button records one page; /admin/seed-apply records and installs
every safe row in one run and stops at the first page that has drifted, naming it. To go
back to an earlier save of the page, restore it from the page's history. A page written before this
feature has no record, so it stays unknown until something establishes where it came from;
there is no backfill of that record.
Deleting a page leaves a tombstone and its history. Saving the path again continues that history:
name the key in Create or open on the page list, and the editor says the page was
deleted and that saving brings it back. A deleted page has no current revision, so every row of its
history can be restored, including the one it was deleted at.
A tombstone keeps its revisions, so its versioned URLs still answer; scrubbing removes them, so those
URLs become 404. Neither can recall a copy a browser or a proxy already holds. If an
asset held a secret, rotate the secret and clean the external copies separately.
Keeping this page current
This page is the seeded page /help. Its source is
src/uk.osric.asp.Web/Pages/Seeds/help; use /pages?edit=/help to change
it.
A change that adds or alters what a page author can do should update this page in the same change:
a new IContext member, capability, layout slot, editor action, content type or response
rule belongs here, next to the tests and the architecture notes. The plan for the change should say
so.