@ts0/dom
v0.3.0-beta.0
Published
Zero-dependency, schema-validated, deterministic scoped DOM driver for ts0 Malleable UI.
Maintainers
Readme
@ts0/dom
Beta. Until v1 a release can break the previous one, with no migration path.
Zero-dependency, schema-allowlisted, deterministic scoped DOM driver for ts0 Malleable UI (@ts0/core).
Features
- Per-tenant scoped
SlotRefhandles: Guests never seeHTMLElement,document,window, or CSS selectors. Every mounted element is bound to a generation-tracked slot lease with explicitread,write,focus, andscrollgrants. - Schema-allowlisted DOM patching: Rejects
on*event attributes, rawstylestrings/objects, URL attributes (href,src,action),srcdoc,innerHTML,contenteditable, and invalidtabindexvalues. CSS custom properties are typed and range-checked ([min, max]+ host-suppliedunit). - Atomic preflighted turns:
DomScope.run()validates reducer state, the full effect batch againstallowedIntents, and the projected view before admitting a revision or callingonPreventDefault(). Apply the admitted revision withflush(revision). - SSR/edge-safe & deterministic replay:
createHeadlessDriver()andcreateBrowserDriver()share the exactDomScopecontract with zero top-level browser global reads.
Install with pnpm add @ts0/[email protected] @ts0/[email protected] to compile and run a scoped guest.
Grants and turn intents
scope.attach(ref, node, grant) requires a grant. Supply {} to deny every
capability, { read: true } to enable measurement and resize observation, or
the exported FULL_SLOT_GRANT for all four capabilities. Omitted flags are
denied. Grant flags must be booleans. Unknown flags are rejected.
A turn that emits effects must list their intent kinds in
TurnInput.allowedIntents. Omitting the list denies every effect. A turn with
no effects may omit it.
Pass the raw guest result directly to run. It checks the { state, effects }
envelope and calls validateState once and validateEffect once per effect.
The view callback receives the state returned by validateState.
import { compile } from "@ts0/core"
import { createDomScope, createHeadlessDriver } from "@ts0/dom"
const driver = createHeadlessDriver()
const pane = driver.createNode({ width: 640 })
const scope = createDomScope(driver, {
slots: { pane: { attrs: { "data-compact": "boolean" } } },
validateState(value) {
if (typeof value !== "boolean") {
throw new Error("Expected a compact-layout flag.")
}
return value
},
validateEffect() {
throw new Error("This controller has no host effects.")
},
intentKind: () => "",
})
scope.attach("pane", pane, { read: true, write: true })
const program = compile(
`
import { measure } from "@ts0/dom/guest"
export function step() {
const box = measure("pane")
return { state: box !== null && box.width < 700, effects: [] }
}
export function project(compact) {
return { pane: { attrs: { "data-compact": compact } } }
}
`,
{ imports: { "@ts0/dom/guest": scope.imports } }
)
const revision = scope.run(
{ kind: "init" },
() => program.call("step"),
(state) => program.call("project", [state])
)
scope.flush(revision)
const snapshot = driver.readSnapshot(pane)
scope.dispose()
export { snapshot }Retrying a flush
If the driver fails during flush, the scope attempts to restore the previous
view. With an onDriverError callback, the scope calls it with phase
"flush" and returns { error }. Without an error callback, or if the callback
throws, the scope throws the driver error. While the revision is current, a
retry reapplies the view and continues with the remaining commands. Each
command is attempted at most once per revision. If a command throws, its
delivery is indeterminate and the retry skips it. Flushing a fully applied
revision again is a no-op.
Attribute constraints and tracing
Each SlotSchema.attrs entry accepts an AttrSpec. Use a scalar type like
"string", { enum: ["compact", "wide"] }, or
{ type: "number", min: 0, max: 10, integer: true }. Numeric bounds are inclusive.
Policy budgets are finite non-negative integers. Zero is a valid cap.
maxAttrLength, maxTextLength, and a slot's text maxLength count UTF-16
code units. maxTotalViewBytes and the bytes returned by
validateSlotPatch also count UTF-16 code units. The total includes slot refs,
normalized attribute and CSS variable names and values, and text. A present
boolean attribute uses one unit for its value.
For untrusted data passed to validateView or validateSlotPatch, cap
serialized bytes before decoding and bound record members before constructing
objects when the decoder supports it. The view slot cap checks enumerable
slot keys before walking descriptors. Native enumeration can still allocate
key lists before the policy rejects a record.
Policy errors expose phase and path, plus slot when a slot is known.
For example, an invalid enum attribute may have phase "view", slot "root"
and path ["root", "attrs", "data-layout"]. An effect rejection has phase
"step" and a path such as ["effects", 0].
DomPolicy.onTrace receives frozen DomTraceEntry objects from either driver,
including slot references, measured boxes, validated patches, and revision IDs
for flushed operations. Trace callback errors go to onDriverError with phase
"trace".
Pass onAnnounce to createBrowserDriver to send announcements to your own
live region. The browser driver creates its built-in region when the callback
is omitted.
Headless history and replay
createHeadlessDriver({ maxHistory: 100 }) keeps the latest 100 entries in each
of trace and announcements. Use maxHistory: 0 to skip recording or omit
it for unbounded history. Headless measurements use the geometry provided by
the host. Compare normalized inputs, accepted revisions, and the measurements
and operations recorded by the scope's onTrace hook. Use browser assertions
for native outcomes such as actual focus, scroll position and resize observer
delivery.
Guest virtual module
Use the declarations-only @ts0/dom/guest import in ts0 guest code.
import {
measure,
focus,
scrollIntoView,
preventDefault,
announce,
} from "@ts0/dom/guest"Bind the virtual module to your scope when compiling the guest.
const program = compile(source, {
imports: { "@ts0/dom/guest": scope.imports },
})Host code imports drivers and scopes from @ts0/dom. Headless hosts can
type-check with an ES2022 library and without installing @ts0/core.
