# Sygnal > Reactive component framework (Model-View-Intent, JSX views, xstream streams, one state tree). It is not React: no hooks, no `onClick`. This file is the core: the model, the anatomy, the canonical examples, and an index of what to read when. Write only the forms shown here: `npx --no-install sygnal-check --strict` flags the others. ## Read before you write The file names are under `node_modules/sygnal/`. When the task touches one of these, read that file before the first line of that feature. Each is one short read. | When the task has | Read | Use | |---|---|---| | a test to write beyond §7's example | `llms/testing.md` | `renderComponent`, `t.*` | | HTTP: a POST, upload, streaming reply, cancel | `llms/http.md` | `makeFetchDriver`, reply actions | | data a component shows, cache, refetch, pagination | `llms/resources.md` | `resources`, `queryCache` | | WebSocket or SSE | `llms/sockets.md` | `connections`, `makeSocketDriver` | | pages, links, guards, leave prompt, title | `llms/router.md` | `makeRouter`, `route`, `head` | | a form with validation | `llms/forms.md`, then `dist/guide/forms.md` | `form` behavior | | shared state + actions, pager, selection, undo | `llms/behaviors.md` | `uses`, `defineBehavior` | | focus, scroll, dialog method, timers, saved state, parent calling a child | `llms/commands.md` | `ELEMENT`, `timers`, `persist`, `createCommand` | | chart, date picker, editor, web component | `llms/widgets.md` | `defineWidget` | | dialog, popover, tooltip, tabs, accordion, toast, menu, select, combobox, drag to reorder, 1,000+ rows, wizard, clipboard, media query | `llms/ui.md` | `sygnal/ui`, `sortable`, ``: never hand-roll these | | LLM chat, tools for an LLM, decisions, composed UI | `llms/ai.md` | `sygnal/ai`: the `chat` behavior; never a provider key in the browser | | TypeScript beyond §4's line | `llms/typescript.md` | `Comp`, `IntentSources` | | CSS Modules, Tailwind | `llms/styling.md` | a plain hook class beside the hashed one | | a prop, option or field not shown here | `llms/api-facts.md`, or grep the name in `dist/index.d.ts` | one symbol, not the whole file | | the long form of an example, or a rule shortened here | `llms/examples.md`, `llms/details.md` | | | a `[Sygnal SYGnnn]` message | `npx --no-install sygnal-check explain SYGnnn` | the message says the fix; every wiring rule: `llms/diagnostics.md` | Experimental subpaths cost nothing here: an import of `sygnal/x` means read the file named for it first. `yjs`: `llms/collaboration.md`. `three`, `canvas`: `llms/graphics.md`. `api`: `llms/typed-apis.md`. `terminal`, `agent-ui`, `react-native`, `primitives`, `host`, `worker`: `llms/renderers.md`. `sandbox`, `replay`: `llms/sandbox.md`, `llms/replay.md`. Longer guides: `dist/guide/`. ## 1. Mental model - A component is a pure view function plus static properties: `.intent` (WHEN: sources → named action streams), `.model` (WHAT: action → one reducer per sink), `.initialState`. - There is one state tree. A child sees its parent's whole state, or a slice with `state="key"` (or a path: `state="settings.rules"`). A Collection item sees one array element. Only the root has `initialState`: a child's start values go in the parent's. - A child belongs to the record its `state` points at: when that target changes the old child is disposed and a new one mounts, so `` needs no key. - Every side effect is a sink of a model entry (STATE, EVENTS, PARENT, EFFECT, drivers such as HTTP). JSX has no event handlers. A view may return `null`. - An intent's DOM selectors only see the component's own JSX, never a child's: handle the event in the child and send it up with `PARENT` or `EVENTS`. - Streams are xstream, not RxJS: `import { xs, debounce } from 'sygnal'`; `switchMap(f)` is `.map(f).flatten()`; an RxJS operator throws a message naming its xstream form. ## 2. Component anatomy ```jsx import { ABORT } from 'sygnal' function Counter({ state, context, label }) { // 1st arg: parent props + state, context, children, slots return (
{label} {state.count} (x2 = {state.double})
) } Counter.initialState = { count: 0 } // root only Counter.calculated = { double: state => state.count * 2 } // read as state.double Counter.context = { total: state => state.count } // itself + descendants: ({ context }) => context.total Counter.intent = ({ DOM }) => ({ // sources: DOM STATE EVENTS CHILD props$ commands$ dispose$ + drivers INC: DOM.click('.inc'), RESET: DOM.click('.reset'), }) Counter.model = { INC: (state, data, next, props) => ({ ...state, count: state.count + 1 }), RESET: (state) => (state.count === 0 ? ABORT : { ...state, count: 0 }), } Counter.onError = (error, { componentName }) =>
{componentName} failed
export default Counter ``` - Reducer `(state, data, next, props)`. `data` is the action stream's value. `next('ACTION', data?, delayMs = 10)` dispatches another action of this component only. `props` holds the parent's props plus `state`, `context`, `children`, `slots`. - Model entry: a function is the STATE reducer. An object `{ STATE, EVENTS, PARENT, EFFECT, LOG, : fn }` maps each sink to a `(state, data, next, props)` function whose return value goes to that sink. - **STATE runs first in every entry**; every other sink gets the committed state: `INC: { STATE: s => ({ ...s, n: s.n + 1 }), PARENT: s => ({ n: s.n }) }` (`s.n + 1` would count twice). The state from before the action is `props.previousState`: payloads read `state`, guards read `previousState`, and a guard stays on the sink because STATE's `ABORT` doesn't cancel other sinks. - The clock and randomness come from the 4th argument, so tests can fix them: `(state, title, next, { now, uuid, random }) => ({ ...state, tasks: [...state.tasks, { id: uuid(), title, created: now() }] })`. - Built-in actions (model only): `BOOTSTRAP` (once, after mount), `DISPOSE` (unmount). Declaration statics computed from state: `connections`, `resources`, `route`, `head`, `timers`. Also `uses`, `persist`, `viewTransitions`. - `ABORT` from STATE: no change; from another sink: nothing sent. Reducers return a new object, never a mutated `state`. ## 3. Canonical examples ### State update, set / toggle, controlled input ```jsx import { ABORT, set, toggle } from 'sygnal' function AddTodo({ state }) { return (
{state.showHelp &&

Type, then Add

}
) } AddTodo.initialState = { draft: '', todos: [], nextId: 1, showHelp: false } AddTodo.intent = ({ DOM }) => ({ DRAFT: DOM.input('.draft').value(), // a bound value={...} needs this listener ADD: DOM.click('.add'), HELP: DOM.click('.help'), }) AddTodo.model = { DRAFT: set((state, draft) => ({ draft })), ADD: (state) => { const text = state.draft.trim() if (!text) return ABORT return { ...state, draft: '', nextId: state.nextId + 1, todos: [...state.todos, { id: state.nextId, text }] } }, HELP: toggle('showHelp'), } ``` ### Multi-sink entry + EVENTS between distant components ```jsx import { event } from 'sygnal' function SaveButton({ state }) { return } SaveButton.intent = ({ DOM }) => ({ SAVE: DOM.click('.save') }) SaveButton.model = { SAVE: { STATE: (state) => ({ ...state, saving: true }), EVENTS: event('DOC_SAVED', (state) => ({ id: state.id })), // event() is the sink entry itself }, } function Toast({ state }) { // anywhere in the tree: EVENTS is a global bus return

{state.lastSaved}

} Toast.intent = ({ EVENTS }) => ({ SAVED: EVENTS.select('DOC_SAVED') }) // emits the payload only Toast.model = { SAVED: (state, payload) => ({ ...state, lastSaved: payload.id }) } ``` ### Child → parent, Collection, item removal ```jsx import { Collection } from 'sygnal' function TaskItem({ state }) { return (
  • {state.title}
  • ) } TaskItem.intent = ({ DOM }) => ({ PICK: DOM.click('.pick'), REMOVE: DOM.click('.remove') }) TaskItem.model = { PICK: { PARENT: (state) => ({ taskId: state.id }) }, // the parent receives exactly this value REMOVE: () => undefined, // a Collection item removes itself } function TaskList({ state }) { return (

    {state.picked}

    ) } TaskList.initialState = { picked: null, tasks: [{ id: 1, title: 'Write' }, { id: 2, title: 'Test' }] } TaskList.intent = ({ CHILD }) => ({ PICKED: CHILD.select(TaskItem) }) // the function, not a string TaskList.model = { PICKED: (state, { taskId }) => ({ ...state, picked: taskId }) } ``` - `from` names an array field. Items are keyed by `.id`, render with no wrapper. `filter={t => !t.done}`, `sort="title"` change only what renders. In the object form removal keeps `STATE: () => undefined`. Tabs and steps on one page: `` (all pages stay live; `instance={key}` re-creates the current one; not a router outlet). - A child gets props by tag: `` → `function Rating({ state, name, value })`; reducers read `props.name`. Reserved props: `state`, `children`, `slots`, `context`, `uid`, `key`. ### HTTP with reply actions ```jsx import { ABORT, debounce } from 'sygnal' function Search({ state }) { return

    {state.status}

      {state.results.map(r =>
    • {r.title}
    • )}
    } Search.initialState = { query: '', status: '', results: [] } Search.intent = ({ DOM }) => ({ // no intent line for the reply TYPE: DOM.input('.q').value(), SEARCH: DOM.input('.q').value().compose(debounce(300)).filter(q => q !== ''), }) Search.model = { TYPE: (state, query) => ({ ...state, query }), SEARCH: { STATE: (state) => ({ ...state, status: 'Searching…' }), HTTP: (state, q) => ({ url: '/api/search', query: { q }, ok: 'RESULTS', error: 'FAILED', latest: true }), }, RESULTS: (state, body) => ({ ...state, status: '', results: body.results }), // ok: the parsed body FAILED: (state, { status, error }) => ({ ...state, status: status === 404 ? 'Not found.' : 'Search failed.', results: [] }), } ``` - `Search.drivers = { HTTP: makeFetchDriver() }` on the root (both from `'sygnal'`). Never `fetch` in a component or EFFECT. The reply reaches exactly the sending instance, so no request ids. `latest: true` aborts this instance's older requests; `{ abort: 'RESULTS' }` cancels without sending. A request sees what STATE stored. Non-fetch promise APIs: `App.drivers = { API: driverFromAsync(fn) }`, then `API: () => ({ value, ok: 'DONE', error: 'FAILED' })`. ### Data a component shows: `resources` ```jsx function Quote({ state }) { const { status, data, error, refreshing } = state.quote // status: 'idle' | 'loading' | 'success' | 'error' const text = status === 'loading' ? 'Loading…' : status === 'error' ? `Failed (${error.status ?? 'network'})` : refreshing ? 'Updating…' : '' return

    {text}

    {data?.text}

    } Quote.initialState = { id: 1 } Quote.resources = { quote: (state) => state.id && `/api/quotes/${state.id}` } // a URL or a request; falsy = idle Quote.intent = ({ DOM }) => ({ NEXT: DOM.click('.next'), REFRESH: DOM.click('.refresh') }) Quote.model = { NEXT: (state) => ({ ...state, id: state.id + 1 }), // new request: 'loading' without data; the old one is aborted REFRESH: { HTTP: { refresh: 'quote' } }, // same request: data kept, refreshing: true } ``` - For reads that follow state; writes and click-triggered requests keep reply actions. Needs `makeFetchDriver()`. Don't put `quote` in `initialState`. A component that reads `state.items` declares `items` in its own `.resources`, even when another page declares it too. When the old value must not show on Refresh, treat `refreshing` as loading. After a write: `{ url, method: 'PUT', json, ok: 'SAVED', error: 'SAVE_FAILED', invalidates: '/api/items', updates: 'item' }`. Cache: `makeFetchDriver({ cache: queryCache() })` + `staleTime` on the read. ### WebSocket / SSE ```jsx Chat.initialState = { room: 'general', status: 'connecting', messages: [] } Chat.connections = (state) => ({ // from state, diffed by name: new opens, falsy/removed closes, changed URL reconnects room: state.room && { socket: `/ws/rooms/${state.room}`, message: 'RECEIVED', open: 'CONNECTED', close: 'DROPPED' }, }) Chat.model = { SAY: { WS: (state, text) => text.trim() ? { to: 'room', json: { text } } : ABORT }, RECEIVED: (state, msg) => ({ ...state, messages: [...state.messages, msg] }), CONNECTED: (state) => ({ ...state, status: 'online' }), DROPPED: (state, { willReconnect }) => ({ ...state, status: willReconnect ? 'reconnecting' : 'offline' }), } ``` - `Chat.drivers = { WS: makeSocketDriver() }` on the root. Options and SSE: `llms/sockets.md`. ### Router ```jsx // src/routes.js import { makeRouter } from 'sygnal' export const router = makeRouter({ routes: { home: '/', task: '/tasks/:id', admin: '/admin', notFound: '*' } }) // first match wins export const { href } = router // href('task', { id: 2 }) → '/tasks/2' ``` ```jsx // src/App.jsx; on the root: App.drivers = { ROUTER: router.driver } import { ABORT } from 'sygnal' import { router, href } from './routes.js' const PAGES = { home: Home, task: TaskPage, admin: Admin, notFound: NotFound } function App({ state }) { const { route } = state, Page = PAGES[route.name] return
    } App.route = 'ROUTE' // ROUTE gets { name, params, query, hash, path } on start and every change App.initialState = { route: router.current(), user: null } App.head = (state) => ({ title: state.route.name === 'task' ? `Task ${state.route.params.id}` : 'Tasks' }) // App.drivers: HEAD: makeHeadDriver() App.model = { ROUTE: { // a guard refuses the route and redirects STATE: (state, route) => (route.name === 'admin' && !state.user ? ABORT : { ...state, route }), ROUTER: (state, route) => (route.name === 'admin' && !state.user ? { to: 'home', replace: true } : ABORT), }, } ``` - Links are plain ``. Commands: `{ to, params, query, replace }`, `{ back: true }`, `{ block: 'CONFIRM_LEAVE' | false }` (the action gets `{ proceed }`). A page shares its parent's state (no `initialState`). Tests pass the router: §6. More: `llms/router.md`. ### Form with validation ```jsx import { form } from 'sygnal' function Signup({ state, uid }) { const f = state.form.fields return (

    {f.email.error}

    ) } Signup.uses = { form: form(schema, { values: { email: '' }, request: { url: '/api/signup' } }) } // any Standard Schema Signup.initialState = {} ``` - Fields match by `name`: no intent per field. `f.email.error` shows after blur or a submit. A valid submit sends `request` (the form adds `json`, `ok: 'form.DONE'`, `error: 'form.ERRORS'`); a host entry `'form.DONE': (state, body) => …` runs after the form's; a submit that sends nothing: `submit: 'NEXT'`. Rows: `'form.ADD'`, `'form.REMOVE'`. Empty on every visit: `resetOnShow: true`. More: `llms/forms.md`. ### One line each (details in the table above) - Behaviors: `uses = { pager: pager({ pageSize: 10, next: '.newer', prev: '.older' }), sel: selection({ item: '.pick', from: 'mails' }), history: undo({ key: 'doc', undo: '.undo', redo: '.redo' }) }` add `state.pager`, `state.sel` (`isSelected(state.sel, id)`), `state.history.canUndo`; your own: `defineBehavior`. A `uses` key isn't also in `initialState`. - `ELEMENT` (built in): `SUBMIT: { ELEMENT: { focus: '.email' } }` calls that method after the render (`scrollIntoView`, `showModal`, `close`, `select`); an element in the sending component's own view. - Timers: `Clock.timers = (state) => ({ tick: state.running && { every: 1000, action: 'TICK' } })` (also `{ after: ms, action }`, `{ frame: 'FRAME' }`), `App.drivers = { TIMER: makeTimerDriver() }`. No `setInterval`. - Saved state (root only): `App.persist = persist({ key: 'app', pick: ['todos'] })`. - Parent calls child: `const player = createCommand()`, ``, `PLAY: { EFFECT: () => player.send('play', data) }`, child `commands$.select('play')`. A DOM node handle: `createRef()`. - Widget: `defineWidget({ tag, mount(el, props, dispatch), update(instance, props), unmount(instance), events: ['pick'] })`; a class on it is the selector: `DOM.select('.due').events('pick').detail()`. - LLM chat: `uses = { chat: chat({ agent: false, form: '.ask', prompt: '.prompt', stop: '.stop' }) }` from `sygnal/ai`. ## 4. Facts you can't guess - `DOM.('.sel')` is `DOM.select('.sel').events('')`, for real DOM event names only. Chain `.value(fn?)`, `.checked(fn?)`, `.key(fn?)`, `.target(fn?)`, `.data('id', Number)` (reads `data-id`; JSX `data={{ id: 7 }}`). `blur`/`focus` work on the element; inside a container use `DOM.focusout('.form')`. Page-wide: `DOM.keydown('document').key().filter(k => k === 'Escape')`. `DOM.select('form').events('submit', { preventDefault: true })`. - React to a state change: `SAVE: STATE.watch(state => state.text).compose(debounce(1000))` in the intent. - One-off async work: `EFFECT: async (state, data, next, { signal }) => { ...; next('DONE', result) }`. A parent's `CHILD.select(Comp)` emits exactly what the child's `PARENT` returned, for every instance: put an id in it. - A feature's drivers go on the root component: `App.drivers = { HTTP: makeFetchDriver() }`, and `main.js` stays `run(App)`. `run(App, { ... })` is only for what differs per environment (a test double, a per-deploy `baseUrl`, a renderer target); it overrides the static by name. Root only (SYG646 elsewhere); `renderComponent` ignores it; no driver is needed in tests. - `run(App, drivers = {}, { mountPoint = '#root', onError })`. Conditional classes: `classes()`. `uid(name?)` (a view prop) is a stable per-instance id for `id`/`for`/`aria-*`. - xstream from `'sygnal'`: `xs.merge/combine/of/periodic`, `.compose(debounce(ms) | throttle(ms) | delay(ms) | dropRepeats() | sampleCombine(other$))`. - TypeScript: `const intent = ({ DOM }: IntentSources) => ({ ... })`, then `const C: Comp<{ state: State; props: Props; actions: ActionsOf }> = ({ state }) => ...`; root: `RootComp<{ state: State; actions: Actions }>`. ## 5. Tools - `npm test`, then `npx --no-install sygnal-check --strict` (Vike: `pages`), both clean; `--fix` applies the mechanical rewrites. Every `[Sygnal SYGnnn]` line says what is wrong and the fix; `sygnal-check explain SYGnnn` says more. A silent no-op (a click does nothing) is almost always a selector in a child, an unmatched action name, or a missing driver in `App.drivers`: `t.actions` shows whether the action ran, `npx --no-install sygnal-check --graph --json` shows the wiring. ## 6. Testing your change ```js import { it, expect } from 'vitest' import { renderComponent } from 'sygnal' import TaskList from './TaskList.jsx' it('picks, then removes a task', async () => { const t = renderComponent(TaskList, { strict: true }) // also: initialState, props, context, http, router, url, dom: 'real' t.simulateEvent('.pick', 'click') // first match; bubbles; reaches child components too await t.next(s => s.picked === 1) // a state emitted after this call await t.simulateEvent('.task[data-id="2"] .remove', 'click') expect(t.state.tasks.length).toBe(1) await t.settle() // nothing pending anywhere in the tree expect(t.html()).not.toContain('Test') t.expectNoDiagnostics() // throws on warn/error }) ``` - `simulateEvent(sel, type, init?)`: init `{ value }`, `{ checked }`, `{ key: 'Enter' }`, `{ data: { id: 2 } }`; `'document'` targets `DOM.select('document')`. `t.simulateAction('LOADED', data)`. - `t.state` is the latest state, `t.states` all of them, `t.next(pred)` waits for a future state, `t.waitForState(pred)` also matches recorded ones, `t.ready()`, `t.settle()`, `t.html()`, `t.query(sel)`, `t.queryAll(sel)`, `t.emitted` (EVENTS), `t.sinkValues('PARENT')`, `t.commands('ELEMENT')`, `t.storage(key)`, `t.head()`, `t.actions` (what ran), `t.explain(pred)`. - Drivers need no wiring in tests. `t.requests('HTTP')`; `await t.respond('HTTP', body, target?)`, `await t.fail('HTTP', 404, target?)` answer one and resolve once rendered (assert on `t.state` next, not `t.next`). Target: an action name, a resource name, a URL, or `{ nth: 0 }`. Sockets: `await t.push('WS', frame)`, `await t.drop('WS')`, `t.sent('WS')`. Router: `renderComponent(App, { router, url: '/tasks/2' })`, `await t.navigate('/admin')`, `t.location`. Widgets: `t.widget('.due').dispatch('pick', d)`. Timers: `vi.useFakeTimers()` first; `t.next`/`t.settle` advance the clock; `await vi.advanceTimersByTimeAsync(ms)`. Focus or real DOM: `{ dom: 'real' }` with `// @vitest-environment jsdom`. The rest: `llms/testing.md`. # Sygnal: testing: the full reference It assumes the core (`llms.txt`). - `simulateEvent(sel, type, init?)`: init `{ value }`, `{ checked }`, `{ files: [file] }` (a FileList), `{ key: 'Enter' }`, `{ data: { id: 2 } }`; `'document'` targets `DOM.select('document')` listeners. Calls made before the component is ready are buffered (`await t.ready()` is optional). `sel` matches the rendered tree like the real DOM (`:nth-child(n)`, `:not()`, `>`, `+`, `~`: `.list:nth-child(2) .card:first-child .next`). Delivered later: await it (resolves once rendered) before `t.query`. If it matches nothing (after waiting up to 300ms for a render), the test fails with an error naming the selector (check `t.html()`, or select by attribute: `[data-id="3"]`); `{ allowMissing: true }` drops the event instead. `:has()` throws. `t.queryAll('.a, .b')`: document order. `sel` is always a selector string, never an element (`t.query()` returns snapshots: select by attribute, `'.remove[data-id="2"]'`). With `dom: 'real'`, simulated inputs wait for a quiet, patched tree between deliveries (10 ms), so a large queued batch may exceed `timeoutMs` without losing writes. Use native button `.click()` calls for a synchronous burst test, or give serialized tests a larger timeout. `eventWaitMs` is the target-readiness budget, not a quiet-window switch; wait timeouts report queued input counts. - `t.next(pred)` matches only future states (right after `await t.ready()`, also those of the buffered calls). `t.waitForState(pred)` also matches states already recorded (e.g. the initial one), so use it only for a state that can't already exist. Both resolve after the whole tree has rendered. `await t.respond(…)` / `t.fail(…)` / `t.settle()` resolve once the state is there: assert on `t.state` next; a `t.next(pred)` after them waits for a further state and times out ("a state recorded before this next() call already matches"). `t.settle()` doesn't wait out a model `next('X', data, ms)` longer than its 20ms window: `await t.next(pred)` instead (timeout errors name the pending `next()`). `t.state` is the latest state (`t.states.at(-1)`), with current calculated fields (also after a child or Collection item writes); `t.states`, `t.emitted` (EVENTS sent) and `t.sinkValues('PARENT')` / `t.sinkValues('API')` (any sink, children's too) are live arrays. `t.html()` is serialised like `innerHTML` (text `Couldn't`, not `'`) and throws before the first render: `await t.ready()` (or a `t.next`) first. Timer tests (debounce/delay): `vi.useFakeTimers()` before `renderComponent`, then `await t.ready()`; `await vi.advanceTimersByTimeAsync(ms)` moves time (e.g. 299 ms: nothing sent yet), and `t.next`/`t.waitForState`/`t.settle`/`t.ready` advance the fake clock themselves until they resolve, so no real waiting. Use it instead of sleeping out a real debounce. Each wait fails after 2000 ms of clock time (fake time too): for a state a longer timer brings, pass more, `t.next(pred, 6000)` (or `renderComponent(C, { timeoutMs })`). `vi.useRealTimers()` in `afterEach`. - `t.actions` logs every action of the tree, `{ type, data, component, instance, sinks, cause, at }` (`cause`: `'intent' | 'next' | 'reply' | 'built-in' | 'simulateAction' | 'behavior' | 'agent'`; `sinks`: those that produced a value): when "nothing happened", it shows whether the action ran and what it produced. `t.explain(s => s.count === 5)` returns the action that produced a state. - `t.simulateAction('LOADED', data)` pushes an action straight into intent → model (all sinks run) of the rendered component only; a child's: `{ component: Child }` (3rd arg); a name it doesn't handle fails the test. Use it for actions without a DOM trigger. **Drivers need no wiring in tests**: the HTTP fake is the real `makeFetchDriver` over an in-memory fetch, so every request stays pending until the test answers it. `t.requests('HTTP')` lists the requests as objects (a string URL is `{ url }`; never `{ abort }`/`{ refresh }`/`{ resources }` values). `await t.respond('HTTP', body, 'RESULTS')` delivers `body` as that request's `ok` action and resolves once it is reduced and rendered; `await t.fail('HTTP', 404 | error, target?)` sends `{ error, status, body, request }` to its `error` action. Target: an action or key name, a resource name, a URL, a partial request (`{ url: '/items/2' }`), or a predicate; none = the newest pending. A request superseded by `latest: true`, aborted or already answered isn't pending, and answering it **throws at the call**: `expect(() => t.respond('HTTP', {}, { query: { q: 'du' } })).toThrow()`. Identical requests (a resource refetch, a second click) match the same targets: `{ nth: 0 }` answers exactly `t.requests('HTTP')[0]` (`-1` the newest; with `request`, counting only its matches), and throws if it isn't pending. A call made while earlier input is still queued (a debounce) waits up to 1s for its request instead. Each send is its own request. The fake can't see `makeFetchDriver({ latest: true })` in `App.drivers`: write `latest: true` on the request. - Sockets need no driver either: a component with `connections` gets a fake `WS` sink running the real driver on in-memory sockets (`{ socketSink: 'SOCKET' }` for another name). Connections open by themselves; `renderComponent(C, { autoConnect: false })` holds them in `'connecting'` until `await t.open('WS')`. `await t.push('WS', { text: 'hi' })` is a server frame (SSE named event: `t.push('WS', data, { event: 'price-update' })`); `await t.drop('WS', { code: 1011 })` is a close the app didn't make (`close` fires, the retry runs on the test's timers: `await vi.advanceTimersByTimeAsync(1000)`); `t.sent('WS')` lists the `{ to, json }` values; `t.connections('WS')` the declared connections (`name`, `url`, `state`). They throw too when nothing matches. - Resources: each fetch is listed as `{ url, ...request, resource: 'quote' }` and answered by resource name, URL or partial request: `await t.respond('HTTP', { text: 'Hi' }, 'quote')`, `await t.fail('HTTP', 500, 'quote')`. A resource request is sent after the state changes; `t.respond` by resource name right after the `simulate*` call that changes it waits for that fetch. Cache: `renderComponent(C, { http: { cache: queryCache({ staleTime: 2000 }) } })` (any driver options); `t.cache('HTTP')` lists `{ key, age, stale, subscribers, data, tags }`; `t.focus()` / `t.online()` fire the refetch triggers; retries and `refetchEvery` run on the test's timers. - Router: `renderComponent(App, { router, url: '/tasks/2' })` (the first render is already on `url`: its route goes through the root's route STATE reducer first) runs the router's real driver over an in-memory history (a component that declares `route` needs the `router` option). `await t.navigate('/admin')` (as a link click) or `await t.navigate({ to: 'task', params: { id: 1 } })`, `await t.back()` / `t.forward()`, `t.location` (`{ path, search, hash, href }`), `t.sent('ROUTER')` (the commands, not the declarations); a `simulateEvent` click on an `
    ` goes through the router's link handling; `{ block }` stops all of them. HEAD: `t.head()` returns the merged `{ title, meta, link }` (`{ titleTemplate }` option). - TypeScript tests: `renderComponent` infers the state type; for a handle assigned in `beforeEach`, declare `let t: RenderResult` (import the type from `'sygnal'`), not `any`. With the Vite plugin, Vitest gets `sygnal/diagnostics` in its setupFiles automatically; otherwise `import 'sygnal/diagnostics'` in the test. - Real DOM (state the user typed or clicked, focus, refs, any CSS selector): `renderComponent(C, { dom: 'real' })` (`'real'`, not `'jsdom'`) in a jsdom test (`// @vitest-environment jsdom`, `npm i -D jsdom`), same `t.*` API in ONE suite (no separate `run()` + jsdom suite). `simulateEvent` then dispatches real events on any CSS selector (`{ value }` types, `'click'` toggles a checkbox/radio and skips disabled buttons, `'focus'`/`'blur'` move focus). Record a session and replay it as a test (`sygnal/replay`, experimental): `llms/replay.md`. - Assert on elements: `t.query(sel)` / `t.queryAll(sel)` (or typed control tokens; generic types are assertions, and a single query is nullable) also work on the default mock DOM, as read-only snapshots of what the view rendered (`textContent`, `value`, `checked`, `disabled`, `getAttribute`, `classList`, `dataset`, `querySelector`, `closest`; `focus()` throws): `expect(t.query('input[name="plan"]:checked').value).toBe('team')`, `t.query('.save').disabled`, `t.queryAll('.row')`; with `dom: 'real'` they are real elements (`document.activeElement === t.query('input[name="city"]')`). Every wait (`ready`, `next`, `waitForState`, `settle`) resolves once its state is rendered, so query right after the `await` (before the first render, `t.query` throws: `await t.ready()`). `await t.next(a); await t.next(b)` also sees a `b` that arrived while the DOM showed `a`. # Sygnal: HTTP requests It assumes the core (`llms.txt`). - `Search.drivers = { HTTP: makeFetchDriver() }` on the root (import both from `'sygnal'`; options `baseUrl headers init timeoutMs`). Request: `{ url, ok, error, key, query, json, multipart, body, method (POST with json/multipart/body, else GET), headers, latest, timeoutMs, parse: 'auto' | 'json' | 'text' | 'response', init: { credentials, mode, cache, ... } }`; other keys (an id) aren't sent and come back on `request`. The `ok` action gets the parsed body; the `error` action gets `{ error, status, body, headers, request }` (non-2xx: `status` + parsed `body` + response `headers`; network error or timeout: `status` undefined, a timeout has `error.name === 'TimeoutError'`). The reply reaches exactly the instance that sent it (two ``es, every Collection item; never an ancestor), so no request ids. Shared loader: a tagged resource + `{ invalidate: tag }`. Never `HTTP.select`/`HTTP.errors` for your own request (SYG508), never `then`/`catch` keys (SYG610: not sent); an `ok`/`error` name with no model entry is SYG112. Don't call `fetch` in a component, intent or EFFECT. Headers on success: `keepHeaders: ['X-Computed-At']` → `state.report.headers['x-computed-at']` (cached; a `parse` function reads the Response, uncached). A POST that streams: `{ url, json, stream: 'sse' | 'ndjson' | 'text', done: '[DONE]', chunk: 'DELTA', ok: 'DONE' }` (pieces as DELTA, SSE `meta: true`: `{ data, id, event }`; DONE: `{ status, headers }`; test: `t.push('HTTP', piece)`, `t.respond('HTTP', null)`). Upload/download progress: `progress: 'UPLOADING'` on the request (`multipart: { file: state.file, title }` builds the multipart/form-data body, never `new FormData()` in a model; the file from `DOM.select('.file').events('change').map(e => e.target.files[0])`) sends `{ phase: 'upload' | 'download', loaded, total, fraction }` steps as that action (`true`: `HTTP.progress(category)`); it goes over XMLHttpRequest; tests: `await t.progress('HTTP', { loaded: 50, total: 100 }, 'UPLOADING')`. Guide: `node_modules/sygnal/dist/guide/http.md` (online: https://sygnal.js.org/guide/http/). **Typed API calls** from a server contract (oRPC, OpenAPI, Hono, function-first `*.server.ts`; `sygnal/api`, experimental): `llms/typed-apis.md`. - `latest: true`: a newer request in the same lane (`key`: a constant name, never an id or URL; default the `ok` action) from the same instance aborts the older ones once it is sent: their replies never arrive after that, but one that lands before it (while the newer input still waits out a debounce) does. `{ abort: 'RESULTS' }` (it names the lane: with a custom `key`, abort that key; or `{ abort: true, key }`) cancels without sending; a removed instance's requests are aborted. **The request sees what STATE stored**: `SHOW: { STATE: (s, id) => ({ ...s, id }), HTTP: (s) => ({ url: '/api/q/' + s.id, ok: 'LOADED' }) }` (or build it from `id`). - Other promise APIs: `driverFromAsync(fn)` takes the same reply actions: `{ value, ok: 'DONE', error: 'FAILED' }` calls `fn(value)`; `DONE` gets the result, `FAILED` `{ error, request }` (no `latest`/abort). One-off async work: `EFFECT: async (state, data, next, { signal }) => { ...; next('DONE', result) }` (rejection: SYG214; `signal` aborts on unmount; no concurrency control). A driver is any function `sink$ => source`; to answer with reply actions (several per request: progress, then ok), `const { replies, reply } = makeReplies(onStop)`, `reply(senderOf(req), req.ok, value)`, return `{ ...replies }` (custom-drivers.md). Page-wide events: `DOM.select('document' | 'body').events(type)`, CSS-filtered with `DOM.select('document').select('.overlay').events('click')`. # Sygnal: resources and the query cache It assumes the core (`llms.txt`). - `resources` is the form for data a component shows (reads derived from state); writes and click-triggered one-off requests keep reply actions (above). Needs `Quote.drivers = { HTTP: makeFetchDriver() }` on the root. The core keeps `state.quote` (named by the resource; don't set it in initialState: it reads as `{ status: 'idle' }`) and writes it with the built-in `RESOURCE` action. When the request changes (by value; behaviour-only fields, e.g. `refetchEvery`, `keepPrevious`, `ok`, don't count: `refetchEvery: s.live ? 5000 : undefined` toggles polling, no refetch) it is fetched and the older one aborted, so a stale reply is never shown: no ids, `latest`, ok/error actions or loading flags to write. `data` is the parsed body; `error` is the Error (`error.status`, `error.body` for a non-2xx). Falsy aborts and goes idle. TS: `quote: Resource` in the state type. - **A component that reads `state.items` declares `items` in its own `.resources`**, even when another page (or its parent) declares the same request: without it `state.items` is undefined on a direct visit (or holds whatever another page loaded last), and a test that starts on the declaring page hides this. Each declaration fetches; with a `queryCache()` the repeat shows the cached data at once and identical requests in flight share one fetch. - **Refetch rule**: a new request (another id) is `'loading'` with no data; a refetch of the same request (`{ refresh: 'quote' }`, an invalidation, focus, polling) keeps `status`, `data` and `error` with `refreshing: true`, and a failed refetch keeps `data`. When the old value must not show (Refresh shows "Loading…"), treat `refreshing` as loading. `keepPrevious: true` keeps the old data across a request change too (pagination). Infinite list: `{ url: (cursor) => ({ url, query: { after: cursor } }), next: (page) => page.next }` → `data: { pages, cursors }`, `hasMore`; `{ more: 'feed' }` adds a page; a refetch reloads all from the first. `ok`/`error` also dispatch after the write. - Invalidation: tag reads `{ url, tags: ['quotes'] }`; a write with `invalidates: ['quotes']` (tags, a `'/api/quotes'` URL prefix, or a predicate) refetches the matching mounted reads after a 2xx (`invalidateOn: 'settled'`: after failures too), keeping their data; `{ invalidate: 'quotes' }` on the HTTP sink does it at once in every component (`{ refresh }`: the sender's only). The refetch aborts the read already in flight, so a reply sent before the write never lands. `{ reset: true | tag }` (logout): matching cache entries dropped, resources back to 'loading' (no data) and refetched; `queryCache().clear()`: entries only. - `updates: 'item'` on a write (React Query's `setQueryData`): after a 2xx, before the `ok` action and `invalidates`, the reply becomes `state.item.data` and its cache entry at once, and the item's read in flight is aborted; `updates: { items: (list, reply) => newList }` derives the data. With `invalidates` the read then refetches keeping the written data (`refreshing`). The `ok` action still gets the reply. - Query cache (opt-in, its own export): `App.drivers = { HTTP: makeFetchDriver({ cache: queryCache({ staleTime: 30000, gcTime: 300000 }) }) }`. A request fetched before shows its cached data at once (`'success'`, `refreshing: true` while it revalidates; nothing is sent while younger than `staleTime`, default 0), identical requests in flight share one fetch, and stale mounted resources refetch on window focus and reconnect. Reply-action GETs use it with `cache: true` or `staleTime`. Per request: `retry: 3` or `{ count, delayMs }` (default 0; network errors, 408, 429, 5xx), `validate: schema` (Standard Schema). `{ prefetch: '/api/quotes/2' }` on the sink warms the cache. SSR: `cache.set(request, data)`, `renderToString(App, { cache })`, `cache.dehydrate()` → `queryCache({ initial: snapshot })` (Vike: `pageContext.queryCache` from `+data`). Guide and recipes (list/detail + save, optimistic update, pagination, infinite list, save status): `node_modules/sygnal/dist/guide/resources.md` (online: https://sygnal.js.org/guide/resources/) - List/detail + save, cached: `items: (s) => s.view === 'list' && { url: '/api/items', staleTime: 2000 }`, `item: (s) => s.view === 'detail' && { url: '/api/items/' + s.id, staleTime: 2000 }` (declared only while shown; shown again: cached data at once, refetched once stale), `makeFetchDriver({ cache: queryCache() })` in `App.drivers` **and** `renderComponent(App, { http: { cache: queryCache() } })` in every test (a `staleTime` without a queryCache is SYG635), the save `{ url, method: 'PUT', json, ok: 'SAVED', error: 'SAVE_FAILED', updates: 'item', invalidates: '/api/items' }`, status `r?.status === 'loading' ? 'Loading…' : r?.refreshing ? 'Updating…' : ''`. - In a hidden Switchable page resources and `connections` pause (fetches abort, sockets close) and resume on show; an entry with `background: true` (`{ url, background: true }`) stays live. Per-page slices: `state={{ projects: 'pages.projects', settings: byId('teams', state.teamId) }}` (key, path, lens or byId per page; each page follows its own binding: another target remakes only that page; unlisted pages share the owner's state; a key that names no page is SYG429). # Sygnal: WebSocket and SSE It assumes the core (`llms.txt`). - `Chat.drivers = { WS: makeSocketDriver() }` on the root (options `baseUrl reconnect queueLimit`). Without it the static opens nothing and nothing reports it. Spec keys: `socket` (a path gets ws:/wss: from the page) or `sse` (read-only; `events: { 'price-update': 'PRICE' }` for named events), `message open close error` (all optional reply actions, to this instance only), `reconnect` (`false` = never), `share` (default true: one socket per URL, ref-counted), `protocols`, `withCredentials`, SSE `headers: { authorization: `Bearer ${state.token}` }` (EventSource can't send headers, so the driver reads such a stream with fetch; keep the token in state: a changed header reconnects); SSE `meta: true` (actions get `{ data, id, event }`), `resume: true | 'param'` (a driver reconnect resumes from the last event id), `staleAfterMs` (silence = a drop that reconnects; `close` gets `stale: true`; heartbeat comments count over fetch). `close` fires only for drops the app didn't cause; leaving, a URL change, unmount and dispose close silently, so no connection-generation ids. A room switch must `ABORT` when the room is unchanged (an unchanged connection fires no new `open`). `error` gets `{ error }`. `{ to, json | text | binary }` on a name this instance didn't declare, a closed-for-good or an SSE connection is SYG611. Use the static OR a model-sent `{ connections }`, never both (each is the whole set). Guide: https://sygnal.js.org/guide/sockets/ # Sygnal: router and HEAD It assumes the core (`llms.txt`). ```jsx import { makeRouter } from 'sygnal' export const router = makeRouter({ routes: { home: '/', task: '/tasks/:id', admin: '/admin', notFound: '*' } }) // first match wins export const { href } = router // href('task', { id: 2 }, { tab: 'notes' }) → '/tasks/2?tab=notes' ``` // src/App.jsx; on the root: App.drivers = { ROUTER: router.driver, HEAD: makeHeadDriver({ titleTemplate: '%s · Tasks' }) } App.model = { ROUTE: { // a guard: refuse the route and redirect STATE: (state, route) => (route.name === 'admin' && !state.user ? ABORT : { ...state, route, draft: '', leaving: null }), ROUTER: (state, route) => (route.name === 'admin' && !state.user ? { to: 'home', replace: true } : ABORT), }, } TaskPage.model = { // a page shares the parent's state: no initialState (SYG405) EDIT: { STATE: (state, draft) => ({ ...state, draft }), ROUTER: () => ({ block: 'CONFIRM_LEAVE' }) }, // unsaved changes CONFIRM_LEAVE: (state, { proceed }) => ({ ...state, leaving: proceed }), // a blocked attempt: { to, route, proceed } LEAVE: { STATE: (state) => ({ ...state, leaving: null }), ROUTER: (state, data, next, { previousState }) => ({ ...previousState.leaving, block: false }) }, DONE: { ROUTER: () => ({ to: 'home', block: false }) }, } ``` - Links are plain ``, never click handlers: the driver intercepts same-origin left clicks at the document (not modified clicks, `target`, `download`, `rel="external"`, `data-router-ignore`, other origins, `makeRouter({ external })`). `params` and `query` values are strings; `href()` is typed from the route table (unknown names, missing params: type errors; SYG130/131 at run time). The `key` makes each visit a new page; `path` excludes the query: add query keys that should re-create it (`` `${route.name}:${route.path}?${route.query.s ?? ''}` ``). Not Switchable (hidden pages stay live). Pages read the route from context (`App.context = { route: (s) => s.route }`): `TaskPage.resources = { task: (s, { context: { route } }) => `/api/tasks/${route.params.id}` }`. - ROUTER commands (pushed unless `replace`, even to the current URL): `{ to, params, query, hash, replace, scroll }`, `{ url }`, `{ back: true }`, `{ forward: true }`, `{ go: n }`, `{ block: 'ACTION' | false }` (also stops back/forward and turns on the `beforeunload` leave-page prompt; `proceed` navigates anyway and clears the block it overrode). A block belongs to the component that set it (only its own `{ block: false }` clears it): put CONFIRM_LEAVE and LEAVE next to the `block`, `{ prefetch: 'task', params }` (calls `makeRouter({ prefetch })`). `route` is reserved for the declaration. A bad command is SYG620. The first declarer (the root) gets each route first, so keep guards there. - Options: `makeRouter({ routes, base: '/app', mode: 'hash', scroll, focus })`. SSR: `router.current(req.url)` in the seeded state; `renderToString(App, { head: list })` + `renderHead(list)`. Vike: `makeRouter({ routes, navigate })` with `navigate` from `'vike/client/router'`, registered in `pages/+drivers.js`. HEAD: a later-mounted component's title wins; `meta`/`link` merge; a model entry can also send `HEAD: (state, data) => ({ title })`. Guides: https://sygnal.js.org/guide/router/, https://sygnal.js.org/guide/head/ # Sygnal: forms It assumes the core (`llms.txt`). - `Signup.uses = { form: form(schema, { values: { email: '', addresses: [{ id: 1, city: '' }] }, request: { url: '/api/signup' } }) }` (`form` from `'sygnal'`), any Standard Schema (zod, valibot, or `{ '~standard': { version: 1, vendor, validate } }`). Fields inside the `
    ` are matched by `name`, a path in `values` (array rows by id: `addresses.7.city`): no intent per field (SYG230: a name not in `values` or `dynamic`). TypeScript: `type State = { … } & UsesState`, `type Actions = UsesActions` (a `submit` action's data: `FormOutput`) (behaviors' slices and namespaced actions); a typed schema (zod, valibot, arktype) types `state.form.values` and `fields.email.value` and checks `values`. File fields: `` (never bind `value`) with `avatar: null` in values gives the `File` (`multiple`: File[]), validated by the schema (`z.file()`); `request: { url }` sends it as multipart, `state.form.progress?.fraction`. - View: `const f = state.form.fields`; ``, `

    {f.email.error}

    `, a `