Script plugins
Write a JavaScript plugin that calls Lightair's methods, reads chat, and adds commands, automation steps, panels and overlays, within its permissions.
In short
- A script plugin is a package with an
extensionfolder holdingmain.js. Lightair runs it in its own sandboxed JavaScript engine. - Everything goes through the global
lightairobject, and every call is checked against the package's permissions. - Each callback gets 250 ms of JavaScript and the script 64 MB of memory. Running over twice in a minute suspends it.
- Scripts run in the desktop app only, on macOS and Windows.
In the appWindow › PackagesWindow › Plugin panels
A script plugin is a package whose contents has an extension entry. Its folder holds main.js
and, if the script draws overlays, the widget folders for them. Lightair runs main.js once when
it starts the plugin, in a JavaScript engine of its own (QuickJS) on its own thread. There’s no
DOM, no require, no modules and no direct access to files or the network: everything the script
does goes through the global lightair object.
Make a script package
Section titled “Make a script package”-
Make a folder with a
lightair-package.json, aLICENSEfile and ascriptfolder. -
Write the manifest. The
extensionentry points at the script’s folder;permissionslists what the script uses.{"id": "io.github.you.chat-counter","name": "Chat Counter","version": "1.0.0","lightair": ">=1.0 <2","licence": "MIT","contents": [{ "kind": "extension", "path": "script" }],"permissions": ["chat.read", "project.write"]} -
Write
script/main.js:lightair.settings.declare([{ key: "word", label: "Word to count", kind: "text", default: "!count" },{ key: "scene", label: "Scene at 10", kind: "text", default: "Be Right Back" },]);let count = lightair.storage.get("count") || 0;const view = () => [{ type: "label", id: "count", text: `Said ${count} times` },{ type: "button", id: "reset", text: "Reset" },];const panel = lightair.panel({id: "main",title: "Chat counter",ui: view(),on: (element) => {if (element === "reset") {count = 0;save();}},});function save() {lightair.storage.set("count", count);panel.update(view());}lightair.on("chat", (event) => {const settings = lightair.settings.get();const word = settings.word ?? "!count";if (!event.text.includes(word)) return;count += 1;save();if (count === 10) {lightair.call("scene.switch", { scene: settings.scene ?? "Be Right Back" });}}); -
Install the folder in Lightair (see Packages). The panel shows in Window › Plugin panels, and the script’s state and settings in its section of Window › Packages.
Each use the script makes, allowed or refused, is recorded in the plugin activity. A refused use also raises a notice naming the plugin.
Call Lightair’s methods
Section titled “Call Lightair’s methods”const state = lightair.call("state.get", {});lightair.call("scene.switch", { scene: "Be Right Back" });lightair.call(method, params) reaches the Remote API: the
same method names and parameters. It returns the result, or throws an Error whose message says
what went wrong. Calls are synchronous: the script waits while Lightair answers, and that time
doesn’t count against its budget.
Which permission a call needs:
| Methods | Needs |
|---|---|
Reading: methods ending in .list, .get, .state, .status, .history, .health, .saved, .categories, .program, .targets or .version, and stream.info.get |
project.read |
Starting or stopping what goes out: output.*, outputs.*, record.*, stream.*, clip.*, vcam.*, replay.* (except their reading methods) |
outputs.control |
chat.send |
chat.write |
chat.history |
chat.read |
audio.levels |
audio.levels |
preview.frame, scene.thumbnail, scene.thumbnails |
screen.capture |
| Everything else (scenes, objects, sources, audio, automations, undo and the rest) | project.write |
Some methods are never open to scripts, whatever they hold: app.exit, script.run,
events.subscribe (use lightair.on), and every auth.*, pair.*, session.*, transfer.*,
takes.*, plugins.* and obswebsocket.* method.
Events
Section titled “Events”lightair.on("chat", (event) => { /* a chat message, from any platform */ });lightair.on("scene", ({ name }) => { /* the program scene changed */ });| Event | Data | Needs |
|---|---|---|
chat |
Lightair’s chat event (below). A script gets the messages that arrive after it starts. | chat.read |
scene |
{ name }: the scene now on program |
project.read |
A chat event has these fields:
| Field | What it is |
|---|---|
id |
Lightair’s number for it, in arrival order |
ts_ms |
When it happened, in milliseconds since 1970 |
platform |
twitch, youtube and so on |
channel |
The channel it came from, as it was set up |
native_id |
The platform’s id for it, when there is one |
kind |
An object whose type is message, paid, membership, raid (with viewers), follow, deletion or notice |
user |
{ id, login, display_name, color, roles, badges }; roles from broadcaster, moderator, vip, subscriber, member, verified |
text |
The message as plain text, emotes as their codes |
fragments |
The message in parts: text, emote (provider, id, code, image), mention (name), link (url), each with its type |
paid |
{ display, amount, currency } for paid messages |
headline |
A membership’s or notice’s own line |
deleted |
true once a moderator removed it |
test |
true for events made up to try something, not read from a platform |
Fields with no value are left out, so check before you use them.
Commands, hotkeys and steps
Section titled “Commands, hotkeys and steps”lightair.command({ id: "next", title: "Next scene", run: () => { /* … */ } });
lightair.hotkey({ id: "flash", title: "Flash the logo", run: () => { /* … */ } });
lightair.step({ id: "add", title: "Add to the count", fields: [{ key: "by", label: "By", kind: "number", default: 1 }], run: (params) => { count += Number(params.by ?? 1); return { count }; },});- Commands show in the command palette as ”
: ”, and can be run with plugins.command . - Hotkeys need the
hotkeyspermission. They show in the command palette like commands. - Steps show in the automations’ Add step menu as ”
: ”. An automation stores one as a call to plugins.step withpackage,stepand the fields’ values, which the handler gets asparams. - A handler may return a value or a promise. What it returns, or what the promise resolves to, is the command’s or step’s result; a thrown error is its error. Lightair waits 20 seconds for a command and 30 seconds for a step.
Settings
Section titled “Settings”lightair.settings.declare([ { key: "greeting", label: "Greeting", kind: "text", default: "Hi" }, { key: "loud", label: "Loud", kind: "toggle", default: false }, { key: "style", label: "Style", kind: "choice", options: ["Calm", "Wild"], default: "Calm" },]);
const values = lightair.settings.get();lightair.settings.onChange((values) => { /* the person saved new values */ });The person edits settings in the package’s section of Window › Packages. A setting has a
key, a label, a kind (text, number, toggle or choice), a default and, for a
choice, options. A setting marked "secret": true, or of kind secret or password, is never
read or written over the Remote API; only the person sets it, in the panel.
settings.get() returns the values the person has saved. A setting they haven’t changed may be
missing, so fall back to your default, as the example above does with ??.
Panels
Section titled “Panels”const panel = lightair.panel({ id: "main", title: "Scene buttons", ui: [ { type: "label", id: "status", text: "Ready" }, { type: "button", id: "next", text: "Next scene" }, { type: "toggle", id: "auto", text: "Switch on raids", value: false }, { type: "slider", id: "delay", text: "Delay", min: 0, max: 10, step: 1, value: 3 }, { type: "text", id: "message", text: "Message", value: "" }, { type: "list", id: "recent", text: "Recent", items: ["one", "two"] }, ], on: (element, value) => { /* element is the id that was used */ },});
panel.update(newUi);A panel is described as data and drawn by Lightair with its own controls, as a card in
Window › Plugin panels that wears the package’s name. Scripts never draw in Lightair’s
interface themselves. Using an element calls on(element, value):
| Element | Shows | value sent |
|---|---|---|
label |
Its text |
Nothing is sent |
button |
A button labelled text |
null |
toggle |
text and a switch at value |
true or false |
slider |
text, value, and − and + buttons that move by step between min and max |
The new number |
text |
text and its value; clicking it opens a field with Send |
The text sent |
list |
text above up to 200 items (strings, or objects with text) |
The item clicked |
The panel doesn’t change by itself: to show a new value, call panel.update() with the whole new
list of elements.
Overlays
Section titled “Overlays”const overlay = lightair.overlay({ id: "counter", title: "Chat counter", page: "counter", width: 600, height: 200, onMessage: (message) => { /* a message from the page */ },});
overlay.send({ count: 3 });page is a widget folder inside the script’s folder (index.html, style.css, main.js,
fields.json), drawn by a browser object like any package widget; see
Widgets. It must be inside the package: no .., no leading /, no
address. width and height are its size, 1920 × 1080 when left out.
While the script runs, the overlay is offered in Add object › Widgets › From packages.
overlay.send(message) reaches every copy of it in the show. On the page, the widget bridge talks
back:
lightair.on("message", (message) => { /* from the script */ });lightair.send({ clicked: true }); // to the script's onMessageThe page reaches only the hosts the package declares.
Network, storage, files and notices
Section titled “Network, storage, files and notices”const r = lightair.fetch("https://api.example.com/v1/status", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ hello: true }),});r.status; r.ok; r.headers; r.text(); r.json();
lightair.storage.set("count", 3);lightair.storage.get("count");
const path = lightair.files.pick();const text = path && lightair.files.read(path);
lightair.notify("Chat said !count 100 times");fetchgoes through Lightair, never the script’s own connection. It takeshttpandhttpsaddresses only, and the methodsGET,POST,PUT,PATCHandDELETE. The host as written must be declared:network:<host>,network:*.example.comfor a domain and its subdomains, ornetwork:*for any. An address on this computer needsnetwork:localhost:<port>, and one on the home network needsnetwork.lan, also when a name turns out to point there. It returns{ status, ok, headers, text(), json() }, the body read up to 5 MB. A request gives up after 20 seconds.storagekeeps JSON values per package, across restarts, up to 1 MB in all. Setting a value tonullorundefinedremoves it. It needs no permission.files.pick()asks the person to choose a file or folder and returns its path, ornullif they cancel.files.read(path)reads a file inside what they picked, as text, 5 MB at most. Both needfs.read:picked.notify(text)shows a notice from the plugin, 200 characters at most. It needsnotifications.console.log,info,warn,erroranddebugwrite to Lightair’s log.- Timers:
setTimeout,setInterval,clearTimeoutandclearInterval. An interval is at least 10 ms; a script may hold 1,000 timers.
Ask for a permission while it runs
Section titled “Ask for a permission while it runs”const held = lightair.permissions.request(["outputs.control"], "To start recording when chat votes");if (lightair.permissions.has("outputs.control")) { lightair.call("record.start", {});}lightair.permissions.release(["outputs.control"]);A permission listed in the manifest’s optional_permissions isn’t granted at install: the script
asks for it when it needs it. request(list, reason) shows the person a second screen with the
reason (300 characters at most) and only those permissions, waits for the answer, and returns the
optional permissions the script holds afterwards. Ask from something the person started, such as
a command. The wait doesn’t count against the budget; no answer within 10 minutes is a no.
Asking for one that isn’t in optional_permissions throws. See
Permissions.
Budgets
Section titled “Budgets”| Limit | Value |
|---|---|
| Memory for the script’s engine | 64 MB |
JavaScript time to load main.js |
2 seconds |
| JavaScript time per callback (a command, step, event, timer, panel element or overlay message) | 250 ms |
| Storage | 1 MB |
Time spent waiting on Lightair (calls, fetches, the person’s answer) doesn’t count. A callback
over its time is stopped, with a notice. A second one within a minute, too long a load, or running
out of memory suspends the script, with a notice that shows even while you’re live. A script
whose main.js fails to load is stopped too. The package’s section in Window › Packages says
why and offers Start again.
Changing the package’s permissions, updating it or switching it off stops the script, and starts it again when it should run.
In the catalog’s checks
Section titled “In the catalog’s checks”The catalog runs main.js in the same engine against a stand-in Lightair that records every
call. The run uses every command, hotkey and step once, each panel element, the settings and a
chat and a scene event, and gives timers a moment to fire. It fails when the script:
- uses anything its
permissionsandoptional_permissionsdon’t cover, or a method scripts can’t call; - builds code at runtime (
eval,new Function,setTimeoutwith a string and the like); - doesn’t load, runs over its budget or is suspended;
- declares an overlay whose page folder has no
index.html.
A command or step that throws is noted, not failed. See Publish a package.