# VRPC in TypeScript

The `vrpc` package brings its types along: nothing to install, nothing to
declare. This guide shows how to get typed proxies, what an agent publishes
of a TypeScript class, how to write event functions in TypeScript, and what
to know about ES modules and bundlers.

## Typed proxies

Name the class a proxy stands for, and the compiler checks every call:
that the function exists, its arguments, and what it answers.

```typescript
import { VrpcClient } from 'vrpc'
import type { Thermostat } from './Thermostat'

const client = new VrpcClient({ domain: 'my-domain', broker: 'mqtt://localhost:1883' })
await client.connect()

const kitchen = await client.create<Thermostat>({
  agent: 'house',
  className: 'Thermostat',
  instance: 'kitchen',
  args: ['kitchen']
})

const target: number = await kitchen.setTarget(21)   // Promise<number>
await kitchen.setTarget('warm')                       // error: not a number
await kitchen.setTemperature(21)                      // error: no such function
```

`create<T>()` and `getInstance<T>()` answer a `Remote<T>`: the functions an
agent publishes of `T` - its public functions, none whose name begins with
`_` -, each answering a promise of what it returns on the agent. An event
function answers `true`, or its registration's `value`.

The type is your word: nothing checks at run time that the agent serves
that class. Share the class, or an interface of it, between the program
that offers it and the one that uses it; `import type` takes the type and
leaves the code where it is. Without a type argument a proxy has any
function, answering `Promise<any>`.

`callStatic<R>()` and `callAll<R>()` take the type of the result the same
way. An error a call rejects with is an `AnsweredError` when its agent
answered it: `err.vrpc` holds the agent, the context, the function and the
agent's words alone (see [Calls](https://vrpc.io/docs/concepts/calls.md)).

Options are checked as well: a misspelt one - `brokerUrl` for `broker` - is
a compile error, where JavaScript gets a warning at run time.

## Offering a TypeScript class

Register the class as in JavaScript:

```typescript
import { VrpcAdapter, VrpcAgent } from 'vrpc'
import { Thermostat } from './Thermostat'

VrpcAdapter.register(Thermostat)
await new VrpcAgent({ domain: 'my-domain', agent: 'house', broker: 'mqtt://localhost:1883' }).serve()
```

### `private` is not private on the network

TypeScript's `private` and `protected` exist for the compiler alone; the
JavaScript that runs has ordinary methods. An agent publishes them like any
other function, unless one of these holds:

| Write | Holds |
| --- | --- |
| `#calibrate () {}` | always: JavaScript's own private method, which nothing outside the class reaches |
| `_calibrate () {}` | unless the class is registered with `{ onlyPublic: false }` |
| `private calibrate () {}` | when the agent reads the TypeScript source: `VrpcAdapter.register(Thermostat, { jsdocPath: './Thermostat.ts' })` |

`jsdocPath` names the `.ts` file as it lies beside the program at run time.
A program that runs from compiled output without its sources has nothing to
read: there, `#private` and `_` are what keeps a function inside. See
[What is published](https://vrpc.io/docs/guides/expose-classes.md#what-is-published).

### Documentation for generic clients

Types do not travel. What an agent publishes about a function - its
description, its parameters, what it returns - comes from the JSDoc of the
source named by `jsdocPath`, tags included (`@param {number} celsius`). Only
clients that show functions to people or to other programs need it.

## Event functions

An event function takes a handler, calls it again and again, and returns a
`Registration` that undoes exactly this call:

```typescript
import { EventEmitter } from 'node:events'
import type { Registration } from 'vrpc'

export class Thermostat {
  #emitter = new EventEmitter()
  #reading: number | undefined

  onReading (handler: (celsius: number) => void): Registration {
    this.#emitter.on('reading', handler)
    return {
      [Symbol.dispose]: () => { this.#emitter.off('reading', handler) },
      greet: greeting => { if (this.#reading !== undefined) greeting(this.#reading) }
    }
  }

  // released when the instance is deleted
  [Symbol.dispose] (): void { /* stop timers, close connections */ }
}
```

- **Name it `on` followed by a capital letter.** A client decides which
  functions are event functions, and it cannot see TypeScript's return
  type: `onReading` every client recognizes. A function of another name -
  `watchReading` - is called as an ordinary function, its handler once and
  never again, without an error. For such a name, declare
  `@returns {Registration}` in the JSDoc, register with `jsdocPath`, and
  let clients read meta data (`requiresSchema: true`) - or call it through
  `proxy.vrpcOn('watchReading', handler)`.
- **`Symbol.dispose` needs no compiler setting.** The types of `vrpc` bring
  the library that declares it, whatever the project targets. At run time
  Node.js has it from 18.18 and 20.4, and `vrpc` provides it before.
- `Registration<string>` says that the subscribing call answers the
  registration's `value`, a string, instead of `true`.

More in [Writing event functions](https://vrpc.io/docs/guides/event-functions.md).

## ES modules

`import { VrpcClient } from 'vrpc'` works in ES modules and in TypeScript of
any module setting, as `require('vrpc')` does in CommonJS.

A relative `jsdocPath`, and a class registered by a relative path, are
meant from the file that registers - an ES module or not. (Before 3.20.0 an
ES module had to give absolute paths.) A class registered by path from an
ES module file needs Node.js 22 or newer, which can `require` one; import
the class and pass it instead, and every version will do.

## Bundlers

- **For the browser**, a bundler takes `browser/vrpc.js`, which the
  package names as its browser build: one file that contains the MQTT
  client, about 160 kB compressed. Vite, webpack and esbuild need no
  setting for it.
- **For Node.js**, a service that imports `vrpc` can be bundled as it is.
  `VrpcAdapter.register('./Thermostat')` and `addPluginPath` load files at
  run time, which a bundle does not contain: register the classes you
  import.
