Plugins and components
The plugin definition, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() with its Component, Instance and Message objects, NPMINSTALL(), REQUIRE() and IMPORT().
On this page
Properties of a plugin index.js, the plugin files, PLUGINS, COMPONENTATOR(), server components compiled with NEWCOMPONENT() (the component, its instances and messages) and the loaders NPMINSTALL(), REQUIRE() and IMPORT(). For an introduction with examples read the guide Plugins and components.
API
type
plugins/{id}/index.js
A folder in plugins/ with an index.js file, loaded at start.
plugins/{id}/index.jsEvery folder in plugins/ with an index.js file is a plugin; the folder name is the plugin id. A folder without index.js is skipped with all its subfolders, and so are folders whose name contains -bk or _bk. Total.js requires index.js, stores its exports in PLUGINS[id], sets exports.id when missing and calls exports.install(). A config file in the folder is merged into CONF. The subfolders controllers/, actions/, schemas/, models/, definitions/, extensions/ and middleware/ are loaded like the folders of the application. An index.flow file is loaded as a FlowStream.
// plugins/contacts/index.js
exports.name = 'Contacts';
exports.icon = 'ti ti-address-book';
exports.permissions = ['contacts'];
exports.install = function() {
ROUTE('+API ? contacts_list --> Contacts/list');
};
delegate
exports.install = function() {}
Called once when the plugin is loaded.
exports.install = function() {}Register routes, events and other definitions of the plugin here. It runs during the loading of the application, in the same pass as the files of controllers/, definitions/ and the other folders, so use ON('ready') when you need everything to be loaded first.
exports.install = function() {
ROUTE('+GET /admin/contacts/', function($) {
$.view('#contacts/views/index');
});
ON('ready', function() {
// all plugins are loaded
});
};
property
exports.id
The id of the plugin.
exports.idReturns String
When index.js does not define it, Total.js sets it to the name of the plugin folder. PLUGINS uses the folder name as the key in both cases.
property
exports.name
A human readable name of the plugin.
exports.nameReturns String
Total.js writes it, with the id and the permissions, to the source map of the application in debug mode. Your UI can read it from PLUGINS to build a menu.
exports.name = 'Orders';
property
exports.permissions
The permissions the plugin defines.
exports.permissionsReturns Array
An array of strings or of objects with an id property (and anything else you need, such as name). The ids are written, joined with commas, to the source map in debug mode. Read the array from PLUGINS to offer the permissions in a user editor and check them with the permissions option of your actions (see Authorization).
exports.permissions = [
{ id: 'orders', name: 'Orders' },
{ id: 'orders_remove', name: 'Remove orders' }
];
property
exports.icon, exports.visible, exports.position, ...
Your own properties of a plugin.
exports.icon, exports.visible, exports.position, ...Total.js does not read any other property of index.js. Properties such as icon, position or visible are a convention for your administration UI, which reads them from PLUGINS.
exports.icon = 'ti ti-truck';
exports.position = 5;
exports.visible = function(user) {
return user.sa || user.permissions.includes('orders');
};
property
PLUGINS
All loaded plugins by id.
PLUGINSReturns Object id: exports
An object whose keys are plugin ids and whose values are the exports of their index.js. It is filled during the loading of the application.
ON('ready', function() {
for (var id in PLUGINS)
console.log(id, PLUGINS[id].name);
});
config
plugins/{id}/config
since 0.0.16
Configuration file of a plugin.
plugins/{id}/configA config file in the folder of a plugin is read before the scripts of the application and the plugins run, after the main config. It has the same format as the main file and its keys are merged into CONF; a key that is also in the main file is overwritten.
shop_currency : EUR
shop_pagesize : 20
type
plugins/{id}/index.flow
since 0.0.19
A FlowStream loaded with the plugin.
plugins/{id}/index.flowAn index.flow file (a FlowStream export in JSON) in the folder of a plugin is read and started after the files of the application and the index.js of the plugin, before the other files of the plugin; the instance is created asynchronously and is stored in PLUGINS[id].flowstream once it is ready. The FlowStream gets the plugin id as id, the translated plugin name (or the id) as name and the plugin folder as directory. The instance is stored in PLUGINS[id].flowstream; errors are logged as Plugin.<id>.flowstream. See FlowStream.
property
PLUGINS[id].flowstream
since 0.0.19
The FlowStream instance loaded from index.flow.
PLUGINS[id].flowstreamReturns FlowStream
Set when the index.flow file of the plugin has been loaded.
method
PATH.plugins([path])
Returns a path in the plugins folder.
PATH.plugins([path])| Parameter | Type | Description |
|---|---|---|
path? |
String |
A relative path such as "shop/data.json" |
Returns String Absolute path
Without an argument it returns the absolute path of plugins/; with a path it joins it. With a path, the plugins folder is created when it does not exist.
var filename = PATH.plugins('shop/data/countries.json');
F.Fs.readFile(filename, 'utf8', function(err, data) {
// ...
});
type
controller.view('#{id}/path')
Renders a view from a plugin folder.
controller.view('#{id}/path')A view name that starts with # is relative to plugins/: #shop/views/index renders plugins/shop/views/index.html. The same prefix works in TEMPLATE('#shop/templates/order.html'), which adds .html when the name does not contain it.
exports.install = function() {
ROUTE('+GET /admin/shop/', function($) {
$.view('#shop/views/index');
});
};
method
COMPONENTATOR(name, components, [removeprev], [attrs])
Downloads a bundle of UI components from Componentator.
COMPONENTATOR(name, components, [removeprev], [attrs])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the bundle; used in the file name and as the key in REPO |
components |
String |
Comma separated component names |
removeprev? |
Boolean |
Delete older bundles with the same name Default: true |
attrs? |
String |
Extra URL-encoded fields sent with the download request Default: '' |
Downloads one minified file with the listed jComponent components from https://componentator.com/download/ into public/ui-<name>-<hash>.min.js (public/ui-<hash>.min.js with removeprev set to false). The hash is computed from components, and the file is downloaded only when it does not exist. With removeprev (default), older ui-<name>-* files are deleted. The URL of the bundle is stored in REPO[name]. Errors are logged. When removeprev is a string, it is taken as attrs.
// definitions/ui.js
COMPONENTATOR('ui', 'exec,locale,input,box,validate,loading,notify,datagrid', true);
<script src="@{REPO.ui}"></script>
event
ON('componentator', function(meta) {})
Emitted before COMPONENTATOR() builds the file name.
ON('componentator', function(meta) {})| Parameter | Type | Description |
|---|---|---|
meta |
Object |
{ name, components } |
meta contains name and components. You can change both, for example to add a component to every bundle; the new values are used for the file name, REPO and the download.
ON('componentator', function(meta) {
meta.components += ',errorhandler';
});
method
NEWCOMPONENT(html, [callback])
Compiles a server component.
NEWCOMPONENT(html, [callback])| Parameter | Type | Description |
|---|---|---|
html |
String |
File name, HTML or URL |
callback? |
Function |
function(err, component) |
Returns Promise<Component> When callback is not set
html is the name of a file in components/ (without .html), the HTML content itself (anything containing <), or an https:// URL that is downloaded first. The server code must be in a <script total> or <script node> block; without it you get the error "Invalid component content". The code runs with exports (the component) and require (REQUIRE()). Packages in exports.npm are installed, schemas of inputs and outputs are compiled and exports.install() is called. Returns a Promise without a callback.
NEWCOMPONENT('uppercase', function(err, com) {
if (err) {
console.error(err);
return;
}
var instance = com.create();
});
var html = '<script total>exports.make = function(instance) { instance.message = msg => msg.send(\'output\', msg.data * 2); };</script>';
var com = await NEWCOMPONENT(html);
type
components/{name}.html
The format of a server component.
components/{name}.htmlAn HTML file with these parts: <script total> or <script node> (server code, required), <settings>, <style>, <script>, <body>, <readme>, <schema> and <template>. The server code is removed from the result; the other parts are available in component.ui (settings, css, js, html, readme, schema, template).
<script total>
exports.name = 'Counter';
exports.config = { step: 1 };
exports.inputs = [{ id: 'input', name: 'Value' }];
exports.outputs = [{ id: 'output', name: 'Sum' }];
exports.make = function(instance, config) {
var sum = 0;
instance.message = function(msg) {
sum += config.step;
msg.send('output', sum);
};
};
</script>
<readme>
Counts incoming messages.
</readme>
<settings>
<div>Step of the counter</div>
</settings>
class
Component
A compiled server component.
ComponentThe object returned by NEWCOMPONENT(). Its properties come from exports of the server code (name, config, inputs, outputs, npm, make, ...) plus ui, instances, variables, secrets and debugger.
delegate
exports.make = function(instance, config, status) {}
Sets up a new instance.
exports.make = function(instance, config, status) {}| Parameter | Type | Description |
|---|---|---|
instance |
Instance |
The new instance |
config |
Object |
Its configuration |
status |
Object |
The second argument of create() |
Called by component.create() with the instance as this and as the first argument. Assign instance.message (and other handlers such as instance.close, instance.configure or instance.service) here.
exports.make = function(instance, config) {
instance.message = function(msg) {
msg.send('output', msg.data);
};
instance.configure = function() {
// config has changed
};
};
property
exports.config
Default configuration of instances.
exports.configReturns Object
Each instance gets a clone of this object, extended with the options passed to component.create().
property
exports.inputs / exports.outputs
Inputs and outputs of the component.
exports.inputs / exports.outputsReturns Array
Arrays of { id, name, schema }. A schema (a schema string such as 'name:String, age:Number') is compiled into a JSON schema. For inputs it is applied in instance.input(): the cleaned data replaces msg.data and errors are in msg.error.
exports.inputs = [{ id: 'user', name: 'User', schema: 'name:String, email:Email' }];
exports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];
exports.make = function(instance) {
instance.message = function(msg) {
if (msg.error)
msg.send('error', msg.error.toString());
else
msg.send('ok', msg.data);
};
};
property
exports.npm
NPM packages the component needs.
exports.npmReturns String[]
An array of package names (optionally name@version). NEWCOMPONENT() installs them with NPMINSTALL() before install() runs; the compilation fails with the npm error when one cannot be installed.
exports.npm = ['mqtt'];
exports.make = function(instance, config) {
var mqtt = require('mqtt');
// ...
};
delegate
exports.install = function(component) {}
Called once after the component is compiled.
exports.install = function(component) {}Runs with the component as this and as the argument, after NPM packages are installed and schemas are compiled.
delegate
exports.onextend = function(instance) {}
Extends each new instance before make().
exports.onextend = function(instance) {}Called in component.create() after the configuration is set and before make().
delegate
exports.oncreate = function(instance) {}
Called after an instance is created.
exports.oncreate = function(instance) {}Runs asynchronously (in setImmediate) after make().
delegate
exports.onremove = function(instance) {}
Called when an instance is removed.
exports.onremove = function(instance) {}Called by instance.remove() after the close and destroy handlers of the instance.
property
component.ui
The UI parts of the component file.
component.uiReturns Object
An object with readme, settings, css, js, html, schema and template (only the parts found in the file).
property
component.instances
All instances of the component.
component.instancesReturns Instance[]
create() adds an instance and instance.remove() removes it.
property
component.debugger
Prints status, debug, error and output messages to the console.
component.debuggerReturns Boolean
true by default. Set it to false to keep the console quiet, or replace component.output, component.status, component.debug, component.throw or component.dashboard with your own functions.
delegate
component.output = function(instance, msg) {}
Receives every message sent to an output.
component.output = function(instance, msg) {}| Parameter | Type | Description |
|---|---|---|
instance |
Instance |
The sender |
msg |
Message |
msg.output and msg.data |
Called for each msg.send() of any instance. The default prints the output and the data when debugger is on. Replace it to connect instances or to process results. component.status(instance, value), component.debug(instance, value), component.throw(instance, err) and component.dashboard(instance, value) receive the calls of the instance methods with the same name.
var com = await NEWCOMPONENT('uppercase');
com.output = function(instance, msg) {
console.log(instance.id, msg.output, msg.data);
};
method
component.create([options], [status])
Creates an instance.
component.create([options], [status])| Parameter | Type | Description |
|---|---|---|
options? |
Object |
Configuration of the instance |
status? |
Object |
Passed to make() as the third argument |
Returns Instance
The instance gets a random id, a clone of component.config extended with options, and is added to component.instances. Then onextend(), make() and (asynchronously) oncreate() are called.
var a = com.create({ prefix: 'A: ' });
var b = com.create({ prefix: 'B: ' });
method
component.service(counter)
Calls instance.service(counter) on all instances.
component.service(counter)| Parameter | Type | Description |
|---|---|---|
counter |
Number |
Any value passed to the instances |
Total.js does not call it for you. Call it from ON('service') when your instances need a periodic tick.
ON('service', function(counter) {
com.service(counter);
});
class
Instance
An instance of a server component.
InstanceReturned by component.create(). Properties: id, config, module (the component) and cache (an empty object for your data). Handlers you can assign in make(): message, message_<input>, configure, close, destroy and service.
delegate
instance.message = function(msg) {}
Handles data that comes to an input.
instance.message = function(msg) {}| Parameter | Type | Description |
|---|---|---|
msg |
Message |
The incoming message |
Called by instance.input(). msg.input is the input id and msg.data the data. A handler named instance.message_<input> is called too, after message. Without instance.message the input is ignored.
exports.make = function(instance) {
instance.message = NOOP;
instance.message_reset = function(msg) {
// only for input "reset"
};
};
method
instance.input(input, data, [callback])
Sends data to an input of the instance.
instance.input(input, data, [callback])| Parameter | Type | Description |
|---|---|---|
input |
String |
Input id |
data |
Object |
The data |
callback? |
Function |
function(msg) |
Creates a message, validates the data with the schema of the input (if any) and calls instance.message(msg) and instance.message_<input>(msg). The callback is called with the message each time it is sent to an output with msg.send().
instance.input('input', 'hello', function(msg) {
console.log(msg.output, msg.data);
});
method
instance.send(output, data)
since 0.0.17
Sends new data to an output.
instance.send(output, data)| Parameter | Type | Description |
|---|---|---|
output |
String |
Output id |
data |
Object |
The data |
Creates a new message with data and sends it to output; it ends in instance.output(msg) and so in component.output(). Use it for data the instance produces on its own (a timer, a socket).
exports.make = function(instance) {
var timer = setInterval(() => instance.send('output', new Date()), 5000);
instance.close = () => clearInterval(timer);
};
method
instance.status(value) / debug(value) / throw(err) / dashboard(value)
Reports a state of the instance.
instance.status(value) / debug(value) / throw(err) / dashboard(value)| Parameter | Type | Description |
|---|---|---|
value |
Object |
Any value |
Each method calls the component method with the same name (component.status(instance, value) and so on). By default they print to the console when component.debugger is on.
instance.status({ connected: true });
instance.throw(new Error('Connection refused'));
method
instance.activity(key, name, value)
since 0.0.19
Reports an activity of the instance.
instance.activity(key, name, value)| Parameter | Type | Description |
|---|---|---|
key |
String |
Identifier of the activity |
name |
String |
Label |
value |
Object |
For example a progress |
Calls component.activity(instance, { key, name, value }), which prints ACTIVITY to the console when component.debugger is on. Replace component.activity to process it.
method
instance.reconfigure(options)
Changes the configuration of an instance.
instance.reconfigure(options)| Parameter | Type | Description |
|---|---|---|
options |
Object |
New values |
Copies the keys of options to instance.config and calls instance.configure(config) when it is defined.
instance.reconfigure({ prefix: '>> ' });
method
instance.remove()
Removes the instance.
instance.remove()Calls instance.close(true) and instance.destroy() when defined, then component.onremove(instance), and removes the instance from component.instances.
instance.remove();
method
instance.replace(str, [data], [encoding])
Replaces {key} placeholders in a string.
instance.replace(str, [data], [encoding])| Parameter | Type | Description |
|---|---|---|
str |
String|Object |
Template |
data? |
Object |
Values |
encoding? |
String|Function |
Encoding of the values |
Returns String|Object
Each {key} (or {{key}}) is taken from component.variables, then component.secrets, then data (nested keys with dots work). Without data the instance itself is used. encoding can be 'url' (or 'urlencoded'), 'json', 'querify' or a function(value, key). Dates are formatted. An object as str replaces its string values. msg.replace() works the same way.
com.variables.api = 'https://api.example.com';
var url = instance.replace('{api}/users/{id}/', { id: 15 });
class
Message
Data that flows through a component instance.
MessageCreated by instance.input() and instance.send(). Properties: data, input, output, error (an ErrorBuilder when the input schema failed, null when it passed, undefined for an input without a schema), from and instance (the instance), repo and vars (empty objects for your data).
method
msg.send(output, [data])
Sends the message to an output.
msg.send(output, [data])| Parameter | Type | Description |
|---|---|---|
output |
String |
Output id |
data? |
Object |
New data |
Sets msg.output and, when data is given, msg.data. Then it calls the callback of instance.input() and instance.output(msg). Nothing happens after msg.end().
instance.message = function(msg) {
msg.send('output', { received: msg.data });
};
method
msg.end() / msg.destroy()
Releases the message.
msg.end() / msg.destroy()Clears data, vars, repo and the instance, so later msg.send() calls do nothing.
method
NPMINSTALL(name, [callback])
Installs an NPM package.
NPMINSTALL(name, [callback])| Parameter | Type | Description |
|---|---|---|
name |
String |
Package name, optionally with @version |
callback? |
Function |
function(err) |
Returns Promise When callback is not set
Runs npm install <name> in CONF.$nodemodules (created when missing). When the package folder already contains a package.json (with the same version for name@version), nothing is installed. When the process runs as user 33 (www-data), CONF.$npmcache is used as the npm cache. Without a callback it returns a Promise. See Configuration for both keys.
NPMINSTALL('qrcode@1.5.4', function(err) {
if (err) {
console.error(err);
return;
}
var QR = REQUIRE('qrcode');
});
method
REQUIRE(name)
Loads a Node.js or NPM module.
REQUIRE(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Module name |
Returns Object The module
Names with the node: prefix and Node.js built-in modules (fs, path, crypto, ...) are loaded directly. Other names are loaded with require() and, when that fails, from CONF.$nodemodules, so packages installed with NPMINSTALL() are found. It throws when the module cannot be loaded.
var Fs = REQUIRE('fs');
var mqtt = REQUIRE('mqtt');
method
IMPORT(url, [callback])
Downloads and loads a remote JavaScript module.
IMPORT(url, [callback])| Parameter | Type | Description |
|---|---|---|
url |
String |
URL of a .js file |
callback? |
Function |
function(err, module, response) |
Returns Promise When callback is not set
The file is downloaded into the temporary folder and required. Further calls with the same URL in the same process return the loaded module without downloading. An answer with the status 400 or more gives the error The address answered with the status <status> and nothing is loaded. A file that is not a valid module gives the error of require(), for example a SyntaxError. The callback receives (err, module, response); without it a Promise resolves with the module.
var helpers = await IMPORT('https://cdn.example.com/helpers.js');
helpers.hello();