`@shadestack/render`
The website editor's rendering core. Framework-free, on @shadestack/tree,
@shadestack/expressions and @shadestack/styles; the four framework packages render what it gives with their own
components (ShadeTree in each, below). Everything is decided on the server; the frameworks only write it.
import { headData, pageSources, resolvePage, sourceKey } from '@shadestack/render'
// The data sources the tree and its components name, fetched first (rendering is synchronous).
const sources = new Map(await Promise.all(pageSources(tree, library).map(async source => [sourceKey(source), await fetchItems(source)] as const)))
const result = resolvePage({
tree, // the page's tree, as stored (any schema version)
treeId: page.id, // what its local styles are keyed by
components: library, // { card: { tree, interface, defaults, variants, treeId } }
entry, site, // plain data
visitor, // the account's allow-listed projection, made on the server; read only in server islands, with `signedIn` added
sources: source => sources.get(sourceKey(source)),
locale: 'nl', defaultLocale: 'nl', timeZone: 'Europe/Amsterdam', translations,
media: id => media[id], // { url, width, height, alt, variants }
localStyles: styles.local, // which nodes get data-s
edit: false // true: every element gets data-shade-node (and data-shade-instance) and its data-s key
})
result.nodes // the resolved tree: elements, texts and islands
result.classes // the style classes used (the CSS is compileStyles', linked once)
result.issues // what wasn't rendered and where: codes and paths, never the data's values (every ShadeTree tells them on the server)
const head = headData({ title, description, canonical, alternates, language: 'nl', image })
- The resolved tree (
resolved.ts) is plain elements with checked attribute values and texts (never HTML: every framework escapes them, andtoHtml, the core's own writer, does too), and islands. Bindings are evaluated with the expressions' interpreter; every URL place (links, quotations, media, a media library image and itssrcset, a menu item,navigate) goes through the runtime'surlwith its own schemes, literal or bound, also for a tree that skipped the save gate; a link value or a media library image there is its address (an entry's throughlinks). If keeps only the branch that holds; Each repeats per item of a list or a data source, with itsemptybranch; component instances render their tree with their properties (literal, bound or the component'sdefaults), their slots' content in the scope it was written in and their variant's classes on the top elements. A bound property is held to its declared type (boundProperty: a choice one of its choices, a number finite…), or gets its empty value and an issue. A failure shows nothing in its place and is reported. - Rich text bound to a text node renders from its schema's nodes and marks only (
richTextNodes; headings areh2,h3orh4, a level rounded and held to them,h2for one that is no number), as much as may stand there: blocks in adiv, texts and marks with line breaks in ap, its text in anoption. - Images from the media library get
srcset(the original among the sizes), the tree'ssizes(default100vw), dimensions,loading="lazy", the library's alt text, and a<picture>with a source per other format (a variant'stype,image/avifbeforeimage/webp). An image without alt text is written withalt=""and reported;alt=""in the tree marks it decorative. - Server islands read
visitor; outside them it is not in scope. They render with the visitor by default (pass it on a dynamic route); the page is then the visitor's (result.personal) and each package sends it withCache-Control: private, no-store(cacheHeaders(result); in AstroapplyCacheHeaders(Astro, result)in the page's frontmatter).serverIslands: 'defer'makes placeholders for Astro'sserver:defer, rendered per request byrenderServerIsland(serverIslandPayload(result, key), { visitor }), which reads only the visitor fields the payload names. A payload holds what only some visitors may see, so it is never part of the result's data: a result sent as a framework's page data, copied or cloned has none. Next, Nuxt and SvelteKit seal it instead (Deferred server islands, below). - Client islands carry
ClientIslandData: their state's first values and types and a template with everything decided but what depends on the state, an event or a live loop's item. Each live expression carries only the fields it reads of the entry, the site, the props and the loops around it, never the visitor.createIsland(data, { callRoute, navigate, onError })is the islands' runtime all four use:view()for the nodes to show (elements answering events markeddata-shade-on),dispatchandstartfor the actions (navigatechecked withurlbefore it goes,callRoutethroughcallAccountRoute, its answer and status kept, an idempotent call's key kept until it is done, a repeating call made again throughschedule(by defaultsetTimeout),playInteractiondispatchingshade:interaction,accountthroughaccount(by defaultaccountStepataccountApiBase(), which reads an email link's#confirm=or#reset=once withaccountLink, takes it off the address bar and gives it only to its step, and empties the step's password fields after it); kept state read fromstorage, by default local storage (sessionStorageforkept: 'session', by default session storage), once the island starts, so the first view stays the server's), andconnectIsland(island, wrapper, onChange)to run it there: subscribed, its events caught on the wrapper (listenIsland) and started, with what stops it all. Islands stand in a<shade-island>wrapper. On a server the defaultonErrorreports nothing (a throw there would stop the server): what fails in an island's first view is an issue ofresolvePage's, with the island's key. In the browser the packages load@shadestack/render/island, the islands' runtime alone (no resolver, sanitiser or schemas;island-entry.test.tsholds what they load to a budget). Two parts are chunks of their own, fetched only on a page that uses them:callAccountRoute(@shadestack/client/account) on an island's first route call,solveChallenge(@shadestack/client/challenge, the island host'ssolveChallengeoption) on acallRoutewithchallenge, and the account action's code when an island shows or runs an account step. A chunk that doesn't load fails its action like any other error: it is reported and the actions after it don't run. - Embeds are sanitised into elements (
sanitizeEmbed): a strict allow-list with its own tokenizer; scripts, styles,iframe,object,svg,math, forms and the like go with their content; noon…,style,srcset; URLs through the scheme allow-lists; ids that would clobber the DOM andshade-/site-classes dropped. It applies the tree's nesting rules from where the embed stands, as a browser does (a link in a link unwrapped, apclosed before a block, a table'stbodyandtradded), so a browser builds exactly what it gives. - Limits (
RENDER_LIMITS): components 16 deep (one inside itself refused at once), 1,000 items per loop, 20,000 nodes and 2,000,000 characters per render, counting texts, attribute values, an embed's attributes and what client islands carry. The client islands' first views (what the server renders of them) share the page's budget: together they get what the page left of its nodes and characters. Past the depth or a loop's limit, that component or loop gives nothing; past the nodes or the characters, the whole render gives nothing (islands included) and atoo-largeissue. - Widgets a tree names by a reserved id (
WIDGETS, in@shadestack/treeso a check knows them without the renderer, holds their interfaces for the tree'sComponentLookup):shade:disclosureandshade:accordion(<details>, no script),shade:dialog(a modal<dialog>with its button),shade:tabswithshade:tab,shade:menuwithshade:menu-item(links), each with ARIA's pattern (until the script runs, every tab panel shows and a menu's links are a plain list, so nothing is out of reach without it), andshade:skip-link(to#main, shown when it has focus) for the top of the header part;shade:navigation, a labelled<nav>(itsitemsslot) with a Menu button below 48rem that Escape and a click outside close, or below one of the site's breakpoints when itsfoldAtnames it, or never withfoldAt: "none"(NO_FOLDof@shadestack/styles, which no breakpoint may be called). It is written asdata-shade-foldon the element; the rules are in the site'sstyles.css, which the website module writes withnavigationFoldCssof@shadestack/render/navigation-foldfor the breakpoints its live navigations name.render.cssstands a navigation withdata-shade-foldin a row (its button hidden) at every width, and the fold rules, more specific, fold it below its breakpoint and stack its menu there; so one set tonone, or whose breakpoint has no rules, never folds and stays in a row.@shadestack/a11ywarns of the second (navigation-fold); andshade:icon, a Lucide icon byname(@iconify-json/lucide), hidden from screen readers unless it has alabel, in a client island only with a fixed name (its SVG travels in the island's template); andshade:year, this year as the render's (intimeZone, atnow), which the visitor's browser sets to its own;shade:mode-switch, a button showing the page's light or dark mode and switching it;shade:code, a code sample (code,language) highlighted on the server with Prism's tokenizer intospans classed by kind, never in a client island; andshade:pause-motion, a button (itspauseMotionword by default) hidden until its script shows it, pressed while the page's animations are paused: a press keeps the choice (localStorage['shade-motion']) and sendsshade:motionondocument, which the interactions runtime follows; never in a client island; andshade:embed(category,url,title,ratio), an outside player or map behind the visitor's consent: give the renderconsent(the site data's categories,renderInputFordoes) and it renders a notice from one of the category's hosts, which the consent runtime turns into the frame once allowed (The consent banner). The words a widget says when the editor gave none (a dialog's close button, the skip link, the navigation's name and Menu button, the mode switch, the pause control, an embed's notice) are the render'swords: the site data's, in the page's language, whichrenderInputForgives (The site's words). Without them such a widget is left out, with an issue. Their behaviour isdefineWidgets()of@shadestack/render/dom: custom elementsshade-dialog,shade-tabs,shade-menu,shade-mode-switch,shade-navigation,shade-pause-motionandshade-year, the same for every framework (each package loads it). An instance's classes go on its widget's outermost element, after the widget's own (a tab's on its tab, a menu item's on its list item). A widget names the inner elements a site may style (ComponentInterface.parts, inWIDGETS):shade:tabslist,tab,panel;shade:menubutton,list,item;shade:navigationtoggle,nav,content;shade:disclosuresummary,content;shade:dialogbutton,dialog,title,close,body;shade:mode-switchandshade:pause-motionbutton. An instance'sparts({ tab: ['pill'] }) puts those classes on them, after the widget's own class, and the styles' statesselected,expandedandcurrent(experimental) match theiraria-selected,aria-expandedandaria-current. Their buttons are 24px high at least (render.css).shade:menutakes anicon(a Lucide name) before its label, and its items may come from an Each; ashade:menu-item'slanguagewrites its link'shreflangandlang, andcurrentitsaria-current="page". The accessibility check sees a widget's own classes, its parts' classes and the labels an instance gives it, so their contrast is checked in every state. Their ids areshade:<idScope>:<n>, the scope the render'streeIdunlessidScopenames one: resolve each part of a page (header, page, footer) with its own. - Code components: components a frontend registers in its own code, by name. Give their names to
resolvePageascodeComponentsand the components to the package'sShadeTreeascode. An instance naming one resolves to acodenode: its properties now (a binding evaluated), its slots' content resolved like the rest; the package renders the frontend's component there (Astro gives itnode,codeandcontext, the page'scontextpassed along; Reactnodeand its renderedslots; Vuenodeand Vue slots; Sveltenode, withShadeNodefor the slots). In edit mode it stands in a<shade-code>wrapper with its markers. Code components render on the server only (never in an island or a live part); a name the library has too is refused; they take no classes and their properties are plain data. - Head data (
headData): title, description, canonical,hreflangwithx-default, Open Graph andstructuredData(JSON-LD objects, written byscriptJsonasjsonLd, which nothing can end); absolute http(s) addresses only (an image https). Each package writes it through its framework's head API, and each JSON-LD writer (Next'sShadeJsonLd, Astro's and Svelte'sShadeHead, Nuxt'sshadeHead) leaves out an entry thatisScriptJson(@shadestack/render/island) refuses: one with a<,>or&, which didn't come fromscriptJson. - Sitemap (
sitemapXml(entries)): the sitemap protocol's XML with each page's other languages, every address checked, for a route of the site's own (an Astro endpoint, Next'sapp/sitemap.xml/route.ts, a Nuxt server route, a SvelteKit+server.ts). @shadestack/render/render.css: the islands' wrappers and the widgets' few styles, in the theme's variables. Link it once.@shadestack/render/dom: the browser side without a framework:defineWidgets(),mountIslandanddefineIslands()(a client island patched in place, used by Astro). A renderer that writes the<shade-island>wrapper by hand writes its data after it withislandDataScript(island)from@shadestack/render, never by hand: it isscriptJson's output in the script elementdefineIslandsreads.@shadestack/render/server-islands:loadServerIslands({ base }), which fills a static page's deferred server islands in Next, Nuxt and SvelteKit from<base>/shade-island(its own chunk, loaded only by a page that has some).@shadestack/render/conformance:FIXTURES(trees with the HTML every renderer must give, XSS and URL fixtures among them),fixtureResultandnormalizeHtml. A renderer passes when every fixture's result (fixtureResult: itsresolvePageresult, or that result tampered with, for what a renderer must check again), rendered, normalises to the fixture's HTML; the core, Astro, Next, Nuxt and SvelteKit are all held to it.
Each framework package's ShadeTree renders a resolvePage result:
| Package | Component | Client islands | Head | A visitor's page |
|---|---|---|---|---|
@shadestack/astro/tree | <ShadeTree result accountApi> | their first view, their data as JSON after it, patched by <shade-island> (@shadestack/render/dom); deferred server islands with server:defer (accountApi: the site's SHADE_API_URL and SHADE_ACCOUNT_URL) | <ShadeHead head> in <head> | applyCacheHeaders(Astro, result) in the page's frontmatter |
@shadestack/next | <ShadeTree result> (a server component) | ShadeClientIsland, a client component on useSyncExternalStore | shadeMetadata(head) from generateMetadata (robots as it says; meta it has no field for in other), <ShadeJsonLd head> | await shadeNoStore(result) (ShadeTree warns once of a personal result it never saw) |
@shadestack/nuxt | <ShadeTree :result> (registered by the module) | ShadeClientIsland, state in a ref, hydrated with the page | useHead(shadeHead(head)) | ShadeTree sends the HTML with no-store; shadeNoStore(event, result) in the server route sends its JSON so |
@shadestack/sveltekit | <ShadeTree {result}> | ShadeClientIsland, state in runes | <ShadeHead {head} /> | shadeNoStore(result, setHeaders) in load (ShadeTree warns once of a personal result it never saw) |
The same in every package (review rendering 7):
- What it renders: the input of
@shadestack/client/render(above), on the server. code: the frontend's code components (above), as each framework writes components (Astro's getnode,codeandcontext; React'snodeand their slots rendered; Vue's and Svelte'snode).interactions: a page's interactions. Astro writes them as the page's JSON script (pageInteractionsJson) and loads the runtime in a script of its own; Next, Nuxt and SvelteKit load the runtime once the page is mounted, only for a page that has some (hasPageInteractions,@shadestack/interactions/present), and give it the interactions as data, again with the next page's when the framework keeps the page's component. All four start it the same way (bootPageInteractions), which also plays what an island'splayInteractionasks for: the island'sshade:interactionevent, with its tree and the element whose action ran, reaches the runtime'splay().- Islands: each runs its client islands through
connectIsland(@shadestack/render/island). - Issues: each tells a result's
issueson the server, once per issue (reportRenderIssues,issueText). - A page by its path:
findPage(client, …)andshadeFromEnv(env)(@shadestack/client/render's; SvelteKit takes the rest route's path as one string). - Deferred server islands: Astro's are
server:defer's; Next, Nuxt and SvelteKit seal them into their placeholders and fill them from the site's island route (below). On a page rendered per request, all four can instead give the visitor toresolvePage.
None of them sets HTML from a string but an icon's SVG, and only once isIconSvg says it is the icon set's own (its
start tag and Lucide's shapes, nothing that links, runs or styles); structured data, scriptJson's output, is a
script's text as it is. Each checks every tag and attribute name again (isWritableTag, which also refuses script,
style, iframe, object and embed, and writableAttributes) and leaves out what fails, an icon that isn't the
set's too, and keys each client island by its key, so new data (the next page of a route, a refresh) makes a new
island. The conformance suite holds them to it with a result tampered with (fixtureResult).
Code, in shade-frontend: packages/render/src/ (resolve.ts, properties.ts, richtext.ts, template.ts, island.ts and
island-entry.ts, sanitize.ts and tokenize.ts, attributes.ts, names.ts, widgets.ts, head.ts,
sitemap.ts, defer.ts and seal.ts, dom/, conformance/), and each package's tree files. Tests: packages/render/test/*.test.ts, the
conformance suite in each package (packages/next/test/tree.test.tsx, packages/nuxt/test/tree.test.ts,
packages/sveltekit/test/tree.test.ts, packages/astro/test/tree/tree.test.ts), the widgets and the DOM runtime in a
real browser (e2e/tests/render-dom.spec.ts), and one island page hydrated by React, Vue, Svelte and the DOM runtime
in a real browser (e2e/tests/render-frameworks.spec.ts, built from the packages' sources by e2e/render-bundles.ts). These browser tests need no SHADE instance: they are in shade-frontend's e2e/, with its own Playwright.
Deferred server islands
A statically built page shows its server islands ("Welcome back, Sam", a cart count, "My bookings") per visitor in
every framework. Astro renders them with server:defer (ShadeTree with accountApi). Next, Nuxt and SvelteKit do
the same in three steps:
- Resolve the page with
serverIslands: 'defer'(renderPublishedPage(page, context, { deferIslands: true })), then seal it on the server:await deferServerIslands(result)(SvelteKit:deferServerIslands(result, env)). Each island becomes an empty<shade-island data-shade-defer="…">holding its payload sealed with the site's secret. Render that result withShadeTree; it may go through the framework's page data. - Add the island route,
GET /shade-islandon the site's own origin, under its base path if it has one (the setup per framework is in the frameworks' pages). ShadeTreeloads@shadestack/render/server-islandsonce the page is mounted, on a page that has deferred islands. It asks the route once per island, with the visitor's sign-in cookie, and puts the answer in the island.
A site under a base path has its island route there too: ShadeTree tells the loader the base, and it asks
<base>/shade-island. Nuxt (app.baseURL) and SvelteKit (paths.base) give it on their own; in Next, pass the
basePath of next.config to ShadeTree (<ShadeTree result={result} basePath="/docs" />; default none).
Set SHADE_ISLAND_SECRET (at least 32 characters, made with openssl rand -base64 48) in the build's environment
and the server's, the same in both. SHADE_API_URL (or SHADE_ACCOUNT_URL when the account API has its own address) tells
the route where to ask who is signed in. The account API must be on the site's origin for the cookie to come along, as
for every visitor route (accounts).
How it holds:
- Sealed, not signed. A payload holds both branches of a condition on the visitor (what a signed-in visitor sees, and what nobody does), so it is encrypted with AES-256-GCM (Web Crypto; the key derived from the secret with HKDF-SHA-256). Nobody can read it in the page or change it: the route refuses a payload that doesn't open. Changing the secret refuses every earlier page's islands until the next build.
- Bounded. A sealed payload is at most 8,000 characters (
SERVER_ISLAND_TOKEN_LIMIT), since it travels in the address. A larger island stays empty, for nobody, with atoo-largeissue in the build's log. - Deny by default. The route answers GET only (405 otherwise), refuses a request whose
Sec-Fetch-Siteis notsame-origin(403) and a payload missing, too long or changed (400), always with an empty body. Its answer is the island's HTML (the core'stoHtml) withCache-Control: private, no-store. A render that fails answers an empty 500; the reason is only in the server's log. - Same origin. The base path comes from the framework's own setting, never from the page or its tree. The loader
refuses, before asking anything, a base that isn't empty or a path starting with
/(no//,\, scheme, query or fragment). - For a year. A seal carries when it was made, and the route refuses one older than a year
(
SERVER_ISLAND_MAX_AGE), so a token copied from a page stops working in time. Build a static page again within a year, or its islands stay empty, for nobody. - Only what it reads. The visitor is the account API's session for the request's
shade_account.*cookies (the site's others stay with the site), projected to the fields the island reads (name,email,signedIn); nobody without a session, or when the API can't say within 3 seconds. - Accessible. Until it is filled, and when the request fails, the island is an empty wrapper, as Astro's fallback:
nothing is announced, and filling it announces nothing either. Calling
loadServerIslandsagain asks again for an island whose request failed.
The functions are sealServerIslands(result, secret) and openServerIsland(token, secret, maxAge?) (@shadestack/render),
answerServerIsland(request, options) and serverIslandRoute(env) (@shadestack/client/render), and
loadServerIslands({ base }). The conformance suite's DEFERRED_FIXTURES hold the core and the three packages to the same
placeholders and the same answers for a signed-in visitor and for nobody, and to refusing a changed payload;
e2e/tests/render-deferred.spec.ts fills an island with React, Vue and Svelte in a real browser, at the root and under a base path.
The website editor's canvas
The website editor edits a page over the frontend itself. A frontend that supports it has two routes:
- The edit route (
/preview/canvas?token=…on SHADE's site): reads the draft with the preview token (shade.canvas(token), the website module's/api/v1/content/website/canvas: the page and its stored node tree), renders the tree withresolvePage({ …, edit: true })in the site's layout, sendscanvasHeaders(adminOrigin)(no-store,noindex,no-referrer, so the address with its token goes nowhere, andframe-ancestorsfor the admin) and startsconnectCanvasin the browser. - The render route (
POST /preview/canvas/render):readCanvasRequest(request)(same host, at most 2 MB, a token and a tree; else the response to answer with), then the same render without the layout: what goes inside<main>.
import { connectCanvas } from '@shadestack/client/canvas'
connectCanvas({
adminOrigin, // the only origin the canvas listens to and answers (of an address, only its origin counts)
async render(body) { // { token, tree }: the editor's draft
const response = await fetch('/preview/canvas/render', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
if (response.status === 401) return { error: 'expired' }
return response.ok ? { html: await response.text() } : { error: 'failed' }
}
})
The admin owns the tree: it sends the whole draft once (tree), then each change as tree operations (patch) on the
revision the canvas has; the canvas applies them with @shadestack/tree's operations (applyEditorMessage in @shadestack/client/canvas), asks for
the tree again when it can't (resync), renders one draft at a time (the newest wins) and swaps in the top-level
nodes that changed. It outlines the selected and hovered nodes (a display: contents wrapper is measured by its
children), selects the outermost component instance around a click, asks for the element menu on a right-click (contextmenu
with the point; Shift keeps the browser's menu), stops links and forms, sets the colour mode
(data-shade-mode on <html>) and scrolls to a node on request. The messages are EditorToCanvasMessage and
CanvasToEditorMessage (@shadestack/tree/canvas, with CANVAS_PROTOCOL_VERSION; core and the module SDK don't
have them), version 2 of the canvas protocol, with its origin rules. The theme
screen uses the canvas too: it sends the home page's tree and, as styles, the theme with the site's styles.
The canvas writes no inline styles: its outlines' CSS and the editor's styles go into constructed style sheets
(CSSStyleSheet with replaceSync, in document.adoptedStyleSheets), which a Content-Security-Policy's style-src
doesn't restrict. Nor does it need 'unsafe-eval': @shadestack/client/canvas first imports @shadestack/tree/jitless,
which runs zod without compiled parsers in the browser, so the tree's schemas never try new Function, in every
framework. The edit route's policy can name its <style> blocks by hash and leave out 'unsafe-inline'
(SHADE's site: previewPolicy). The page's own <style data-shade-styles> draws the first paint; the first styles
message removes it once the adopted sheet holds the styles. Adopted sheets come after the page's own style sheets, so
the editor's styles come after the saved theme.
SHADE's site: src/pages/preview/canvas.astro, src/pages/preview/canvas/render.astro, src/lib/canvas.ts,
src/scripts/canvas.ts. Code, in shade-frontend: packages/client/src/canvas.ts, packages/tree/src/canvas.ts (@shadestack/tree/canvas). Tests:
packages/client/test/canvas.test.ts, and the website module's e2e/site/canvas.spec.ts on the built site.
Details
- A formula that can't give its value when a page is rendered shows nothing in its place, and the problem is reported without the data in it (the report never carries the page's or visitor's values).