Skip to main content

Standard Library

Jade ships a standard library of built-in packages. Import any package with :: notationuse std::<name> — and it becomes a global variable in scope for the rest of the file.

use std::json
use std::path
use std::random

let data = json.parse('{"x": 1}')
let p = path.join("/home/user", "projects", "app")
let n = random.int(1, 100)
warning

Every import uses :: notation (or a bare name) that names a module — there are no quoted file paths and no as alias. use "std/json" and use "lib.jde" as lib are rejected at compile time (QuotedImport / ImportAlias). See Imports.

ImportGlobal nameDescription
use std::mathmathNumeric functions
use std::stringstringString utilities
use std::arrayarrayHigher-order array functions
use std::dictdictDict utilities
use std::fsfsFile system I/O
use std::timetimeClock and sleep
use std::httphttpHTTP client
use std::uhttpuhttpHTTP client over a Unix domain socket
use std::shshShell command execution
use std::jsonjsonJSON encode / decode
use std::envenvEnvironment variables and process info
use std::pathpathPath manipulation
use std::randomrandomRandom number generation

std/math

use std::math
FunctionReturnsDescription
math.floor(x)intLargest integer ≤ x
math.ceil(x)intSmallest integer ≥ x
math.abs(x)same as inputAbsolute value (int or float)
math.sqrt(x)floatSquare root
math.min(a, b)numberSmaller of two numbers
math.max(a, b)numberLarger of two numbers
math.pow(base, exp)floatbase raised to exp
use std::math

print(math.floor(3.7)) // 3
print(math.ceil(3.2)) // 4
print(math.abs(-5)) // 5
print(math.sqrt(16.0)) // 4.0
print(math.min(3, 7)) // 3
print(math.max(3, 7)) // 7
print(math.pow(2.0, 10.0)) // 1024.0

std/string

use std::string

The std/string package exposes functions that take the target string as the first argument. The same operations are also available as primitive methods directly on any str value — see the method form in the table below.

FunctionMethod formReturnsDescription
string.split(s, sep)s.split(sep)arraySplit s on sep; returns array of str
string.upper(s)s.upper()strUppercase
string.lower(s)s.lower()strLowercase
string.trim(s)s.trim()strStrip leading and trailing whitespace
string.contains(s, sub)s.contains(sub)boolTrue if sub appears in s
string.replace(s, from, to)s.replace(from, to)strReplace first occurrence of from with to
string.starts_with(s, prefix)s.starts_with(prefix)boolTrue if s starts with prefix
string.ends_with(s, suffix)s.ends_with(suffix)boolTrue if s ends with suffix

str also has len() and encode(), neither of which needs a package import. encode() gives the string's UTF-8 as a bytes value, and bytes.decode() goes back the other way — see Types.

let s = "Hello, Jade!"
print(s.len()) // 12
print(s.encode().len()) // 12 — bytes, not characters
print(s.upper()) // HELLO, JADE!
print(s.lower()) // hello, jade!
print(s.trim()) // Hello, Jade! (no change here)
print(s.split(", ")) // ["Hello" "Jade!"]
print(s.contains("Jade")) // true
print(s.replace("Jade", "World")) // Hello, World!
print(s.starts_with("Hello")) // true
print(s.ends_with("!")) // true

std/array

use std::array

The std/array package adds higher-order functions (map, filter) that are not available as primitive methods, plus standalone versions of sort and reverse that return new arrays.

FunctionDescription
array.map(arr, fn)Apply fn to each element; return new array of results
array.filter(arr, fn)Keep elements for which fn returns true; return new array
array.sort(arr)Return a new sorted copy of arr (does not mutate)
array.reverse(arr)Return a new reversed copy of arr (does not mutate)

Primitive methods (available without import):

MethodReturnsDescription
arr.len()intNumber of elements
arr.push(x)nilAppend x in place
arr.pop()valueRemove and return the last element
arr.contains(x)boolTrue if x is in the array
arr.sort()nilSort in place
arr.reverse()nilReverse in place
use std::array

let nums = [3, 1, 4, 1, 5, 9]

// Higher-order functions
let doubled = array.map(nums, |x| x * 2)
let evens = array.filter(nums, |x| x % 2 == 0)
let sorted = array.sort(nums) // new copy, nums unchanged
let rev = array.reverse(nums) // new copy

print(doubled) // [6, 2, 8, 2, 10, 18]
print(evens) // [4]
print(sorted) // [1, 1, 3, 4, 5, 9]
print(rev) // [9, 5, 1, 4, 1, 3]

// Primitive methods (mutate in place)
nums.push(2)
let last = nums.pop() // 2
print(nums.contains(4)) // true
nums.sort()
print(nums) // [1, 1, 3, 4, 5, 9]
note

arr.sort() and arr.reverse() mutate the array in place and return nil. array.sort(arr) and array.reverse(arr) return a new array and leave the original unchanged.


std/dict

use std::dict

The std/dict package adds a merge function plus standalone versions of the primitive dict methods.

FunctionDescription
dict.keys(d)Return all keys as an array
dict.values(d)Return all values as an array
dict.has(d, key)True if key is present
dict.get(d, key)Value at key, or nil if absent
dict.merge(d1, d2)Return new dict combining both; d2 wins on duplicate keys

Primitive methods (available without import):

MethodReturnsDescription
d.len()intNumber of key-value pairs
d.keys()arrayAll keys
d.values()arrayAll values
d.has(key)boolTrue if key exists
d.get(key)value | nilValue at key, or nil if missing
use std::dict

let a = {"x": 1, "y": 2}
let b = {"y": 99, "z": 3}

let merged = dict.merge(a, b) // {"x": 1, "y": 99, "z": 3}
print(merged["y"]) // 99

// Primitive methods
let keys = a.keys() // ["x", "y"]
print(a.has("x")) // true
print(a.get("missing")) // nil

std/fs

use std::fs
FunctionReturnsDescription
fs.read(path)strRead entire file as a string
fs.read_bytes(path)bytesThe file as raw octets. Unlike read, works on binary. Tainted.
fs.write_bytes(path, b)nilWrite raw octets, truncating
fs.append_bytes(path, b)nilAppend raw octets
fs.read_stdin_bytes()bytesAll of stdin as raw octets. Tainted.
fs.write_stdout_bytes(b)nilRaw octets to stdout, flushed
fs.write(path, content)nilWrite string to file, creating or overwriting
fs.append(path, content)nilAppend string to file (creates if absent)
fs.exists(path)boolTrue if path exists (file or directory)
fs.delete(path)nilDelete a file
fs.list_dir(path)arrayList entries in a directory (names only, not full paths)
fs.mkdir(path)nilCreate directory (and all parents)
use std::fs

fs.write("hello.txt", "Hello, world!\n")
let content = fs.read("hello.txt")
print(content) // Hello, world!

print(fs.exists("hello.txt")) // true
print(fs.exists("no_such_file.txt")) // false

let entries = fs.list_dir(".")
for entry in entries {
print(entry)
}

fs.mkdir("output/logs")
fs.append("output/logs/run.log", "started\n")
fs.delete("hello.txt")
note

fs.read raises an IoError if the file does not exist. Use fs.exists to check first when the file may be absent.


std/time

use std::time
FunctionReturnsDescription
time.now()intCurrent Unix timestamp in seconds
time.now_ms()intCurrent Unix timestamp in milliseconds
time.sleep(secs)nilBlock execution for secs seconds (int or float)
time.local(tz)strFormatted local time string. Pass a timezone name (e.g. "America/Denver") or nil for the system timezone.
use std::time

let start = time.now_ms()
time.sleep(0.1)
let elapsed = time.now_ms() - start
print(f"elapsed: {elapsed}ms") // elapsed: ~100ms

std/http

use std::http

All HTTP functions return a dict with two keys:

KeyTypeDescription
statusintHTTP status code (e.g. 200)
bodystrResponse body as a string

An optional headers dict may be passed as the last argument to any function. Keys and values must be strings.

A str body is not safe for binary

A str is UTF-8 and NUL-terminated, so a response body read as text loses two things: an invalid UTF-8 sequence becomes , and everything from the first NUL byte onward is dropped. An image, an audio frame, or a gzip stream hits both.

Use get_bytes / post_bytes for those. .body is then a bytes value, which holds any octet. Both spellings exist on std::http and std::uhttp, and both work under jade run and jade build as of v1.2.5.

FunctionDescription
http.get(url, headers?)HTTP GET
http.get_bytes(url, headers?)HTTP GET with an undecoded body (.body is bytes)
http.post_bytes(url, body, headers?)HTTP POST sending raw octets
http.post(url, body, headers?)HTTP POST with string body
http.put(url, body, headers?)HTTP PUT with string body
http.delete(url, headers?)HTTP DELETE
http.head(url, headers?)HTTP HEAD (body will be empty)
use std::http
use std::json

// Simple GET
let resp = http.get("https://api.example.com/status")
print(resp["status"]) // 200
print(resp["body"])

// POST with JSON body and headers
let payload = json.stringify({"name": "jade"})
let resp2 = http.post(
"https://api.example.com/items",
payload,
{"Content-Type": "application/json", "Authorization": "Bearer sk-..."}
)
let result = json.parse(resp2["body"])
note

HTTP errors (non-2xx status) do not raise — check resp["status"] yourself. Only a transport failure raises an IoError: DNS failure, connection refused, a TLS handshake that fails, or a timeout.

std/http runs requests through the curl binary, which has to be on PATH — a missing one is reported as a transport failure. Two consequences follow from that: there is no overall request timeout beyond curl's own defaults, and redirects are not followed, so a 301 comes back as status 301 with the redirect page as its body.


std/uhttp

use std::uhttp

Speaks HTTP/1.1 over a Unix domain socket instead of a TCP host — for talking to local daemons such as the Docker Engine API (/var/run/docker.sock) or other socket-backed OS services. The API mirrors std/http: every function returns the same {status, body} dict, and an optional headers dict may be passed as the last argument.

The target is a single pseudo-URL string of the form:

unix://<socket-path>:<request-path>

The socket path runs up to the first : after the unix:// scheme; everything after it is the request path (so colons inside a query string are preserved). If no request path is given it defaults to /.

FunctionDescription
uhttp.get(url, headers?)HTTP GET
uhttp.get_bytes(url, headers?)HTTP GET with an undecoded body (.body is bytes)
uhttp.post_bytes(url, body, headers?)HTTP POST sending raw octets
uhttp.post(url, body, headers?)HTTP POST with string body
uhttp.put(url, body, headers?)HTTP PUT with string body
uhttp.delete(url, headers?)HTTP DELETE
uhttp.head(url, headers?)HTTP HEAD (body will be empty)
uhttp.stream(url, handler, headers?)Stream a long-lived response, calling handler(line) per line
use std::uhttp
use std::json

// Query the Docker Engine API over its socket
let resp = uhttp.get("unix:///var/run/docker.sock:/v1.43/containers/json")
print(resp["status"]) // 200
let containers = json.parse(resp["body"])

Streaming endpoints

uhttp.stream consumes a response that stays open indefinitely — Docker's /events, /logs?follow=1, or image-pull progress — one line at a time. It calls handler(line) for each newline-delimited line of the body (the newline is stripped) and returns the HTTP status code once the stream ends. The framing is decoded incrementally, so Transfer-Encoding: chunked responses work.

A handler that returns false stops the stream early and closes the socket; any other return value continues.

use std::uhttp
use std::json

// Follow the Docker event stream, printing each event's action
fn on_event(line) {
let event = json.parse(line)
print(event["Action"])
// return false here to stop after the first event
}

uhttp.stream("unix:///var/run/docker.sock:/v1.43/events", on_event)
note

One-shot requests (get/post/…) time out after 30 seconds and send Connection: close; stream keeps the connection open with no read timeout (events may be sparse). Response framing honors Content-Length, Transfer-Encoding: chunked (de-chunked), and read-to-EOF on connection close. HTTP errors (non-2xx status) do not raise — check resp["status"] yourself. A missing socket, a malformed pseudo-URL, or a connection failure raises an IoError.


std/sh

use std::sh

All three functions run commands through sh -c, so shell features like pipes, redirection, and globbing work.

FunctionReturnsDescription
sh.exec(cmd)strRun command, return stdout (trailing newline stripped). Raises if exit code is non-zero.
sh.run(cmd)intRun command with inherited stdio. Returns exit code. Never raises.
sh.output(cmd)dictCapture all output. Returns {stdout: str, stderr: str, code: int}. Never raises.
use std::sh

// exec — great for capturing output of simple commands
let branch = sh.exec("git rev-parse --abbrev-ref HEAD")
print(f"current branch: {branch}")

// run — when you want the command's output to go directly to the terminal
let code = sh.run("npm test")
if code != 0 {
raise "tests failed"
}

// output — when you need full control
let result = sh.output("ls -la nonexistent 2>&1")
print(result["code"]) // 1 or 2
print(result["stderr"]) // ls: cannot access...
warning

sh.exec raises an IoError if the command exits with a non-zero code. Use sh.run or sh.output when you expect failure or need to inspect the exit code.

Untrusted strings cannot become commands

Jade tracks where a string came from. Anything read from outside the program — a model reply, an HTTP body, a file, stdin — is tainted, and the taint spreads through concatenation, f-strings, indexing, and .encode() / .decode().

sh.exec and sh.run refuse a tainted command rather than running it:

use std::sh
use std::fs

let cmd = fs.read("command.txt")
sh.exec(cmd)
// raises: refused tainted string in sh.exec(cmd) — value derived from an
// untrusted source (LLM, network, file, stdin) and cannot flow to a
// code-execution sink

Catch it, or build the command from string literals and interpolate only the parts you have checked yourself.

The output of a shell command is itself tainted, so you cannot launder a value by running it through sh and feeding the result back in.

All three functions check, because all three reach the same sh -c. Until v1.3.3 sh.output did not, which did not narrow what an untrusted command could do — it only meant it had to be written as sh.output(x).stdout.


std/json

use std::json
FunctionReturnsDescription
json.parse(s)valueParse a JSON string into a Jade value
json.stringify(val)strSerialize a Jade value to compact JSON
json.stringify_pretty(val)strSerialize to indented (pretty-printed) JSON

Type mapping:

JSON typeJade type
nullnil
true / falsebool
integer numberint
floating-point numberfloat
stringstr
arrayarray
objectdict
use std::json

// Parse
let data = json.parse('{"name": "jade", "version": 1, "stable": true}')
print(data["name"]) // jade
print(data["version"]) // 1

// Serialize
let compact = json.stringify(data)
print(compact) // {"name":"jade","stable":true,"version":1}

let pretty = json.stringify_pretty(data)
print(pretty)
// {
// "name": "jade",
// "stable": true,
// "version": 1
// }

// Round-trip
let arr = [1, 2, {"x": 3}]
let back = json.parse(json.stringify(arr))
print(back[2]["x"]) // 3
note

json.parse raises an IoError if the input is not valid JSON. Numbers with a decimal point become float; numbers without one become int.


std/env

use std::env
FunctionReturnsDescription
env.get(name)str | nilValue of environment variable name, or nil if unset
env.set(name, value)nilSet environment variable name to value
env.args()arrayCommand-line arguments (including the program name as args[0])
env.cwd()strCurrent working directory as an absolute path
use std::env

// Read an env var with a fallback
let key = env.get("API_KEY")
if key == nil {
raise "API_KEY is not set"
}

// Set a variable (visible to child processes spawned via std/sh)
env.set("DEBUG", "1")

// Inspect command-line arguments
let args = env.args()
print(f"running: {args[0]}")
if args.len() > 1 {
print(f"first arg: {args[1]}")
}

// Working directory
print(env.cwd()) // /home/user/myproject
What args[0] is

env.args() is the process's argument list, so it depends on how the program was started.

A compiled binary run as ./app one two gives ["./app", "one", "two"] — the shape you would expect.

Under the interpreter the process is jade, so the list starts with the jade binary and includes the subcommand: jade run app.jde gives ["…/jade", "run", "app.jde"]. jade run also takes no arguments of its own beyond the file, so there is no way to pass any through it. The old shorthand does accept them — jade app.jde one two gives ["…/jade", "app.jde", "one", "two"] — but the positions still differ from the built program's.

Build the program when argument positions have to be stable.


std/path

use std::path
FunctionReturnsDescription
path.join(base, part, ...)strJoin two or more path segments with the OS separator
path.basename(p)strFilename with extension (last path component)
path.dirname(p)strParent directory; "." for a bare filename
path.ext(p)str | nilFile extension including the dot (e.g. ".rs"), or nil if none
path.stem(p)strFilename without extension
path.abs(p)strAbsolute path (resolves relative to cwd; path need not exist)
path.is_abs(p)boolTrue if the path is absolute
use std::path

let p = path.join("/home/user", "projects", "app", "main.jde")
print(p) // /home/user/projects/app/main.jde

print(path.basename(p)) // main.jde
print(path.dirname(p)) // /home/user/projects/app
print(path.ext(p)) // .jde
print(path.stem(p)) // main
print(path.is_abs(p)) // true

let rel = "src/main.jde"
print(path.dirname(rel)) // src
print(path.is_abs(rel)) // false
print(path.abs(rel)) // /current/working/dir/src/main.jde
note

path.join accepts two or more arguments. If any component is an absolute path it resets the result (same behaviour as Python's os.path.join). path.abs does not resolve symlinks and does not require the path to exist.


std/random

use std::random

Jade uses a single global RNG (seeded from OS entropy at first use). Calling random.seed replaces it with a deterministic seed.

FunctionReturnsDescription
random.int(min, max)intUniformly random integer in [min, max] inclusive
random.float()floatUniformly random float in [0.0, 1.0)
random.choice(arr)valueRandom element from an array. Raises if empty.
random.shuffle(arr)nilShuffle array in place (Fisher-Yates)
random.seed(n)nilReseed the global RNG with integer n for reproducible output
use std::random

// Reproducible output
random.seed(42)

let n = random.int(1, 6) // simulated die roll, 1–6
print(n)

let f = random.float() // 0.0 ≤ f < 1.0
print(f)

let items = ["rock", "paper", "scissors"]
let pick = random.choice(items) // random element
print(pick)

let deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(deck) // in-place shuffle
print(deck)

LLM inference

There is no llm package. Running inference is language syntax, not a package: declare a prompt and dereference it (?p, ?p |> Type). Everything a program used to reach for through use llm — the model, token budget/accounting, anchor handling, retries, health, model profiles, and tool-call parsing — is owned by the provider package now. See LLM Integration.

prompt p = "Write a one-sentence summary of Jade."
let summary = ?p
print(summary)