Skip to main content

Using Stof in Your App

Stof runs inside your app, as a library. Your app creates documents, puts data and logic into them, calls their functions, and reads the results. This page covers each of those steps. The examples are TypeScript; Python and Rust work the same way, with the method names listed at the end.

Loading a Document​

StofDoc.new creates a document from Stof source, a JavaScript object, or bytes:

import { StofDoc } from '@formata/stof';

const doc = await StofDoc.new(`
pricing: {
rate: 2
fn total(units: int) -> float { units * self.rate }
}
`);

A document can keep taking in more, in any format it knows. Each parse adds to what's already there:

doc.parse({ customer: { name: 'Ada', plan: 'pro' } }); // a JavaScript object
doc.parse('limits:\n calls: 100\n', 'yaml'); // YAML (also 'json', 'toml', ...)
doc.parse(rulesFromAModel); // more Stof: data, functions, or both
doc.parse(pluginSource, 'stof', 'plugins.weather', 'untrusted'); // into an object, running nothing

That's how data and logic from different places end up in one document. Parsing Stof can run it (a field's value can be an expression, and #[init] functions run), so parse source you didn't write with the 'untrusted' profile and seal it confined before calling it. See Formats for every format.

Calling Functions​

call takes a path to a function and its arguments, and returns what the function returns:

await doc.call('pricing.total', 21); // 42
await doc.call('pricing.total', '4'); // 8: arguments are cast to the parameter's type

Paths start at the document's top level, so 'pricing.total' is the total function on the pricing object. Calls are async because a document can do async work, like waiting on one of your functions.

Running Code Without Keeping It​

Sometimes you have logic to run once, like a check or a script from a model, and don't want it in the document afterward. callSource parses a function, calls it as if it were defined at the top level of the document (or on the object you pass), and removes it after:

await doc.callSource(`
fn quote(qty: int) -> float {
self.pricing.total(qty) * self.discount()
}
fn discount() -> float { 0.9 }
`, [10]); // the first function is called; the rest are helpers it can reach through self

Changes the function makes to the document stay; the function and its helpers don't. To take something out of the document yourself, remove takes a path, like drop in Stof:

doc.remove('pricing.old_total'); // a function or field
doc.remove('customers.c_42'); // an object
doc.remove('order.customer', true); // shallow: just the field, not the object it points to

Running by Attribute​

When you don't know what a document's functions are called, tag them. run calls every function with an attribute:

const doc = await StofDoc.new(`
ticket: { text: 'Where is my refund?' }

#[triage]
fn route() {
if (self.ticket.text.lower().contains('refund')) self.ticket.team = 'billing';
}
`);

await doc.run('triage'); // every #[triage] function
doc.get('ticket.team'); // 'billing'

This is the usual setup when logic comes from somewhere else, like a model or a customer. The attribute is the agreement: your app runs #[triage] functions, and the document can have as many as it needs, with any names. run() with no attribute runs #[main] functions.

Reading and Writing Values​

get and set read and write any value by path:

doc.get('pricing.rate'); // 2
doc.set('pricing.rate', 3);
doc.set('customer.vip', true); // creates the field if it isn't there

Numbers, strings, booleans, lists, and maps come back as JavaScript values. An object comes back as its ID, a string you can pass to the functions that take a node (like blobify below).

Giving Documents Your Functions​

A document can only call what it's given. lib adds one of your functions as a library function the document can call:

doc.lib('App', 'notify', (message: string) => notifications.send(message));

// async functions: pass true, and the document can await them
doc.lib('App', 'customer_name', async (id: number) => (await db.customers.find(id)).name, true);
fn on_refund(id: int) {
const name = await App::customer_name(id);
App::notify(`Refund started for ${name}`);
}

This is how you connect a document to the rest of your app on your terms: it gets these functions and nothing else. See Adding Your Own in Libraries.

What a Document Can Reach​

A document can read and change itself and call library functions. It can't reach the file system, environment variables, other files, or the network unless you allow it:

doc.allowHttp(['api.example.com']); // network access to these hosts only
doc.allowHttp(); // network access to any public host (never your machine or private network)

In Python and Rust, allow_system() also gives access to files and environment variables. The JavaScript package has no file system access at all. Libraries has the full table.

Each call also has a time limit (2 minutes by default) and a memory limit (256 MB by default), so a document that loops forever or keeps growing can't hang or crash your app:

doc.setMaxExecutionTime(500); // milliseconds, or null for no limit
doc.setMaxMemory(64 * 1024 * 1024); // bytes, or null for no limit
execution timed out (max execution time exceeded)
at root.spin (defined at 1:1)

To lock the parts of a document you trust so other code can call them but not change them, seal them: doc.seal('<Engine>'). To keep code you didn't write to what you give it, parse it untrusted and seal it confined: doc.parse(src, 'stof', 'plugins.weather', 'untrusted'), then doc.seal('plugins.weather', { reads: ['inputs'], hosts: ['api.weather.example'], libs: ['Std', 'Str', 'Http'], time: 2000 }), with calls for the functions of yours it may call. To check where logic or data came from, sign and verify it with the same keys in your app and in documents (StofDoc.sign, Key::verify). Security and the Sandbox covers sealing, keys and signatures, confining, the network rules, and the limits in full.

Errors​

A function that throws makes call or run reject, with a plain message and the Stof call stack:

try {
await doc.call('pricing.total');
} catch (error) {
console.log(String(error)); // missing argument 'units' for total(units: int)
}

A document that doesn't parse throws from new or parse, with the line and column:

parse error: unexpected end of input (expected '}')
--> line 1, column 5
|
1 | a: {
| ^

For line numbers on runtime errors too, parse with the test profile: StofDoc.new(src, 'stof', 'test'). The default profile leaves them out to keep documents smaller.

These messages are written to be read by people and by models. When a model wrote the document, pass the error back to it and ask for a fix.

Exporting​

A document exports to any format it knows:

doc.stringify('json'); // a JSON string (functions are left out)
doc.stringify('yaml');
doc.record(); // a plain JavaScript object

To keep the functions, export binary Stof (bstf). It holds the whole document, or one object, and loads anywhere Stof runs:

const bytes = doc.blobify('bstf', doc.get('pricing')); // just the pricing object, functions included
const copy = await StofDoc.new(bytes, 'bstf');
await copy.call('total', 5); // 10

Store those bytes, send them over HTTP or a WebSocket, and run them in another service, a browser, or Python.

An html export is safe to put on a page (see Formats), and your app can limit it to exactly the elements it renders, like its own components. A document can't change that list:

doc.allowHtmlTags(['div', 'section', 'ui-card', 'ui-metric']);
el.innerHTML = doc.stringify('html', 'dashboard');

A stof export is the document as readable Stof, with its functions as source (see Formats).

Editing Stof text in place​

To change a document people also edit by hand (Ex. a settings page saving into a hand-written file), edit its text instead of exporting it again: only what you change is rewritten, and comments, formatting, and everything else stay as they were. Nothing in the text runs while it's outlined or edited.

const defs = StofDoc.outline(text); // every field and function: path, kind, value, source
const next = StofDoc.edit(text, [
{ set: 'pricing.rate', value: 3 }, // a JSON value
{ set: 'pricing.limit', stof: '2GB' }, // Stof source
{ set_fn: 'pricing.total', stof: 'fn total(units: int) -> float { units * self.rate * 0.9 }' },
{ rename: 'pricing.old', to: 'legacy' },
{ remove: 'pricing.legacy' },
]);

A set adds what isn't there, with the objects on its path, in the style of the object it goes into. If the text or the result doesn't parse, or an edit doesn't make sense, edit throws and nothing changes.

Exports call a format's computed values (#[attr] and #[text] functions) first. A computed value that calls one of your async host functions can't finish in stringify: export from Stof instead, with await doc.callSource('fn view() -> str { stringify("html", self) }', [], 'dashboard').

Cleaning Up​

In JavaScript, a document lives in WebAssembly memory, which the garbage collector doesn't free. Call doc.dispose() when you're done with a document you created for a short task.

Python and Rust​

The same steps, by language:

StepJavaScriptPythonRust
Createawait StofDoc.new(src)doc = Doc() then doc.parse(src)Graph::default() then graph.parse_stof_src(src, None, Default::default())
Parse other formatsdoc.parse(src, 'yaml')doc.string_import(src, 'yaml')graph.string_import("yaml", src, None, &Default::default())
Parse untrusted Stofdoc.parse(src, 'stof', path, 'untrusted')doc.parse(src, path, 'untrusted')graph.string_import("stof", src, Some(node), &Profile::untrusted())
Callawait doc.call('pricing.total', 21)doc.call('pricing.total', [21])Runtime::call(&mut graph, "pricing.total", vec![Val::from(21i64)])
Call sourceawait doc.callSource(src, [21])doc.call_source(src, [21])Runtime::call_source(&mut graph, src, None, vec![Val::from(21i64)])
Removedoc.remove(path)doc.remove(path)graph.remove(path, false)
Run by attributeawait doc.run('triage')doc.run('triage')graph.run(Some("triage".into()), true)
Read and writedoc.get(path), doc.set(path, value)doc.get(path), doc.set(path, value)the crate docs
Host functionsdoc.lib('App', 'notify', fn)doc.lib('App', 'notify', fn)graph.insert_libfunc(LibFunc { .. })
Network accessdoc.allowHttp(hosts)doc.allow_http_hosts(hosts)graph.allow_http_hosts(hosts)
Files and environmentnot availabledoc.allow_system()graph.allow_system()
Time limitdoc.setMaxExecutionTime(ms)doc.set_max_execution_time(seconds)graph.max_execution_time = Some(duration)
Memory limitdoc.setMaxMemory(bytes)doc.set_max_memory(bytes)graph.max_memory = Some(bytes)
HTML elementsdoc.allowHtmlTags(tags)doc.allow_html_tags(tags)graph.allow_html_tags(tags)
Sealdoc.seal(path)doc.seal(path)graph.seal_path(path, false, None)
Keep function sourcedoc.keepSource()doc.keep_source()graph.keep_source(true)
Edit textStofDoc.outline(text), StofDoc.edit(text, edits)Doc.outline(text), Doc.edit(text, edits)stof::parser::edit::{outline, edit}
Exportdoc.stringify('json'), doc.blobify('bstf')doc.string_export('json'), doc.binary_export()graph.stringify("json", None), graph.blobify("bstf", None)

The same document gives the same results in all three.