runtime

package
v5.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2026 License: MIT Imports: 21 Imported by: 0

README

Internal Runtime

Location: internal/runtime/

This is the default single-threaded renderer and hook runtime behind the public ui package.

File Layout

  • runtime.go: runtime construction, render entrypoints, and adapter wiring
  • scheduler.go: update scheduling and transition behavior
  • reconciler.go, reconciler_elements.go, reconciler_commit.go: fiber reconciliation and DOM commit flow
  • hooks.go, hooks_fetch.go, state.go, transition.go: hook behavior and reactive state plumbing
  • events.go: event adaptation and typed event helpers
  • hydration.go, ssr.go: hydration and server-rendering paths
  • inspect.go, inspect_reporting.go, diagnostic_metadata.go, strict_diagnostics.go: inspection and diagnostics support
  • runtime_controls.go, memory_hygiene.go: priority lanes, strict mode, deterministic replay, bounded state, and long-session memory hygiene
  • panic_*.go, profiling.go, hot_reload.go: panic reporting, profiling, and hot-reload support
  • *_test.go and *_benchmark_test.go: contract, regression, and performance coverage

How To Navigate Changes

  • Start with runtime.go and scheduler.go for render lifecycle issues.
  • Start with runtime_controls.go for lane scheduling, strict-mode probes, replay capture/replay, and runtime limits.
  • Start with the reconciler* files for DOM shape, fiber identity, or commit bugs.
  • Start with hooks.go plus the nearest focused hook file for state or effect behavior.
  • Start with hydration.go or ssr.go for server-rendered flows.

The public entrypoint remains ui/; this folder is implementation detail for maintainers.

Known Scope Limits

Recorded here rather than left as an unstated gap between what the plan claims and what the code does.

  • schedulerMu is package-level, not per-runtime. P2.3 scoped runtime state to internal/runtime and moved the ready signal, atom registry, and diagnostic limits onto the Runtime. The scheduler mutex did not move, so two runtimes in one process serialize every Schedule* call against each other. This is invisible today: §7 of the v5 plan declares multi-runtime support a non-goal across the public surface, and a green P2.3 suite means "two renderers with independent state and atoms", not "N runtimes rendering concurrently".

    What it would take: schedulerMu is taken by every scheduling entry point, by commitRoot's state transition, and by the profiling recorder, so moving it onto the Runtime is mechanical but wide. It should be done with a measurement attached — an uncontended mutex is nearly free, so the change buys nothing until there is a second runtime actually rendering, and that is the thing §7 says is out of scope. Do not do it as cleanup; do it when a two-runtime workload exists to justify it.

  • Inline closure props defeat memoization by design. sameFunctionIdentity compares the code pointer AND the funcval data pointer, so two allocations of the same closure literal are unequal and the owning fiber is dirty every render. That is correct — the alternative is stale closures — but it means a component passing func() { ... } inline as a prop re-renders and re-writes that handler to the DOM on every commit, and SetProperty is not covered by the attribute batch. Use ui.UseEvent, whose wrapper is stable across renders and therefore compares equal and is skipped. See the note on ui.WrapHandler.

Telemetry And CSP Notes

  • Panic reports are redacted through logging.ConfigureTelemetryRedaction before console emission or OnReport callbacks.
  • SSR streaming accepts a per-request script nonce and applies it to emitted boundary patch scripts.

Runtime Controls

  • Use NewRuntime for each mounted root that needs isolated atom state, scheduling, IDs, and event wrappers.
  • Use Config.StrictMode for dev-time double-render, setState-during-render, and effect cleanup-contract checks.
  • Use Config.Limits to bound pending effects, queued update coalescing, replay events, and diagnostics.
  • Use StartReplayRecording / StopReplayRecording and ReplayUpdates to capture and replay deterministic scheduling streams.
  • Use InternalStateSnapshot and CheckMemoryHygiene for long-session fiber, atom, subscriber, queue, goroutine, and heap-pressure diagnostics. Neither is free, and neither belongs in a per-frame poll. InternalStateSnapshot walks the whole committed fiber tree while holding schedulerMu, so it blocks scheduling for O(tree) per sample, and CheckMemoryHygiene additionally calls runtime.ReadMemStats, which stops the world. Sampling either on a timer manufactures the pauses M7 exists to bound. Call them on demand, or on a slow interval when investigating.
  • Set MemoryHygieneOptions.MaxGoroutines when investigating a leak: the heap and fiber thresholds cannot see a goroutine parked on a channel, which is how the suspended-boundary watcher leak (fixed in ee39ac99) stayed invisible.

Documentation

Index

Constants

View Source
const (
	// BudgetPendingEffects is the effect queue that degrades to a full-tree scan.
	BudgetPendingEffects = "pending-effects"
	// BudgetQueuedUpdates is the update queue that coalesces past its limit.
	BudgetQueuedUpdates = "queued-updates"
	// BudgetAsyncInbox is the off-loop ingress queue (P2.1). Past its soft bound
	// batching degrades; past the hard bound the drain moves onto the producing
	// goroutine and frame isolation is suspended for that batch.
	BudgetAsyncInbox = "async-inbox"
)

The stable cliff names.

View Source
const (
	// SSRStreamChunkShell identifies the initial shell chunk.
	SSRStreamChunkShell = "shell"
	// SSRStreamChunkBoundary identifies an out-of-order async boundary chunk.
	SSRStreamChunkBoundary = "boundary"
)
View Source
const DOMRefKey = "__gwc_dom_ref__"

DOMRefKey is the reserved props key that carries a DOMRefSink. It is namespaced like the other internal keys (e.g. the custom-element property prefix) so it can never collide with a real attribute name.

Variables

View Source
var AsyncBoundaryNodeType = &AsyncBoundaryElementType{}

AsyncBoundaryNodeType marks async fallback boundaries.

View Source
var ErrAgentAtomHasSubscribers = errors.New("agent atom has live subscribers")

ErrAgentAtomHasSubscribers reports that a bridge.delete-atom command tried to delete an atom that still has live subscribers without force=true.

View Source
var ErrAgentNoHandler = errors.New("fiber has no handler for the requested event")

ErrAgentNoHandler reports that the named event (e.g. "onclick") has no handler registered on the resolved fiber. It is distinct from ErrAgentRefStale so callers can distinguish "node is gone" from "node exists but has no such handler".

View Source
var ErrAgentRefInvalid = errors.New("agent ref is invalid")

ErrAgentRefInvalid reports a malformed agent ref (for example an empty string). The agent bridge maps it to the bad-payload wire error.

View Source
var ErrAgentRefStale = errors.New("agent ref does not resolve in the current tree")

ErrAgentRefStale reports that an agent node ref no longer resolves in the current fiber tree (the component unmounted or the tree was replaced). The agent bridge maps it to the stale-ref wire error so callers re-query instead of retrying the same ref.

View Source
var ErrAgentStateSlotInvalid = errors.New("agent state slot is invalid")

ErrAgentStateSlotInvalid reports that a bridge.set-state command addressed a hook slot that does not exist or is not a state hook.

View Source
var PortalNodeType = &PortalElementType{}

PortalNodeType marks subtrees that should commit into a separate target container.

View Source
var ReactiveRegionNodeType = &ReactiveRegionElementType{}

ReactiveRegionNodeType marks anchored fine-grained update regions.

View Source
var ReactiveTextNodeType = &ReactiveTextElementType{}

ReactiveTextNodeType marks text-like fine-grained update regions.

Functions

func ActionableFrameworkPanic

func ActionableFrameworkPanic(parseOptions ActionablePanicOptions) string

ActionableFrameworkPanic is a core package helper.

func AgentRefForFiber

func AgentRefForFiber(parseFiber *Fiber) string

AgentRefForFiber returns the stable agent ref for a live fiber: the same key/index-disambiguated path the hot reload snapshot keys component state by, so a ref survives re-renders that recreate the fiber. The root fiber has no ref (empty string) - agents address nodes, not the mount point.

func BeginStartupProfiling

func BeginStartupProfiling(parseMode string)

BeginStartupProfiling marks the beginning of a startup workflow when one has not already been started for the current runtime.

func BuildDOMWrappedFunctionIfReadyGlobal

func BuildDOMWrappedFunctionIfReadyGlobal(parseHandlerFn any) (any, bool)

BuildDOMWrappedFunctionIfReadyGlobal reports that DOM callback wrapping is unavailable on non-browser targets.

func BuildDiagnosticsService

func BuildDiagnosticsService() pluginruntime.DiagnosticsService

BuildDiagnosticsService returns one runtime1-backed diagnostics facade.

func BuildRuntimeInspectionService

func BuildRuntimeInspectionService() pluginruntime.RuntimeInspectionService

BuildRuntimeInspectionService returns one runtime1-backed inspection service.

func ClassIdProps

func ClassIdProps(parseClass, parseId string) map[string]any

ClassIdProps returns a props map with the given class and id.

func ClassProps

func ClassProps(parseClass string) map[string]any

ClassProps returns a props map with the given CSS class.

func ClearDiagnostics

func ClearDiagnostics()

ClearDiagnostics removes all recorded diagnostics.

func ClearLogs

func ClearLogs()

ClearLogs removes all buffered framework logs.

func ClearProfiling

func ClearProfiling()

ClearProfiling resets collected profiling counters and timeline events.

func ConfigurePanicReportRedaction

func ConfigurePanicReportRedaction(parsePolicy PanicReportRedactionPolicy)

ConfigurePanicReportRedaction installs runtime-local redaction for panic report fields.

func ConfigureStrictDiagnostics

func ConfigureStrictDiagnostics(parseOptions StrictDiagnosticsOptions)

ConfigureStrictDiagnostics sets the current strict-diagnostics behavior.

func ConfigureUnhandledPanicLogging

func ConfigureUnhandledPanicLogging(parseOptions PanicLoggingOptions)

ConfigureUnhandledPanicLogging sets the panic logging options including raw output visibility and the report hook.

func ContainPanic

func ContainPanic(parseSource string, parsePhase PanicPhase, parseSubject string, parseRecovered any)

ContainPanic reports a recovered panic through the structured panic-report pipeline and never re-panics. Call it from a deferred recover at a containment boundary (goroutine top, host callback, work loop).

func CurrentFiberPath

func CurrentFiberPath() string

CurrentFiberPath returns the current component path while a hook is rendering.

func DemoteDirectTextChild

func DemoteDirectTextChild(parseElem *Element)

DemoteDirectTextChild converts an element that carries its only text child directly on the host (the direct-text fast path) back to an explicit TEXT_ELEMENT child. Post-creation child appenders (html.WithChildren) must call this first: the direct-text representation renders TextContent and ignores structural children, so appending to Children alone would drop the new nodes.

func EmitAgentEvent

func EmitAgentEvent(parseRt *Runtime, parseRef string, parseEventName string, parsePayload map[string]any) error

EmitAgentEvent resolves parseRef to its live fiber under schedulerMu, locates the handler for parseEventName (e.g. "click" or "onclick") in the fiber's props map, and invokes it with a synthesised zero-value event. It mirrors exactly the type-switch dispatch testkit/render uses so the same handler signatures that work in tests work here. The scheduler lock is acquired via resolveAgentRefLocked (not ResolveAgentRef) so the caller must NOT already hold schedulerMu. Panics inside the handler are caught and returned as errors (crash containment — an agent command must never kill the runtime). Returns ErrAgentRefStale when the ref no longer resolves, ErrAgentRefInvalid when the ref string is malformed, and ErrAgentNoHandler when the fiber carries no handler under parseEventName.

func EmptyProps

func EmptyProps() map[string]any

EmptyProps returns an empty props map.

func EnsureElementProps

func EnsureElementProps(parseElem *Element) map[string]any

EnsureElementProps materializes and caches a legacy props-map view on one typed fast-lane element. Public tooling that reads Element.Props directly should call this first; elements built through the map lane are returned unchanged.

func FinalizeUnhandledPanicContext

func FinalizeUnhandledPanicContext(parseSource string, parsePhase PanicPhase, parseSubject string, parsePath string, parseComponentStack []string, parseRecovered any) (any, bool)

FinalizeUnhandledPanicContext is a core package helper.

func FlushGlobalDiscreteWork

func FlushGlobalDiscreteWork()

FlushGlobalDiscreteWork flushes the global runtime's freshly scheduled pass; the wasm DOM event bridge uses it because adapter-level wrappers do not carry a runtime reference.

func GetAgentState

func GetAgentState(parseRt *Runtime, parseRef string, parseHookSlot int) (any, error)

GetAgentState resolves parseRef, validates parseHookSlot is a state hook, and returns the current value stored in that state slot WITHOUT mutating it. It is the read counterpart of SetAgentState, used to capture a prior value so an agent set-state can be recorded as a reversible mutation.

func GoUseAtom

func GoUseAtom[T any](parseRt *Runtime, parseId string, parseInitialValue T) (func() T, func(any))

GoUseAtom provides access to global state with fine-grained reactivity. Unlike useState which is local to a component, atoms are shared across components. When an atom updates, only components that use that specific atom re-render.

func GoUseAtomGlobal

func GoUseAtomGlobal[T any](parseAtomID string, parseAtomInitialValue T) (func() T, func(T))

GoUseAtomGlobal wraps GoUseAtom on non-browser targets, resolving the atom registry to the CURRENT SERVER RENDER's scope when there is one and to the process-global runtime otherwise.

The "otherwise" is the browser-equivalent case (native reconciler renders, unit tests, out-of-render access) and must stay on the global registry: an atom is supposed to be shared and to outlive renders.

The scoped case is not an optimization, it is the fix for a cross-request state leak. Resolving straight to GetGlobalRuntime() here meant every server render in the process shared one registry, and AtomRegistry.InitAtom is init-if-absent — so request 1 seeded the atom and request 2's initial value was ignored, putting request 1's data in request 2's HTML. A server render also never unmounts, so its subscriptions were never released and the registry grew forever.

If you are tempted to put GetGlobalRuntime() back because "atoms are global": they are, per PAGE. On a server, per REQUEST is the equivalent boundary. ssr_atom_scope.go states the whole contract.

func GoUseCallback

func GoUseCallback(parseFn any, parseDeps ...any) any

GoUseCallback memoizes a callback function with dependency tracking

func GoUseContextValue

func GoUseContextValue(parseDescriptor *ContextDescriptor) any

GoUseContextValue reads the nearest provider value for a context descriptor.

func GoUseEffect

func GoUseEffect(parseEffect func() func(), parseDeps ...any)

GoUseEffect runs side effects and supports cleanup The effect function can return a cleanup function that will be called before the next effect runs or on unmount GoUseEffect registers a passive effect that runs after the commit's DOM mutation. See goUseEffectImpl.

func GoUseEffectGlobal

func GoUseEffectGlobal(parseEffectFn func() func(), parseEffectDeps ...any)

GoUseEffectGlobal wraps GoUseEffect on non-browser targets.

func GoUseEffectOf

func GoUseEffectOf[D comparable](parseEffect func() func(), parseDep D)

GoUseEffectOf registers a passive effect keyed by a single comparable dependency without the variadic []any deps allocation. Same slot machinery as GoUseEffect ("effect" signature); not swappable with it between renders.

func GoUseFetch

func GoUseFetch(parseFetchURL string, parseFetchOptions ...any) (func() FetchState, func())

GoUseFetch is a stub for non-WASM environments

func GoUseFunc

func GoUseFunc(parseFn any) any

GoUseFunc validates and stores a function for event handling The actual wrapping to js.Value happens in the WASM shim layer

func GoUseId

func GoUseId() string

GoUseId generates a unique, stable identifier for accessibility attributes The ID is generated once and persists across renders without changing This is useful for associating labels with form inputs and other accessibility needs

func GoUseIdGlobal

func GoUseIdGlobal() string

GoUseIdGlobal wraps GoUseId on non-browser targets.

func GoUseLayoutEffect

func GoUseLayoutEffect(parseEffect func() func(), parseDeps ...any)

GoUseLayoutEffect registers a layout effect (G36): it runs synchronously after DOM mutation, before the browser paints, and before this fiber's passive effects. Use it for post-render DOM reads/writes that must be observed before paint — focusing a freshly mounted element, measuring layout, scrolling — so they need no setTimeout/rAF guess. Same (effect, deps...) contract as GoUseEffect.

func GoUseLayoutEffectGlobal

func GoUseLayoutEffectGlobal(parseEffectFn func() func(), parseEffectDeps ...any)

GoUseLayoutEffectGlobal wraps GoUseLayoutEffect on non-browser targets (G36).

func GoUseMemo

func GoUseMemo(parseCompute func() any, parseDeps ...any) any

GoUseMemo memoizes expensive computations

func GoUseMemoFor

func GoUseMemoFor[T any](parseCompute func() T, parseDeps ...any) T

GoUseMemoFor memoizes one typed computation without the func()-any adapter closure the untyped entry point forces on generic callers: the compute function passes through unwrapped, and the hot-reload type coercion target comes from the type parameter (reflect only runs on the restore path).

func GoUseMemoGlobal

func GoUseMemoGlobal(parseMemoCompute func() any, parseMemoDeps ...any) any

GoUseMemoGlobal wraps GoUseMemo on non-browser targets.

func GoUseMemoGlobalTyped

func GoUseMemoGlobalTyped(parseMemoCompute func() any, parseMemoTargetType reflect.Type, parseMemoDeps ...any) any

GoUseMemoGlobalTyped wraps GoUseMemoTyped on non-browser targets.

func GoUseMemoOf

func GoUseMemoOf[T any, D comparable](parseCompute func(D) T, parseDep D) T

GoUseMemoOf memoizes one computation keyed by a single comparable dependency with zero steady-state allocations: the compute function receives the dependency (so it can be a static, non-capturing func), the unchanged-dep check type-asserts the stored box instead of boxing the new value, and the cached result is returned by assertion. It shares the memo slot machinery (and hook signature) with GoUseMemo, so the two may not be swapped for one another between renders of one component.

func GoUseMemoTyped

func GoUseMemoTyped(parseCompute func() any, parseTargetType reflect.Type, parseDeps ...any) any

GoUseMemoTyped memoizes expensive computations and coerces restored hot reload values to the caller's expected type when possible.

func GoUseState

func GoUseState[T any](parseRt *Runtime, parseInitialValue T) (func() T, func(any))

GoUseState provides state management for components

func GoUseStateGlobal

func GoUseStateGlobal[T any](parseStateInitialValue T) (func() T, func(any))

GoUseStateGlobal wraps GoUseState with the global runtime on non-browser targets.

func GuardCallback

func GuardCallback(parseSource string, parseSubject string, parseFn func()) func()

GuardCallback wraps fn with panic containment for host-callback boundaries (js.FuncOf bodies, timer callbacks, observer callbacks). The returned function never lets a panic escape into the host bridge.

func HrefProps

func HrefProps(parseHref string) map[string]any

HrefProps returns a props map with the given href attribute.

func IdProps

func IdProps(parseId string) map[string]any

IdProps returns a props map with the given element ID.

func InitGlobalRuntime

func InitGlobalRuntime(parseConfig Config)

InitGlobalRuntime initializes or upgrades the global runtime with specific adapters.

func InputTypeProps

func InputTypeProps(parseTyp string) map[string]any

InputTypeProps returns a props map with the given input type.

func IsCurrentFiberTransitionUpdate

func IsCurrentFiberTransitionUpdate() bool

IsCurrentFiberTransitionUpdate reports whether the current fiber render originated from deferred transition work.

func IsDOMNodeNull

func IsDOMNodeNull(parseNode DOMNode) bool

IsDOMNodeNull reports whether a DOMNode is absent, whether that absence is represented as a nil interface or one explicit null-node wrapper.

func IsSameDOMNode

func IsSameDOMNode(parseLeft DOMNode, parseRight DOMNode) bool

IsSameDOMNode reports whether two DOMNode values reference the same platform node, treating all null-node representations as equivalent.

func NormalizeHotReloadValue

func NormalizeHotReloadValue(parseValue any) any

NormalizeHotReloadValue exposes the hot-reload value normalizer for bridge code that receives JSON-decoded snapshots.

func OnFirstCommit

func OnFirstCommit(parseFn func())

OnFirstCommit registers fn against the global runtime.

Retained so existing callers (ui.OnReady and the wasm "gwc:ready" bridge) keep working unchanged; apps with one runtime — which is every app today — see no difference.

func PlaceholderProps

func PlaceholderProps(parsePlaceholder string) map[string]any

PlaceholderProps returns a props map with the given placeholder text.

func PlainTextContent

func PlainTextContent(parseElem *Element) (string, bool)

PlainTextContent reports the text carried by one plain text node (as built by ui.Text / html.Text — no props, no key), so construction sugar can route single text children through the direct-text fast path without allocating a child slice.

func RecordStartupBootstrapRead

func RecordStartupBootstrapRead(parseDurationNs int64, parseSource string)

RecordStartupBootstrapRead stores bootstrap read or decode timing and emits a profiling timeline event.

func RecordStartupRouteContext

func RecordStartupRouteContext(parseRoutePath string)

RecordStartupRouteContext captures which route family the active startup flow is targeting so first-interaction budgets can be attributed correctly.

func RecoverContainedPanic

func RecoverContainedPanic(parseSource string, parseSubject string)

RecoverContainedPanic is the deferred form of ContainPanic: place `defer runtime.RecoverContainedPanic(source, subject)` at the top of any goroutine or host callback that must never crash the program.

func RefreshElementHostProps

func RefreshElementHostProps(parseElem *Element)

RefreshElementHostProps rebuilds one element's cached host-prop view after post-creation prop mutation. Typed fast-lane elements materialize their props map first, so a refresh never drops attributes that only lived in the compact slice.

func RenderDetached

func RenderDetached(parseSelector string, parseElement *Element) error

RenderDetached renders parseElement into the DOM container at parseSelector using a runtime INDEPENDENT of the global app runtime. Agent-injected or agent-mounted content therefore renders into its own root and can never clobber the app's single currentRoot (which a plain RenderTo into a second container would). Each selector gets its own isolated runtime, reused across calls, sharing the global runtime's DOM/event adapters and scheduler so the detached tree renders into the same live browser. A nil element clears the container.

func RenderToStream

func RenderToStream(parseCtx context.Context, parseWriter io.Writer, parseElement *Element, parseOptions SSRStreamOptions) (parseErr error)

RenderToStream writes an SSR shell immediately and then flushes async boundary replacement chunks as their render-time suspensions resolve.

func RenderToString

func RenderToString(parseElement *Element) (parseMarkup string, parseErr error)

RenderToString renders a virtual element tree to HTML.

This is the first internal SSR slice: it supports host elements, text nodes, fragments, and simple function components that return *Element. Hydration and browser bootstrap are intentionally out of scope here.

func RenderToStringWithAtoms

func RenderToStringWithAtoms(parseElement *Element, parseInitialAtoms map[string]any) (string, error)

RenderToStringWithAtoms renders parseElement with parseInitialAtoms seeded into this render's atom scope before the walk begins.

This is the explicit form of the SSR contract: a request's state is INPUT to the render, not something left over from the last one. Because seeding happens first and InitAtom is init-if-absent, precedence is

seeded request value  >  the component's UseAtom initial  >  nothing

It is the supported replacement for "write the global registry, then render", which cannot work once each render has its own scope (and was never safe under concurrency anyway). Native-only on purpose: seeding a request has no meaning in a browser, where there is one page and one set of live atoms.

func ReportDiagnostic

func ReportDiagnostic(parseSource string, parseSeverity DiagnosticSeverity, parseMessage string)

ReportDiagnostic records or increments a runtime diagnostic entry.

func ReportDiagnosticWithContext

func ReportDiagnosticWithContext(parseSource string, parseSeverity DiagnosticSeverity, parseMessage string, parsePath string, parseComponentStack []string)

ReportDiagnosticWithContext records or increments a runtime diagnostic entry and optionally attaches fiber-path context for devtools and debugging.

func ReportLog

func ReportLog(parseDomain string, parseLevel LogLevel, parseMessage string)

ReportLog records one structured framework log entry.

func ReportLogWithFields

func ReportLogWithFields(parseDomain string, parseLevel LogLevel, parseClassification DiagnosticClassification, parseMessage string, parseCorrelationID string, parseFields map[string]string)

ReportLogWithFields records one structured framework log entry with optional correlation id and fields.

func ReportProfilingEvent

func ReportProfilingEvent(parseDomain string, parseName string, parsePhase string, parseTarget string, parseDurationNs int64, parseFields map[string]string)

ReportProfilingEvent records a profiling timeline entry on the global runtime.

func ReportUnhandledPanicContext

func ReportUnhandledPanicContext(parseSource string, parsePhase PanicPhase, parseSubject string, parsePath string, parseComponentStack []string, parseRecovered any) string

ReportUnhandledPanicContext is a core package helper.

func ResetFirstCommitHooksForTest

func ResetFirstCommitHooksForTest()

ResetFirstCommitHooksForTest restores the global runtime's pre-commit state. Test-only.

func ResetWASMArtifactMetadata

func ResetWASMArtifactMetadata()

ResetWASMArtifactMetadata clears the current emitted artifact metadata.

func ResetWASMStackFrameMapper

func ResetWASMStackFrameMapper()

ResetWASMStackFrameMapper clears the current wasm stack-frame mapper.

func SafeGo

func SafeGo(parseSource string, parseSubject string, parseFn func())

SafeGo starts fn on a new goroutine with panic containment. A panic inside fn is reported to the console (agent-readable, with stack buckets) and the goroutine ends; the program and the committed UI keep running.

func SanitizeURLAttributeValue

func SanitizeURLAttributeValue(parseName, parseValue string) string

SanitizeURLAttributeValue neutralizes a script-executing scheme (javascript: or vbscript:) in the value of a URL-bearing attribute such as href/src/action. Non-URL attributes and safe schemes (http(s), data, mailto, relative, fragment) are returned unchanged. It is shared by the SSR serializer and the browser DOM adapter so both render paths block the identical XSS vector at the point a value reaches the document.

func SetAgentState

func SetAgentState(parseRt *Runtime, parseRef string, parseHookSlot int, parseValue any) error

SetAgentState resolves parseRef, validates parseHookSlot against the fiber's recorded hook signature, writes the matching state hook's current and pending slots, and schedules the same owned-fiber update path used by GoUseState.

func SetCurrentFiber

func SetCurrentFiber(parseFiber *Fiber)

SetCurrentFiber sets the current fiber (used during component rendering)

func SetWASMArtifactMetadata

func SetWASMArtifactMetadata(parseArtifactMeta WASMArtifactMetadata)

SetWASMArtifactMetadata stores the current emitted artifact metadata for panic correlation.

func SetWASMStackFrameMapper

func SetWASMStackFrameMapper(parseFrameMapper WASMStackFrameMapper)

SetWASMStackFrameMapper installs the current wasm stack-frame mapper.

func SrcProps

func SrcProps(parseSrc string) map[string]any

SrcProps returns a props map with the given src attribute.

func StoreStartupCostAttribution

func StoreStartupCostAttribution(storeAttribution StartupCostAttribution)

StoreStartupCostAttribution stores startup-cost attribution values.

func StyleProps

func StyleProps(parseStyle string) map[string]any

StyleProps returns a props map with the given inline style string.

func SuspendUntil

func SuspendUntil(parseDone <-chan struct{}, parseReason string)

SuspendUntil interrupts the current render until done closes.

func TypeProps

func TypeProps(parseTyp string) map[string]any

TypeProps returns a props map with the given type attribute.

func ValueProps

func ValueProps(parseValue any) map[string]any

ValueProps returns a props map with the given value.

Types

type ActionablePanicOptions

type ActionablePanicOptions struct {
	Source         string
	Subject        string
	Message        string
	Path           string
	ComponentStack []string
	Consequence    string
}

type AgentDeleteAtomResult

type AgentDeleteAtomResult struct {
	Deleted     bool
	Subscribers []string
}

AgentDeleteAtomResult describes the outcome of DeleteAgentAtom.

func DeleteAgentAtom

func DeleteAgentAtom(parseRt *Runtime, parseID string, parseForce bool) (AgentDeleteAtomResult, error)

DeleteAgentAtom deletes one atom from the registry. When live subscribers exist and parseForce is false, it fails closed and reports their refs.

type AgentDetachedRoot

type AgentDetachedRoot struct {
	// Selector is the container the tree was rendered into.
	Selector string `json:"selector"`
	// Root is the budgeted, redacted fiber tree for the detached runtime. Refs
	// within it are relative to this detached root, scoped to Selector.
	Root *AgentNodeSnapshot `json:"root,omitempty"`
}

AgentDetachedRoot is one isolated, agent-injected tree (e.g. from bridge.render-tree / bridge.mount) and the selector it was rendered into.

type AgentHookPreview

type AgentHookPreview struct {
	// Slot is the hook slot index.
	Slot int `json:"slot"`
	// Kind is the hook kind string (state, memo, ref, effect, …).
	Kind string `json:"kind"`
	// Value is the preview string; "[redacted]" when a redaction policy is active.
	Value string `json:"value"`
}

AgentHookPreview is a JSON-serializable hook value preview produced by BuildAgentSnapshot. It reuses the string previews from inspectHooks.

type AgentNodeSnapshot

type AgentNodeSnapshot struct {
	// Name is the component or element name from describeFiber.
	Name string `json:"name"`
	// Kind is "component", "host", "text", "root", etc. from describeFiber.
	Kind string `json:"kind"`
	// Text is the full rendered text content for text nodes (empty otherwise),
	// redacted to "[redacted]" when a redaction policy is active. This lets a
	// reader recover the actual rendered copy, not just the node structure.
	Text string `json:"text,omitempty"`
	// AgentRef is the stable agent ref for this node; empty on the root fiber.
	AgentRef string `json:"agentRef,omitempty"`
	// HookCount is the number of hook slots on this fiber.
	HookCount int `json:"hookCount"`
	// Dirty reports whether this fiber has pending updates.
	Dirty bool `json:"dirty,omitempty"`
	// NeedsUpdate reports whether an ancestor queued an update for this fiber.
	NeedsUpdate bool `json:"needsUpdate,omitempty"`
	// Hooks carries hook value previews; values are redacted when a panic-report
	// redaction policy is active (fail-closed: any configured policy silences
	// hook values).
	Hooks []AgentHookPreview `json:"hooks,omitempty"`
	// Children is the (possibly truncated) list of child nodes in tree order.
	Children []AgentNodeSnapshot `json:"children,omitempty"`
}

AgentNodeSnapshot is a JSON-serializable summary of one fiber node built by BuildAgentSnapshot. It carries the component name, kind, stable agent ref, hook count, dirty flags, hook value previews, and a children slice. Nodes beyond the depth or node budget are omitted and counted in the parent AgentSnapshot's TruncatedNodes field.

type AgentQueryMatch

type AgentQueryMatch struct {
	// AgentRef is the stable agent ref for the matched node.
	AgentRef string `json:"agentRef"`
	// Name is the component or element name.
	Name string `json:"name"`
	// Kind is "component", "host", "text", "root", etc.
	Kind string `json:"kind"`
	// Tag is the host element tag; empty for non-host nodes.
	Tag string `json:"tag,omitempty"`
}

AgentQueryMatch describes one node returned by QueryAgentNodes.

func QueryAgentNodes

func QueryAgentNodes(parseRt *Runtime, parseSel AgentQuerySelector) []AgentQueryMatch

QueryAgentNodes walks the live fiber tree under schedulerMu and returns all fibers that match the selector in tree (pre-order) order. It mirrors the testkit ByRole/ByLabel/ByText/ByID/AllByTag semantics:

  • Role: derived from the host element tag via the same implicit role mapping as testkit (button→button, a[href]→link, input[type=*]→…, etc.) and from the "role" or "aria-role" prop (checked first); comparison is case-insensitive after normalisation.
  • Label: matched against the "aria-label" prop as a case-insensitive substring.
  • Text: matched against the concatenated textContent of the fiber subtree as a case-insensitive substring (same depth-first concatenation as testkit nodeText).
  • ID: matched against the "id" prop exactly (case-sensitive).
  • Tag: matched against the host element tag case-insensitively.

When multiple selector fields are set, all must match (logical AND). An empty selector returns all non-root fibers. A nil or empty runtime returns an empty slice, never an error.

type AgentQuerySelector

type AgentQuerySelector struct {
	// Role matches the computed ARIA role derived from the element tag or the
	// "role" / "aria-role" prop (case-insensitive, same mapping as testkit
	// ByRole).
	Role string
	// Label matches the accessible label from "aria-label" prop (substring,
	// case-insensitive). When Role is also set, only nodes that have both the
	// correct role AND a matching label are returned.
	Label string
	// Text matches the concatenated text content of the fiber subtree
	// (substring, case-insensitive), the same text that testkit ByText uses.
	Text string
	// ID matches the "id" prop exactly (case-sensitive, same rule as testkit
	// ByID).
	ID string
	// Tag matches the host element tag (case-insensitive), same rule as testkit
	// AllByTag.
	Tag string
}

AgentQuerySelector carries the optional selector fields recognised by QueryAgentNodes. All fields are optional; a match requires every non-empty field to match.

type AgentSnapshot

type AgentSnapshot struct {
	// Root is the budgeted, redacted fiber tree starting from the runtime root.
	Root *AgentNodeSnapshot `json:"root,omitempty"`
	// TruncatedNodes is the count of nodes omitted to satisfy the depth or node
	// budget; zero when the full tree fit within the budget.
	TruncatedNodes int `json:"truncatedNodes,omitempty"`
	// BudgetApplied is true whenever either budget (maxDepth or maxNodes) was
	// reached and at least one node was omitted. Callers must check this field
	// rather than inferring truncation from the shape of Root.
	BudgetApplied bool `json:"budgetApplied,omitempty"`
	// Detached carries the trees rendered into separate containers via
	// RenderDetached (agent-injected/mounted content), keyed by their selector.
	// These live in their own isolated runtimes, so they are NOT part of Root;
	// including them here lets an agent read injected content it cannot
	// otherwise see in the global tree.
	Detached []AgentDetachedRoot `json:"detached,omitempty"`
}

AgentSnapshot is the top-level result returned by BuildAgentSnapshot.

func BuildAgentSnapshot

func BuildAgentSnapshot(parseRt *Runtime, parseMaxDepth int, parseMaxNodes int) AgentSnapshot

BuildAgentSnapshot wraps the full Inspect() output into a JSON-serializable tree (AgentSnapshot) that is safe to send over the agent bridge wire. It enforces a depth budget (parseMaxDepth, 0 = unlimited) and a node-count budget (parseMaxNodes, 0 = unlimited). Whenever either budget is reached the result carries explicit truncation metadata in TruncatedNodes and BudgetApplied – truncation is never silent. Hook value previews are redacted when a PanicReportRedactionPolicy is configured (fail-closed: presence of any policy silences hook values to "[redacted]" rather than risk leaking sensitive data).

The panic-report redaction hook (ConfigurePanicReportRedaction) is the runtime-local redaction mechanism used here because the telemetry redaction policy in internal/telemetryredaction is package-inaccessible from internal/runtime (it would create an import cycle through logging/). Using the panic-report state is therefore the documented pattern for runtime-local redaction, not a workaround.

type AsyncBoundaryElementType

type AsyncBoundaryElementType struct{}

AsyncBoundaryElementType marks a subtree that can recover render-time suspensions by rendering fallback content until the suspended work resolves.

type AtomRegistry

type AtomRegistry struct {
	// contains filtered or unexported fields
}

AtomRegistry manages global state atoms with fine-grained reactivity. Each atom has a unique ID and tracks which fibers are subscribed to it.

func NewAtomRegistry

func NewAtomRegistry() *AtomRegistry

NewAtomRegistry creates a new atom registry.

func (*AtomRegistry) GetAtom

func (parseAr *AtomRegistry) GetAtom(parseId string) (any, bool)

GetAtom retrieves an atom's current value.

func (*AtomRegistry) GetAtomCount

func (parseAr *AtomRegistry) GetAtomCount() int

GetAtomCount returns the total number of atoms.

func (*AtomRegistry) GetSubscriberCount

func (parseAr *AtomRegistry) GetSubscriberCount(parseAtomID string) int

GetSubscriberCount returns the number of fibers subscribed to an atom.

func (*AtomRegistry) GetSubscriberTotal

func (parseAr *AtomRegistry) GetSubscriberTotal() int

GetSubscriberTotal returns the total number of atom subscriptions across all atoms.

func (*AtomRegistry) InitAtom

func (parseAr *AtomRegistry) InitAtom(parseId string, parseInitialValue any)

InitAtom initializes an atom if it doesn't exist.

func (*AtomRegistry) MoveSubscription

func (parseAr *AtomRegistry) MoveSubscription(parseAtomID string, parseFrom *Fiber, parseTo *Fiber)

MoveSubscription transfers a fiber's ownership for a single atom subscription.

func (*AtomRegistry) MoveSubscriptions

func (parseAr *AtomRegistry) MoveSubscriptions(parseAtomIDs []string, parseFrom *Fiber, parseTo *Fiber)

MoveSubscriptions transfers a fiber's ownership across several atom subscriptions under one lock.

func (*AtomRegistry) RegisterDerivedAtom

func (parseAr *AtomRegistry) RegisterDerivedAtom(parseId string, parseDeps []string, parseCompute func() any) error

RegisterDerivedAtom registers or replaces a derived atom and computes its current value.

func (*AtomRegistry) RestoreSnapshot

func (parseAr *AtomRegistry) RestoreSnapshot(parseSnapshot map[string]any) []*Fiber

RestoreSnapshot merges atom values from snapshot and returns subscribed fibers that should be notified about the updates.

func (*AtomRegistry) SetAtom

func (parseAr *AtomRegistry) SetAtom(parseId string, parseValue any) []*Fiber

SetAtom updates an atom's value and returns subscribed fibers.

func (*AtomRegistry) Snapshot

func (parseAr *AtomRegistry) Snapshot() map[string]any

Snapshot returns a shallow copy of all atom values currently stored.

func (*AtomRegistry) Subscribe

func (parseAr *AtomRegistry) Subscribe(parseAtomID string, parseFiber *Fiber)

Subscribe adds a fiber to an atom's subscription list.

func (*AtomRegistry) Unsubscribe

func (parseAr *AtomRegistry) Unsubscribe(parseAtomID string, parseFiber *Fiber)

Unsubscribe removes a fiber from an atom's subscription list.

func (*AtomRegistry) UnsubscribeFiberFromAll

func (parseAr *AtomRegistry) UnsubscribeFiberFromAll(parseFiber *Fiber)

UnsubscribeFiberFromAll removes a fiber from all atom subscriptions.

func (*AtomRegistry) UnsubscribeMany

func (parseAr *AtomRegistry) UnsubscribeMany(parseAtomIDs []string, parseFiber *Fiber)

UnsubscribeMany removes a fiber from several atom subscriptions under one lock.

type Attrs

type Attrs map[string]any

Attrs is a convenience type for component props.

type Blurrer

type Blurrer interface {
	Blur()
}

Blurrer / Clicker / ScrollIntoViewer are the optional capabilities a DOMNode may implement for the remaining common imperative-handle operations, mirroring Focuser. The wasm node implements all three; ui.DOMRef.Blur/Click/ScrollIntoView route through them so they work cross-build (no-op when the node — or the build — does not support the operation).

type BrowserState

type BrowserState interface {
	// History
	PushState(state any, title, url string)
	ReplaceState(state any, title, url string)
	GetCurrentPath() string
	OnPopState(callback func(path string))

	// Storage
	SetItem(key, value string) error
	GetItem(key string) (string, bool)
	RemoveItem(key string)

	// Location
	GetHash() string
	SetHash(hash string)
	Reload()
}

BrowserState abstracts browser state APIs.

type BudgetBehavior

type BudgetBehavior uint8

BudgetBehavior names what a cliff does when it is reached.

const (
	// BudgetDegrade preserves correctness at a higher cost.
	BudgetDegrade BudgetBehavior = iota
	// BudgetCoalesce merges excess work into work already scheduled, losing
	// nothing because the work is idempotent.
	BudgetCoalesce
	// BudgetReject refuses new work outright. Not currently used by any cliff;
	// defined so a future cliff that does reject can say so in the same
	// vocabulary rather than inventing one.
	BudgetReject
	// BudgetBlock stalls the producer until capacity frees. Also unused, and
	// deliberately so: blocking the render thread is the failure this whole
	// version exists to prevent.
	BudgetBlock
)

func (BudgetBehavior) LosesWork

func (parseBehavior BudgetBehavior) LosesWork() bool

LosesWork reports whether reaching this cliff can discard work.

The question a reader of a devtools panel actually has. Degrade and coalesce do not; reject does. Answering it as a method keeps every consumer from re-deriving it and getting it wrong for the coalesce case, which reads like a loss and is not.

func (BudgetBehavior) String

func (parseBehavior BudgetBehavior) String() string

type BudgetSignal

type BudgetSignal struct {
	// Name identifies the cliff. Stable across versions; devtools and tests key
	// on it.
	Name string
	// Limit is the configured capacity, zero meaning unbounded.
	Limit int
	// Observed is the current occupancy, for a "how close are we" reading rather
	// than only a "did it blow" one. The distinction matters: a workload sitting
	// at 95% is a warning, and one that never trips is not a bug.
	Observed int
	// Behavior is what happens at the limit.
	Behavior BudgetBehavior
	// Triggered counts how many times this cliff has been reached in the
	// runtime's lifetime.
	Triggered int
	// Active reports whether the cliff is currently in its degraded state.
	Active bool
}

BudgetSignal is one cliff's current state.

func (BudgetSignal) AtCapacity

func (parseSignal BudgetSignal) AtCapacity() bool

AtCapacity reports whether the cliff is at or past its limit right now.

func (BudgetSignal) Headroom

func (parseSignal BudgetSignal) Headroom() int

Headroom reports remaining capacity, or -1 when unbounded.

type Clicker

type Clicker interface {
	Click()
}

type ComponentRenderTraceSnapshot

type ComponentRenderTraceSnapshot struct {
	Name                    string
	Path                    string
	RenderCount             int
	RerenderCount           int
	LastTrigger             string
	LastRenderDurationNs    int64
	TotalRenderDurationNs   int64
	AverageRenderDurationNs int64
	LastRenderedAt          string
	TriggerCounts           map[string]int
}

ComponentRenderTraceSnapshot captures per-component render activity.

type ComponentSignature

type ComponentSignature struct {
	Kind          string
	Name          string
	QualifiedName string
	Key           string
	HookKinds     []string
}

ComponentSignature captures the dev-time identity and hook shape of a component.

func (ComponentSignature) CompatibleWith

func (parseSignature ComponentSignature) CompatibleWith(parseOther ComponentSignature) bool

CompatibleWith reports whether two component signatures can safely preserve state.

func (ComponentSignature) Summary

func (parseSignature ComponentSignature) Summary() string

Summary renders a compact human-readable description of the signature.

type ComponentType

type ComponentType struct {
	ID            string
	Name          string
	QualifiedName string
	// contains filtered or unexported fields
}

ComponentType provides a stable runtime-recognized component handle that can carry logical identity separately from the current callable implementation.

func NewComponentType

func NewComponentType(parseComponentID string, parseComponentName string, parseComponentQualifiedName string, parseComponentImplementation any, render func(any, map[string]any) *Element) *ComponentType

NewComponentType constructs a component handle recognized by the runtime.

func (*ComponentType) IdentityKey

func (parseComponentType *ComponentType) IdentityKey() string

IdentityKey returns the logical identity used to compare component handles.

func (*ComponentType) ImplementationMatches

func (parseComponentType *ComponentType) ImplementationMatches(parseComponentImplementation any) bool

ImplementationMatches reports whether the handle's current implementation is the very same function value — code pointer AND closure data, so two closures compiled from one `func` literal with different captures do NOT match.

That distinction is the whole point: a name (or a bare code pointer) cannot tell those two closures apart, and treating them as one component is what let sibling components overwrite each other's implementations. Callers use this to answer "is this handle already carrying exactly this code?" — yes means reuse it as-is (the steady-state fast path for top-level components, which present one stable function value forever), no means this is a different program and needs a handle of its own.

func (*ComponentType) Render

func (parseComponentType *ComponentType) Render(parseComponentProps map[string]any) *Element

Render invokes the current implementation attached to the component handle.

func (*ComponentType) SetImplementation

func (parseComponentType *ComponentType) SetImplementation(parseComponentImplementation any)

SetImplementation updates the current implementation for a stable component handle.

func (*ComponentType) SetImplementationRenderer

func (parseComponentType *ComponentType) SetImplementationRenderer(parseComponentImplementation any, parseRender func(any, map[string]any) *Element)

SetImplementationRenderer updates the current implementation and, when provided, swaps in one matching renderer.

ONLY THE OWNER OF A HANDLE MAY CALL THIS. A handle is shared by every element built from it, so a swap here retroactively changes what those elements render — that is the point for hot reload and for ui.Typed installing its static renderer, and it is a data-corruption bug for anything else.

Concretely: ui.getComponentHandle used to call this whenever a lookup arrived with a function value different from the cached one. Since every closure created from a single `func` literal reports the same qualified name, N sibling components built from one literal resolved to one handle and each registration overwrote the last — so all N rendered the final closure's captured props (observed: four form inputs all named "subject"). Distinct closures now get distinct handles; see the identity discussion in ui/component_handle_shared.go before reintroducing a name-keyed swap.

type Config

type Config struct {
	DOMAdapter   DOMAdapter
	EventAdapter EventAdapter
	Scheduler    Scheduler
	BrowserState BrowserState
	Reset        bool
	// HideRawPanicOutput is deprecated: crash containment (structured report,
	// no raw rethrow) is now the default. Use ShowRawPanicOutput to opt back
	// into re-panicking with the raw Go panic output.
	HideRawPanicOutput bool
	// ShowRawPanicOutput re-throws contained panics with their raw output
	// after the structured report. In wasm this kills the page; only enable
	// it for debugging native test runs.
	ShowRawPanicOutput     bool
	OnUnhandledPanicReport func(PanicReport)
	StrictMode             StrictModeOptions
	Limits                 RuntimeLimits
	// PassiveEffectsAfterPaint enables the v5 P1.1 commit split: layout effects
	// run synchronously in the commit task (so they observe committed DOM before
	// paint), passive effects run after the browser has painted.
	//
	// Off by default. Enabling it changes effect ORDERING, not just timing:
	// every layout effect in the tree now precedes every passive effect, where
	// previously each fiber ran both tiers before the next fiber ran either.
	// See internal/runtime/effect_ordering_contract_test.go.
	PassiveEffectsAfterPaint bool
	// FrameBudgetMs enables the v5 P1.2 wall-clock slice budget: the work loop
	// yields when a slice has consumed this many milliseconds, instead of only
	// after a fixed fiber count.
	//
	// ON by default: zero takes the 5ms default, a positive value sets an
	// explicit budget, and NEGATIVE opts out to count-only slicing.
	//
	// This flag was flipped on, reverted, and flipped back, and the middle step
	// is the useful one. Turning it on froze the Example 201 core-* and
	// enterprise-* scenarios: the tree never rendered and the harness timed out
	// with zero items, in both builds. Slicing did not cause that defect, it
	// EXPOSED one — an update arriving while a pass was already walking the tree
	// was folded into pendingLane and never run, because the coalescing path
	// acted only when the new work was MORE urgent than the running pass. A pass
	// completes inside one task without a budget, so the window was nearly
	// closed; a budget opens it at every yield.
	//
	// With that fixed (scheduleFollowUpForInFlightUpdate) the browser benchmark
	// is green with the budget on, which is now the gate. The first flip was
	// validated against `go test ./...` alone, where only this flag's own
	// "off by default" test failed — a clean-looking result that could not have
	// caught it, because nothing native drives those scenarios.
	//
	// Requires the interrupt-safe restart path (P2.5); without it the runtime
	// falls back to count-only slicing and emits a diagnostic rather than
	// degrading silently.
	FrameBudgetMs float64
	// LaneQueues enables per-lane deferral with expiration (v5 P2.2): work
	// marked at a lower priority than the running pass is deferred to a
	// follow-up pass rather than rendered inside this one.
	//
	// ON by default; set DisableLaneQueues to opt out. Each deferrable lane
	// carries a deadline (transition 500ms, background 2s) after which it is
	// admitted regardless of priority,
	// so deferral cannot become starvation under sustained input.
	LaneQueues bool
	// DisableLaneQueues turns per-lane deferral back off.
	//
	// A separate field rather than inverting LaneQueues, so existing callers
	// that set LaneQueues:true keep compiling and keep meaning what they said.
	DisableLaneQueues bool

	// AsyncIngress routes state updates made outside the frame loop through the
	// async inbox (v5 P2.1).
	//
	// Without it, a gRPC callback, a worker reply, or any goroutine mutates hook
	// state at whatever moment it happens to run — which is the race the inbox
	// was built to remove, and which no amount of care at the call site can fix
	// because the call site does not know whether a render is in flight. With
	// it, such a write is queued and applied at one defined point per frame, so
	// the in-flight tree is isolated by construction and N async writes in a
	// frame produce one render rather than N.
	//
	// Off by default: it changes WHEN an async write lands (one task later, at
	// the drain), and that is a semantic change existing apps should opt into.
	//
	// Measured 2026-07-25 rather than assumed: forcing it on for the whole suite
	// fails nine tests, all of the same shape — a test calls a setter directly
	// from its own goroutine and asserts the new value on the next line. That is
	// precisely the write this defers, so the failures are the feature working,
	// not a defect in it. They are also proof the change is observable to code
	// that already exists, which is why it stays opt-in until an app has been
	// migrated deliberately rather than by a default flip.
	AsyncIngress bool
}

Config holds runtime adapter configuration.

type ContextDescriptor

type ContextDescriptor struct {
	ID           int64
	DefaultValue any
}

ContextDescriptor identifies a context value stream within a component tree.

func NewContextDescriptor

func NewContextDescriptor(parseDefaultValue any) *ContextDescriptor

NewContextDescriptor creates a new context descriptor with a unique runtime ID.

type ContextProviderType

type ContextProviderType struct {
	Descriptor *ContextDescriptor
}

ContextProviderType marks provider elements in the runtime tree.

func NewContextProviderType

func NewContextProviderType(parseDescriptor *ContextDescriptor) *ContextProviderType

NewContextProviderType creates a provider marker for the given descriptor.

type DOMAdapter

type DOMAdapter interface {
	// Element creation and manipulation
	CreateElement(tag string) DOMNode
	CreateTextNode(text string) DOMNode
	SetAttribute(node DOMNode, name, value string)
	RemoveAttribute(node DOMNode, name string)
	SetProperty(node DOMNode, name string, value any)
	GetProperty(node DOMNode, name string) any

	// Tree manipulation
	AppendChild(parent, child DOMNode)
	RemoveChild(parent, child DOMNode)
	InsertBefore(parent, newNode, referenceNode DOMNode)
	ReplaceChild(parent, newNode, oldNode DOMNode)

	// Queries
	GetParent(node DOMNode) DOMNode
	GetChildren(node DOMNode) []DOMNode
	GetFirstChild(node DOMNode) DOMNode
	GetNextSibling(node DOMNode) DOMNode

	// Text nodes
	SetTextContent(node DOMNode, text string)

	// Styling
	SetStyle(node DOMNode, property, value string)
	SetStyles(node DOMNode, styles map[string]string)

	// Function wrapping
	WrapFunction(fn any) any
}

DOMAdapter abstracts all DOM operations used by the runtime.

type DOMNode

type DOMNode interface {
	IsNull() bool
	Equals(other DOMNode) bool
}

DOMNode is an opaque reference to a platform-specific DOM node.

Contract: - implementations must treat a nil receiver as null and return true from IsNull - nil interface values and explicit null-node wrappers are equivalent absence states - callers should prefer IsDOMNodeNull and IsSameDOMNode instead of open-coding mixed nil and IsNull checks

type DOMRefSink

type DOMRefSink interface {
	SetDOMNode(node DOMNode)
}

DOMRefSink receives the live DOM node when its element mounts and nil when the element unmounts. ui.UseDOMRef returns a handle implementing this; the runtime only ever calls SetDOMNode from the (single-threaded) commit phase.

type Deadline

type Deadline interface {
	TimeRemaining() float64
	DidTimeout() bool
}

Deadline provides timing information for idle callbacks.

type Diagnostic

type Diagnostic struct {
	Source         string
	Severity       DiagnosticSeverity
	Classification DiagnosticClassification
	Code           string
	Docs           string
	Remediation    string
	Recoverable    bool
	TopFrame       string
	Consequence    string
	Message        string
	Count          int
	Path           string
	ComponentStack []string
	Fields         map[string]string
}

Diagnostic describes one deduplicated runtime diagnostic entry.

func GetDiagnostics

func GetDiagnostics() []Diagnostic

GetDiagnostics returns a copy of the current diagnostic list. The entries are value copies; their ComponentStack slices and Fields maps are shared with the store, which never mutates them after insert — treat them as read-only. (Deep-cloning them per read dominated the cost of devtools inspection snapshots.)

type DiagnosticClassification

type DiagnosticClassification string
const (
	DiagnosticInformational      DiagnosticClassification = "informational"
	DiagnosticCorrectness        DiagnosticClassification = "correctness"
	DiagnosticPerformance        DiagnosticClassification = "performance"
	DiagnosticRecovered          DiagnosticClassification = "recovered"
	DiagnosticUnsupportedRecover DiagnosticClassification = "unsupported_recovered"
)

type DiagnosticSeverity

type DiagnosticSeverity string
const (
	DiagnosticInfo    DiagnosticSeverity = "info"
	DiagnosticWarning DiagnosticSeverity = "warning"
	DiagnosticError   DiagnosticSeverity = "error"
)

type Effect

type Effect struct {
	Fn           func() func()
	CleanupIndex int
	// Layout marks an effect that must run synchronously after DOM mutation but
	// before the browser paints, and before this fiber's passive effects (G36 /
	// UseLayoutEffect). Passive effects (UseEffect) leave it false.
	Layout bool
}

Effect represents a side effect to be run after render.

type Element

type Element struct {
	Type     any
	Props    map[string]any
	Children []any
	// Key carries the reconciliation key for elements built through the typed
	// fast lane (html.Props). Map-built elements keep their key in Props; the
	// key helpers consult this field first.
	Key         string
	TextContent string // Optimization for TEXT_ELEMENT to avoid map allocation
	// contains filtered or unexported fields
}

Element represents a virtual DOM node.

func A

func A(parseProps map[string]any, parseChildren ...any) *Element

A creates an a element.

func Abbr

func Abbr(parseProps map[string]any, parseChildren ...any) *Element

Abbr creates an abbr element.

func Address

func Address(parseProps map[string]any, parseChildren ...any) *Element

Address creates an address element.

func Article

func Article(parseProps map[string]any, parseChildren ...any) *Element

Article creates an article element.

func Aside

func Aside(parseProps map[string]any, parseChildren ...any) *Element

Aside creates an aside element.

func Audio

func Audio(parseProps map[string]any, parseChildren ...any) *Element

Audio creates an audio element.

func B

func B(parseProps map[string]any, parseChildren ...any) *Element

B creates a b element.

func Bdi

func Bdi(parseProps map[string]any, parseChildren ...any) *Element

Bdi creates a bdi element.

func Bdo

func Bdo(parseProps map[string]any, parseChildren ...any) *Element

Bdo creates a bdo element.

func Blockquote

func Blockquote(parseProps map[string]any, parseChildren ...any) *Element

Blockquote creates a blockquote element.

func Body

func Body(parseProps map[string]any, parseChildren ...any) *Element

Body creates a body element.

func Br

func Br(parseProps map[string]any) *Element

Br creates a br element.

func Button

func Button(parseProps map[string]any, parseChildren ...any) *Element

Button creates a button element.

func Canvas

func Canvas(parseProps map[string]any, parseChildren ...any) *Element

Canvas creates a canvas element.

func Caption

func Caption(parseProps map[string]any, parseChildren ...any) *Element

Caption creates a caption element.

func Circle

func Circle(parseProps map[string]any) *Element

Circle creates a circle element.

func Cite

func Cite(parseProps map[string]any, parseChildren ...any) *Element

Cite creates a cite element.

func Code

func Code(parseProps map[string]any, parseChildren ...any) *Element

Code creates a code element.

func Col

func Col(parseProps map[string]any) *Element

Col creates a col element.

func Colgroup

func Colgroup(parseProps map[string]any, parseChildren ...any) *Element

Colgroup creates a colgroup element.

func CreateElement

func CreateElement(parseTyp any, parseProps map[string]any, parseChildren ...any) *Element

CreateElement creates a new virtual DOM element.

func CreateElementCompactHostOwned

func CreateElementCompactHostOwned(parseTag string, parseKey string, parseAttrs []HostAttr, parseChildren ...any) *Element

CreateElementCompactHostOwned creates one typed fast-lane host element from a reconciliation key and a caller-normalized, deterministic compact string-attribute view. Fast-lane elements carry no props map at all; cold readers materialize one on demand (see ensureElementProps).

func CreateElementCompactHostOwnedText

func CreateElementCompactHostOwnedText(parseTag string, parseKey string, parseAttrs []HostAttr, parseText string) *Element

CreateElementCompactHostOwnedText creates one typed fast-lane host element whose only child is plain text, skipping child-slice normalization entirely.

func CreateElementOwned

func CreateElementOwned(parseTyp any, parseProps map[string]any, parseChildren ...any) *Element

CreateElementOwned creates a new virtual DOM element and takes ownership of the provided props map.

func Data

func Data(parseProps map[string]any, parseChildren ...any) *Element

Data creates a data element.

func Datalist

func Datalist(parseProps map[string]any, parseChildren ...any) *Element

Datalist creates a datalist element.

func Dd

func Dd(parseProps map[string]any, parseChildren ...any) *Element

Dd creates a dd element.

func Del

func Del(parseProps map[string]any, parseChildren ...any) *Element

Del creates a del element.

func Details

func Details(parseProps map[string]any, parseChildren ...any) *Element

Details creates a details element.

func Dfn

func Dfn(parseProps map[string]any, parseChildren ...any) *Element

Dfn creates a dfn element.

func Dialog

func Dialog(parseProps map[string]any, parseChildren ...any) *Element

Dialog creates a dialog element.

func Div

func Div(parseProps map[string]any, parseChildren ...any) *Element

Div creates a div element.

func DivWithComponents

func DivWithComponents(parseProps map[string]any, parseComponentRefs ...func(map[string]any) *Element) *Element

DivWithComponents creates a div element and renders component refs as children.

func Dl

func Dl(parseProps map[string]any, parseChildren ...any) *Element

Dl creates a dl element.

func Dt

func Dt(parseProps map[string]any, parseChildren ...any) *Element

Dt creates a dt element.

func Em

func Em(parseProps map[string]any, parseChildren ...any) *Element

Em creates an em element.

func Embed

func Embed(parseProps map[string]any) *Element

Embed creates an embed element.

func Fieldset

func Fieldset(parseProps map[string]any, parseChildren ...any) *Element

Fieldset creates a fieldset element.

func Figcaption

func Figcaption(parseProps map[string]any, parseChildren ...any) *Element

Figcaption creates a figcaption element.

func Figure

func Figure(parseProps map[string]any, parseChildren ...any) *Element

Figure creates a figure element.

func Footer(parseProps map[string]any, parseChildren ...any) *Element

Footer creates a footer element.

func Form

func Form(parseProps map[string]any, parseChildren ...any) *Element

Form creates a form element.

func G

func G(parseProps map[string]any, parseChildren ...any) *Element

G creates a g (SVG group) element.

func H1

func H1(parseProps map[string]any, parseChildren ...any) *Element

H1 creates an h1 element.

func H2

func H2(parseProps map[string]any, parseChildren ...any) *Element

H2 creates an h2 element.

func H3

func H3(parseProps map[string]any, parseChildren ...any) *Element

H3 creates an h3 element.

func H4

func H4(parseProps map[string]any, parseChildren ...any) *Element

H4 creates an h4 element.

func H5

func H5(parseProps map[string]any, parseChildren ...any) *Element

H5 creates an h5 element.

func H6

func H6(parseProps map[string]any, parseChildren ...any) *Element

H6 creates an h6 element.

func Head(parseProps map[string]any, parseChildren ...any) *Element

Head creates a head element.

func Header(parseProps map[string]any, parseChildren ...any) *Element

Header creates a header element.

func Hgroup

func Hgroup(parseProps map[string]any, parseChildren ...any) *Element

Hgroup creates an hgroup element.

func Hr

func Hr(parseProps map[string]any) *Element

Hr creates an hr element.

func Html

func Html(parseProps map[string]any, parseChildren ...any) *Element

Html creates an html element.

func I

func I(parseProps map[string]any, parseChildren ...any) *Element

I creates an i element.

func Iframe

func Iframe(parseProps map[string]any, parseChildren ...any) *Element

Iframe creates an iframe element.

func Img

func Img(parseProps map[string]any) *Element

Img creates an img element.

func Input

func Input(parseProps map[string]any) *Element

Input creates an input element.

func Ins

func Ins(parseProps map[string]any, parseChildren ...any) *Element

Ins creates an ins element.

func Kbd

func Kbd(parseProps map[string]any, parseChildren ...any) *Element

Kbd creates a kbd element.

func Label

func Label(parseProps map[string]any, parseChildren ...any) *Element

Label creates a label element.

func Legend

func Legend(parseProps map[string]any, parseChildren ...any) *Element

Legend creates a legend element.

func Li

func Li(parseProps map[string]any, parseChildren ...any) *Element

Li creates a li element.

func Line

func Line(parseProps map[string]any) *Element

Line creates a line element.

func Link(parseProps map[string]any) *Element

Link creates a link element.

func Main

func Main(parseProps map[string]any, parseChildren ...any) *Element

Main creates a main element.

func MainWithComponents

func MainWithComponents(parseProps map[string]any, parseComponentRefs ...func(map[string]any) *Element) *Element

MainWithComponents creates a main element and renders component refs as children.

func Mark

func Mark(parseProps map[string]any, parseChildren ...any) *Element

Mark creates a mark element.

func Menu(parseProps map[string]any, parseChildren ...any) *Element

Menu creates a menu element.

func Meta

func Meta(parseProps map[string]any) *Element

Meta creates a meta element.

func Meter

func Meter(parseProps map[string]any, parseChildren ...any) *Element

Meter creates a meter element.

func Nav(parseProps map[string]any, parseChildren ...any) *Element

Nav creates a nav element.

func Object

func Object(parseProps map[string]any, parseChildren ...any) *Element

Object creates an object element.

func Ol

func Ol(parseProps map[string]any, parseChildren ...any) *Element

Ol creates an ol element.

func Optgroup

func Optgroup(parseProps map[string]any, parseChildren ...any) *Element

Optgroup creates an optgroup element.

func Option

func Option(parseProps map[string]any, parseChildren ...any) *Element

Option creates an option element.

func Output

func Output(parseProps map[string]any, parseChildren ...any) *Element

Output creates an output element.

func P

func P(parseProps map[string]any, parseChildren ...any) *Element

P creates a p element.

func Param

func Param(parseProps map[string]any) *Element

Param creates a param element.

func Path

func Path(parseProps map[string]any) *Element

Path creates a path element.

func Picture

func Picture(parseProps map[string]any, parseChildren ...any) *Element

Picture creates a picture element.

func Polygon

func Polygon(parseProps map[string]any) *Element

Polygon creates a polygon element.

func Portal

func Portal(parseProps map[string]any, parseChildren ...any) *Element

Portal creates a portal element.

func Pre

func Pre(parseProps map[string]any, parseChildren ...any) *Element

Pre creates a pre element.

func Progress

func Progress(parseProps map[string]any, parseChildren ...any) *Element

Progress creates a progress element.

func Q

func Q(parseProps map[string]any, parseChildren ...any) *Element

Q creates a q element.

func Rect

func Rect(parseProps map[string]any) *Element

Rect creates a rect element.

func Rp

func Rp(parseProps map[string]any, parseChildren ...any) *Element

Rp creates an rp element.

func Rt

func Rt(parseProps map[string]any, parseChildren ...any) *Element

Rt creates an rt element.

func Ruby

func Ruby(parseProps map[string]any, parseChildren ...any) *Element

Ruby creates a ruby element.

func S

func S(parseProps map[string]any, parseChildren ...any) *Element

S creates an s element.

func Samp

func Samp(parseProps map[string]any, parseChildren ...any) *Element

Samp creates a samp element.

func Script

func Script(parseProps map[string]any, parseChildren ...any) *Element

Script creates a script element.

func Section

func Section(parseProps map[string]any, parseChildren ...any) *Element

Section creates a section element.

func SectionWithComponents

func SectionWithComponents(parseProps map[string]any, parseComponentRefs ...func(map[string]any) *Element) *Element

SectionWithComponents creates a section element and renders component refs as children.

func Select

func Select(parseProps map[string]any, parseChildren ...any) *Element

Select creates a select element.

func Slot

func Slot(parseProps map[string]any, parseChildren ...any) *Element

Slot creates a slot element.

func Small

func Small(parseProps map[string]any, parseChildren ...any) *Element

Small creates a small element.

func Source

func Source(parseProps map[string]any) *Element

Source creates a source element.

func Span

func Span(parseProps map[string]any, parseChildren ...any) *Element

Span creates a span element.

func Strong

func Strong(parseProps map[string]any, parseChildren ...any) *Element

Strong creates a strong element.

func Style

func Style(parseProps map[string]any, parseChildren ...any) *Element

Style creates a style element.

func Sub

func Sub(parseProps map[string]any, parseChildren ...any) *Element

Sub creates a sub element.

func Summary

func Summary(parseProps map[string]any, parseChildren ...any) *Element

Summary creates a summary element.

func Sup

func Sup(parseProps map[string]any, parseChildren ...any) *Element

Sup creates a sup element.

func Svg

func Svg(parseProps map[string]any, parseChildren ...any) *Element

Svg creates an svg element.

func Table

func Table(parseProps map[string]any, parseChildren ...any) *Element

Table creates a table element.

func Tbody

func Tbody(parseProps map[string]any, parseChildren ...any) *Element

Tbody creates a tbody element.

func Td

func Td(parseProps map[string]any, parseChildren ...any) *Element

Td creates a td element.

func Template

func Template(parseProps map[string]any, parseChildren ...any) *Element

Template creates a template element.

func Textarea

func Textarea(parseProps map[string]any, parseChildren ...any) *Element

Textarea creates a textarea element.

func Tfoot

func Tfoot(parseProps map[string]any, parseChildren ...any) *Element

Tfoot creates a tfoot element.

func Th

func Th(parseProps map[string]any, parseChildren ...any) *Element

Th creates a th element.

func Thead

func Thead(parseProps map[string]any, parseChildren ...any) *Element

Thead creates a thead element.

func Time

func Time(parseProps map[string]any, parseChildren ...any) *Element

Time creates a time element.

func Title

func Title(parseProps map[string]any, parseChildren ...any) *Element

Title creates a title element.

func Tr

func Tr(parseProps map[string]any, parseChildren ...any) *Element

Tr creates a tr element.

func Track

func Track(parseProps map[string]any) *Element

Track creates a track element.

func U

func U(parseProps map[string]any, parseChildren ...any) *Element

U creates a u element.

func Ul

func Ul(parseProps map[string]any, parseChildren ...any) *Element

Ul creates a ul element.

func Var

func Var(parseProps map[string]any, parseChildren ...any) *Element

Var creates a var element.

func Video

func Video(parseProps map[string]any, parseChildren ...any) *Element

Video creates a video element.

func Wbr

func Wbr(parseProps map[string]any) *Element

Wbr creates a wbr element.

func WithComponents

func WithComponents(parseTagName string, parseProps map[string]any, parseComponentRefs ...func(map[string]any) *Element) *Element

WithComponents creates an element with the given tag and renders component refs as children.

type ErrorBoundaryType

type ErrorBoundaryType struct{}

ErrorBoundaryType marks runtime-recognized error-boundary elements.

func NewErrorBoundaryType

func NewErrorBoundaryType() *ErrorBoundaryType

NewErrorBoundaryType creates a marker type recognized by the runtime as an error boundary.

type Event

type Event interface {
	PreventDefault()
	StopPropagation()
	GetValue() string
	GetTarget() DOMNode
	GetKeyCode() int
	GetKey() string
	IsChecked() bool
}

Event abstracts platform-specific events.

type EventAdapter

type EventAdapter interface {
	AddEventListener(node DOMNode, eventType string, handler EventHandler)
	RemoveEventListener(node DOMNode, eventType string, handler EventHandler)
	CreateEventHandler(fn func(Event)) EventHandler
	ReleaseEventHandler(handler EventHandler)
}

EventAdapter abstracts event handling.

type EventHandler

type EventHandler interface {
	Release()
}

EventHandler is an opaque reference to a platform-specific event handler.

type FetchState

type FetchState struct {
	Data    any    // The fetched data
	Error   string // Error message if fetch failed
	Loading bool   // Whether currently fetching
}

FetchState represents the state of a fetch operation.

type Fiber

type Fiber struct {
	// contains filtered or unexported fields
}

Fiber represents a unit of work in the virtual DOM tree.

func GetCurrentFiber

func GetCurrentFiber() *Fiber

type FiberSnapshot

type FiberSnapshot struct {
	Name string
	Path string
	// AgentRef is the stable key/index-disambiguated ref the agent bridge
	// resolves back to this node (empty on the root, which is not addressable).
	AgentRef string
	// Text is the full text content for text fibers (empty otherwise). Name
	// only carries a short preview; Text lets a reader recover the rendered copy.
	Text              string
	Kind              string
	Dirty             bool
	NeedsUpdate       bool
	FineGrained       bool
	ReactiveSource    string
	UpdateOrigin      string
	EffectCount       int
	HookCount         int
	Signature         *ComponentSignature
	RenderDurationNs  int64
	DiffDurationNs    int64
	CommitDurationNs  int64
	EffectDurationNs  int64
	CleanupDurationNs int64
	SelfDurationNs    int64
	SubtreeDurationNs int64
	Hooks             []HookSnapshot
	Children          []FiberSnapshot
}

FiberSnapshot captures one inspected fiber subtree.

type FlamegraphFrameSnapshot

type FlamegraphFrameSnapshot struct {
	Name              string
	Kind              string
	Path              string
	Depth             int
	StartNs           int64
	DurationNs        int64
	SelfDurationNs    int64
	RenderDurationNs  int64
	DiffDurationNs    int64
	CommitDurationNs  int64
	EffectDurationNs  int64
	CleanupDurationNs int64
}

FlamegraphFrameSnapshot captures one nested flamegraph frame.

type Focuser

type Focuser interface {
	Focus()
}

Focuser is the optional capability a DOMNode may implement to move keyboard focus to itself. The wasm node implements it (element.focus()); ui.DOMRef.Focus and ui.UseAutoFocus route through it so they work cross-build (no-op when the node — or the build — does not support focusing).

type HookSnapshot

type HookSnapshot struct {
	Slot         int
	Kind         string
	Value        string
	Dependencies string
	Status       string
}

HookSnapshot captures one hook entry from an inspected fiber.

type Hooks

type Hooks struct {
	// contains filtered or unexported fields
}

Hooks manages component hook state for a fiber.

type HostAttr

type HostAttr struct {
	Name  string
	Value string
}

HostAttr stores one normalized string attribute for one compact host mount.

type HostMountSpec

type HostMountSpec struct {
	Tag   string
	Attrs []HostAttr
	Text  string
}

HostMountSpec stores one simple host mount description for one batched DOM append path.

type HotBranchSnapshot

type HotBranchSnapshot struct {
	Name              string
	Kind              string
	Path              string
	RenderDurationNs  int64
	DiffDurationNs    int64
	CommitDurationNs  int64
	EffectDurationNs  int64
	CleanupDurationNs int64
	SelfDurationNs    int64
	SubtreeDurationNs int64
}

HotBranchSnapshot captures one high-cost subtree from profiling output.

type HotReloadComponentSnapshot

type HotReloadComponentSnapshot struct {
	Signature     ComponentSignature       `json:"signature"`
	Path          string                   `json:"path,omitempty"`
	IdentityTrail []string                 `json:"identityTrail,omitempty"`
	States        []any                    `json:"states,omitempty"`
	Memos         []HotReloadMemoSnapshot  `json:"memos,omitempty"`
	Refs          []any                    `json:"refs,omitempty"`
	IDs           []string                 `json:"ids,omitempty"`
	Fetches       []HotReloadFetchSnapshot `json:"fetches,omitempty"`
}

HotReloadComponentSnapshot stores the serializable hook slots for a single function component render in preorder traversal order.

type HotReloadFetchSnapshot

type HotReloadFetchSnapshot struct {
	URL   string     `json:"url"`
	State FetchState `json:"state"`
}

HotReloadFetchSnapshot stores the serializable portion of a fetch hook.

type HotReloadMemoSnapshot

type HotReloadMemoSnapshot struct {
	Value any   `json:"value"`
	Deps  []any `json:"deps,omitempty"`
}

HotReloadMemoSnapshot stores a memoized computation and its dependencies.

type HotReloadRestoreDecision

type HotReloadRestoreDecision struct {
	Strategy     string
	UnsafeReason string
}

HotReloadRestoreDecision reports whether selective restore was applied or the runtime fell back to the legacy full compatible restore path.

type HotReloadRestorePlan

type HotReloadRestorePlan struct {
	Selective         bool
	ChangedIdentities []string
}

HotReloadRestorePlan controls whether hot-reload restore should preserve all compatible component snapshots or selectively drop changed subtrees.

type HotReloadSnapshot

type HotReloadSnapshot struct {
	Components []HotReloadComponentSnapshot `json:"components,omitempty"`
}

HotReloadSnapshot captures the component-local state that can be restored after a compatible hot reload.

type HydrationDebugSnapshot

type HydrationDebugSnapshot struct {
	CorrelationID        string
	StartedAt            string
	FinishedAt           string
	DurationNs           int64
	ExistingDOMNodeCount int
	FallbackCount        int
	MismatchCount        int
	DiscardedNodeCount   int
	Strict               bool
	Failed               bool
	Failure              string
	RecentMessages       []string
}

type HydrationMetrics

type HydrationMetrics struct {
	CorrelationID        string
	StartedAt            time.Time
	FinishedAt           time.Time
	Duration             time.Duration
	DurationNs           int64
	ExistingDOMNodeCount int
	FallbackCount        int
	MismatchCount        int
	DiscardedNodeCount   int
	Strict               bool
	Failed               bool
	Failure              string
}

HydrationMetrics summarizes one hydration pass for observability hooks.

type InspectionSnapshot

type InspectionSnapshot struct {
	Root        *FiberSnapshot
	Stats       InspectionStats
	Profiling   ProfilingSnapshot
	Hydration   HydrationDebugSnapshot
	Diagnostics []Diagnostic
	Logs        []LogEntry
}

InspectionSnapshot is the top-level runtime inspection payload.

type InspectionStats

type InspectionStats struct {
	TotalFibers       int
	DirtyFibers       int
	ComponentFibers   int
	HostFibers        int
	TextFibers        int
	FineGrainedFibers int
	HookEntries       int
	Effects           int
}

InspectionStats summarizes the inspected runtime tree.

type InternalStateSnapshot

type InternalStateSnapshot struct {
	FiberCount            int
	AtomCount             int
	AtomSubscriberCount   int
	PendingEffectFibers   int
	UIQueueSize           int
	DiagnosticCount       int
	LogCount              int
	ProfilingEventCount   int
	SchedulerBackpressure bool
}

InternalStateSnapshot captures bounded runtime state useful for long-session monitoring.

type LogEntry

type LogEntry struct {
	Domain         string
	Level          LogLevel
	Classification DiagnosticClassification
	Code           string
	Docs           string
	Remediation    string
	Recoverable    bool
	TopFrame       string
	Consequence    string
	Message        string
	Timestamp      string
	CorrelationID  string
	Fields         map[string]string
}

LogEntry describes one recent structured framework log.

func GetLogs

func GetLogs() []LogEntry

GetLogs returns a copy of the current in-memory log buffer, oldest first. The entries are value copies; their Fields maps are shared with the store, which never mutates them after insert — treat them as read-only.

type LogLevel

type LogLevel string
const (
	LogDebug LogLevel = "debug"
	LogInfo  LogLevel = "info"
	LogWarn  LogLevel = "warn"
	LogError LogLevel = "error"
)

type MemoryHygieneOptions

type MemoryHygieneOptions struct {
	MaxHeapAllocBytes  uint64
	MaxHeapObjects     uint64
	MaxFiberCount      int
	MaxAtomCount       int
	MaxSubscriberCount int
	// MaxGoroutines bounds live goroutines.
	//
	// Added because its absence was measurable: a suspended async boundary parked
	// a fresh watcher goroutine on every render (fixed in ee39ac99), and none of
	// the thresholds above could see it. Heap bytes barely moved, the fiber tree
	// was the same size, and no atom or subscriber count changed — the leak was
	// entirely in goroutines holding channels. A framework that spawns goroutines
	// for suspensions, fetches, and worker replies needs the one counter that
	// makes those visible.
	MaxGoroutines int
}

MemoryHygieneOptions configures leak and GC-pressure diagnostics.

type MemoryHygieneSnapshot

type MemoryHygieneSnapshot struct {
	HeapAllocBytes uint64
	HeapObjects    uint64
	Goroutines     int
	Internal       InternalStateSnapshot
	Diagnostics    []string
}

MemoryHygieneSnapshot reports memory and internal-state pressure.

type PanicLoggingOptions

type PanicLoggingOptions struct {
	HideRawPanicOutput bool
	OnReport           func(PanicReport)
}

func CurrentUnhandledPanicLoggingOptions

func CurrentUnhandledPanicLoggingOptions() PanicLoggingOptions

CurrentUnhandledPanicLoggingOptions returns a snapshot of the current panic logging configuration.

type PanicPhase

type PanicPhase string
const (
	PanicPhaseRender    PanicPhase = "render"
	PanicPhaseEffect    PanicPhase = "effect"
	PanicPhaseCleanup   PanicPhase = "cleanup"
	PanicPhaseEvent     PanicPhase = "event"
	PanicPhaseLoader    PanicPhase = "loader"
	PanicPhaseHydration PanicPhase = "hydration"
	PanicPhaseStartup   PanicPhase = "startup"
	PanicPhaseDeferred  PanicPhase = "deferred"
	PanicPhaseSSR       PanicPhase = "ssr"
	PanicPhaseAsync     PanicPhase = "async"
)

type PanicReport

type PanicReport struct {
	Source          string
	Phase           PanicPhase
	Subject         string
	Where           string
	Path            string
	ComponentStack  []string
	Summary         string
	Code            string
	Docs            string
	Remediation     string
	Consequence     string
	TopFrame        string
	AppFrames       []string
	FrameworkFrames []string
	PlatformFrames  []string
	Artifact        WASMArtifactMetadata
	Formatted       string
}

PanicReport describes one wrapped framework-owned fatal panic report.

type PanicReportRedactionContext

type PanicReportRedactionContext struct {
	Path  string
	Field string
	Value any
}

type PanicReportRedactionPolicy

type PanicReportRedactionPolicy struct {
	Fields []string
	Redact func(PanicReportRedactionContext) (any, error)
}

func CurrentPanicReportRedaction

func CurrentPanicReportRedaction() PanicReportRedactionPolicy

CurrentPanicReportRedaction returns the active runtime-local panic report redaction policy.

type PassiveEventHandler

type PassiveEventHandler struct {
	Handler any
}

PassiveEventHandler marks an event handler that should be attached with passive listener options when the DOM adapter supports listener binding.

type PortalElementType

type PortalElementType struct{}

PortalElementType marks a subtree whose committed DOM children should render into a separate target container.

type ProfilingEvent

type ProfilingEvent struct {
	Domain        string
	Name          string
	Phase         string
	Target        string
	CorrelationID string
	DurationNs    int64
	Timestamp     string
	Fields        map[string]string
	// contains filtered or unexported fields
}

ProfilingEvent captures one structured profiling timeline entry.

type ProfilingPhaseTotalsSnapshot

type ProfilingPhaseTotalsSnapshot struct {
	RenderDurationNs  int64
	DiffDurationNs    int64
	CommitDurationNs  int64
	EffectDurationNs  int64
	CleanupDurationNs int64
}

ProfilingPhaseTotalsSnapshot summarizes attributed phase time totals.

type ProfilingSnapshot

type ProfilingSnapshot struct {
	RenderCalls                      int
	ScheduledRootUpdates             int
	ScheduledFiberMarks              int
	ScheduledGranularMarks           int
	WorkLoopPasses                   int
	ProcessedUnits                   int
	CommitCount                      int
	FineGrainedCommits               int
	FineGrainedDescendantHostCommits int
	FineGrainedDescendantTextCommits int
	EffectExecutions                 int
	CleanupExecutions                int
	LastRenderDurationNs             int64
	LastCommitDurationNs             int64
	LastEffectDurationNs             int64
	LastCleanupDurationNs            int64
	PhaseTotals                      ProfilingPhaseTotalsSnapshot
	ComponentRenders                 []ComponentRenderTraceSnapshot
	RecentEvents                     []ProfilingEvent
	FlamegraphFrames                 []FlamegraphFrameSnapshot
	Startup                          StartupProfilingSnapshot
	HotBranches                      []HotBranchSnapshot
}

ProfilingSnapshot summarizes runtime profiling counters and hot branches.

type ReactiveRegionElementType

type ReactiveRegionElementType struct{}

ReactiveRegionElementType marks a subscribed fine-grained region that can rerender its own child subtree without rerendering the owning component.

type ReactiveTextElementType

type ReactiveTextElementType struct{}

ReactiveTextElementType marks a text node that can update from an explicit atom-backed subscription without rerendering the owning component.

type RefValue

type RefValue struct {
	Current any
}

RefValue represents a reference object that persists across renders.

func GoUseRef

func GoUseRef(parseInitialValue any) *RefValue

GoUseRef creates a mutable reference that persists across renders It returns a RefValue object with a .Current field that can hold any value Unlike state, updating a ref does NOT trigger a re-render

type ReplayEvent

type ReplayEvent struct {
	Kind    string
	Path    []int
	Origin  string
	Lane    string
	Seq     int
	Dropped bool
}

ReplayEvent captures one deterministic scheduling event.

type RouteStartupBudgetSnapshot

type RouteStartupBudgetSnapshot struct {
	RouteFamily                       string
	LastRoutePath                     string
	SampleCount                       int
	AverageBootstrapReadDurationNs    int64
	AverageWASMTransferBytes          int64
	AverageWASMDecodedBytes           int64
	AverageBootstrapDecodedBytes      int64
	AverageCacheWarmupDurationNs      int64
	AverageServiceWorkerOverheadNs    int64
	AverageInitialRouteDataBytes      int64
	AverageHydrationDurationNs        int64
	AverageStartupCommitDurationNs    int64
	AverageFirstInteractionDurationNs int64
}

RouteStartupBudgetSnapshot captures startup budget samples grouped by route family.

type Runtime

type Runtime struct {
	// contains filtered or unexported fields
}

Runtime represents the reconciliation and rendering engine.

func GetGlobalRuntime

func GetGlobalRuntime() *Runtime

GetGlobalRuntime returns the global Runtime instance, creating it if needed. For WASM builds, this can be upgraded later by InitGlobalRuntime.

func NewRuntime

func NewRuntime(parseConfig Config) *Runtime

NewRuntime creates a new runtime instance.

func ResolveRuntime

func ResolveRuntime() *Runtime

runtimeForFiber returns the owning runtime for a fiber subtree, falling back to the global runtime for legacy tests that install a bare current fiber. ResolveRuntime returns the runtime that owns the component currently rendering, falling back to the global runtime outside a render (v5 P2.6).

Packages that reach for GetGlobalRuntime to read or write atoms should call this instead. During a render it resolves to the runtime that actually owns the tree, so a second Runtime in the same process keeps its own atom state — which is what P3.7 requires, since projections are published into the atom registry and would otherwise all land in whichever runtime happened to be global.

func (*Runtime) AdvanceAgentStateVersion

func (parseRt *Runtime) AdvanceAgentStateVersion() uint64

AdvanceAgentStateVersion increments and returns the bridge-visible runtime state version. Agent write commands call this after a successful mutation or side-effect dispatch; commitRoot also advances it after a DOM commit.

func (*Runtime) AgentStateVersion

func (parseRt *Runtime) AgentStateVersion() uint64

AgentStateVersion returns the monotonic runtime version exposed by the live agent bridge. It advances on commits and on bridge-visible write commands so command acks can preserve read-your-writes ordering without inspecting DOM timing internals.

func (*Runtime) AsyncInboxDepth

func (parseRt *Runtime) AsyncInboxDepth() int

AsyncInboxDepth reports how many entries are waiting. Used by memory hygiene and by tests asserting the batching property.

func (*Runtime) AsyncInboxStats

func (parseRt *Runtime) AsyncInboxStats() (parsePosts int, parseDrains int)

AsyncInboxStats reports cumulative post and drain counts, so the "N posts become one pass" claim is observable rather than asserted.

func (*Runtime) AsyncInboxSuspensions

func (parseRt *Runtime) AsyncInboxSuspensions() int

AsyncInboxSuspensions reports how many times the inbox drained on a producer goroutine, suspending frame isolation for that batch.

Separate from the aggregate Triggered count because these two conditions are not the same event and folding them together hides the serious one behind the ordinary one — the distinction the inbox's own comments already draw between "batching degraded" and "the guarantee was suspended".

func (*Runtime) AsyncIngressEnabled

func (parseRt *Runtime) AsyncIngressEnabled() bool

AsyncIngressEnabled reports whether off-loop state writes are routed through the inbox, so an app can check what it is running under.

func (*Runtime) BeginReplayCapture

func (parseRt *Runtime) BeginReplayCapture()

BeginReplayCapture is a compatibility alias for StartReplayRecording.

func (*Runtime) BeginStartupProfiling

func (parseRt *Runtime) BeginStartupProfiling(parseMode string)

BeginStartupProfiling marks the beginning of a startup workflow when one has not already been started for the current runtime.

func (*Runtime) Budgets

func (parseRt *Runtime) Budgets() WorkloadBudgets

Budgets reports the current workload budget state.

Safe on a nil runtime, because a devtools panel polls on a timer and can easily outlive the runtime it was watching.

func (*Runtime) CaptureHotReloadSnapshot

func (parseRt *Runtime) CaptureHotReloadSnapshot() HotReloadSnapshot

CaptureHotReloadSnapshot is an internal hot-reload helper.

func (*Runtime) CheckMemoryHygiene

func (parseRt *Runtime) CheckMemoryHygiene(parseOptions MemoryHygieneOptions) MemoryHygieneSnapshot

CheckMemoryHygiene samples Go memory stats and reports configured long-session pressure diagnostics.

This STOPS THE WORLD. runtime.ReadMemStats pauses every goroutine while it copies the stats, and this then calls InternalStateSnapshot, which walks the fiber tree under schedulerMu. Sampling it on a timer therefore manufactures exactly the pauses M7 is trying to bound — a memory diagnostic that shows up in the GC-pause metric it exists to explain.

Call it on demand, or on a slow interval when investigating a long session. Not per frame, and not from a devtools panel that refreshes.

func (*Runtime) CleanupAtomSubscriptions

func (parseRt *Runtime) CleanupAtomSubscriptions(parseFiber *Fiber)

CleanupAtomSubscriptions removes all atom subscriptions for a fiber This should be called when a fiber is being removed from the tree

func (*Runtime) ClearProfiling

func (parseRt *Runtime) ClearProfiling()

ClearProfiling resets collected profiling counters and timeline events.

func (*Runtime) DeleteAtomValueIfUnsubscribed

func (parseRt *Runtime) DeleteAtomValueIfUnsubscribed(parseId string) bool

DeleteAtomValueIfUnsubscribed removes an atom and its registry bookkeeping when no fiber is subscribed to it, and reports whether it did.

The registry has no eviction of its own — atoms live for the process — which is correct for the app-global state they were designed for and wrong for the layers that key atoms by a DYNAMIC id (a cache key, a row id). Those grow the registry monotonically, and writing a zero VALUE over a dead key reclaims the payload but leaves the key. This is how such a layer hands the key back.

It refuses when the atom still has subscribers rather than reporting success, so a caller cannot accidentally cut a mounted component off from its updates; see deleteAtomIfUnsubscribed.

func (*Runtime) DrainAsyncInbox

func (parseRt *Runtime) DrainAsyncInbox()

DrainAsyncInbox applies queued entries under a time budget.

Applying the WHOLE batch in one block was the original design, on the reasoning that each entry marks its own state and the updateScheduled gate collapses them into a single render pass. The coalescing part is right and is kept. The unbounded part is not: the queue's soft bound is 16,384 entries and its hard bound 262,144, so a burst converts queue pressure into one enormous main-thread task — the inbox would be causing precisely the frame the architecture exists to protect.

So the batch is applied in slices against a deadline, and whatever does not fit is returned to the FRONT of the queue with another drain scheduled. Order is preserved: entries left over ran before anything posted since.

Coalescing survives being sliced. Every entry still marks state through the same updateScheduled gate, so N entries across M drains still produce one render pass per frame rather than one per entry.

func (*Runtime) EndReplayCapture

func (parseRt *Runtime) EndReplayCapture() []ReplayEvent

EndReplayCapture is a compatibility alias for StopReplayRecording.

func (*Runtime) FindNodesWithAttributeInSelector

func (parseRt *Runtime) FindNodesWithAttributeInSelector(parseSelector string, parseName string) []DOMNode

FindNodesWithAttributeInSelector collects descendant DOM nodes under one selector-matched container that carry the requested attribute.

func (*Runtime) FindNodesWithAttributeInTarget

func (parseRt *Runtime) FindNodesWithAttributeInTarget(parseTarget any, parseName string) []DOMNode

FindNodesWithAttributeInTarget collects descendant DOM nodes under one resolved target that carry the requested attribute.

func (*Runtime) FlushScheduledDiscreteWork

func (parseRt *Runtime) FlushScheduledDiscreteWork()

FlushScheduledDiscreteWork synchronously runs a freshly scheduled, not yet started render pass. The DOM event bridge calls it after a component event handler returns, so a discrete user action commits inside its own task (React-style sync discrete flush) instead of waiting out the setTimeout(0) kick — while state writes from goroutines the handler spawned still land in a follow-up pass exactly as they would have with the macrotask hop. The already-queued kick later finds no pending work and no-ops. It refuses to run when any work loop is active on this stack (a handler fired synchronously by a commit-phase DOM write) or when the pass has already consumed work slices.

func (*Runtime) GetAtomValue

func (parseRt *Runtime) GetAtomValue(parseId string) (any, bool)

GetAtomValue is a helper to get an atom value directly (for debugging/testing)

func (*Runtime) GetAttributeValue

func (parseRt *Runtime) GetAttributeValue(parseNode DOMNode, parseName string) (string, bool)

GetAttributeValue reports one attribute value from one DOM node when the active adapter exposes attribute reads.

func (*Runtime) GetTagName

func (parseRt *Runtime) GetTagName(parseNode DOMNode) (string, bool)

GetTagName reports one normalized lower-case tag name from one DOM node when the active adapter exposes host tag reads.

func (*Runtime) HasCommitted

func (parseRt *Runtime) HasCommitted() bool

HasCommitted reports whether this runtime has completed its first commit.

func (*Runtime) HasPendingHotReloadSnapshot

func (parseRt *Runtime) HasPendingHotReloadSnapshot() bool

HasPendingHotReloadSnapshot is an internal hot-reload helper.

func (*Runtime) Hydrate

func (parseRt *Runtime) Hydrate(parseElement *Element, parseContainer DOMNode)

Hydrate starts a client resume attempt from an existing container.

func (*Runtime) HydrateInto

func (parseRt *Runtime) HydrateInto(parseTarget any, parseElement *Element) error

HydrateInto hydrates an element tree into an explicit DOM node.

func (*Runtime) HydrateTo

func (parseRt *Runtime) HydrateTo(parseSelector string, parseElement *Element)

HydrateTo renders into a selector while preserving a dedicated hydration path. It attempts to reuse matching DOM, restores bootstrap state before resume via the public ui layer, and falls back per subtree if hydration cannot continue.

func (*Runtime) InitAtomValue

func (parseRt *Runtime) InitAtomValue(parseId string, parseValue any) bool

InitAtomValue seeds an atom with value only if it has no value yet, without notifying any subscribers. It is the no-side-effect seeding primitive used by non-hook global-atom handles (state.GlobalAtom) so constructing a handle never clobbers a value written earlier (the G39 pre-render-write-survives guarantee) and never schedules a spurious render. Returns true if it seeded.

func (*Runtime) Inspect

func (parseRt *Runtime) Inspect() InspectionSnapshot

Inspect captures a snapshot of the current runtime tree, profiling state, and diagnostics.

func (*Runtime) InternalStateSnapshot

func (parseRt *Runtime) InternalStateSnapshot() InternalStateSnapshot

InternalStateSnapshot returns bounded internal queue, fiber, and listener counters.

NOT free, and not for a per-frame poll. It walks the whole committed fiber tree to count it, and it does that while holding schedulerMu — the lock every Schedule* entry point and commitRoot take — so a caller polling this on a timer blocks scheduling for O(tree) on each sample. GetSubscriberTotal walks every atom's subscriber set under the registry lock as well.

That is a fine price for an occasional long-session sample, which is what this is for, and the wrong price for a devtools panel refreshing at frame rate. The package README recommends this API without saying so; it does now.

func (*Runtime) OnFirstCommit

func (parseRt *Runtime) OnFirstCommit(parseFn func())

OnFirstCommit registers fn to run once, immediately after this runtime's first commit. If that commit already happened, fn runs synchronously now. A nil fn is ignored.

func (*Runtime) PostAsync

func (parseRt *Runtime) PostAsync(parseWork func())

PostAsync queues work to be applied at the next frame boundary.

Safe to call from any goroutine. The function runs later, on the frame loop, and should perform the state mutation it wants rendered — calling the normal Schedule* paths from inside it is correct and is what produces the coalescing.

func (*Runtime) PrepareForHotReload

func (parseRt *Runtime) PrepareForHotReload()

PrepareForHotReload is an internal hot-reload helper.

func (*Runtime) RecordProfilingEvent

func (parseRt *Runtime) RecordProfilingEvent(parseEvent ProfilingEvent)

RecordProfilingEvent records a profiling timeline entry on this runtime.

func (*Runtime) RecordStartupBootstrapRead

func (parseRt *Runtime) RecordStartupBootstrapRead(parseDurationNs int64, parseSource string)

RecordStartupBootstrapRead stores bootstrap read or decode timing and emits a profiling timeline event.

func (*Runtime) RecordStartupRouteContext

func (parseRt *Runtime) RecordStartupRouteContext(parseRoutePath string)

RecordStartupRouteContext captures which route family the active startup flow is targeting so first-interaction budgets can be attributed correctly.

func (*Runtime) RefreshEffectsForFiber

func (parseRt *Runtime) RefreshEffectsForFiber(parseFiber *Fiber)

RefreshEffectsForFiber forces a fiber subtree's effects to clean up and rerun on the next render.

func (*Runtime) RegisterDerivedAtom

func (parseRt *Runtime) RegisterDerivedAtom(parseId string, parseDeps []string, parseCompute func() any) error

RegisterDerivedAtom is a core package helper.

func (*Runtime) Render

func (parseRt *Runtime) Render(parseElement *Element, parseContainer DOMNode)

Render starts rendering a component tree

func (*Runtime) RenderInto

func (parseRt *Runtime) RenderInto(parseTarget any, parseElement *Element) error

RenderInto renders an element tree into an explicit DOM node.

func (*Runtime) RenderTo

func (parseRt *Runtime) RenderTo(parseSelector string, parseElement *Element)

RenderTo renders an element to a DOM node specified by selector.

func (*Runtime) ReplayEvents

func (parseRt *Runtime) ReplayEvents() []ReplayEvent

ReplayEvents returns a copy of captured deterministic scheduling events.

func (*Runtime) ReplayUpdates

func (parseRt *Runtime) ReplayUpdates(parseEvents []ReplayEvent)

ReplayUpdates replays captured scheduling events against the current fiber tree.

func (*Runtime) ResetFirstCommitHooksForTest

func (parseRt *Runtime) ResetFirstCommitHooksForTest()

ResetFirstCommitHooksForTest restores this runtime's pre-commit state. Test-only.

func (*Runtime) ResolveAgentRef

func (parseRt *Runtime) ResolveAgentRef(parseRef string) (*Fiber, error)

ResolveAgentRef resolves a stable agent ref to its live fiber under the scheduler lock (the same discipline as Inspect). Resolution is read-only: it never marks fibers dirty or touches hook state.

func (*Runtime) RestoreAtomSnapshot

func (parseRt *Runtime) RestoreAtomSnapshot(parseSnapshot map[string]any) error

RestoreAtomSnapshot merges atom values from snapshot and schedules updates for any subscribed fibers.

func (*Runtime) RestoreHotReloadSnapshot

func (parseRt *Runtime) RestoreHotReloadSnapshot(parseSnapshot HotReloadSnapshot)

RestoreHotReloadSnapshot is an internal hot-reload helper.

func (*Runtime) RestoreHotReloadSnapshotWithPlan

func (parseRt *Runtime) RestoreHotReloadSnapshotWithPlan(parseSnapshot HotReloadSnapshot, parsePlan HotReloadRestorePlan) HotReloadRestoreDecision

RestoreHotReloadSnapshotWithPlan is an internal hot-reload helper.

func (*Runtime) ScheduleGranularUpdateForFiber

func (parseRt *Runtime) ScheduleGranularUpdateForFiber(parseFiber *Fiber)

ScheduleGranularUpdateForFiber marks only the target fiber dirty and lets clean ancestors clone through to the dirty descendant on the next root pass.

func (*Runtime) ScheduleGranularUpdateForFiberWithOrigin

func (parseRt *Runtime) ScheduleGranularUpdateForFiberWithOrigin(parseFiber *Fiber, parseOrigin string)

ScheduleGranularUpdateForFiberWithOrigin marks only the target fiber dirty and records the triggering cause for profiling and devtools inspection.

func (*Runtime) ScheduleOwnedFiberUpdate

func (parseRt *Runtime) ScheduleOwnedFiberUpdate(parseFiber *Fiber)

ScheduleOwnedFiberUpdate chooses the narrowest safe scheduling path for one component-owned update.

func (*Runtime) ScheduleOwnedFiberUpdateWithOrigin

func (parseRt *Runtime) ScheduleOwnedFiberUpdateWithOrigin(parseFiber *Fiber, parseOrigin string)

ScheduleOwnedFiberUpdateWithOrigin chooses the narrowest safe scheduling path for one component-owned update and records the triggering cause.

func (*Runtime) ScheduleSubscribedFiberUpdate

func (parseRt *Runtime) ScheduleSubscribedFiberUpdate(parseFiber *Fiber)

ScheduleSubscribedFiberUpdate chooses the narrowest safe scheduling path for a subscription target.

func (*Runtime) ScheduleSubscribedFiberUpdateWithOrigin

func (parseRt *Runtime) ScheduleSubscribedFiberUpdateWithOrigin(parseFiber *Fiber, parseOrigin string)

ScheduleSubscribedFiberUpdateWithOrigin chooses the narrowest safe scheduling path for a subscription target and records the triggering cause.

func (*Runtime) ScheduleTransition

func (parseRt *Runtime) ScheduleTransition(parseFn func())

ScheduleTransition is a core package helper.

func (*Runtime) ScheduleUpdate

func (parseRt *Runtime) ScheduleUpdate()

ScheduleUpdate schedules a full tree update from the root

func (*Runtime) ScheduleUpdateForFiber

func (parseRt *Runtime) ScheduleUpdateForFiber(parseFiber *Fiber)

ScheduleUpdateForFiber schedules an update for a specific fiber.

func (*Runtime) ScheduleUpdateForFiberWithOrigin

func (parseRt *Runtime) ScheduleUpdateForFiberWithOrigin(parseFiber *Fiber, parseOrigin string)

ScheduleUpdateForFiberWithOrigin schedules an update for a specific fiber and records the triggering cause for profiling and devtools inspection.

func (*Runtime) ScheduleUpdateWithLane

func (parseRt *Runtime) ScheduleUpdateWithLane(parseLane UpdateLane)

ScheduleUpdateWithLane schedules a full root update on an explicit priority lane.

func (*Runtime) SchedulerSnapshot

func (parseRt *Runtime) SchedulerSnapshot() SchedulerSnapshot

SchedulerSnapshot returns priority-lane and backpressure counters for diagnostics.

func (*Runtime) SelectorResolves

func (parseRt *Runtime) SelectorResolves(parseSelector string) bool

SelectorResolves reports whether parseSelector resolves to a live DOM container in the current runtime. The agent bridge uses it to reject a bridge.mount onto a non-existent selector up front: RenderTo signals a missing selector by panicking, but the production panic policy suppresses that signal, so callers cannot otherwise tell a bad selector from success.

func (*Runtime) SerializedMountRoots

func (parseRt *Runtime) SerializedMountRoots() int

SerializedMountRoots reports how many placement roots (single subtrees or sibling-run members) mounted through the serialized-HTML strategy — the observable signal that the fast mount paths are actually firing.

func (*Runtime) SetAtomValue

func (parseRt *Runtime) SetAtomValue(parseId string, parseValue any) error

SetAtomValue is a helper to set an atom value directly (for debugging/testing)

func (*Runtime) SetIDSeed

func (parseRt *Runtime) SetIDSeed(parseSeed int)

SetIDSeed is a core package helper.

func (*Runtime) SetNextHydrationObserver

func (parseRt *Runtime) SetNextHydrationObserver(parseCorrelationID string, parseNotify func(HydrationMetrics))

SetNextHydrationObserver registers a one-shot observer for the next hydration attempt.

func (*Runtime) SetNextHydrationStrict

func (parseRt *Runtime) SetNextHydrationStrict(isStrict bool)

SetNextHydrationStrict configures whether the next hydration attempt should fail fast on mismatches instead of warning and falling back per subtree.

func (*Runtime) ShouldDeferStateUpdates

func (parseRt *Runtime) ShouldDeferStateUpdates() bool

ShouldDeferStateUpdates reports whether the CALLER is inside a transition.

func (*Runtime) SnapshotAtoms

func (parseRt *Runtime) SnapshotAtoms() map[string]any

SnapshotAtoms returns a copy of all currently registered atoms.

func (*Runtime) StartReplayRecording

func (parseRt *Runtime) StartReplayRecording()

StartReplayRecording clears and starts the runtime update replay buffer. It takes schedulerMu because the replay buffer is also written by recordReplayUpdate under that lock — accessing it unlocked is a data race.

func (*Runtime) StartTransition

func (parseRt *Runtime) StartTransition(parseFn func())

StartTransition marks state and atom updates inside fn as non-urgent.

The scope is this goroutine and this call. A goroutine spawned by fn is NOT inside the transition — the same rule React's startTransition follows, and the same distinction the async inbox draws — because the spawned work outlives the call and its urgency is not fn's to declare.

func (*Runtime) StopReplayRecording

func (parseRt *Runtime) StopReplayRecording() []ReplayEvent

StopReplayRecording stops recording and returns a stable copy of captured events.

func (*Runtime) StoreStartupCostAttribution

func (parseRt *Runtime) StoreStartupCostAttribution(storeAttribution StartupCostAttribution)

StoreStartupCostAttribution stores startup-cost attribution values.

func (*Runtime) UpdateAtomValue

func (parseRt *Runtime) UpdateAtomValue(parseId string, parseDefault any, parseFn func(any) any) error

UpdateAtomValue atomically transforms an atom's value with parseFn, holding the registry lock across the read-compute-write so concurrent functional updates cannot lose each other's writes. parseDefault supplies the previous value when the atom has no entry yet. parseFn MUST be pure and MUST NOT re-enter the atom registry (that deadlocks under the held lock); see updateAtomAndNotify.

type RuntimeLimits

type RuntimeLimits struct {
	MaxPendingEffectFibers int
	MaxQueuedUpdates       int
	MaxReplayEvents        int
	MaxDiagnostics         int
	MaxProfilingEvents     int
	MaxLogEntries          int
}

RuntimeLimits bounds internal queues so long-lived applications fail soft instead of accumulating unbounded framework state.

type SSRStreamChunk

type SSRStreamChunk struct {
	Kind       string
	BoundaryID string
	HTML       string
	Err        error
}

SSRStreamChunk describes one emitted streaming SSR chunk.

type SSRStreamOptions

type SSRStreamOptions struct {
	BoundaryIDPrefix      string
	DisableBoundaryScript bool
	ScriptNonce           string
	OnChunk               func(SSRStreamChunk)
	Flush                 func()
	// InitialAtoms seeds this stream's per-render atom scope before the shell walk
	// starts, so request state is an INPUT to the render rather than something a
	// previous request left in a shared registry. Seeded ids beat the component's
	// UseAtom initial (InitAtom is init-if-absent); ignored in the browser, where
	// SSR keeps using the live page's atoms. See ssr_atom_scope.go.
	InitialAtoms map[string]any
}

SSRStreamOptions configures streaming SSR output.

type Scheduler

type Scheduler interface {
	RequestIdleCallback(callback func(deadline Deadline))
	SetTimeout(callback func(), delay int)
}

Scheduler abstracts work scheduling.

type SchedulerSnapshot

type SchedulerSnapshot struct {
	PendingLane      string
	CurrentLane      string
	EnqueuedUpdates  int
	CoalescedUpdates int
	// CoalescedAtLimit counts updates that arrived once the queue was full and
	// were merged into the pending render. NOT dropped — it was named
	// DroppedUpdates, and nothing is lost: re-render requests are idempotent.
	CoalescedAtLimit int
	InterruptedWork  int
	Backpressure     bool
}

type ScrollIntoViewer

type ScrollIntoViewer interface {
	ScrollIntoView(behavior string)
}

type StartupCostAttribution

type StartupCostAttribution struct {
	WASMTransferBytes       int64
	WASMDecodedBytes        int64
	BootstrapDecodedBytes   int64
	CacheWarmupDurationNs   int64
	ServiceWorkerOverheadNs int64
	InitialRouteDataBytes   int64
}

StartupCostAttribution captures startup-cost components for startup reporting.

type StartupProfilingSnapshot

type StartupProfilingSnapshot struct {
	Mode                       string
	StartedAt                  string
	BootstrapReadDurationNs    int64
	WASMTransferBytes          int64
	WASMDecodedBytes           int64
	BootstrapDecodedBytes      int64
	CacheWarmupDurationNs      int64
	ServiceWorkerOverheadNs    int64
	InitialRouteDataBytes      int64
	HydrationDurationNs        int64
	StartupCommitDurationNs    int64
	FirstInteractionDurationNs int64
	FirstInteractionCaptured   bool
	FirstInteractionEvent      string
	RouteBudgets               []RouteStartupBudgetSnapshot
}

StartupProfilingSnapshot summarizes startup and hydration milestones.

type StrictDiagnosticsOptions

type StrictDiagnosticsOptions struct {
	Enabled               bool
	Codes                 []string
	Sources               []string
	Classifications       []DiagnosticClassification
	RecoverableOnly       bool
	EscalationConsequence string
}

StrictDiagnosticsOptions controls whether selected recoverable diagnostics escalate into hard failures.

func CurrentStrictDiagnosticsOptions

func CurrentStrictDiagnosticsOptions() StrictDiagnosticsOptions

CurrentStrictDiagnosticsOptions returns the current strict-diagnostics behavior.

type StrictModeOptions

type StrictModeOptions struct {
	Enabled                   bool
	DoubleRender              bool
	WarnSetStateDuringRender  bool
	RequireEffectCleanup      bool
	PanicOnViolation          bool
	ViolationDiagnosticSource string
}

StrictModeOptions enables development-time runtime checks.

type Suspension

type Suspension struct {
	Reason string
	Done   <-chan struct{}
}

Suspension describes render-time async work that should be retried after Done closes.

func AsSuspension

func AsSuspension(parseRecovered any) (*Suspension, bool)

AsSuspension returns a suspension payload when recovered carries one.

func NewSuspension

func NewSuspension(parseDone <-chan struct{}, parseReason string) *Suspension

NewSuspension creates a render suspension payload.

func (*Suspension) Error

func (parseS *Suspension) Error() string

Error returns the suspension reason.

type UpdateLane

type UpdateLane uint8

UpdateLane names one runtime scheduling priority. Lower values run with larger work slices and win coalescing when multiple update causes arrive before a pending render commits.

const (
	UpdateLaneSync UpdateLane = iota + 1
	UpdateLaneInput
	UpdateLaneDefault
	UpdateLaneTransition
	UpdateLaneBackground
)

func (UpdateLane) String

func (parseLane UpdateLane) String() string

String returns the stable diagnostic label for one update lane.

type WASMArtifactMetadata

type WASMArtifactMetadata struct {
	BuildID      string
	ArtifactPath string
	SHA256       string
	ManifestPath string
	SymbolSet    string
	Version      string
}

WASMArtifactMetadata identifies the emitted browser artifact and related build records.

type WASMStackFrame

type WASMStackFrame struct {
	Function string
	File     string
	Line     int
}

WASMStackFrame describes one parsed wasm/browser panic frame before formatting.

type WASMStackFrameMapper

type WASMStackFrameMapper func(WASMStackFrame) (WASMStackFrame, bool)

WASMStackFrameMapper maps one observed wasm/browser panic frame back to a higher-signal application-owned location when source-map metadata is available.

type WorkloadBudgets

type WorkloadBudgets struct {
	PendingEffects BudgetSignal
	QueuedUpdates  BudgetSignal
	// AsyncInbox is the off-loop ingress queue. It was missing for as long as
	// this file existed, which left the runtime's most consequential cliff
	// readable only as a console line: past the hard bound the drain moves onto
	// the producing goroutine and the frame-isolation guarantee — the whole
	// point of P2.1 — is suspended for that batch.
	AsyncInbox BudgetSignal
}

WorkloadBudgets is every cliff's state at one moment.

A fixed-size array rather than a slice or map: R6 says diagnostics carry an allocation budget, and a devtools panel polls this every frame. Returning it by value allocates nothing.

func GlobalBudgets

func GlobalBudgets() WorkloadBudgets

GlobalBudgets reports the global runtime's workload budgets, for callers that have no runtime handle — which is every devtools surface today.

func (WorkloadBudgets) Degraded

func (parseBudgets WorkloadBudgets) Degraded() bool

Degraded reports whether any cliff is currently active.

func (WorkloadBudgets) Signals

func (parseBudgets WorkloadBudgets) Signals() [3]BudgetSignal

Signals returns the cliffs in a stable order, for iteration.

Returns an array, not a slice, so ranging over it in a per-frame devtools poll does not allocate.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL