---
title: FlowStream
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/flowstream/
updated: 2026-11-18T16:57:29.576Z
---

# FlowStream

> The Flow global, running FlowStreams, components, instances, messages and the flow5 command.

Methods, properties and events of the `Flow` global, of a running FlowStream (`Flow.instances[id]`), of component definitions, component instances and messages, plus the `flow5` command. For an introduction with examples read the guide [FlowStream](../../guides/flowstream/).

## API

### Flow / FlowStream

Type: `class`

The global object of the FlowStream engine.

`Flow` and `FlowStream` are the same object. It loads flows, keeps them in `Flow.instances` and emits the events `load`, `save` and `remove`. The running flows are objects described here as `flowstream`.

Example: List running flows
```js
for (var id in Flow.instances)
	console.log(id, Flow.instances[id].stats);
```

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

Type: `method`

Starts a FlowStream from its schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `Object` | yes |  | The FlowStream schema |
| `callback` | `Function` | no |  | `function(err, flowstream)` |

Missing keys get defaults: a random `id`, `name` = `id`, empty `components`, `design`, `sources` and `variables`. When a FlowStream with the same `id` is running, it is reloaded with the new schema instead. The callback runs when the components and the design are loaded. See [FlowStream](../../guides/flowstream/) for the keys of the schema.

Example: Load a file
```js
var schema = (await F.readfile(PATH.root('orders.json'), 'utf8')).parseJSON();
Flow.load(schema, function(err, flowstream) {
	err && console.error(err);
});
```

Example: Run in a worker thread
```js
Flow.load({ id: 'import', worker: 'worker', components: {}, design: {} });
```

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

Type: `method`

Loads all .flow files of a directory.

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

Reads every `*.flow` file (a JSON schema) of the directory and loads it with `Flow.load()`. Files with `-bk` or `_bk` in the name are skipped. The directory defaults to `/flowstreams/` in the app root. The framework calls it once at start, so you only need it for other directories. The `index.flow` file of a plugin is loaded with the plugin.

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

### Flow.reload(schema, [restart])

Type: `method`

Applies a new schema to a running FlowStream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `Object` | yes |  | The new schema |
| `restart` | `Boolean` | no | `false` | Restart the worker |

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

The schema must have the `id` of a running FlowStream. The components and the design are replaced in place and removed components are unregistered. With `restart` (workers only) the worker is ended and started again with its current schema; the new schema is not applied. Returns `false` when no FlowStream has this id.

### Flow.remove(id)

Type: `method`

Stops and removes a FlowStream.

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

Closes all instances, ends the worker, removes the FlowStream from `Flow.instances` and emits `remove`.

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

### Flow.restart(id)

Type: `method`

Restarts a FlowStream that runs in a worker.

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

Returns: `Boolean` `true` when found

Ends the worker thread or the child process; it is started again automatically with the current schema after a second. Returns `true` when the FlowStream exists (otherwise `undefined`). A FlowStream in the main process is ended and not started again.

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

Type: `method`

Connects the Total.js Flow editor to a FlowStream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | FlowStream id |
| `websocket` | `WebSocket` | yes |  | The WebSocket of the route |
| `verify` | `Function` | no |  | `function(client, next)` |
| `check` | `Function` | no |  | `function(client, message)` returns `true` or an error |

Pass the WebSocket object of a `SOCKET` route. `verify(client, next)` can accept a new client before it gets the flow (call `next()`), and `check(client, message)` can block single commands: return `true` to allow, or an error text. An unknown id closes the WebSocket.

Example: Route for the editor
```js
exports.install = function() {
	ROUTE('+SOCKET /flowstreams/{id}/ <8MB', function($) {
		$.autodestroy();
		Flow.socket($.params.id, $, null, function(client, msg) {
			return client.user.sa ? true : 'Only for admins';
		});
	});
};
```

### Flow.notify($, id)

Type: `method`

Passes an HTTP request to the notify delegate of an instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller` | yes |  | The controller of the route |
| `id` | `String` | yes |  | `flowid-instanceid` |

`id` is `flowid-instanceid` (more `-` parts become `params`). The `notify` delegate of the instance gets `{ id, method, headers, query, body, url, ip, params }`, and the editor gets the same object. Then the response redirects to `?REDIRECT=url`, sends a small page that closes the window (for browsers) or a success JSON.

Example: Routes
```js
ROUTE('GET /notify/{id}/', $ => Flow.notify($, $.params.id));
ROUTE('POST /notify/{id}/ <1MB', $ => Flow.notify($, $.params.id));
```

Example: In a component
```js
instance.notify = function(data) {
	instance.send('output', data.body);
};
```

### Flow.test(name, source, [config], init)

Type: `method`

Loads one component in a test flow.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Component id |
| `source` | `String` | yes |  | Source of the component |
| `config` | `Object` | no | `{}` | Configuration of the instance |
| `init` | `Function` | yes |  | `function(test)` |

Creates a flow with the component (instance id `component`) and a helper instance connected to all its inputs and outputs. `init(test)` gets the `Test` object:

| Member | Use |
| --- | --- |
| `test.send(input, data)` | Sends data to an input of the component (alias `input`) |
| `test.message = function($, data)` | Receives what the component sends to its outputs |
| `test.status = function(status)` | Receives the status of the component |
| `test.debug = function(...)` | Receives `instance.debug()` calls |
| `test.configure = function(config)` | Called after a reconfiguration |
| `test.trigger(data)` | Runs the `trigger` delegate |
| `test.reconfigure(config)` | Changes the configuration |
| `test.variables(obj)` | Sets the variables |
| `test.assert(ok, text)`, `test.ok(text)`, `test.fail(text)` | Print the result; `fail` throws |

An error in the flow ends the process.

Example: Test
```js
var source = await F.readfile(PATH.root('components/uppercase.html'), 'utf8');
Flow.test('uppercase', source, { field: 'name' }, function(test) {
	test.message = function($, data) {
		test.assert(data.name === 'PETER');
	};
	test.send('input', { name: 'Peter' });
});
```

### Flow.instances

Type: `property`

The running FlowStreams by id.

Returns: `Object`

An object: FlowStream id → `flowstream` object. `Flow.db` holds the last schema of each FlowStream (updated on every save).

Example: Get one
```js
var flowstream = Flow.instances.orders;
```

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

Type: `event`

A FlowStream is loaded.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `flowstream` | `Object` | yes |  | The running FlowStream |
| `schema` | `Object` | yes |  | The schema |

Emitted after `Flow.load()` has loaded the components and the design.

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

Type: `event`

The schema of a FlowStream has changed.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `Object` | yes |  | The whole schema |

Emitted about 5 seconds after a change in the editor or a call of `instance.save()`. The schema contains `id`, `name`, `components`, `design`, `variables`, `sources`, `paused` and the other keys. Store it yourself, for example in a `.flow` file. Flows with `readonly: true` are not saved.

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

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

Type: `event`

A FlowStream was removed.

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

Emitted by `Flow.remove()` with the last schema of the removed FlowStream.

### Flow.on('stats', function(id, stats) {})

Type: `event`

Counters of a FlowStream that runs in a worker.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | FlowStream id |
| `stats` | `Object` | yes |  | Counters |

Emitted every 15 seconds for each FlowStream in a worker thread or child process. `stats` has `paused`, `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` and `pid`.

### ON('flowstream', function(flowstream) {})

Type: `event` · Since: `0.0.16`

A FlowStream has started.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `flowstream` | `Object` | yes |  | The running FlowStream |

Global framework event emitted when a FlowStream is created, also after the automatic restart of a worker.

Example: Log
```js
ON('flowstream', function(flowstream) {
	console.log('FlowStream', flowstream.id);
});
```

### ON('flowstream_error', function(meta) {})

Type: `event`

An error occurred in a FlowStream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `meta` | `Object` | yes |  | Error details |

Errors are printed to the console and emitted as this global event. `meta` has `id` and `name` (of the FlowStream), `error`, `source`, `instanceid` and `componentid`.

Example: Audit errors
```js
ON('flowstream_error', function(meta) {
	console.log(meta.name, meta.componentid, meta.error);
});
```

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

Type: `type`

The object that describes a FlowStream.

`components` maps a component id to its source code. `design` maps an instance id to `{ component, config, connections, x, y, note, tab }`; `connections` maps an output id to an array of `{ id, index }` (target instance and its input). Further keys: `variables`, `sources` (TMS), `worker`, `memory` (with `worker`: the heap limit of the worker thread or the child process in MB), `proxypath`, `cloning`, `paused`, `readonly`, `import`, `initscript`, `env`, `directory` and `asfiles` (`true` compiles the components into files in `/tmp/`). Descriptive keys like `icon`, `color`, `author`, `version` and `readme` are shown in the editor.

Example: Two connected instances
```json
{
	"id": "demo",
	"name": "Demo",
	"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": {}
}
```

### schema.proxytimeout

Type: `config` · Since: `0.0.18`

Timeout of the proxy of a worker with proxypath.

Returns: `Number`

Milliseconds for the timeout of the proxy that forwards requests under `proxypath` to the worker. It is applied when the schema is loaded again into the running FlowStream (`Flow.load()` with the same id or `Flow.reload()`).

Example: Reload with a timeout
```js
Flow.reload({ id: 'api', worker: 'worker', proxypath: '/api/', proxytimeout: 10000, components: components, design: design });
```

### flowstream.stats

Type: `property`

Counters of the FlowStream.

Returns: `Object`

`messages` (total), `pending`, `memory` (bytes), `minutes` (uptime), `errors` (the number of the last errors, at most 10), `mm` (messages in the last minute) and `paused`. For a flow in the main process, `online` is the number of connected editors. For a worker the values arrive every 15 seconds.

### flowstream.trigger(id, [data])

Type: `method`

Runs the trigger delegate of instances.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | Instance id, `@componentid` or `#name` |
| `data` | `Object` | no |  | Passed to the delegate |

Returns: `Object` The flowstream

Calls `instance.trigger(data)` of the instance `id`, of all instances of a component (`@componentid`) or of a component name (`#name`). Nothing runs while the flow is paused.

Example: Start all timers
```js
Flow.instances.orders.trigger('@timer');
```

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

Type: `method`

Sends data into an instance and waits for the result.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | Target, optionally with `/input` |
| `data` | `Object` | yes |  | Payload |
| `callback` | `Function` | no |  | `function(err, response)` |

Creates a new message with `data` and passes it to the `message` delegate of the instance (`id`, `@componentid` or `#name`; the first match). Add `/inputid` to set `$.input`. The callback runs when the message and all its clones are ended, with `{ error, repo, data, count, cloned, duration, meta: { id, component } }`.

Example: Call a flow from an API
```js
NEWACTION('Orders/process', {
	action: function($, model) {
		Flow.instances.orders.send('@order/input', model, function(err, response) {
			if (err)
				$.invalid(err);
			else
				$.callback(response.data);
		});
	}
});
```

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

Type: `method`

Sends a message to all matching instances.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `opt` | `Object` | yes |  | Options |
| `callback` | `Function` | no |  | `function(err, response)` |

Like `send()`, but for every matching instance. `opt.id` is the target (`id`, `@componentid` or `#name`), `opt.data` the payload, `opt.vars` and `opt.repo` the `$.vars` and `$.repo`, `opt.timeout` a timeout in ms (the message ends with error `408`). `opt.uid` and `opt.ref` come back in the response. The callback runs for each target (for a flow in a worker only for the first one), or with `404` when nothing matches.

Example: Exec with a timeout
```js
Flow.instances.orders.exec({ id: '#Validate', data: model, timeout: 5000, uid: model.id }, function(err, response) {
	console.log(response.uid, response.data);
});
```

### flowstream.pause([is])

Type: `method`

Pauses or resumes the FlowStream.

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

Returns: `Object` The flowstream

A paused flow does not deliver messages. Without the argument the state is toggled. The `pause` delegate of each instance is called.

### flowstream.variables(obj)

Type: `method`

Replaces the variables of the FlowStream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | New variables |

Returns: `Object` The flowstream

Calls the `variables` delegate of each instance (and `vary('variables')` for a flow in the main process), sends the variables to the editor and saves the flow.

Example: Rotate a token
```js
Flow.instances.orders.variables({ token: newtoken });
```

### flowstream.reconfigure(id, config)

Type: `method`

Changes the configuration of an instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | Instance id |
| `config` | `Object` | yes |  | Values to merge |

Returns: `Object` The flowstream

The values are merged into `instance.config`, the `configure` delegate is called, the editor is updated and the flow is saved.

### flowstream.export(callback)

Type: `method`

Reads the current schema.

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

The callback gets the whole schema, the same object as the `save` event.

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

### flowstream.restart()

Type: `method`

Restarts a FlowStream that runs in a worker.

Closes the editor connections and ends the worker; it starts again automatically with the current schema.

### flowstream.remove()

Type: `method`

Removes the FlowStream.

The same as `Flow.remove(flowstream.id)`.

### flowstream.edit([url])

Type: `method` · Since: `0.0.16`

Connects the FlowStream to a remote editing proxy.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no | `'wss://flow.totaljs.com/{0}/'` | Proxy WebSocket URL |

Returns: `WebSocketClient` The client

Opens a WebSocket client to the URL (`{0}` is replaced by the FlowStream id) and lets the editor work through it, so the application does not need a public WebSocket route. A previous connection is closed. Returns the WebSocket client.

Example: Remote editing
```js
Flow.instances.orders.edit();
```

### exports.* in <script total>

Type: `type`

The definition of a FlowStream component.

The server part of the component sets properties of `exports`:

| Property | Meaning |
| --- | --- |
| `name`, `icon`, `color`, `group`, `version`, `author` | Shown in the editor |
| `type` | For example `input`, `output` or `config`; these appear in `io()` listings |
| `inputs`, `outputs` | Arrays of `{ id, name }` |
| `config` | Default configuration of new instances |
| `npm` | NPM packages installed before registering |
| `permissions`, `meta` | Custom data passed to the editor |
| `make` | `function(instance, config)` for each instance |
| `install`, `uninstall` | `function(component)` when the component is registered and removed |
| `call` | `function(data, callback)` called by the editor with `@componentid` |

The other parts of the file: `<settings>` (the configuration form), `<body>`, `<style>`, `<script>` (editor code), `<readme>`, `<template>` and `<schema>`.

Example: Minimal component
```html
<script total>
	exports.name = 'Print';
	exports.inputs = [{ id: 'input', name: 'Input' }];
	exports.make = function(instance) {
		instance.message = function($) {
			console.log($.data);
			$.end();
		};
	};
</script>
```

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

Type: `method`

Creates an instance of the component.

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

Runs for each instance placed on the canvas, and again when the component code changes. `config` is `instance.config`. Assign the delegates of the instance here.

Example: Interval
```js
exports.make = function(instance, config) {
	var timer;
	instance.configure = function() {
		clearInterval(timer);
		timer = setInterval(() => instance.send('output', { ts: NOW }), (instance.config.interval || 10) * 1000);
	};
	instance.close = () => clearInterval(timer);
	instance.configure();
};
```

### exports.inputs / exports.outputs

Type: `property`

The inputs and outputs of a component.

Returns: `Array`

Arrays of `{ id, name }`. The `id` is what `$.input` contains and what `$.send(id)` and `instance.send(id)` use. An instance can override them with its own `inputs` / `outputs`.

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

### instance

Type: `type`

One placed instance of a component.

The first argument of `exports.make()`. Properties: `id`, `component` (component id), `config`, `cache`, `main` (the flow engine), `module` (the component), `env`, `stats` (`pending`, `input`, `output`, `duration`, `destroyed`), `instances` (all instances of the flow) and `components`.

Delegates you can assign: `message($)`, `message_INPUTID($)`, `configure(config)`, `close()`, `init()` (after the first load), `refresh()` (after each change of the design), `trigger(data)`, `notify(data)`, `call(data, callback)`, `service(minutes)` (every minute), `pause(is)`, `variables(obj)`, `secrets(obj)` and `vary(type)`.

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

Type: `delegate`

Receives a message on an input.

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

`$.input` is the input id. `instance.message_INPUTID` receives messages of one input only; when both exist, both are called. A message that is not sent further must be ended with `$.end()`.

Example: Route by input
```js
instance.message = function($) {
	if ($.input === 'reset') {
		count = 0;
		$.end();
	} else {
		count++;
		$.send('output', { count: count });
	}
};
```

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

Type: `delegate`

The configuration has changed.

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

Called after a change in the editor or a call of `reconfigure()`. `instance.config` already contains the new values.

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

Type: `delegate`

The instance is being removed.

Called when the instance is removed from the design, the component is unregistered or the flow ends. Clear timers and close connections here.

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

Type: `method`

Starts a new message from an output or from all outputs.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `output` | `String` | yes |  | Output id, or `null` for all outputs |
| `data` | `Object` | no |  | Payload |

Returns: `Number` Count of sent messages

Sends `data` to every instance connected to the output. With `output` `null` it sends to all outputs. For the second and next connection the data are cloned (unless `cloning: false`). Returns the number of sent messages; `0` when nothing is connected or the flow is paused.

Example: From a timer
```js
setInterval(() => instance.send('output', { ts: NOW }), 1000);
```

Example: All outputs
```js
instance.send(null, { ts: NOW });
```

### instance.newmessage([data])

Type: `method`

Creates a message without sending it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | Payload |

Returns: `Message` A new message

The message belongs to the instance; set `$.repo`, listen to `end` and then call `$.send(output)`.

Example: Wait for the end
```js
var msg = instance.newmessage({ id: 1 });
msg.on('end', function($) {
	console.log('Done', $.data);
});
msg.send('output');
```

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

Type: `method`

Sets the status shown under the instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | Any JSON value |
| `delay` | `Number` | no |  | Throttle in ms |

The status is sent to the editor and emitted as `status` on `instance.main`. With `delay` (ms) many calls are merged into one update. Without arguments the last status is sent again.

Example: Counter
```js
instance.status({ count: count }, 1000);
```

### instance.dashboard([data])

Type: `method`

Sends data to the dashboard of the editor.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | Any JSON value |

The data are kept and sent to the editor; without arguments the last data are sent again.

### instance.throw(error)

Type: `method`

Reports an error of the instance.

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

The error is added to the last 10 errors of the flow (`instance.main.errors`), shown in the editor, printed to the console and emitted as `ON('flowstream_error')`. `$.throw(error)` does the same and sets `$.error`.

Example: In a callback
```js
RESTBuilder.GET(config.url).callback(function(err, response) {
	if (err) {
		instance.throw(err);
		$.end();
	} else
		$.send('output', response);
});
```

### instance.debug(a, [b], [c], [d])

Type: `method`

Emits a debug event.

Emits `debug` on `instance.main` with the instance and the arguments. `Flow.test()` passes it to `test.debug`.

### instance.save([redraw])

Type: `method`

Saves the instance after a change from code.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `redraw` | `Boolean` | no | `true` | Redraw the instance in the editor |

Use it after you change `instance.config`, `x`, `y`, `note`, `inputs` or `outputs` in the code. The flow is saved (the `save` event follows after about 5 seconds) and, unless `redraw` is `false`, the editor redraws the instance.

Example: Remember a value
```js
instance.config.lastid = $.data.id;
instance.save();
```

Example: Without redraw
```js
instance.config.counter++;
instance.save(false);
```

### instance.reconfigure(config)

Type: `method`

Changes the configuration of this instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `config` | `Object` | yes |  | Values to merge |

The same as `flowstream.reconfigure(instance.id, config)` called from the component.

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

Type: `method`

Replaces {variables} in a text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String|Object` | yes |  | Text with placeholders |
| `data` | `Object` | no |  | Extra values |
| `encoding` | `String|Function` | no |  | Encoding of the values |

Returns: `String` The text

A `{name}` (or `{{name}}`) takes the value from the variables of the flow, the global variables, the secrets, `{hostname}` (origin plus `proxypath`) or the `data` object (nested keys with dots). `encoding` can be `url`, `json`, `querify` or a `function(value, key)`. An object replaces each string value. In a message use `$.variables()` (alias `$.replace()`), where `data` defaults to the message.

Example: URL
```js
var url = instance.replace('https://api.example.com/{token}/orders/?id={id}', { id: 5 }, 'url');
```

### instance.cache

Type: `property`

An in-memory object for runtime data of the instance.

Returns: `Object`

A plain object in memory, kept by the flow for the instance id: when the instance is initialized again (for example when its component is updated), it gets the same object back. It is not saved, so it is empty after a restart.

Example: Last value
```js
instance.message = function($) {
	instance.cache.last = $.data;
	$.send('output');
};
```

### instance.repo

Type: `property` · Since: `0.0.17`

Persistent data of the instance stored in the design.

Returns: `Object`

An object saved in the schema together with the instance. It survives a reload and a restart, and the editor keeps it unchanged when it saves the design. Call `instance.save()` after a change.

Example: Keep a cursor
```js
instance.repo.lastid = $.data.id;
instance.save();
```

### instance.activity(key, name, [progress])

Type: `method` · Since: `0.0.19`

Reports a running activity of the instance.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | Activity id |
| `name` | `String` | yes |  | Description |
| `progress` | `Number` | no |  | Percent |

Creates or updates the activity `key`, shows it in the editor and emits `activity` on `instance.main` with `(instance, key, name, progress)`. An empty `name` or `progress` `100` removes it. Activities of instances removed from the design are dropped.

Example: Progress
```js
instance.activity('sync', 'Synchronizing', 40);
// ...
instance.activity('sync', 'Synchronizing', 100);
```

### instance.main

Type: `property`

The flow engine of the instance.

Returns: `FlowStream`

Useful members: `variables`, `secrets`, `stats` (with `online`, the number of connected editors), `errors`, `paused`, `env`, `activities`, `find(id)` (an instance), `instances()` (ready instances), `send('ID__OUTPUT', data)`, `trigger('ID__INPUT', data)` (sends a new message to an input), `pause(is)`, `save()` and `restart()` (restarts the worker of the flow; in the main process it asks the Total.js process manager to restart the application). It emits `status`, `debug`, `activity`, `message`, `end` and `reset` events.

Example: Send to another instance
```js
instance.main.trigger('b1__input', { id: 1 });
```

### instance.main.on('reset', function() {})

Type: `event`

The errors of the flow were reset.

Emitted by the flow engine when the editor sends the reset command: the last errors of the flow (`instance.main.errors`) are cleared first, then the event runs without arguments. In a flow that runs in a worker it is emitted inside the worker. The engine stays when an instance is created again, so remove the listener in `instance.close`.

Example: Reset a counter
```js
exports.make = function(instance) {

	instance.cache.count = 0;

	var onreset = function() {
		instance.cache.count = 0;
		instance.status({ count: 0 });
	};

	instance.main.on('reset', onreset);

	instance.close = function() {
		instance.main.off('reset', onreset);
	};

};
```

### $

Type: `class`

A message travelling through the flow.

Properties: `data`, `repo` (shared by all clones), `vars`, `input`, `output`, `from`/`fromid`, `to`/`toid` (instances), `instance`, `main`, `id`, `count`, `duration`, `error`, `controller`, and from the controller `user`, `body`, `query`, `params`, `headers`, `ip`, `language`.

Methods: `send()`, `end()` (alias `destroy()`), `rewrite(data)`, `clone()`, `variables()`, `timeout()`, `status()`, `dashboard()`, `debug()`, `throw()` and `on(name, fn)`. Events: `end` (the message and all clones are ended), `timeout` and `message`.

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

Type: `method`

Sends the message to an output or to all outputs.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `output` | `String` | yes |  | Output id, or `null` for all outputs |
| `data` | `Object` | no |  | New payload |
| `clone` | `Boolean` | no | `the `cloning` of the flow` | Clone the data |
| `check` | `Function` | no |  | `function(from, to, output, input)` returns a Boolean |

Returns: `Number` Count of targets

Sends a clone of the message to every instance connected to the output. With `output` `null` it sends to all outputs: an output without a ready target is skipped, the other outputs still get the message, and the message ends once, when all its clones end. `data` replaces the payload; `clone` (default: the `cloning` of the flow) deep-copies object data for each target. `check(from, to, output, input)` is called for each target of a named output (`from` and `to` are instances); return `false` to skip the target. Returns the number of targets; with `0` the message ends.

Example: Pass on
```js
instance.message = function($) {
	$.data.checked = true;
	$.send('output');
};
```

Example: Skip some targets
```js
$.send('output', null, null, function(from, to, output, input) {
	return to.component !== 'debug';
});
```

Example: All outputs
```js
instance.message = function($) {
	$.send(null);
};
```

### $.end()

Type: `method`

Ends the message.

Call it when the message is not sent further. When the message and all its clones are ended, its `end` event fires (and the `callback` of `flowstream.send()`).

Example: Stop here
```js
instance.message = function($) {
	save($.data);
	$.end();
};
```

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

Type: `method`

Sets a timeout for the next instances.

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

Returns: `Message`

Each clone sent after this call must be processed within `time` ms; otherwise it ends with `$.error = 408` and the callback runs. `$.totaltimeout([callback], time)` limits the whole message instead.

Example: Timeout
```js
$.timeout(function($) {
	instance.throw('Timeout');
}, 5000);
$.send('output');
```

### flow5 [path or URL ...] [port]

Type: `command`

Runs FlowStream schemas from the command line.

Loads each JSON file (one schema, or an object with several schemas) or HTTPS URL, starts an HTTP server on the port (default `8000`) with the route `SOCKET /flowstreams/{id}/` and the `/notify/{id}/` routes, and prints the editor link for each flow. Changes from the editor are written back to the local files. Without arguments it prints help.

Example: Two flows on port 8001
```bash
flow5 orders.json import.json 8001
```
