---
title: FlowStream
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/flowstream/
updated: 2026-11-16T15:41:20.819Z
---

# FlowStream

> The Flow module, FlowStream instances, component definitions, component instances and messages.

FlowStreams are graphs of components loaded from `.flow` files in `/flowstreams/` or with `Flow.load()`. This page lists the `Flow` object, the FlowStream instance, the component definition (`exports`), the component instance and the message (`$`). The guide [FlowStream](../../guides/flowstream/) explains how to use them with examples; this page is the exact reference.

## API

### CONF.directory_flowstreams = '/flowstreams/'

Type: `config`

The directory with `.flow` files that are loaded when the app starts.

Every file with the `.flow` extension in this directory is read as JSON and passed to `Flow.load()` when the app starts. Files whose name contains `-bk` or `_bk` are skipped, so you can keep backups next to them. The directory `plugins/{name}/flowstreams/` of each plugin is loaded the same way.

In debug mode the watcher restarts the app when a `.flow` file changes. The default is `/flowstreams/`; an empty value turns the loading off.

Example: Directory layout
```text
flowstreams/
	orders.flow
	orders_bk.flow     // skipped
plugins/
	crm/
		flowstreams/
			leads.flow
```

### { id, name, components, design, variables, worker, ... }

Type: `config`

The JSON object stored in a `.flow` file and passed to `Flow.load()`.

- `id` {String}: the identifier, the key in `Flow.instances`. A random one is generated when it is missing.
- `name` {String}: a readable name (default: the `id`).
- `components` {Object}: component id → the component as an HTML string with a `<script total>` block.
- `design` {Object}: instance id → `{ component, config, connections, x, y }`. `connections` maps an output id to an array of `{ id: 'instanceid', index: 'inputid' }`.
- `variables` {Object}: values that components read with `instance.replace()` or `$.variables()`.
- `worker` {String/Boolean}: `'worker'` runs the FlowStream in a worker thread, another truthy value (for example `'fork'`) in a child process; `false` (default) in the main process.
- `memory` {Number}: the heap limit in MB for a child process (`--max-old-space-size`).
- `cloning` {Boolean}: clones the message data for every connection (default `true`).
- `paused` {Boolean}: starts the FlowStream paused.
- `readonly` {Boolean}: no `save` events are emitted.
- `origin` {String}: the public URL of the app, used by `instance.href()` and the `{hostname}` variable.

`flowstream.export()` returns the same shape, so you can write it back to the `.flow` file.

Example: A minimal .flow file
```json
{
	"id": "orders",
	"name": "Orders",
	"components": {
		"uppercase": "<script total>...</script>",
		"print": "<script total>...</script>"
	},
	"design": {
		"a1": { "component": "uppercase", "config": { "field": "name" }, "connections": { "output": [{ "id": "b1", "index": "input" }] } },
		"b1": { "component": "print", "config": {} }
	},
	"variables": { "currency": "EUR" }
}
```

### Flow.load(schema, [callback])

Type: `method`

Loads a FlowStream from its schema and starts it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `Object` | yes |  | The FlowStream schema (the content of a `.flow` file). |
| `callback` | `Function` | no |  | `function(err, instance)`; `instance` is the FlowStream instance. |

Creates the FlowStream, registers its components, creates the instances of the design and calls `callback` when everything is ready. The instance is stored in `Flow.instances[schema.id]` and the schema in `Flow.db[schema.id]`.

When a FlowStream with the same `id` is already loaded, it is updated with the new schema instead (components, design and variables are replaced) and the callback gets the existing instance.

A schema without `name`, `components`, `design`, `sources` or `variables` gets empty defaults, so an empty flow loads.

Example: Load a flow from code
```js
// definitions/flowstream.js
ON('ready', function() {

	var schema = {};
	schema.id = 'orders';
	schema.name = 'Orders';
	schema.components = {};
	schema.components.uppercase = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');
	schema.components.print = F.Fs.readFileSync(PATH.root('components/print.html'), 'utf8');
	schema.design = {};
	schema.design.a1 = { component: 'uppercase', config: { field: 'name' }, connections: { output: [{ id: 'b1', index: 'input' }] } };
	schema.design.b1 = { component: 'print', config: {} };

	Flow.load(schema, function(err, instance) {
		instance.send('a1', { name: 'Peter' });
	});
});
```

### Flow.init([directory], [callback])

Type: `method`

Loads all `.flow` files of a directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `directory` | `String` | no | `PATH.root('flowstreams')` | An absolute path. |
| `callback` | `Function` | no |  | Called when all files are loaded. |

Reads every `.flow` file of `directory` (default `flowstreams/` in the app root), skips names with `-bk` or `_bk` and loads each one with `Flow.load()`. A missing directory is not an error. The framework calls it for `/flowstreams/` at startup; call it yourself for another directory.

Example: Another directory
```js
Flow.init(PATH.root('databases/flows'), function() {
	console.log(Object.keys(Flow.instances));
});
```

### Flow.instances

Type: `property`

The loaded FlowStream instances by their `id`.

Returns: `Object`

An object where each key is the `id` of a schema and each value is the FlowStream instance returned by `Flow.load()`. Use it to send data to a FlowStream from routes, schemas or jobs.

Example: Send from a route
```js
exports.install = function() {
	ROUTE('POST /api/orders/', create);
};

function create() {
	var self = this;
	var flow = Flow.instances.orders;
	if (!flow) {
		self.invalid(404);
		return;
	}
	flow.send('a1', self.body, function(err, response) {
		if (err)
			self.invalid(err);
		else
			self.json(response.data);
	});
}
```

### Flow.db

Type: `property`

The schemas of the loaded FlowStreams by their `id`.

Returns: `Object`

Holds the schema passed to `Flow.load()`; it is replaced by the exported schema each time the FlowStream saves itself (see `Flow.on('save')`).

### Flow.remove(id)

Type: `method`

Destroys a FlowStream and removes it from `Flow.instances` and `Flow.db`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The FlowStream id. |

Stops all instances, closes a worker, removes the FlowStream and emits `remove` with its schema. The `.flow` file is not deleted.

Example: Remove
```js
Flow.remove('orders');
```

### Flow.reload(schema)

Type: `method`

Updates a loaded FlowStream with a new schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `Object` | yes |  | The new schema; `id` selects the FlowStream. |

Returns: `Boolean` `true` when the FlowStream exists.

Finds the FlowStream by `schema.id`, stores the schema in `Flow.db` and rewrites the running FlowStream with it (components, design and variables). Returns `false` when no FlowStream with this `id` is loaded. `Flow.load()` calls it for an `id` that is already loaded.

### Flow.socket(id, websocket, [check])

Type: `method`

Connects a WebSocket controller to a FlowStream for the Flow designer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The FlowStream id (or the FlowStream itself). |
| `websocket` | `WebSocket` | yes |  | The WebSocket controller (`this` in a `SOCKET` route). |
| `check` | `Function` | no |  | `function(client, next)`; call `next()` to let the client in. |

The designer talks to the FlowStream through this WebSocket: it reads components, the design and the stats, and sends changes back. `check(client, next)` runs for each new client; call `next()` to accept it. The socket is detached when the WebSocket controller is destroyed. An unknown `id` destroys the socket.

Example: Designer endpoint
```js
exports.install = function() {
	ROUTE('+SOCKET /flowstreams/{id}/', designer);
};

function designer(id) {
	var self = this;
	Flow.socket(id, self, function(client, next) {
		if (client.user && client.user.sa)
			next();
		else
			client.close();
	});
}
```

### Flow.onerror = function(err, source, id, componentid, stack) {}

Type: `delegate`

Handles errors of all FlowStreams.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error/String` | yes |  | The error. |
| `source` | `String` | yes |  | Where it happened, for example `instance_message` or `instance_make`. |
| `id` | `String` | yes |  | The instance id. |
| `componentid` | `String` | yes |  | The component id. |
| `stack` | `String` | no |  | The stack, for FlowStreams in a worker. |

The default prints a block with the FlowStream name, the source, the instance id and the component id to the console. Assign your own function before the FlowStreams are loaded; `this` is the FlowStream instance (`this.id` is its id).

Example: Log errors
```js
Flow.onerror = function(err, source, id, componentid) {
	console.error('FlowStream', this.id, source, id, componentid, err);
};
```

### Flow.on('load', function(instance, schema) {})

Type: `event`

A FlowStream was loaded and is ready.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `instance` | `Object` | yes |  | The FlowStream instance. |
| `schema` | `Object` | yes |  | The schema. |

Emitted after `Flow.load()` finished, before its callback.

Example: Log
```js
Flow.on('load', function(instance, schema) {
	console.log('FlowStream ready:', schema.name);
});
```

### Flow.on('save', function(schema) {})

Type: `event`

A FlowStream changed and its schema should be stored.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `Object` | yes |  | The exported schema with `id`, `components`, `design`, `variables` and the other fields. |

Emitted about five seconds after the last change: an edit in the designer, `flowstream.variables()`, `flowstream.reconfigure()` or `instance.save()`. The framework does not write `.flow` files itself; store the schema here. Nothing is emitted for a schema with `readonly: true`.

Example: Write the .flow file
```js
Flow.on('save', function(schema) {
	delete schema.unixsocket;
	F.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\t'), NOOP);
});
```

### FLOWSTREAM([name], [errorhandler])

Type: `method`

Creates or returns a FlowStream engine by name, without workers or the designer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | `'default'` | The engine name. |
| `errorhandler` | `Function` | no | `console.error` | `function(err, source, instance)`. |

Returns: `FlowStream` The engine.

Returns the engine that runs components and messages. The same `name` returns the same engine (default name `default`). It has no `.flow` file, no worker and no saving; `Flow.load()` builds on it. Main methods:

- `add(id, html, [callback])` registers a component from its HTML.
- `use(design, [callback])` creates instances from a design object (returns a Promise without callback); `insert(design, [callback])` adds instances; `remove(keys, [callback])` removes them.
- `trigger('instanceid__inputid', data)` sends data to an input; `send('instanceid__outputid', data)` sends data from an output.
- `find(id)` returns an instance; `pause(is)`; `reconfigure(id, config)`; `destroy()`.
- Events: `message`, `end`, `connect`, `disconnect`, `configure`, `schema`.

Example: A local engine
```js
var flow = FLOWSTREAM('local');

var print = '<script total>exports.inputs = [{ id: \'input\', name: \'Input\' }]; exports.make = function(instance) { instance.message = function($) { console.log($.data); $.destroy(); }; };</script>';

flow.add('print', print, function() {
	flow.use({ p1: { component: 'print', config: {} } }, function() {
		flow.trigger('p1__input', { hello: 'world' });
	});
});
```

### flowstream.send(path, data, [callback])

Type: `method`

Sends data to one instance and waits for the end of the message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | The target instance. |
| `data` | `Object` | yes |  | The message data. |
| `callback` | `Function` | no |  | `function(err, response)`. |

`path` is an instance id, `@componentid` (the first instance of the component) or `#name` (the first instance whose component has this name). Add `/inputid` to set `$.input`. The data goes to `instance.message` of the target, so it must define `instance.message`.

The callback runs when the message and all its copies are destroyed. It gets `{ error, repo, data, count, cloned, duration, meta: { id, component } }`, where `data` is the data of the last message. An unknown target calls `callback(404)`.

Example: Wait for the result
```js
Flow.instances.orders.send('a1', { name: 'Peter' }, function(err, response) {
	console.log(response.data, response.duration + ' ms');
});
```

### flowstream.exec(opt, [callback])

Type: `method`

Sends a message to one or more instances with a repository, variables and a timeout.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `opt` | `Object` | yes |  | Options. |
| `callback` | `Function` | no |  | `function(err, response)`; `response` has `uid`, `ref`, `error`, `repo`, `data`, `count`, `cloned`, `duration`, `meta`. |

`opt.id` is an instance id, `@componentid` (all instances of the component) or `#name` (all instances with the component name). Each target must define `instance.message`. The callback runs for each target when its message ends; an unknown target gives `404`.

- `opt.data` {Object}: the data (default `{}`).
- `opt.repo` {Object}: the initial `$.repo`.
- `opt.vars` {Object}: the initial `$.vars`.
- `opt.timeout` {Number}: ms; then the message ends with `error` `408`.
- `opt.uid`, `opt.ref`: returned back in the response.

Example: With a timeout
```js
Flow.instances.orders.exec({ id: '@uppercase', data: { name: 'Peter' }, timeout: 5000 }, function(err, response) {
	if (err === 408)
		console.log('Timeout');
});
```

### flowstream.trigger(id, data)

Type: `method`

Calls the `instance.trigger` handler of instances.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The target. |
| `data` | `Object` | no |  | Passed to `instance.trigger(data)`. |

Returns: `FlowStreamInstance` The instance.

`id` is an instance id, `@componentid` (all instances of the component) or `#name`. Only instances that define `instance.trigger` are called; nothing happens while the FlowStream is paused.

Example: Run all timers
```js
Flow.instances.orders.trigger('@timer', { manual: true });
```

### flowstream.pause([is])

Type: `method`

Pauses or resumes the FlowStream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `is` | `Boolean` | no |  | `true` pauses, `false` resumes. |

Returns: `FlowStreamInstance` The instance.

A paused FlowStream drops new messages and calls `instance.pause(is)` of each instance that defines it. Without an argument it toggles the state.

Example: Pause
```js
Flow.instances.orders.pause(true);
```

### flowstream.reconfigure(id, config)

Type: `method`

Changes the configuration of one instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The instance id. |
| `config` | `Object` | yes |  | The keys to change. |

Returns: `FlowStreamInstance` The instance.

The keys of `config` are merged into the instance configuration, then `instance.configure(config)` is called and the FlowStream saves itself.

Example: Change a field
```js
Flow.instances.orders.reconfigure('a1', { field: 'email' });
```

### flowstream.variables(variables)

Type: `method`

Replaces the variables of the FlowStream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `variables` | `Object` | yes |  | The new variables. |

Returns: `FlowStreamInstance` The instance.

Calls `instance.variables(variables)` and `instance.vary('variables')` of each instance that defines them and saves the FlowStream.

Example: Set variables
```js
Flow.instances.orders.variables({ currency: 'USD', api: 'https://api.example.com' });
```

### flowstream.components(callback)

Type: `method`

Reads the registered components.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(err, components)`. |

Returns: `FlowStreamInstance` The instance.

The callback gets an array with `id`, `name`, `type`, `icon`, `color`, `group`, `version`, `author`, `config`, `inputs`, `outputs`, `readme`, `html`, `css`, `js` and `settings` of each component.

Example: List names
```js
Flow.instances.orders.components(function(err, components) {
	console.log(components.map(c => c.name));
});
```

### flowstream.add(id, html, [callback])

Type: `method`

Registers or replaces a component at runtime.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The component id. |
| `html` | `String` | yes |  | The component source. |
| `callback` | `Function` | no |  | `function(err)`. |

Returns: `FlowStreamInstance` The instance.

`html` is the component file with a `<script total>` block. Existing instances of the component are created again with the new code. Use `flowstream.rem(id, [callback])` to unregister a component and remove its instances.

Example: Add a component
```js
var html = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');
Flow.instances.orders.add('uppercase', html, function(err) {
	err && console.error(err);
});
```

### flowstream.export(callback)

Type: `method`

Exports the current schema of the FlowStream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(err, schema)`. |

Returns: `FlowStreamInstance` The instance.

The callback gets the schema in the `.flow` format: `components` (raw HTML), `design`, `variables`, `sources`, `paused` and the other fields of the loaded schema.

Example: Backup
```js
Flow.instances.orders.export(function(err, schema) {
	F.Fs.writeFile(PATH.root('flowstreams/orders_bk.flow'), JSON.stringify(schema), NOOP);
});
```

### flowstream.stats

Type: `property` · Since: `0.0.96`

Statistics of the FlowStream.

Returns: `Object`

Contains `messages` (messages sent), `pending` (messages in progress), `minutes` (minutes running), `mm` (messages in the last minute), `errors` (count of the last errors, at most 10), `memory` and `paused`. `memory` (heap in bytes) is measured only in a worker or child process. For a FlowStream in a worker the object comes from the worker about every 15 seconds and also contains `pid`; before the first report it is `undefined`.

Example: Read stats
```js
var stats = Flow.instances.orders.stats;
console.log(stats.messages, stats.pending);
```

### flowstream.remove()

Type: `method`

Destroys this FlowStream and removes it from `Flow`.

The same as `Flow.remove(flowstream.id)`. `flowstream.destroy()` only stops the FlowStream and its worker; it stays in `Flow.instances`.

Example: Remove
```js
Flow.instances.orders.remove();
```

### exports.make = function(instance, config) {}

Type: `method`

Creates one instance of the component.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `instance` | `Object` | yes |  | The new instance. |
| `config` | `Object` | yes |  | The instance configuration. |

A component is an HTML file whose `<script total>` block is the server code; `exports` is the component. `make` runs for each instance of the design, with `this` and `instance` both the instance and `config` its configuration (`exports.config` merged with the design `config`). Assign handlers such as `instance.message` here.

The other blocks of the file are for the designer: `<readme>`, `<settings>`, `<style>`, `<script>` (client code), `<body>` and `<template>`.

Example: A complete component
```html
<script total>

	exports.name = 'Uppercase';
	exports.icon = 'ti ti-font';
	exports.config = { field: 'name' };
	exports.inputs = [{ id: 'input', name: 'Input' }];
	exports.outputs = [{ id: 'output', name: 'Output' }];

	exports.make = function(instance, config) {
		instance.message = function($) {
			var data = $.data;
			if (data && typeof(data[config.field]) === 'string')
				data[config.field] = data[config.field].toUpperCase();
			$.send('output', data);
		};
	};

</script>

<readme>
Converts one field of the incoming object to upper case.
</readme>
```

### exports.inputs = [{ id: 'input', name: 'Input' }]

Type: `property`

The inputs and outputs of the component.

Returns: `Array`

`exports.inputs` and `exports.outputs` are arrays of `{ id, name }`. Connections in the design refer to these ids: `connections: { outputid: [{ id: 'instanceid', index: 'inputid' }] }`. A connection to an input that the target component does not declare is removed. A component without inputs only sends (for example a timer); one without outputs ends the messages.

Example: Two outputs
```js
exports.inputs = [{ id: 'input', name: 'Input' }];
exports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];
```

### exports.config = {}

Type: `property`

The default configuration of each instance.

Returns: `Object`

A copy is merged with the `config` of the instance in the design and passed to `exports.make()` as `config`.

Example: Defaults
```js
exports.config = { field: 'name', timeout: 5000 };
```

### exports.name = 'Uppercase'

Type: `property`

The name and the other metadata of the component.

Returns: `String`

Metadata for the designer and for `flowstream.components()`: `exports.name`, `exports.icon`, `exports.color`, `exports.group`, `exports.type`, `exports.version`, `exports.author` and `exports.meta`. The `#name` selector of `send()`, `exec()` and `trigger()` matches `exports.name`. The component id is the key in the `components` object of the schema.

Example: Metadata
```js
exports.name = 'Uppercase';
exports.icon = 'ti ti-font';
exports.color = '#5D9CEC';
exports.group = 'Text';
exports.version = '1';
exports.author = 'Total.js';
```

### exports.npm = ['package']

Type: `property`

NPM packages that the component needs.

Returns: `Array`

The packages are installed with `NPMINSTALL()` before the component is registered.

Example: Use a package
```js
exports.npm = ['qrcode'];

exports.make = function(instance) {
	instance.message = function($) {
		var QR = require('qrcode');
		QR.toDataURL($.data.text, function(err, url) {
			$.send('output', url);
		});
	};
};
```

### instance.message = function($) {}

Type: `delegate`

Receives the messages that arrive at the inputs.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Message` | yes |  | The message. |

`$` is the message; `$.input` is the id of the input. Instead of one handler you can define `instance.message_INPUTID` for one input. A message that no handler takes is destroyed. Each message must end: send it on with `$.send()` or call `$.destroy()`.

Example: Two inputs
```js
exports.make = function(instance) {

	instance.message_a = function($) {
		$.send('output', { from: 'A', data: $.data });
	};

	instance.message_b = function($) {
		$.destroy();
	};
};
```

### instance.send(output, data, [controller])

Type: `method`

Sends data from an output of the instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `output` | `String` | yes |  | The output id. |
| `data` | `Object` | yes |  | The data or a message. |
| `controller` | `Controller` | no |  | Makes `$.user`, `$.body` and the other request properties available. |

Returns: `Number` Count of sent messages.

Creates a new message for each connection of `output`. When `data` is a message, its copies keep the repository and the callbacks of that message. Returns the number of messages sent (`0` when the output has no connection or the FlowStream is paused).

Example: A timer
```js
exports.outputs = [{ id: 'output', name: 'Tick' }];

exports.make = function(instance, config) {
	var timer = setInterval(function() {
		instance.send('output', { ts: new Date() });
	}, config.interval || 5000);

	instance.close = function() {
		clearInterval(timer);
	};
};
```

### instance.newmessage([data])

Type: `method`

Creates a new message owned by this instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | The data. |

Returns: `Message` The message.

Send it with `$.send(output)`. Unlike `instance.send()`, you can add listeners and a repository before sending.

Example: Wait for the end
```js
var msg = instance.newmessage({ id: 1 });
msg.repo.started = Date.now();
msg.on('end', function(msg) {
	instance.status('Last run: ' + (Date.now() - msg.repo.started) + ' ms');
});
msg.send('output');
```

### instance.status(data, [delay])

Type: `method`

Shows a status of the instance in the designer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object/String` | yes |  | The status. |
| `delay` | `Number` | no |  | Delay in ms. |

`data` is any value that the component design (`<body>`, `<script>`) can render. With `delay` (ms) the status is sent once after this time, which avoids flooding the designer. Without arguments the last status is sent again.

Example: Count messages
```js
var count = 0;
instance.message = function($) {
	count++;
	instance.status({ count: count }, 1000);
	$.send('output');
};
```

### instance.dashboard(data)

Type: `method`

Sends data to the dashboard of the designer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | yes |  | Dashboard data. |

Like `instance.status()`, but for dashboard widgets. The last value is kept and sent again when called without arguments.

Example: Temperature
```js
instance.dashboard({ temperature: 21.5 });
```

### instance.throw(err)

Type: `method`

Reports an error of the instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `Error/String` | yes |  | The error. |

The error is stored in the last ten errors of the FlowStream (counted in `stats.errors`), shown in the designer and passed to `Flow.onerror`. `$.throw(err)` does the same and also sets `$.error`. Neither ends the message.

Example: Invalid data
```js
instance.message = function($) {
	if (!$.data.email) {
		$.throw('Missing email');
		$.destroy();
		return;
	}
	$.send('output');
};
```

### instance.config

Type: `property`

The configuration of the instance.

Returns: `Object`

The default `exports.config` merged with the `config` of the design. A change from the designer or `flowstream.reconfigure()` updates the same object and calls `instance.configure(config)`.

Example: Read a value
```js
var field = instance.config.field;
```

### instance.configure = function(config) {}

Type: `delegate`

Runs when the configuration of the instance changes.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `config` | `Object` | yes |  | The new configuration. |

Called after the designer, a new design or `flowstream.reconfigure()` changed `instance.config`. Not called for the first configuration; use `exports.make()` for that.

Example: Restart a timer
```js
var timer;

instance.configure = function(config) {
	timer && clearInterval(timer);
	timer = setInterval(() => instance.send('output', {}), config.interval || 5000);
};

instance.configure(instance.config);
```

### instance.close = function(removed) {}

Type: `delegate`

Runs when the instance stops.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `removed` | `Boolean` | no |  | `true` when the instance is removed, not only re-created. |

Called when the instance is removed from the design, its component is replaced or removed, or the FlowStream is unloaded. Clear timers and close connections here. Other optional handlers: `instance.init()` (once, after the design is created), `instance.refresh()` (after each design change), `instance.pause(is)` and `instance.variables(variables)`.

Example: Clean up
```js
instance.close = function() {
	clearInterval(timer);
};
```

### instance.trigger = function(data) {}

Type: `delegate`

Runs when the instance is triggered.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | The trigger data. |

Called by `flowstream.trigger()` and by the trigger button of the designer. Typically it starts a new message.

Example: Start on demand
```js
instance.trigger = function() {
	instance.send('output', { ts: new Date() });
};
```

### instance.replace(str, [data], [encoding])

Type: `method`

Replaces `{key}` placeholders with variables.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `str` | `String/Object` | yes |  | The text. |
| `data` | `Object` | no |  | Additional values. |
| `encoding` | `String/Function` | no |  | How to encode each value. |

Returns: `String` The text with values.

Each `{key}` (or `{{key}}`) is looked up in the FlowStream variables, then `variables2`, then the secrets, then `{hostname}`, then in `data` (nested keys such as `{user.name}` work). Unknown keys stay as they are. `encoding` is `'url'`, `'json'`, `'querify'` or `function(value, key)`. An object as `str` replaces all its string values.

Example: A URL
```js
var url = instance.replace('{api}/orders/{id}/', { id: 15 }, 'url');
```

### instance.save()

Type: `method`

Saves changes of the instance and redraws it in the designer.

Use it after you change `instance.config` or other design properties in code. The FlowStream then emits `save`.

Example: Remember a value
```js
instance.config.last = Date.now();
instance.save();
```

### instance.main

Type: `property`

The FlowStream engine that runs the instance.

Returns: `FlowStream`

Useful properties: `instance.main.variables` (the variables), `instance.main.paused`, `instance.main.stats` and `instance.main.id`. `instance.instances` holds all instances of the design and `instance.components` all registered components. `instance.id` is the instance id, `instance.component` the component id and `instance.module` the component.

Example: Read a variable
```js
var currency = instance.main.variables.currency;
```

### $.data

Type: `property`

The data of the message.

Returns: `Object`

Any value. Each connection gets its own copy of objects and Buffers when cloning is on (the default). The request properties `$.user`, `$.body`, `$.query`, `$.params`, `$.headers`, `$.ip` and `$.files` exist only when the message was started with a controller.

Example: Read and change
```js
instance.message = function($) {
	$.data.total = $.data.price * $.data.count;
	$.send('output');
};
```

### $.send([output], [data], [clone])

Type: `method`

Sends the message on from an output of the current instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `output` | `String` | no |  | The output id. |
| `data` | `Object` | no |  | New data. |
| `clone` | `Boolean` | no | `cloning` | Clones the data for each connection. |

Returns: `Number` Count of sent messages.

Without `output` it is sent from all outputs. Without `data` it keeps its data. When nothing is connected to the output, the message is destroyed. `clone` overrides the `cloning` option of the FlowStream for this call. Returns the number of sent messages.

Example: Route by a condition
```js
instance.message = function($) {
	$.send($.data.valid ? 'ok' : 'error');
};
```

### $.destroy()

Type: `method`

Ends the message.

Call it in the last component of a chain. When the last copy of a message ends, `end` is emitted and the callback of `flowstream.send()` or `flowstream.exec()` runs. `$.end()` is an alias.

Example: Last component
```js
instance.message = function($) {
	console.log($.data);
	$.destroy();
};
```

### $.repo

Type: `property`

An object shared by the message and all its copies.

Returns: `Object`

Use it to pass values along the whole chain without changing `$.data`. It is returned as `repo` to the callback of `flowstream.send()` and `flowstream.exec()`. `$.vars` is another shared object.

Example: Keep a value
```js
// first component
$.repo.started = Date.now();
$.send('output');

// last component
$.data.duration = Date.now() - $.repo.started;
$.destroy();
```

### $.variables(str, [data], [encoding])

Type: `method`

Replaces `{key}` placeholders with variables and message values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `str` | `String/Object` | yes |  | The text. |
| `data` | `Object` | no | `the message` | Values. |
| `encoding` | `String/Function` | no |  | `url`, `json`, `querify` or a function. |

Returns: `String`

The same as `instance.replace()`, but without `data` the message itself is used, so `{data.id}` reads `$.data.id`. `$.replace()` is an alias.

Example: Build a URL
```js
var url = $.variables('{api}/users/{data.id}/', null, 'url');
```

### $.on(name, callback)

Type: `method`

Listens to events of the message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The event. |
| `callback` | `Function` | yes |  | `function(msg)`. |

Returns: `Message` The message.

Events: `end` (the last copy ended), `destroy` (same moment), `terminate` (any copy ended), `message` (a copy reached an instance), `timeout`. The listeners are shared by all copies. `$.once()` and `$.off()` exist too.

Example: Measure the chain
```js
var msg = instance.newmessage(data);
msg.on('end', function(msg) {
	console.log('Done', msg.data);
});
msg.send('output');
```

### $.timeout([callback], time)

Type: `method`

Limits how long each next step of the message may take.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | `function(msg)`. |
| `time` | `Number` | yes |  | Milliseconds. |

Returns: `Message` The message.

Every copy sent after this call ends with `$.error = 408` when it is not processed within `time` ms; `callback` is called with that copy. `$.totaltimeout([callback], time)` limits the whole chain instead.

Example: Five seconds for the whole chain
```js
$.totaltimeout(function(msg) {
	instance.throw('Timeout');
}, 5000);
$.send('output');
```
