`@shadestack/tree`
The website editor's page tree. Framework-free, with zod and
@shadestack/expressions as its only dependencies, and not a site
package itself: the expressions, styles, the rendering core and the four renderers, interactions, the accessibility
checker and the editor build on its types. The website module keeps a page's tree in a json field and checks it
itself (website:tree: readTree with the site's languages, its component library, its embed permission, the
editor roles and the media types each place takes), and the content API gives it to sites as page.tree.
asNodeTree(stored) reads a stored value as a tree for showing it (an older version migrated, anything else an empty
tree), and isNodeTree says whether a value has a tree's shape.
A stored tree is { version, nodes }. Eight node types; the first seven match what a developer writes in code:
| Node | Is | In code |
|---|---|---|
element | an allow-listed tag with allow-listed attributes, style classes and children | <section class="…"> |
text | plain text, per language, escaped when rendered | Welcome |
component | an instance of a component (a library's card, a module's shop.offer, or one of SHADE's widgets, shade:dialog): its properties and its slots' nodes | <Card title="…"><p>…</p></Card> |
if | a condition with a then and an else branch | {#if}…{:else}…{/if} |
each | a loop over a list or a data source, with an item name, an optional index name and a key | {#each items as product (product.id)} |
slot | where an instance's content goes, in a component's own tree | <slot name="…"> |
island | rendered per visitor on the server (server), or hydrated with state (client) | server:defer, client:load |
embed | raw HTML, behind its own permission, sanitised into elements by the rendering core | {@html …} |
import { insertNode, readTree, validateTree, diffTrees, type NodeTree } from '@shadestack/tree'
const tree: NodeTree = {
version: 2,
nodes: [{
id: 'intro', type: 'element', tag: 'section',
children: [
{ id: 'title', type: 'element', tag: 'h1', children: [
{ id: 'title-text', type: 'text', value: { kind: 'binding', expression: { type: 'path', root: 'entry', keys: ['title'] } } }
] },
{ id: 'lead', type: 'element', tag: 'p', children: [
{ id: 'lead-text', type: 'text', value: { kind: 'literal', value: { nl: 'Welkom', en: 'Welcome' } } }
] }
]
}]
}
const result = validateTree(tree, {
languages: { default: 'nl', others: ['en'] },
components: name => library[name], // what an instance is checked against
expressions: createExpressionChecker({ entry: entryType, site: siteType }), // types every name in scope
embeds: user.mayEmbed // the permission to save raw HTML embeds
})
if (!result.ok) console.log(result.issues) // [{ code, path, nodeId, message }]
- Values are tagged:
{ kind: 'literal', value }or{ kind: 'binding', expression }. Text, and every translatable attribute or property, is per language:{ nl: '…', en: '…' }. An image'ssrcis a media library image,{ mediaId }, which the renderer resolves to its address (or an address on the site). A link'shrefis an address or a page by id,{ kind: 'entry', collection, id, anchor? }(EntryLink, aurlattribute withentriesinhtml.ts), which the renderer resolves to that page's address in the page's language throughlinks, as navigation links are; one without an address there is left out and reported. Ids, names, enums and tokens are literal only, except an enum markedbindable(aria-current,isBindable,bindingType), whose binding gives text held to its values when rendered, and thenameof aninput,selectortextarea, so a form's controls can be drawn from data (the forms module's Form starter names each by its field's key). A bound control name is checked when rendered (isBoundNameAllowed): lowercase letters, digits and dashes (BOUND_NAME) and never a property of the page or a form, such asactionorsubmit(DOM clobbering); any other leaves the name out, so the control sends nothing, and is reported. A form's, a fieldset's and an output's name, and everytypeandid, stay literal. The only roles a tree sets are a live region's,role="status"orrole="alert", on adiv,p,spanorsection. - Expressions are
@shadestack/expressions' AST.validateTreedecides where a binding may stand, what type it must give there and which names are in scope (entryandsiteeverywhere,visitoronly inside a server island,stateonly inside a client island,propsonly in a component's own tree,eventonly in an event's actions, and each enclosing Each's item and index), and passes that to theexpressionschecker.createExpressionChecker(environment)is that checker: give it the types of the entry, the site, the visitor's projection, a component's properties (propertyTypes(interface.props)), the data sources' items (sources) and the site's translation keys; what it has no type for can't be read. Each place accepts whatEXPECTEDsays (a text shows nothing for an empty value, a condition must decide; a text node may show rich text,content; a URL place takes a link or a media library image too, resolved to its address when rendered), and an issue'spathpoints into the expression (nodes.0.value.expression.args.0). A checker is told the place (ExpressionPlace): what it expects, the scope, for a URL its schemes, and forsetStatethe state's exact type. A bound URL's texts that are known when the tree is saved (a literal, a ternary's or a??'s literal branch, a literal start such as'javascript:' + x) go through the attribute's allow-list then (knownUrlProblem; more than 64 such texts and the binding is refused, never checked in part); the rest is checked when it is shown (the runtime'surl). Each loop's item is typed once, where its Each stands (ScopeItem.scope), so checking is linear in the tree's size, and a tree's expressions may hold at mostmaxExpressionPartsparts together (default 50,000). Without a checker every binding is refused; withoutcomponentsevery component instance is; withoutembeds: trueevery embed is. - Events and actions: an element inside a client island may answer
events(click,submit,change,input,keydownnarrowed to akey,load), each with actions run in order:setState,toggleState,navigate(the link scheme allow-list),submitForm(a form of the island, by id),callRoute(a module's public or account route, throughcallAccountRouteat SHADE's account API (accountApiBase, the page'sshade-account-apiaddress), with values in its body and its address and maybe a form of the island, its answer kept in ananswerstate of that route and how it went in a text state;challengesolves the module's proof of work first and sends it asaltcha),playInteraction, andaccount(a step of SHADE's own account routes,ACCOUNT_STEPS: how it went in a text state,ACCOUNT_STATUSES, and who is signed in in anaccountstate ofnameandemail; onlysessionruns on load; a step with a form sends its fields by the namesACCOUNT_FIELDSgives). A password field (type="password") stands only in a form of a client island, takes no events, and its form goes only toaccount, nevercallRoute; the renderer writes that form withmethod="post". Text, number and on/off state may bekeptin the visitor's browser, shared by every island of the site with a kept state of that name. A text state may have a fixed set ofoptions(2–16 lower-case names such assiteorall-plugins) and a number arange({ min, max }); styles read them through the island's wrapper (see Expressions and styles), so neither may bekept, the first value is one of the options or inside the range, and asetStatewith a literal outside the options is refused when saving (a computed one at run time, like a value of another type). The runtime writes the options' values asdata-shade-state="picked:site"on<shade-island>, already in the first view, and each number kept to its range as--shade-value-<name>once the island runs, at most once a frame. Events stand only inside client islands and on elements that answer them, invalidateTreeand the operations alike;validateTreechecks actions against the island's state and forms,visitorRoutes(plugin, method, route)andinteractions(id), and refuses every route call and interaction without those lookups.setStatetakes exactly the state's type (never nothing, a list's items of its type, never a data source); a boundnavigatetarget is never nothing, its known texts are checked when saved and the islands' runtime checks what it gives withurlbefore going.loadruns without the visitor doing anything, so it takes onlyLOAD_ACTIONS: set or toggle state, play an interaction, or aGETroute call; nevernavigate,submitFormor a route call that changes something. - Loops over data sources: an Each's
sourceis a data source written in the tree ({ kind: 'literal', value: { source: 'collection:posts', parameters: { order: 'newest', limit: 6 } } }), whose items the renderer fetches on the server, or a binding that gives a list or a source. A component property of typesourceholds a data source, so an Each in the component's tree can loop overprops.feed: asourcecounts as alist(acceptsValue). - What
validateTreerefuses: tags off the allow-list (script,style,iframe,svg,object,template…), attributes a tag doesn't take, everyon*attribute,style, a form'saction, URLs outside the scheme allow-lists (urls.ts: links http, https, mailto, tel; audio, video, tracks and posters https; relative paths; whitespace, control characters and backslashes refused), images from another host, ids and form names that are a property of the document, a form or the window (submit,action,cookie,name…: DOM clobbering), names such asconstructorortoString, an interactive element inside another (also in a summary), flow content where only phrasing may stand, misplaced list items, table rows (only inthead,tbody,tfoot), table cells,dtanddd, and options, islands where only some tags or only text may stand, children in void elements, duplicate ids, locks on fields a node doesn't have, oversized or too deep input (checked before parsing) and__proto__keys. - Components are seen through, both ways. An instance counts as the tag it renders as, with the tags, the
interactive content, the islands and the embeds it holds (a card holding a link can't stand in a link, a component
holding an island not in an island, one holding an embed not in a form), and the nodes in one of its slots are
checked where that slot stands in the component's own tree (no link in a link component's slot).
describeComponent(componentTree, { components })computes that part of a component's interface (root,phrasing,interactive,tags,islands,embeds, and per slotcontent,parentTag,forbidden,noInteractive,island); the library stores it with the component, a code component declares it. - A component as data is a
ComponentDefinition(its tree, properties, slots, variants, default variant and defaults), whoever keeps it;validateComponent(definition, { name, languages, components, types, visitorRoutes, forms })checks one without a database (properties, defaults, variants' classes, its tree as a component's, its slots placed once, no instance of itself), andinstancesInandplacedSlotsread a tree. The website module's library and its SDK'scheckComponent(@shadestack/module-website/sdk/testing) use it;@shadestack/render'sLibraryComponentis made from it.@shadestack/tree/buildbuilds trees in code (el,words,show,when,each,slot,use). - Embeds hold raw HTML: at most 20,000 characters, refused when they contain
<script, anon…=attribute, ajavascript:/vbscript:URL (also with a tab or newline in the scheme, or written with character references such asa) orsrcdoc(a first check, not a sanitiser), and every renderer sanitises them before output. They stand only where flow content may, outside links, buttons and forms. - Locks (for the editor's roles): any node may carry
locks: { structure, properties, styles }, the properties by the field namesdiffTreesreports (tag,attributes.href,props.title,value). The tree checks their shape; the website module's content check enforces them when saving:editProblems(before, after, role)inrights.tssays what a builder or content editor changed beyond their role or past a lock, each problem with acode(RIGHTS_PROBLEMS), andmayChangeField,mayAddToandmayMoveOrRemoveanswer an editor's questions per node. The website module's roles arewebsite.pages.designandwebsite.pages.build. - Renderers check bound URLs again when they are known, with the runtime's
url(value, schemes)(or the samesafeUrl(value, schemes), from@shadestack/expressions): the rules are@shadestack/expressions' (urls.ts), and the tree re-exports the scheme lists andurlProblem. - Schema versions:
readTree(stored, options)migrates a tree of any earlier version (migrateTree,MIGRATIONS) and validates it. RaisingSCHEMA_VERSIONwithout a migration fails the package's tests. Version 2 stores expressions as their AST, parsed from version 1's{ expr }placeholders; one that doesn't parse, or isn't exactly{ expr: '<formula>' }, stops the migration with its reason and where. - Operations:
insertNode,moveNode,removeNode,duplicateNode,updateNodereturn a new tree and share untouched subtrees; they throwTreeOperationErrorwith acodefor what the nesting rules refuse, the same rulesvalidateTreeapplies (nesting.ts). A node they are given is checked for size before its schema reads it (too-large,structure), andmaxNodes/maxDepthin their rules refuse an insert, move or duplicate past them. Every walk is iterative, so no tree is too deep for them. A position is{ parentId, list, index }, wherelistischildren,then,else,empty,fallbackorslot:<name>. - Comparison:
diffTrees(before, after)lists nodes added, removed, moved and changed, with the changed fields (attributes.href,props.title,value.nl,locks.structure).summarizeChanges(before, after, locale?)is that for a person: a removed or added subtree once, each node with its tag or component and first words, at most 200 changes (morecounts the rest).
Code, in shade-frontend: packages/tree/src/. Tests: packages/tree/test/*.test.ts.