Skip to content

ADR-002: Adapter Ergonomics

  • Status: Accepted
  • Date: 2026-12-06
  • Target release: v0.4.0, as a clean break from v0.3.0 with no deprecated aliases
  • Scope: @zwire/react, @zwire/vue, @zwire/solid, @zwire/svelte, plus one addition to the @zwire/core root entry (scoped). Rust crates, bridges, and the wire spec are unaffected.

The four UI adapters share a small vocabulary (useSignal, useAtom, useSelector, useStoreScope) and a /hooks subpath with three structurally typed hooks. Reading the v0.3.0 sources turned up the following friction.

# Problem Evidence
1 Transaction hooks take an injected factory and return an accessor: useOptimistic(createOptimisticLayer) then layer().update(...). The handle exposes no reactive state. ts/packages/adapters/react/src/hooks.ts:49-63. The only adapter example skips the hook and tracks the layer by hand with a module variable and useState(held): examples/wasm-orderbook/view.ts:18-50.
2 useOptimistic collides with React 19’s built-in useOptimistic. Same export name, different package.
3 No hook covers runOptimistic, resource, or any collection view other than topK. /hooks exports only useOptimistic, useDraft, useCollectionTopK. No adapter test covers resource or Suspense.
4 scope is a trailing positional argument on every hook, so passing it to useSelector means useSelector(src, sel, undefined, scope). For reads it does little: scope.subscribe already subscribes through the signal’s own scope and uses the caller’s scope only to co-own the subscription’s lifetime. ts/packages/core/src/core/scope.ts:1419-1445.
5 Atoms are bound to one scope at creation, and hydratable(key, ...) creates a new atom on every call. There is no way to keep a definition at module level and get the instance for the current request’s scope, so ScopeProvider cannot select state on its own. ts/packages/core/src/protocol/ssr.ts:35-41.
6 Two misuse cases fail silently. In Vue, useSignal outside an effect scope returns a ref that never updates. In React, an inline selector on an ObjectStore/DeepStore resubscribes on every render. ts/packages/adapters/vue/src/index.ts:45; ts/packages/adapters/react/src/index.ts:93-115.
7 Surface is scattered: a /hooks subpath split by history, duplicate aliases (useAtomValue, useDeferredAtomValue), and useStoreScope returning a ReactiveScope. Adapter index.ts files.
8 Adapter READMEs are 23 to 36 lines with no flow-level guidance. One example uses an adapter (React, without JSX). ts/packages/adapters/*/README.md, examples/.

Problems 1 to 3 share a cause. The architecture rule says adapters import only the @zwire/core root entry, so anything from @zwire/core/tx, /collections, /resource, or /protocol must be injected or duck-typed. No lint enforces the rule; it exists as prose in AGENTS.md and docs/ARCHITECTURE.md.


# Decision
D1 Relax the adapter dependency rule to mirror subpaths (section 3).
D2 Ship as a clean break in v0.4.0. Old names are removed, not deprecated. A migration table goes in the changes/ fragments (section 6).
D3 Replace /hooks with /tx, /collections, /resource, and /protocol in every adapter.
D4 Optimistic mutation: useOptimisticLayer (manual handle) and useOptimisticAction (async, wraps runOptimistic). In-flight actions continue after unmount by default. Concurrent calls run as parallel layers by default, with a concurrency option.
D5 Collections: four dedicated hooks (useCollectionTopK, useCollectionRange, useCollectionItem, useCollectionSize).
D6 Per-scope state: add scoped(factory) to the @zwire/core root and useScoped(def) to every adapter.
D7 Scope lifetime and SSR: ScopeProvider creates and disposes its own scope when scope is omitted; useHydrate and HydrationBoundary live in /protocol. Meta-framework integration is documented as recipes, not shipped as code.
D8 Resources: useResource returns a state object in all four adapters and never suspends. useSuspenseResource is separate, for React and Solid.
D9 Every hook takes an options object as its last parameter. useSelector also accepts a bare equality function in that position.
D10 Rename useStoreScope to useScope. Remove useAtomValue and useDeferredAtomValue.
D11 Misuse that cannot work throws an error prefixed with the package name. No NODE_ENV branches and no warnings, matching the current codebase.
D12 Documentation: four recipes in each adapter README, the order-book example rewritten on the new hooks, and one runnable example each for Vue, Solid, and Svelte wired into mise run test:examples.
D13 Delivery in four PRs (section 8).

Replace the adapter clause of the star-topology invariant in AGENTS.md, docs/ARCHITECTURE.md (section 1, principle 4), and docs/API.md (section 7) with:

UI adapter packages depend only on published @zwire/core entry points. An adapter’s root entry imports @zwire/core alone. An adapter subpath @zwire/<fw>/<x> may additionally import its mirror @zwire/core/<x> and nothing else from core. Adapter subpaths may import their own package root. Adapters never import core/internal.ts, another core subpath, or another adapter.

What stays true: core never imports adapters, companion subpaths never import each other, and an application that imports only @zwire/<fw> pulls in no companion code. The 1:1 mapping keeps each adapter subpath’s cost attributable to one core subpath in the bundle matrix.

Adapter entry May import from core Contents
@zwire/<fw> @zwire/core Scope provision, useSignal, useAtom, useSelector, useScope, useScoped
@zwire/<fw>/tx @zwire/core, @zwire/core/tx useOptimisticLayer, useOptimisticAction, useDraft
@zwire/<fw>/collections @zwire/core (types from @zwire/core/collections) useCollectionTopK, useCollectionRange, useCollectionItem, useCollectionSize
@zwire/<fw>/resource @zwire/core, @zwire/core/resource useResource, useSuspenseResource (React, Solid)
@zwire/<fw>/protocol @zwire/core, @zwire/core/protocol useHydrate, HydrationBoundary (React, Vue, Solid)

@zwire/<fw>/hooks is deleted.


Options object. The last parameter of every hook is an optional options object. scope is always available there and overrides the scope from context. useSelector is the one exception to “object only”: its third parameter accepts EqualityFn<S> | { equals?, scope? }, so useSelector(user, pick, shallowEqual) keeps working.

Reactive fields by framework. Hooks that return an object with reactive fields follow each framework’s idiom.

Framework Reactive field is Object identity
React A plain value A new object whenever a reactive field changes; methods are referentially stable. This keeps React Compiler memoization correct, since a stable object with changing getters would be cached.
Vue Readonly<Ref<T>> Stable; safe to destructure
Solid Accessor<T> Stable; safe to destructure
Svelte A getter on the object Stable; do not destructure

Single-value hooks keep today’s return shapes: a value in React, Readonly<Ref<T>> in Vue, Accessor<T> in Solid, and SignalRef<T> ({ current }) in Svelte. Vue, Solid, and Svelte keep accepting getters for arguments that may change.

Errors. Thrown errors start with [@zwire/<fw>] and state the cause and the fix, for example [@zwire/vue] useSignal() must be called inside setup() or an effect scope.

export interface Scoped<T> {
(scope?: ReactiveScope): T;
}
export function scoped<T>(factory: (scope: ReactiveScope) => T): Scoped<T>;
// state/account.ts: a definition, no state at module level
import { scoped } from '@zwire/core';
import { hydratable } from '@zwire/core/protocol';
import { resource } from '@zwire/core/resource';
export const account = scoped((scope) => ({
balance: hydratable('balance', 0, { scope }),
note: scope.atom(''),
profile: resource((signal) => fetchProfile(signal), { scope, lazy: true }),
}));
account(requestScope).balance.set(1000); // server loader or test
  • The factory runs once per scope, on first call. Instances are held in a WeakMap keyed by scope and owned by the definition, so no reactive state lives at module level and an instance is collectable with its scope.
  • Omitting scope resolves to defaultScope.
  • The factory runs untracked and under the scope’s root owner, so effects it creates live as long as the scope even when the first call happens inside a computed or effect.
  • Calling a definition with a disposed scope throws. A definition whose factory re-enters itself for the same scope throws.
  • Resolution is nearest-scope only. A child scope gets its own instance and does not inherit the parent’s.
  • TypeScript only. No spec, conformance, or Rust change. The core bundle budgets (5600 and 6400 bytes gzip) must still pass.
Export React Vue Solid Svelte
useSignal(signal, options?) T Readonly<Ref<T>> Accessor<T> SignalRef<T>
useAtom(signal, options?) [T, set] Ref<T> [Accessor<T>, set] AtomRef<T>
useSelector(source, selector, equalsOrOptions?) S ComputedRef<S> Accessor<S> SignalRef<S>
useScope() ReactiveScope ReactiveScope ReactiveScope ReactiveScope
useScoped(def, options?) T T T T
ScopeProvider component component component component
provideScope(scope?) n/a returns the scope n/a returns the scope
useDeferredSignal(signal, options?) { value, isPending } n/a n/a n/a
toReadable / toWritable(signal, options?) n/a n/a n/a store contract

useScoped(def, options?) returns def(scope) for the active scope.

ScopeProvider. The scope prop becomes optional.

  • With scope: provided as given and never disposed by the provider. A disposed scope throws.
  • Without scope: the provider creates a scope tied to the scope it finds in context, provides it, and disposes it when the provider unmounts. A mode prop ('client' | 'ssr') overrides the mode; the default is the parent scope’s mode. The mode is not auto-detected from the environment, because React Native and DOM-less test renderers would be misread as server rendering.
  • provideScope() in Vue and Svelte gains the same behavior when called without arguments and returns the scope, so the same component can pass it to useHydrate.
  • In Vue, replacing a provider’s scope should remount the subtree with a key, since useScoped resolves its instance during setup(). Svelte’s provider already remounts.

React needs two specific behaviors. Disposal of an auto-created scope is deferred until the unmount is final, so StrictMode’s simulated unmount and remount never hands children a disposed scope. The scope is created detached and linked to the parent scope’s disposal only on commit, so a render React abandons leaves nothing reachable from the parent.

function useOptimisticLayer(options?: { scope?: ReactiveScope }): OptimisticLayerHandle;
interface OptimisticLayerHandle {
readonly active: boolean; // reactive
update<T>(signal: WritableSignal<T>, updater: (prev: T) => T): void;
settle(serverUpdate?: () => void): void;
revert(): void;
}
  1. No layer exists until the first update, which opens one in the active scope and applies the intent.
  2. active is true from that update until settle or revert.
  3. settle(serverUpdate) closes the layer atomically with serverUpdate, as in core. When no layer is open it still runs serverUpdate inside scope.batch, so an authoritative write is never dropped.
  4. revert() closes the open layer and is otherwise a no-op.
  5. After a layer closes, the next update opens a new one.
  6. Unmounting reverts an open layer. Calling update after unmount throws.
  7. The handle satisfies { update }, so it can be passed as the layer argument of TransactionalCollection.upsert, update, and delete.
function useOptimisticAction<A extends unknown[], R>(
fn: (tx: OptimisticTx, ...args: A) => Promise<R> | R,
options?: {
settle?: (result: R) => void;
concurrency?: 'parallel' | 'latest' | 'drop'; // default 'parallel'
abortOnUnmount?: boolean; // default false
scope?: ReactiveScope;
},
): OptimisticAction<A, R>;
interface OptimisticAction<A extends unknown[], R> {
run(...args: A): void; // never throws; a failure lands in `error`
runAsync(...args: A): Promise<R>; // rejects on failure or abort
readonly pending: boolean; // reactive: at least one call in flight
readonly error: unknown; // reactive: reason of the last failed call
reset(): void; // clears `error`
}
const reserve = useOptimisticAction(
async (tx, amount: number) => {
tx.update(balance, (b) => b - amount);
return api.reserve(amount, { signal: tx.signal });
},
{ settle: (res) => balance.set(res.balance) },
);
<button disabled={reserve.pending} onClick={() => reserve.run(150)}>Reserve 150</button>;
  • Each call runs runOptimistic in the active scope: one layer per call, reverted on rejection or abort, settled atomically with options.settle(result) on success.
  • concurrency: 'parallel' gives every call its own layer; layers rebase in creation order. 'latest' aborts the calls still in flight when a new one starts. 'drop' ignores run while a call is in flight, and runAsync returns the in-flight promise.
  • error is cleared when a call starts and by reset(). Aborts (superseded by 'latest', abortOnUnmount, scope disposal) are not recorded as error; the matching runAsync promise rejects with the abort reason.
  • Unmount does not abort by default: the request finishes and the layer settles or reverts, and only the component’s state updates stop. A request already sent may have been applied by the server, and reverting locally would leave the screen out of step until the next sync. abortOnUnmount: true opts into aborting. Disposing the scope always aborts.
  • Each call uses the fn and options of the latest committed render, so React callers do not need to memoize them.
function useDraft(options?: { base?: 'committed' | 'effective'; scope?: ReactiveScope }): DraftHandle;
interface DraftHandle {
readonly open: boolean; // reactive
get<T>(signal: ReadableSignal<T>): T;
set<T>(signal: WritableSignal<T>, next: T | ((prev: T) => T)): void;
run<R>(fn: () => R): R;
commit(options?: { verifyReads?: boolean }): void;
discard(): void;
}

set and run open a draft when none is open. get reads the draft overlay when one is open and the signal’s current value otherwise, without opening a draft. set, commit, and discard notify the component, so draft.get(signal) in markup reflects draft writes. To also follow live changes of the base value, read the signal with useSignal. Unmount discards an open draft.

useCollectionTopK(collection, k, options?: { filter?, scope? }); // readonly T[]
useCollectionRange(collection, offset, limit, options?: { filter?, scope? }); // readonly T[]
useCollectionItem(collection, id, options?: { scope? }); // T | undefined
useCollectionSize(collection, options?: { scope? }); // number

Parameters are structural ({ topK }, { range }, { getSignal }, { sizeSignal }), so the hooks contain no runtime import of @zwire/core/collections.

Hook Collection QueryCollection TransactionalCollection
useCollectionTopK yes yes no
useCollectionRange no yes yes (no filter)
useCollectionItem no yes no
useCollectionSize no yes no

topK(k) without a filter is cached per k in core, but range(), getSignal(), hasSignal(), and any filtered view return a new Computed on every call (ts/packages/core/src/collections/index.ts:1135-1154, 1283-1299). The React hooks therefore memoize the signal on [collection, k | offset, limit | id, filter]. A filter must be referentially stable (module-level, useCallback, or React Compiler); an inline one resubscribes on every render.

function useResource<T>(resource: Resource<T>, options?: { scope?: ReactiveScope }): ResourceView<T>;
type ResourceView<T> = {
refetch(): void;
mutate(next: T | ((prev: T | undefined) => T)): void;
} & (
| { status: 'pending'; data: undefined; error: undefined; pending: true }
| { status: 'refreshing'; data: T; error: undefined; pending: true }
| { status: 'ready'; data: T; error: undefined; pending: false }
| { status: 'error'; data: T | undefined; error: unknown; pending: false }
| { status: 'disposed'; data: undefined; error: undefined; pending: false }
);
function useSuspenseResource<T>(resource: Resource<T>, options?: { scope?: ReactiveScope }): T; // React, Solid
  • useResource never suspends. data keeps the last successful value during refreshing and error. React returns the union directly, so checking status narrows data; the other adapters expose status, data, error, and pending as separate reactive fields.
  • Subscribing activates a lazy resource.
  • The hooks read an existing resource and do not create one. A resource created inside a component that suspends is recreated on every retry, so resources belong in a scoped() definition or at module level.
  • useSuspenseResource (React) throws the pending promise on the initial load, throws the load error to the nearest error boundary, and returns the last value while refreshing.
  • useSuspenseResource (Solid) returns Accessor<T> and integrates with Solid 2’s <Loading> boundary.
  • Vue and Svelte get no Suspense variant in v0.4.0.
function useHydrate(state: HydratedState | undefined, options?: { scope?: ReactiveScope }): void;
// React, Vue, Solid:
<HydrationBoundary state={state}>{children}</HydrationBoundary>
  • hydrate(scope, state) is applied synchronously, before descendants read, and once per (scope, state object) pair. Re-renders and StrictMode’s double render do not re-apply it.
  • In React the state present at mount is applied during render so the first client render matches the server HTML. A later state identity is applied in an effect after commit, because writing atoms that already have subscribers during render triggers React’s cross-component update warning. (A layout effect would warn during server rendering on React 18, and an insertion effect may not schedule updates.)
  • HydrationBoundary exists because a hook called in the component that renders <ScopeProvider> resolves the outer scope. Svelte has no boundary component: call const scope = provideScope() and then useHydrate(state, { scope }) in the same component.
// Next.js App Router, client component
'use client';
export function Providers({ state, children }: { state: HydratedState; children: ReactNode }) {
return (
<ScopeProvider mode={typeof window === 'undefined' ? 'ssr' : 'client'}>
<HydrationBoundary state={state}>{children}</HydrationBoundary>
</ScopeProvider>
);
}

Servers that serialize state themselves create the scope explicitly, render inside <ScopeProvider scope={scope}>, call dehydrate(scope), and dispose the scope. That sequence is framework-specific and is documented per meta-framework.


  • Inline selectors on field-subscribable sources (React). A field subscription derives its dependency set from the selector, so a new selector identity must resubscribe. The READMEs will recommend useSignal(store.field('name')), whose per-key atoms are cached, or a module-level selector.
  • TransactionalCollection has no getSignal or sizeSignal, so useCollectionItem and useCollectionSize do not accept it.

v0.3.0 v0.4.0
useStoreScope() useScope()
useAtomValue(signal) useSignal(signal)
useDeferredAtomValue(signal) (React) useDeferredSignal(signal)
useSignal(signal, scope) useSignal(signal, { scope })
useAtom(signal, scope) useAtom(signal, { scope })
useSelector(src, sel, eq) unchanged
useSelector(src, sel, eq, scope) useSelector(src, sel, { equals: eq, scope })
useOptimistic(createOptimisticLayer, scope) from /hooks, then layer().update(...) useOptimisticLayer({ scope }) from /tx, then layer.update(...)
useDraft(createDraft, scope) from /hooks, then draft().set(...) useDraft({ scope }) from /tx, then draft.set(...)
useCollectionTopK(col, k, scope) from /hooks useCollectionTopK(col, k, { scope }) from /collections
toReadable(signal, scope) / toWritable(signal, scope) (Svelte) toReadable(signal, { scope }) / toWritable(signal, { scope })
<ScopeProvider scope={scope}> unchanged; scope is now optional
Vue useSignal outside an effect scope returned a ref that never updated throws

  • Adapter READMEs. Each gets install, a quick start, and the same recipes written in that framework’s syntax: state per scope, optimistic mutation, lists, async resources, and scope and SSR (Next.js App Router, Nuxt, a Solid root, SvelteKit respectively). Each ends with the migration table. The meta-framework snippets are documentation only and are not exercised by a test.
  • docs/API.md section 7. Rewritten per subpath. scripts/check-docs.ts compares this file against the emitted declarations, so the export tables change in the same PR as the exports.
  • examples/wasm-orderbook. Rewritten on useOptimisticLayer and ScopeProvider, removing the module-level reservation variable and the held state.
  • New examples. examples/adapter-orders implements the same small app (a scoped definition, hydration, an optimistic action, a Top-K list, a lazy resource) in Vue, Solid, and Svelte against an in-memory server, with a headless smoke script. mise run test:adapter-examples bundles and runs all three against the built packages, mise run test includes it, and CI runs it in the examples job. The build reuses the bundler and compilers the test workspace already installs, so no toolchain was added; as a result the Solid view builds its DOM without JSX, because no Solid 2 JSX compiler is installed there.

PR Contents
1 New dependency rule text. Core scoped(). Adapter roots: options object, useScope, alias removal, useScoped, optional-scope ScopeProvider and provideScope(), prefixed errors.
2 /tx in all four adapters. useOptimistic and useDraft leave /hooks.
3 /collections, /resource, /protocol in all four adapters. /hooks is deleted.
4 READMEs, docs/API.md prose, the order-book rewrite, three new examples, test:examples wiring.

Every PR changes all four adapters together, so main never holds adapters with diverging APIs, and adds a changes/<slug>.md fragment. v0.4.0 is tagged after PR 4.

Gates per PR: mise run check, mise run build:ts then mise run check:docs, mise run test, and the bundle check on Node and Bun (node ./bench/run_precision_bench.ts --check-bundles). The places that name /hooks today and must follow the subpath changes: each adapter’s package.json exports, ts/scripts/verify-dist.ts, ts/scripts/verify-dist-runtime.mjs, and the budget rows in ts/bench/run_precision_bench.ts.

Tests extend the pattern in ts/tests/adapters/transactions.ts: one framework-neutral fixture per flow, exercised through each adapter’s mounted component.

Bundle budgets (gzip). The root is measured over core and stays at 1500 bytes (measured 444 to 992). Each subpath is measured over core plus the core subpath it mirrors.

Entry Budget
@zwire/<fw> 1500
@zwire/<fw>/tx 1300 (measured 1074 to 1190, over core plus @zwire/core/tx)
@zwire/<fw>/collections 500 (measured 197 to 343)
@zwire/<fw>/resource 600 (measured 283 to 357)
@zwire/<fw>/protocol 500 (measured 141 to 300)

# Item Resolve in
O1 Resolved in PR 3: Solid’s useSuspenseResource is a memo that returns the pending promise, which Solid 2 treats as not ready; <Loading> and <Errored> behavior is covered by the Solid client suite. Done
O2 Resolved in PR 1: the largest root (React) measures 992 bytes. Done
O3 Add getSignal and sizeSignal to TransactionalCollection so item and size hooks accept it. After v0.4.0
O4 Optional inheritance for scoped() across nested scopes. After v0.4.0
O5 Suspense variants for Vue and Svelte once their async rendering APIs are stable. After v0.4.0

Alternative Why not
Keep the root-only rule and bind tx once per app (bindTx(tx)) Every user writes a binding file and every documented example depends on it.
Keep factory injection and only add reactive state Two imports and a factory argument remain at every call site.
One handle with a run method instead of two hooks A manually held layer and per-call layers on one object make active and pending ambiguous.
Abort and revert in-flight actions on unmount The server may already have applied the request; the screen would disagree until the next sync.
Generic useSignal(factory, deps) instead of collection hooks Harder to discover, and React callers manage a deps array by hand.
A useCollectionPage pagination helper Unusable when page state lives in the URL or router.
scoped() in each adapter instead of core Server loaders and tests would import a UI adapter, and the code would exist four times.
Meta-framework subpaths such as @zwire/react/next Tracks four frameworks’ internal APIs indefinitely.
Suspense-first useResource Return shape would differ between React/Solid and Vue/Svelte under the same name.
Removing scope from read hooks Leaves ScopeProvider as the only way to bind a subscription’s lifetime to a scope.
Development-mode warnings Introduces the first bundler-dependent branch in the codebase, and warnings are easy to miss.
Deprecation cycle for old names Two parallel surfaces to test and budget for one minor version, before 1.0.