The Standard Library
Everything marina programs can call without installing a package: a handful of built-in globals, nine import-able std modules, and the methods every array and string carries.
Overview
Two kinds of library ship with the language:
- Built-in globals —
console,setTimeoutandPromiseare always available, no import needed. - Std modules —
net,http,fs,crypto,time,os,sql,mapandrandare brought in with a top-levelimportstatement:
import http
import crypto
Every std function has a synchronous form and an async form that returns a promise — fs.readFile(path) blocks, await fs.readFile(path) runs on the event loop's worker pool. Blocking I/O errors panic with the operation and OS error text.
Built-in globals
| Global | Signature | Description |
|---|---|---|
console.log | log(value) | Prints the value's string form plus a newline. The only console member. |
setTimeout | setTimeout(fn, ms) | Runs fn on a worker thread after ms milliseconds (negative values are treated as 0). |
Promise | new Promise((resolve, reject) => { ... }) | Creates a promise; the executor runs synchronously (JS semantics). await the promise to resume after resolve(value). |
console.log("hello")
setTimeout(() => {
console.log("2 seconds later")
}, 2000)
let p = new Promise((resolve, reject) => {
resolve(42)
})
console.log(await p) // 42
net — raw TCP
net.connect(host, port) opens a TCP connection and returns a Stream. Streams have three methods:
| Method | Description |
|---|---|
stream.write(data) | Send bytes (a string) over the connection. |
stream.read_all() | Read until EOF and return the payload as a string (30s read timeout). |
stream.close() | Close the stream. Unclosed streams are closed when the process exits. |
All four operations (connect included) have async variants. I/O errors panic.
import net
async function main() {
let stream = await net.connect("example.com", 80)
await stream.write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
console.log(await stream.read_all())
await stream.close()
}
http — client & server
The http module has a small client, a low-level server, and an express-style layer on top.
Client
| Function | Description |
|---|---|
http.get(url) | HTTP GET; resolves to an http.Response object { status, body }. |
http.post(url, body) | HTTP POST with a string body; same response shape. |
let res = await http.get("https://api.example.com/v1/ping")
console.log(res.status) // 200
console.log(res.body)
Low-level server
http.listen(port, handler) binds 0.0.0.0:port and serves requests sequentially; the handler receives (req, res) and must be a lambda. res.send(value) replies with plain text, res.json(value) serializes arrays, objects, strings and numbers.
Express-style server
| Member | Description |
|---|---|
new http.Server() | Create a server. Takes no arguments. |
server.router({ path: "/x" }) | Bind a router to a path prefix and register routes with router.get(path, handler) / router.post(path, handler). |
await server.listen(host, port) | Bind and start the poll(2)-multiplexed event loop — many concurrent connections. |
req.body | The raw request body string on http.Request. |
http.JsonValidator | Validate JSON bodies: http.JsonValidator.string() / .number() create field validators, chainable with .required(), .min(n), .max(n); validator.validate(body) returns a checked object. |
fs — filesystem
| Function | Description |
|---|---|
fs.args() | Process arguments (everything after the script name) as Array<String>. |
fs.readFile(path) | Read a whole file into a string. |
fs.writeFile(path, data) | Write a string to a file. |
fs.exists(path) | Does the path exist? |
fs.readDir(path) | Directory entry names, sorted. |
fs.mkdir(path) | Create a directory (recursive). |
fs.remove(path) | Remove a file or directory (recursive for dirs). |
Every function except args also has an async variant. Errors panic with fs.<op> '<path>': <os error>.
import fs
async function main() {
await fs.writeFile("notes.txt", "hello")
console.log(await fs.readFile("notes.txt"))
for (let name in await fs.readDir(".")) {
console.log(name)
}
}
crypto — hashing & encoding
Pure C++ implementations — no OpenSSL dependency:
| Function | Description |
|---|---|
crypto.sha256(data) | Lowercase hex SHA-256 digest. |
crypto.base64Encode(data) | Base64-encode a string. |
crypto.base64Decode(data) | Base64-decode; skips = padding and whitespace, yields lossy UTF-8. |
crypto.randomHex(numBytes) | Cryptographically random bytes from /dev/urandom as lowercase hex (clamped to 0–4096 bytes). |
crypto.uuid() | Random UUID v4. |
import crypto
console.log(crypto.sha256("marina"))
console.log(crypto.base64Encode("marina"))
console.log(crypto.uuid())
time — clocks & sleep
All values are Int64. now-family clocks read the wall clock; mono is unaffected by system clock changes and meant for measuring elapsed time.
| Function | Description |
|---|---|
time.now() | Unix epoch milliseconds (wall clock). |
time.nowSecs() | Unix epoch seconds (wall clock). |
time.nowNanos() | Unix epoch nanoseconds (wall clock). |
time.mono() | Monotonic milliseconds since an arbitrary fixed point. |
time.sleep(ms) | Block the calling thread for ms milliseconds (negatives are 0). |
time.format(ms) | ISO-8601 UTC string for epoch milliseconds, e.g. 2026-10-20T15:04:05.123Z. |
import time
let start = time.mono()
time.sleep(50)
console.log(`slept ${time.mono() - start}ms`)
console.log(time.format(time.now()))
os — platform & process
Platform info, environment variables and process ops. Failures panic (catchable with try/catch); os.env panics on an unset name — use os.envOr for a fallback.
| Function | Description |
|---|---|
os.platform() | "macos", "linux" or "windows". |
os.arch() | Machine architecture, e.g. "arm64", "x86_64". |
os.hostname() | The machine's host name. |
os.cwd() | Current working directory. |
os.tmpdir() | $TMPDIR, falling back to "/tmp". |
os.pid() | Process id (Int64). |
os.env(name) | Environment variable; panics when unset. |
os.envOr(name, fallback) | Environment variable or the fallback when unset. |
os.setEnv(name, value) / os.unsetEnv(name) | Set (overwriting) / remove an environment variable. |
os.exec(command) | Run via /bin/sh and capture stdout; stderr passes through; panics on a non-zero exit status. |
os.exit(code) | Terminate the process with the given exit status. |
import os
console.log(os.platform()) // macos
console.log(os.arch())
os.setEnv("GREETING", "hi")
console.log(os.env("GREETING"))
console.log(os.exec("echo rendered by /bin/sh"))
sql — SQLite
SQLite via the system libsqlite3 (MySQL/Postgres drivers are not available yet). Values are always bound as prepared-statement parameters — never string-concatenated — through the sql.stmt tagged template: ${expr} binds a value; only integers, floats, strings and bools can be bound.
| Member | Description |
|---|---|
new sql.Connection(driver, url) | Open a connection; only "sqlite" is supported. |
db.execute(stmt) | Run a statement that returns no rows; resolves to { lastInsertId, changes }. |
db.query(stmt) | Collect rows as objects whose fields are the column names (Array<Row>). |
db.close() | Close the connection. |
import sql
async function main() {
let db = new sql.Connection("sqlite", "app.db")
await db.execute(sql.stmt`CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, name TEXT)`)
let result = await db.execute(sql.stmt`INSERT INTO t (name) VALUES (${"marina"})`)
console.log(result.lastInsertId)
let rows = await db.query(sql.stmt`SELECT id, name FROM t`)
console.log(rows)
}
map — a dictionary, written in Marina itself
Like rand below, the whole module is Marina code (stdlib/map/main.tsm) — the proof that the module system and generics are real. A string-keyed dictionary Map<V>; each distinct value type V produces its own specialized copy of the code at compile time, so lookups cost a plain function call.
| Member | Description |
|---|---|
map.newMap<V>() | Create an empty map (the factory is the public way in; generic new map.Map<V>() is not supported yet). |
m.set(key, value) | Insert or overwrite; keys keep insertion order. |
m.get(key) | The value at key; a missing key aborts with the array bounds panic (no error values). |
m.getOr(key, fallback) | Safe read — returns fallback when the key is absent. |
m.has(key) | Key present? |
m.delete(key) / m.clear() | Remove one entry / remove everything. |
m.size / m.keys / m.values | Getters: entry count, the keys (Array<string>) and the values, in key insertion order. |
import map
let ages = map.newMap<Int32>()
ages.set("lena", 30)
ages.set("kim", 25)
console.log(ages.get("lena")) // 30
console.log(ages.getOr("zoe", 0)) // 0
console.log(ages.has("kim")) // true
console.log(ages.keys) // [lena, kim]
rand — randomness
Written in Marina itself (stdlib/rand/main.tsm, merged like a package). A Rand holds a 64-bit linear congruential state advanced with multiply/add; the array helpers draw from an independent 32-bit stream seeded from /dev/urandom (integer widths do not convert to each other, so Int32 indices need their own sequence).
| Member | Description |
|---|---|
rand.newSeeded() | A generator seeded from the wall clock and the monotonic clock. |
rand.newRand(seed) | A generator from an explicit Int64 seed (same seed → same Int64 sequence; the Int32 stream stays urandom-seeded). |
r.next() | The raw next value — the full signed Int64 state. |
r.below(n) | Uniform Int64 in [0, n). |
r.range(lo, hi) | Uniform Int64 in [lo, hi). |
r.float() | Uniform Float64 in [0, 1) with 48 bits of precision. |
r.bool() | Uniform bool. |
r.int(max) | Uniform Int32 in [0, max) — sized for array indexing. |
rand.pick<T>(r, items) | A random element of a non-empty array. |
rand.shuffle<T>(r, items) | Fisher–Yates shuffle — returns a new array, the input is untouched. |
Invalid inputs (empty arrays, non-positive bounds) throw and are catchable with try/catch.
import rand
let r = rand.newSeeded()
console.log(r.below(100)) // 0..99
console.log(r.range(1, 7)) // dice roll
console.log(r.float()) // 0.0..<1.0
console.log(rand.pick<string>(r, ["apple", "banana", "cherry"]))
console.log(rand.shuffle<Int32>(r, [1, 2, 3, 4, 5]))
Array methods
Every array value carries these members (callbacks run synchronously):
| Member | Description |
|---|---|
length | Number of elements. |
push(v) / unshift(v) | Append / prepend a value; returns the new length. |
pop() / shift() | Remove and return the last / first element (panics on empty). |
splice(start, count) | Remove count elements at start (clamped); returns them as a new array. |
slice(start, end) | Copy elements [start, end) (clamped) into a new array. |
concat(other) | New array with the elements of both arrays. |
join(sep) | Join the elements' string forms with a separator. |
reverse() / sort() | In place; returns the same array. sort is stable — numbers numerically, strings bytewise. |
forEach(item => Void) | Run a callback for each element. |
map(item => T) | New array of the callback results. |
filter(item => bool) | New array of elements whose callback returned true. |
reduce((acc, item) => T, init) | Fold the array into a single value. |
Indexing (arr[i]) is bounds-checked and panics when out of range.
String members
Strings are UTF-8 byte sequences; indices are byte offsets:
| Member | Description |
|---|---|
length | Length in bytes. |
charAt(index) | The 1-char string at byte index ("" when out of bounds, like JavaScript). |
charCodeAt(index) | Byte (code unit) at index, 0 when out of bounds. |
substring(start, end) | Substring over byte indices [start, end), clamped; an end below start yields "". |
String.fromCharCode(code) builds a 1-char string from a code unit: String.fromCharCode(72) is "H". It also accepts a 1-char string (String.fromCharCode(s.charAt(0))), using its byte code. String equality (==/!=) compares content, and any value can be interpolated into template literals: `hello ${name}`. console.log formats any value via its string form.