<!-- https://tinyactors.dev/guides/browser/ -->
# In the browser

Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).

> Run the charts you run on Node.js in a page or a Worker with @tinyactors/wasm, the same API on core compiled to WebAssembly.

Change one import, and the charts you run on Node.js run in a page or a Worker, on tinyactors compiled to WebAssembly. The same package runs Node.js and Bun where no native addon is built, such as Windows.

<a id="same-api"></a>

## Import the WebAssembly package instead

Import `@tinyactors/wasm` in place of `@tinyactors/node`, and every other guide holds unchanged. This program logs the same line in a page as in Node.js:

```javascript title="hello.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';

const compiled = compileCharts([{ name: 'hello.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="hello" initial="s">
  <state id="s"><onentry><log expr="'hello from ' + _ioprocessors.scxml.location"/></onentry></state>
</scxml>` }]);
const host = new Host(compiled, { system: 'web', log: (entry) => console.log(entry.text) });
compiled.close();
host.spawn('hello');
await host.idle();
host.close();
```

```text title="output"
hello from tinyactors://web/#_scxml_1
```

<a id="bytes-are-uint8arrays"></a>

## Treat bytes as Uint8Arrays, not Buffers

Where `@tinyactors/node` gives a `Buffer`, this package gives a plain `Uint8Array`. A `Buffer` is a `Uint8Array` too, so code written against `Uint8Array` runs on both.

That covers every output in bytes: `compiled.image`, `host.hibernate()`, `host.snapshot()`, `host.metrics()`, telemetry and `encode()`.

Decode text with `TextDecoder` instead of `buf.toString()`, and copy or compare with the typed array's own methods. This program copies an encoded value and writes it as base64:

```javascript title="bytes.mjs"
import { decode, encode } from '@tinyactors/wasm';

const bytes = encode({ sku: 'tea', qty: 2 });
console.log(bytes instanceof Uint8Array, bytes.length, 'bytes');
const copy = bytes.slice(); // a Uint8Array again, on both packages
console.log(decode(copy).sku, btoa(String.fromCharCode(...copy))); // base64, in a page as in Node.js
```

```text title="output"
true 14 bytes
tea omNza3VjdGVhY3F0eQI=
```

`index.d.ts`, which both packages share, types every one of them as `Uint8Array`.

<a id="loading-top-level-await-or-init"></a>

## Call init() under a bundler or Service Worker

The package's entry loads its module, `tinyactors.wasm` beside its files, with top-level `await`. A browser fetches the file, Node.js and Bun read it, and every name works once the import settles.

A Service Worker refuses a module graph with top-level `await`. Some bundlers neither handle it nor place `tinyactors.wasm` beside the bundle: esbuild does not follow `new URL(..., import.meta.url)`.

There, import `@tinyactors/wasm/init`: it exports the same names and `init(source?)`, which loads the module once. Every call made before it settles throws `TA_ERROR_STATE`.

Give `init` a URL, a `Response`, the bytes or a compiled `WebAssembly.Module`, or nothing to load the package's own file. This program makes a host before and after `init()`:

```javascript title="init.mjs"
import { Host, init } from '@tinyactors/wasm/init';

try {
  new Host([], { system: 'early' });
} catch (error) {
  console.log('before init:', error.status);
}
await init(); // or init(new URL('/assets/tinyactors.wasm', location.href)), wherever your build put it
const host = new Host([], { system: 'ready' });
console.log('after init: closed', host.closed);
host.close();
```

```text title="output"
before init: TA_ERROR_STATE
after init: closed false
```

The package targets ES2022 and serves the module as `@tinyactors/wasm/tinyactors.wasm`, so a bundler or a CDN can place it.

<a id="what-a-page-needs-the-floor-and-the-csp"></a>

## Target Chrome 114, Firefox 119 and Safari 16.4

By the engines' release notes, Chrome and Edge 114, Firefox 119 and Safari 16.4 have every feature the package uses. Only Chromium 141 is tested.

- **WebAssembly**: `extended-const`, `multivalue`, `bulk-memory` and `nontrapping-fptoint`, in the module.
- **JavaScript**: top-level `await` and `String.prototype.isWellFormed`, in the package.

<a id="content-security-policy"></a>

## Allow WebAssembly and eval in your CSP

The module needs `'wasm-unsafe-eval'` in `script-src`. The default engine, the native datamodel, runs your charts' expressions and scripts as JavaScript, so it needs `'unsafe-eval'` too.

```text
Content-Security-Policy: script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'
```

Under any of these policies, `new Host(...)` on the native datamodel throws `TinyactorsError` with `TA_ERROR_UNSUPPORTED`, its message naming the directive:

- a `script-src` without `'unsafe-eval'`;
- a `sandbox` policy without `allow-same-origin`;
- Trusted Types enforced (`require-trusted-types-for 'script'`), which guards string evaluation even with `'unsafe-eval'`.

Under them, `compileCharts` also skips its check of the charts' JavaScript syntax, since it parses with the same constructor. Run such a page's charts on [quickjs](https://tinyactors.dev/guides/browser/index.md#the-quickjs-sandbox).

<a id="the-quickjs-sandbox"></a>

## Run charts on quickjs under a strict policy

With `datamodel: 'quickjs'`, chart code runs on quickjs-ng inside the package's module, so the page's policy needs only `'wasm-unsafe-eval'`. Use it for charts you do not trust, too.

Every quickjs option and behaviour of `@tinyactors/node` holds here ([The quickjs sandbox](https://tinyactors.dev/guides/quickjs/index.md)). This host sets `maxOps` and reads the engine's heap size:

```javascript title="quickjs.mjs"
import { Host } from '@tinyactors/wasm';

const host = new Host([], { system: 'rules', datamodel: 'quickjs', quickjs: { maxOps: 10000 } });
console.log(host.quickjsHeapBytes > 0);
host.close();
```

```text title="output"
true
```

Every page downloads quickjs, since the one module holds it: 378 KiB with brotli, against 137 KiB without it. `mise run pack:wasm` reports the sizes.

The engine's stack is the module's, at most 256 KiB whatever `quickjs.stackLimit` asks. A deeper recursion is its evaluation's `error.execution`, `RangeError: Maximum call stack size exceeded`.

Inside quickjs, `Date` reads the real clock, as in `@tinyactors/node`, whatever clock the host runs on.

<a id="where-charts-run-declare-your-variables"></a>

## Declare every variable your scripts assign

Scripts and expressions run as strict code, so an assignment to a name nobody declared is the script's `error.execution`. It never becomes a global.

Declare a variable with a top-level `var` or with `<data>`. Here the declared chart keeps `visits` through hibernation, and the undeclared one fails:

```javascript title="declare.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';

const chart = (name, script) => `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="${name}" initial="s">
  <script>${script}</script>
  <state id="s">
    <transition event="visit"><script>visits = next(visits)</script><log expr="'${name}: ' + visits"/></transition>
    <transition event="error.execution"><log expr="'${name}: ' + _event.data.message.split(':')[0]"/></transition>
  </state>
</scxml>`;
const compiled = compileCharts([
  { name: 'declared.scxml', text: chart('declared', 'var visits = 0; function next(n) { return n + 1; }') },
  { name: 'undeclared.scxml', text: chart('undeclared', 'visits = 0; function next(n) { return n + 1; }') },
]);
const host = new Host(compiled, { system: 'web', log: (entry) => console.log(entry.text) });
compiled.close();

const declared = host.spawn('declared');
declared.send('visit');
await host.idle();
host.wake(declared, host.hibernate(declared)); // out of memory and back, its visits with it
declared.send('visit');
await host.idle();

host.spawn('undeclared');
await host.idle();
host.close();
```

```text title="output"
declared: 1
declared: 2
undeclared: ReferenceError
```

Top-level declarations follow the rules of `@tinyactors/node` ([Writing charts](https://tinyactors.dev/guides/charts/index.md#scripts)):

- a chart-level script's `function`s are the chart's helpers, made once;
- a top-level `var` is a variable of the session;
- `let`, `const` and `class` at a script's top level are refused.

A host runs its charts in a realm of its own, a set of globals it makes at its first chart. Each actor's variables are a scope object there, and the realm differs by platform:

| Where | A host's charts run in |
|---|---|
| a page | a hidden iframe of the page's origin, one per host, removed at `close()` |
| a Worker | the worker's own global (a Worker has no `document`) |
| Node.js, Bun | a `node:vm` context, as in `@tinyactors/node` |

A hidden iframe looks like a sandbox but is not one: chart code runs in your engine and must be trusted.

<a id="a-dedicated-worker"></a>

## Move the charts off the page's thread

On the page's thread, a chart step that runs long is a frame the page does not draw.

In a dedicated Worker the page stays responsive, and the charts' realm holds none of the page's code. Only values cross `postMessage`, as between any two systems.

The page waits until the worker says it listens, since a message sent before the worker's module ran is lost. Then it asks for a counter and two visits:

```javascript title="page.mjs"
const worker = new Worker(new URL('./counters-worker.mjs', import.meta.url), { type: 'module' });
// the worker says when it listens: a message sent before its module ran (it loads
// the package with top-level await) has no listener and is lost
await new Promise((resolve) => { worker.onmessage = resolve; });
const ask = (message) => new Promise((resolve) => {
  worker.onmessage = (event) => resolve(event.data);
  worker.postMessage(message);
});
console.log(await ask({ op: 'spawn', name: 'ada' }));
console.log(await ask({ op: 'visit', name: 'ada' }));
console.log(await ask({ op: 'visit', name: 'ada' }));
worker.terminate();
```

```text title="output"
spawned ada
ada: 1
ada: 2
```

The worker, `counters-worker.mjs` beside the page, runs the host. It answers each question once the host is idle, with the count the counter sends to `urn:page`:

```javascript title="counters-worker.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';

const compiled = compileCharts([{ name: 'counter.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="counter" initial="s">
  <datamodel><data id="visits" expr="0"/></datamodel>
  <state id="s">
    <transition event="visit">
      <assign location="visits" expr="visits + 1"/>
      <send event="counted" target="#_page" type="urn:page"><param name="visits" expr="visits"/></send>
    </transition>
  </state>
</scxml>` }]);
let answer = null; // the page's pending question
const host = new Host(compiled, {
  system: 'worker',
  ioProcessors: { 'urn:page': { receive: (send) => answer?.(`${send.host.actor('ada').equals(send.sender) ? 'ada' : '?'}: ${send.data.visits}`) } },
});
compiled.close();

self.onmessage = async ({ data }) => {
  const reply = new Promise((resolve) => { answer = resolve; });
  if (data.op === 'spawn') {
    host.spawn('counter', { name: data.name });
    answer(`spawned ${data.name}`);
  } else host.actor(data.name).send('visit');
  await host.idle();
  postMessage(await reply);
};
postMessage('ready');
```

A module Worker has no import map. A bundler resolves `@tinyactors/wasm` in the worker as in the page, or the worker imports the package's `index.mjs` by its URL.

<a id="the-store-indexeddb"></a>

## Keep hibernated actors in IndexedDB

Your code chooses where a browser host's hibernated actors and snapshots live. A browser has no SQLite, so it refuses `SQLiteStore` ([Hibernation](https://tinyactors.dev/guides/hibernation/index.md)).

A page has IndexedDB, which stores a `Uint8Array` as it is. The host follows a store's promises, so IndexedDB can be a host's `store` directly.

This counter is hibernated into IndexedDB, then loaded from it when its next event comes:

```javascript title="store.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';

// IndexedDB, as promises: one object store of blobs, the session as the key
const done = (request) => new Promise((resolve, reject) => {
  request.onsuccess = () => resolve(request.result);
  request.onerror = () => reject(request.error);
});
const opening = indexedDB.open('tinyactors-blobs', 1);
opening.onupgradeneeded = () => opening.result.createObjectStore('blobs');
const db = await done(opening);
const blobs = (mode) => db.transaction('blobs', mode).objectStore('blobs');
const store = {
  save: (session, blob) => done(blobs('readwrite').put(blob, String(session))),
  load: (session) => done(blobs('readonly').get(String(session))),
  delete: (session) => done(blobs('readwrite').delete(String(session))),
};

const compiled = compileCharts([{ name: 'counter.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="counter" initial="s">
  <datamodel><data id="count" expr="0"/></datamodel>
  <state id="s">
    <transition event="inc"><assign location="count" expr="count + 1"/></transition>
    <transition event="report"><log expr="'count ' + count"/></transition>
  </state>
</scxml>` }]);
const host = new Host(compiled, {
  system: 'web',
  store, // with resident: n, the host would also hibernate into it after each turn
  log: (entry) => console.log(entry.text),
});
compiled.close();

const counter = host.spawn('counter');
counter.send('inc');
await host.idle();
host.sweep(100, 100); // a first sweep marks; the actor has not run since
for (const session of host.sweep(100, 100)) await store.save(session, host.hibernate(session));
console.log('stored:', await done(blobs('readonly').count()));

counter.send('inc'); // it is loaded from the store first; idle() waits for the load
counter.send('report');
await host.idle();
host.close();
db.close();
await done(indexedDB.deleteDatabase('tinyactors-blobs'));
```

```text title="output"
stored: 1
count 2
```

<a id="liveness-a-page-is-not-a-process"></a>

## Expect late timers in a hidden tab

In Node.js an open host with a pending deadline keeps the process alive. A page's hosts run only while the page does.

A host runs its turns as `MessageChannel` messages and arms one `setTimeout` at its next deadline. A browser throttles that timer while the tab is hidden.

Chromium runs a hidden tab's timers about once a second, and once a minute after a few minutes hidden. A dedicated Worker is throttled less, but still throttled.

A delayed `<send>` or a timeout then comes late, when the timer fires, and is never lost.

<a id="page-goes-away"></a>

## Snapshot the host when the page hides

A tab can be closed or discarded without notice, and its actors go with it. Keep what must survive in your store.

Hibernate actors as they go cold, or snapshot the host on `visibilitychange`, the last event a page is sure to get. Restore the snapshot when the page loads again.

This cart is snapshotted into IndexedDB, and a second load restores it with its item kept:

```javascript title="cart.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/wasm';

const done = (request) => new Promise((resolve, reject) => {
  request.onsuccess = () => resolve(request.result);
  request.onerror = () => reject(request.error);
});
const opening = indexedDB.open('tinyactors-host', 1);
opening.onupgradeneeded = () => opening.result.createObjectStore('hosts');
const db = await done(opening);
const hosts = (mode) => db.transaction('hosts', mode).objectStore('hosts');

const options = () => ({ system: 'web', clock: new SimulatedClock(), log: (entry) => console.log(entry.text) });
const compiled = compileCharts([{ name: 'cart.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="cart" initial="open">
  <datamodel><data id="items" expr="[]"/></datamodel>
  <state id="open">
    <transition event="add"><script>items.push(_event.data)</script></transition>
    <transition event="show"><log expr="'cart: ' + items.join(', ')"/></transition>
  </state>
</scxml>` }]);

// at load: the host as the page left it, else a new one
async function load() {
  const saved = await done(hosts('readonly').get('host'));
  if (saved !== undefined) return Host.restore(saved, compiled, options());
  const host = new Host(compiled, options());
  host.spawn('cart', { name: 'cart' });
  return host;
}
// when the page is hidden: a snapshot needs a quiescent host, so after idle()
async function save(host) {
  await host.idle();
  await done(hosts('readwrite').put(host.snapshot(), 'host'));
}

const host = await load();
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') save(host);
});
host.actor('cart').send('add', 'tea');
await save(host); // what the event would do, here at once
host.close();

const again = await load(); // the page loaded again
again.actor('cart').send('add', 'cake');
again.actor('cart').send('show');
await again.idle();
again.close();
compiled.close();
db.close();
await done(indexedDB.deleteDatabase('tinyactors-host'));
```

```text title="output"
cart: tea, cake
```

A snapshot leaves out the services your program runs, which a restore announces again ([Snapshots](https://tinyactors.dev/guides/snapshots/index.md)).

<a id="memory"></a>

## Size a page for its peak memory

The host's memory is the module's linear memory, which grows and is never given back: a page keeps its peak.

- **Hibernation makes room, not a smaller page.**: Hibernating actors frees room for others in that memory. A snapshot is packed there before it is copied out, so a 100 MB snapshot leaves the memory 100 MB larger.
- **4 GiB at most.**: wasm32 addresses 4 GiB, and a region that grows is copied before the old one is freed. So one host holds about two million resident actors at most, where `@tinyactors/node` goes on.
- **What the package hands out stays valid.**: Bytes, values and views are never views of that memory, so they stay valid when it grows.

What one actor costs in that memory is measured in [Capacity and memory](https://tinyactors.dev/guides/capacity/index.md#what-an-actor-costs).

<a id="one-store-two-packages"></a>

## Share a database with a Node.js server

A server on `@tinyactors/node` and a browser client on `@tinyactors/wasm` can share a database, but not the bytes a host packs.

- **Send values across.**: `encode` and `decode` are one format in both packages ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)): move work between the server and the client as events and their data, from one system to another.
- **A snapshot does not cross.**: It is the host's memory as the build that made it lays it out, and the addon is a 64-bit build where the module is a 32-bit one. Each package labels its snapshots with its own name and refuses the other's with `TA_ERROR_INVALID`, the message naming the package that made it.
- **A hibernation blob belongs to its host.**: It wakes in the host that hibernated it, or in one restored from that host's snapshot, which the other package cannot restore; another host's blob throws `TA_ERROR_INVALID`. Keep the server's blobs and the client's apart in the store, by host.
