Skip to main content

Data that carries its own logic.

Project description

Stof

One document, any runtime. Send functions over the wire. Documents that validate themselves.

Playground · Docs · Discord · Site


Stof is a portable document format where functions, validation, and behavior live alongside the data they belong to. It's a superset of JSON - your existing data works as-is. Add logic only where you need it.

server: {
    str host: "0.0.0.0"
    int port: 8080
    MiB memory: 2GB

    fn url() -> str { `https://${self.host}:${self.port}` }
    fn valid() -> bool { self.memory > 200MB }
}

Built in Rust. Runs natively, in WASM (Node, Deno, Bun, browser), and in Python. Sandboxed execution - safe to run untrusted Stof from external sources.

Why Stof?

Interoperability is the reality of modern software. JSON alone no longer cuts it - too much ambiguity, too much brittleness, and every API has its own flavor of interchange format or DSL. There is no single correct way in distributed systems.

Stof doesn't try to replace them. It's the layer that works with all of them - parse JSON, YAML, TOML, STOF, binary, etc. into one document, add the logic that belongs with the data (functions), and send it anywhere. Export to any format as needed internally.

Here's what that looks like in practice:

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

const doc = await stofAsync`
#[type]
Server: {
    port: 8080
    host: 'localhost'
    secure: false
    MiB memory: 500GiB

    fn url() -> str {
        let url = self.secure ? 'https://' : 'http://';
        url += self.host + ':' + self.port;
        url
    }
}`;

// Parse STOF, JSON, YAML, binary, etc. into the same document
doc.parse(`Server "prod": {
    "host": "prod.example.com",
    "port": 443,
    "secure": true,
    "memory": "2GB"
}`);

console.log(await doc.call('prod.url'));     // https://prod.example.com:443
console.log(doc.get('prod.memory'));         // ~1907 MiB (auto-converted from GB)

Runtime Self-Assembly

Stof documents can parse new Stof into themselves at runtime, receiving code over the network and executing it immediately. The document grows while it runs, always sandboxed.

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

const doc = await stofAsync`
    fn loaded() -> str {
        const stof = await Ext.fetch();
        parse(stof, self);
        self.say_hello()
    }
`;

doc.lib('Ext', 'fetch', async () => {
    return `fn say_hello() -> str { 'Hello, world!' }`;
});

console.log(await doc.call('loaded'));      // Hello, world!

This is how Limitr dynamically assembles API capabilities across services, a document receives new code, parses it in, and executes it with full type safety.

Units & Types

Rich type system with automatic unit conversions — time, distance, memory, temperature, and more.

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

const doc = await stofAsync`
#[type]
Point: {
    meters x: 0
    meters y: 0
    
    fn dist(other: Point) -> m {
        Num.sqrt((other.x - self.x).pow(2) + (other.y - self.y).pow(2))
    }
}

Point reference: {
    x: 1ft
    y: 2ft
}

fn distance(imported_json: str) -> inches {
    const imported = new {};
    parse(imported_json, imported, 'json');
    (self.reference.dist(imported) as inches).round(2)
}
`;

const dist = await doc.call('distance', '{ "x": 3, "y": 4 }');
console.log(dist); // 170.52

CLI

See installation docs for CLI instructions and more information.

#[main]
fn say_hi() {
    pln("Hello, world!");
}
> stof run example.stof
Hello, world!

Get Started

Stof is written in Rust, but use it where you work. Join the project Discord to contribute.

Rust

[dependencies]
stof = "0.9.*"
use stof::model::Graph;

fn main() {
    let mut graph = Graph::default();
    
    graph.parse_stof_src(r#"
        #[main]
        fn main() {
            pln("Hello, world!");
        }
    "#, None).unwrap();

    match graph.run(None, true) {
        Ok(res) => println!("{res}"),
        Err(err) => panic!("{err}"),
    }
}

Python

pip install stof

from pystof import Doc

STOF = """
#[main]
fn main() {
    const name = Example.name('Stof,', 'with Python');
    pln(`Hello, ${name}!!`)
}
"""

def name(first, last):
    return first + ' ' + last

def main():
    doc = Doc()
    doc.lib('Example', 'name', name)
    doc.parse(STOF)
    doc.run()

if __name__ == "__main__":
    main()

# Output:
# Hello, Stof, with Python!!

JavaScript/TypeScript

npm i @formata/stof

Initialization

Stof uses WebAssembly, so make sure to initialize it once.

// Node.js, Deno, & Bun - Auto-detects and loads WASM
import { initStof } from '@formata/stof';
await initStof();

// Vite
import { initStof } from '@formata/stof';
import stofWasm from '@formata/stof/wasm?url';
await initStof(stofWasm);

// Browser with bundler - Pass WASM explicitly (e.g. @rollup/plugin-wasm)
import { initStof } from '@formata/stof';
import stofWasm from '@formata/stof/wasm';
await initStof(await stofWasm());

Usage

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

await initStof();

const doc = new StofDoc();
doc.parse(`
    name: "Alice"
    age: 30
    fn greet() -> str {
        'Hello, ' + self.name
    }
`);

const greeting = await doc.call('greet');
console.log(greeting); // "Hello, Alice"
console.log(doc.get('age')); // 30

JavaScript Interop

await initStof();
const doc = new StofDoc();

doc.lib('console', 'log', (...args: unknown[]) => console.log(...args));
doc.lib('fetch', 'get', async (url: string) => {
    const res = await fetch(url);
    return await res.json();
});

doc.parse(`
    fn main() {
        const data = await fetch.get("https://api.example.com/data");
        console.log(data);
    }
`);

await doc.call('main');

Parse & Export

doc.parse({ name: "Bob", age: 25 });

const json = doc.stringify('json');
const obj = doc.record();

Supports: Node.js, Browser, Deno, Bun, Edge runtimes

Learn More

  • Docs - core concepts, standard library, and format reference
  • GitHub Issues - bugs and feature requests
  • Discord - talk to the team and community
  • Playground - try Stof in your browser, no install required

VS Code extension available - search "Stof" in your editor's extension marketplace.

License

Apache 2.0. See LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

stof-0.9.18.tar.gz (2.6 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

stof-0.9.18-cp314-cp314-win_amd64.whl (8.4 MB view details)

Uploaded CPython 3.14Windows x86-64

File details

Details for the file stof-0.9.18.tar.gz.

File metadata

  • Download URL: stof-0.9.18.tar.gz
  • Upload date:
  • Size: 2.6 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: maturin/1.13.1

File hashes

Hashes for stof-0.9.18.tar.gz
Algorithm Hash digest
SHA256 dedcdb9ed09bc7dc6fbc8eb957c22c623676e7d1b180bb6978fcf3ecde77c1da
MD5 3a54e7acbba66405b16c9414c1153523
BLAKE2b-256 ba68ea0e671caea00a90ab0df58dac5287b5558d4b0357e4c45988a511e9cbbf

See more details on using hashes here.

File details

Details for the file stof-0.9.18-cp314-cp314-win_amd64.whl.

File metadata

  • Download URL: stof-0.9.18-cp314-cp314-win_amd64.whl
  • Upload date:
  • Size: 8.4 MB
  • Tags: CPython 3.14, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: maturin/1.13.1

File hashes

Hashes for stof-0.9.18-cp314-cp314-win_amd64.whl
Algorithm Hash digest
SHA256 7482543cda8aa9d0ec4ea1ce1850b95bb0898f773c6573154acfeb040445fa63
MD5 5da171f6bcd0c2d2283554a000e3f3cb
BLAKE2b-256 8846729df95c7bd51bfaabe05b82f61a6e1bdb059c467c34ef784008a11d1c97

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page