Standard library
Docs index
Everything here is built in; no imports needed.
Global functions
| Function |
Description |
print(...values: any) -> null |
Prints values separated by spaces, then a newline. |
input(prompt?: str) -> ?str |
Reads one line from stdin (without the newline). Returns null at end of input. |
len(x: str \| array \| map \| range) -> int |
Length of a str (characters), array, map, range or struct instance. |
type(x: any) -> str |
Type name: "int", "str", "User", … |
str(x: any) -> str |
Text form of any value. |
int(x: any, default?: int) -> int |
Converts str/float/bool to int. Raises ValueError, or returns default if given. |
float(x: any, default?: float) -> float |
Converts to float, same rules as int. |
bool(x: any) -> bool |
Truthiness of x. |
range(end: int) -> array / range(start: int, end: int, step?: int) -> array |
Array of ints (Python-style, step may be negative). |
error(message: str, kind?: str) -> error |
Creates an error value to throw. |
assert(cond: any, message?: str) -> null |
Raises AssertionError if cond is falsy. |
assert_eq(a: any, b: any, message?: str) -> null |
Raises AssertionError showing both values if a != b. |
validate(data: ?map, rules: map) -> map |
Checks and converts input (req.form, req.json, …) against rules such as "int min:0 max:150"; returns { ok, errors, data }. See Validation. |
clock() -> float |
Milliseconds since the program started (float). |
str methods
| Method |
Result |
s.len() -> int |
number of characters |
s.upper() -> str / s.lower() -> str / s.capitalize() -> str |
case changes |
s.trim() -> str / s.trim_start() -> str / s.trim_end() -> str |
remove whitespace |
s.split(sep?: str, limit?: int) -> array |
array of parts; no sep splits on whitespace; "" splits into characters |
s.lines() -> array |
array of lines |
s.chars() -> array |
array of characters |
s.contains(sub: str) -> bool / s.starts_with(p: str) -> bool / s.ends_with(p: str) -> bool |
bool |
s.index_of(sub: str) -> int |
character index or -1 |
s.count(sub: str) -> int |
non-overlapping occurrences |
s.replace(from: str, to: str) -> str |
replaces every occurrence |
s.repeat(n: int) -> str / s.reverse() -> str |
new string |
s.pad_start(width: int, fill?: str) -> str / s.pad_end(width: int, fill?: str) -> str |
padded string |
s.slice(start: int, end?: int) -> str |
substring by character index (same as s[start..end]) |
s.is_empty() -> bool |
bool |
array methods
Read / transform (return new values, never change the array):
| Method |
Result |
a.len() -> int / a.is_empty() -> bool |
size checks |
a.get(i: int, default?: any) -> any |
item at i or default/null (no error) |
a.first() -> any / a.last() -> any |
first / last item or null |
a.contains(v: any) -> bool / a.index_of(v: any) -> int |
membership / index or -1 |
a.map(f: fn) -> array / a.filter(f: fn) -> array / a.each(f: fn) -> null |
callbacks receive (item) or (item, index) |
a.reduce(f: fn, initial?: any) -> any |
folded value |
a.find(f: fn) -> any / a.find_index(f: fn) -> int |
first match / its index (null / -1) |
a.any(f: fn) -> bool / a.all(f: fn) -> bool / a.count(f?: fn) -> int |
bool / bool / int |
a.sum() -> num / a.min() -> any / a.max() -> any |
numbers (min/max also compare strings) |
a.sort(key?: fn) -> array |
sorted copy; key_fn picks the sort key: users.sort(fn(u) => u.age) |
a.reverse() -> array / a.unique() -> array / a.flatten() -> array |
new arrays |
a.slice(start: int, end?: int) -> array / a.take(n: int) -> array / a.skip(n: int) -> array |
sub-arrays |
a.chunk(n: int) -> array / a.zip(other: array) -> array |
[[...], ...] |
a.group_by(f: fn) -> map |
map from key to array of items |
a.concat(...others: array) -> array / a.join(sep?: str) -> str / a.copy() -> array |
combined array / string / shallow copy |
Mutate (change the array in place):
| Method |
Effect |
a.push(...items: any) -> null |
append |
a.pop() -> any / a.shift() -> any |
remove and return the last / first item (null if empty) |
a.unshift(...items: any) -> null |
insert at the front |
a.insert(index: int, item: any) -> null |
insert at a position |
a.remove_at(index: int) -> any |
remove and return the item at index |
a.remove(value: any) -> bool |
remove the first equal item; returns true if found |
a.clear() -> null |
remove everything |
map methods
| Method |
Result |
m.len() -> int / m.is_empty() -> bool |
size checks |
m.keys() -> array / m.values() -> array / m.entries() -> array |
arrays (insertion order); entries are [key, value] |
m.has(key: str) -> bool |
bool (same as key in m) |
m.get(key: str, default?: any) -> any |
value or default/null |
m.set(key: str, value: any) -> null |
same as m[key] = value |
m.remove(key: str) -> any |
removes and returns the value (or null) |
m.merge(...others: map) -> map |
new map with later maps winning |
m.filter(f: fn) -> map / m.each(f: fn) -> null |
new map / iteration |
m.copy() -> map |
shallow copy |
m.clear() -> null |
remove every key |
If a map contains a function under a key, m.key(...) calls that function first
(this is how modules and http.app() objects work).
number methods
| Method |
Example |
n.abs() -> num |
(-3).abs() == 3 |
n.round(digits?: int) -> num |
3.14159.round(2) == 3.14; without digits returns an int |
n.floor() -> int / n.ceil() -> int |
ints |
n.fixed(digits: int = 2) -> str |
string with exactly digits decimals: 2.5.fixed(2) == "2.50" |
n.clamp(lo: num, hi: num) -> num |
value limited to the range |
range methods
r.len(), r.contains(n), r.to_array(), and every array method
((1..5).map(...), (0..10).filter(...), …).
math
| Name |
Description |
math.pi: float, math.e: float, math.inf: float |
constants |
math.abs(x: num) -> num, math.floor(x: num) -> int, math.ceil(x: num) -> int, math.round(x: num, digits?: int) -> num |
rounding |
math.div(a: int, b: int) -> int |
floor division of ints (math.div(-7, 2) == -4) |
math.sqrt(x: num) -> float, math.pow(x: num, y: num) -> float, math.exp(x: num) -> float, math.log(x: num, base?: num) -> float, math.log10(x: num) -> float, math.log2(x: num) -> float |
powers and logs |
math.sin(x: num) -> float, math.cos(x: num) -> float, math.tan(x: num) -> float, math.atan2(y: num, x: num) -> float |
trigonometry (radians) |
math.min(...values: num) -> num, math.max(...values: num) -> num |
of arguments or of one array |
math.random() -> float |
float in [0, 1) (not for secrets; use crypto) |
math.random_int(lo: int, hi: int) -> int |
int in [lo, hi] |
json
| Function |
Description |
json.encode(value: any, pretty: bool = false) -> str |
JSON text. Maps, arrays, struct instances, strings, numbers, bools and null are supported. <, > and & are escaped so the output is safe inside <script>. |
json.decode(text: str) -> any |
Korr values. Raises JSONError with the position on invalid input. Nesting is limited to 256 levels. |
let text = json.encode({ name: "Korr", tags: ["web", "cli"] }, true)
let back = json.decode(text)
print(back.tags[0])
fs
Paths are relative to the current working directory (use __dir__ for paths
relative to the source file).
| Function |
Description |
fs.read(path: str) -> str |
whole file as a string |
fs.write(path: str, text: str) -> null / fs.append(path: str, text: str) -> null |
write / append (creates the file) |
fs.exists(path: str) -> bool / fs.is_file(path: str) -> bool / fs.is_dir(path: str) -> bool |
checks |
fs.list(dir: str) -> array |
sorted array of entry names |
fs.mkdir(path: str) -> null |
creates the directory and its parents |
fs.remove(path: str) -> null |
removes a file or an empty directory |
fs.copy(from: str, to: str) -> null / fs.rename(from: str, to: str) -> null |
copy / move |
fs.size(path: str) -> int |
size in bytes |
fs.walk(dir: str) -> array |
every file below dir, as sorted relative paths with / (hidden files and folders are skipped) |
fs.glob(pattern: str) -> array |
files matching a pattern: * and ? within a name, ** for any folders, e.g. fs.glob("src/**/*.krr") |
Failures raise IOError with the path and the OS reason.
os
| Name |
Description |
os.args() -> array |
command-line arguments after the script name |
os.env(name: str, default?: str) -> ?str |
environment variable or default/null |
os.cwd() -> str |
current directory |
os.platform: str |
"linux", "macos", "windows", … |
os.is_main() -> bool |
true when the current file is the program entry point |
os.exit(code: int = 0) -> null |
stop the program with an exit code |
os.load_env(path: str = ".env") -> map |
reads KEY=VALUE lines (comments, export, "..." and '...' quoting) and returns them as a map; os.env() then sees them. Real environment variables always win. |
os.exec(program: str, args: array = []) -> map |
runs a program without a shell and returns { code, ok, stdout, stderr } |
os.exec("git", ["log", user_input]) is safe: arguments are passed directly to the
program, so text like ; rm -rf / is never interpreted by a shell.
time
| Function |
Description |
time.now() -> int |
Unix time in milliseconds (int) |
time.unix() -> int |
Unix time in seconds (int) |
time.sleep(ms: int) -> null |
pause |
time.date(ms?: int) -> map |
{ year, month, day, hour, minute, second, weekday } in UTC (weekday 0 = Sunday) |
time.iso(ms?: int) -> str |
ISO-8601 UTC string, e.g. "2026-11-28T12:00:00Z" |
time.format(fmt: str, ms?: int, utc_offset_minutes: int = 0) -> str |
strftime-style text: time.format("%d %B %Y %H:%M", t, 420) gives "28 November 2026 14:30" |
time.parse(text: str) -> int |
milliseconds from ISO-8601: "2026-11-28", "2026-11-28 14:30:00", "2026-11-28T14:30:00.250+07:00" (no offset = UTC); ValueError if invalid |
Format codes: %Y year, %y 2-digit year, %m month, %d day, %e day without
padding, %H hour (24h), %I hour (12h), %p AM/PM, %M minute, %S second,
%L milliseconds, %j day of year, %a/%A weekday, %b/%B month name,
%z +0700, %:z +07:00, %Z UTC or offset, %s Unix seconds, %% %.
Time zones are fixed offsets in minutes (WIB = 420, WITA = 480, WIT = 540).
encoding
encoding.base64_encode(s), encoding.base64_decode(s),
encoding.url_encode(s), encoding.url_decode(s) (+ becomes a space),
encoding.hex_encode(s).
crypto
All implemented in Korr’s own Rust code (no external crypto library); secure
randomness comes from the operating system.
| Function |
Description |
crypto.sha256(text: str) -> str |
hex digest |
crypto.hmac_sha256(key: str, message: str) -> str |
hex HMAC (for signing tokens/cookies) |
crypto.token(bytes: int = 32) -> str |
random hex string (session IDs, CSRF tokens, API keys) |
crypto.uuid() -> str |
random UUID v4 |
crypto.equal(a: str, b: str) -> bool |
constant-time string comparison (use it for secrets) |
crypto.hash_password(password: str, iterations: int = 600000) -> str |
PBKDF2-HMAC-SHA256 with a random salt, returns "pbkdf2_sha256$iterations$salt$hash" |
crypto.verify_password(password: str, stored: str) -> bool |
true if the password matches the stored hash |
let stored = crypto.hash_password("correct horse battery staple")
print(crypto.verify_password("correct horse battery staple", stored)) // true
html
| Function |
Description |
html.escape(text: str) -> str |
escapes & < > " ' |
html.raw(text: str) -> html |
marks text as trusted HTML so html"..." templates do not escape it |
http
http.app() creates a web application. See Full-stack web for a guide.
| Function |
Description |
http.app() -> app |
new app with routing methods (below) |
http.worker_id() -> int |
which server worker runs this code: 0 for the first, 1, 2, … for the others |
http.json(data: any, status: int = 200, headers?: map) -> response |
JSON response |
http.html(body: str, status: int = 200, headers?: map) -> response |
HTML response |
http.text(body: str, status: int = 200, headers?: map) -> response |
plain-text response |
http.redirect(url: str, status: int = 302) -> response |
redirect |
http.response(body: any, status: int = 200, headers?: map) -> response |
custom response |
http.cookie(name: str, value: str, options?: map) -> str |
Set-Cookie value; options path, max_age, http_only (default true), secure, same_site (default "Lax") |
http.sse(topics: str \| array) -> response |
a Server-Sent Events stream: the connection stays open and receives http.publish messages for these topics |
http.publish(topic: str, message: any, event?: str) -> null |
send a message to every WebSocket and SSE subscriber of topic, in every worker (maps and arrays are sent as JSON) |
App methods:
| Method |
Description |
app.get/post/put/patch/delete/any(path: str, handler: fn) -> null |
add a route; :name captures a segment, * captures the rest |
app.ws(path: str, handlers: map) -> null |
a WebSocket route; handlers open(ws), message(ws, text), close(ws); options origins (extra page origins allowed to connect) and max_message (bytes, default 1 MB). See WebSockets |
app.static(prefix: str, dir: str) -> null |
serve files from dir under prefix |
app.before(hook: fn) -> null |
runs before routing; return a response to stop, or null to continue |
app.not_found(handler: fn) -> null |
custom 404 |
app.limit(bytes: int) -> null |
maximum request body (default 10 MB) |
app.cors(options: map) -> null |
let pages on other sites call this server: origins (required; ["*"] for any site), methods, headers, expose, credentials (cookies; not with "*"), max_age (seconds, default 600). See CORS |
app.rate_limit(options: map) -> null |
at most requests per per seconds (default 60) for each client address, shared by all workers; paths limits only these prefixes. Over the limit: 429 with Retry-After |
app.trust_proxy(on: bool) -> null |
behind a reverse proxy: take req.ip (and the rate limit’s client address) from X-Forwarded-For |
app.logging(on: bool) -> null |
access log on/off (errors are always logged) |
app.sessions(secret: str, options?: map) -> null |
cookie sessions (req.session) and CSRF protection; options cookie, max_age (seconds, default 7 days), secure, csrf (default true). See Sessions. |
app.request(method: str, path: str, options?: map) -> map |
simulate a request (for tests); options: headers, json, form, body, files |
app.listen(port: int, host: str = "127.0.0.1") -> null |
start serving (blocks) |
app.listen(port: int, options: map) -> null |
options host (str) and workers (int, or "auto" for one per CPU thread): serve several requests at once; also KORR_WORKERS |
A WebSocket connection (ws in the handlers of app.ws):
| Field or method |
Description |
ws.id: int |
the connection’s number, unique in the server |
ws.path: str |
the path it connected to |
ws.request: map |
the upgrade request: params, query, headers, cookies, session (read-only) |
ws.data: map |
your own data for this connection (for example the user name) |
ws.send(message: any) -> bool |
send a text message (maps and arrays as JSON); false if the connection is closed |
ws.subscribe(topic: str) -> null |
receive http.publish(topic, ...) messages |
ws.unsubscribe(topic: str) -> null |
stop receiving a topic |
ws.close(code: int = 1000, reason?: str) -> null |
close the connection |
Uploaded files (req.files.<field>, see File uploads):
| Field |
Description |
f.filename: str |
safe file name: last path part, only letters, digits, ., -, _ |
f.original_filename: str |
the name the browser sent (do not use it in paths) |
f.content_type: str |
type the browser sent, e.g. "image/png" (not verified) |
f.size: int |
size in bytes |
f.save(path: str) -> int |
write the file (creates missing folders); returns the size |
f.text() -> str |
the content as text (UTF-8) |
http client
Call other APIs and websites (HTTPS certificates are always verified):
| Function |
Description |
http.get(url: str, options?: map) -> map |
GET request |
http.post(url: str, options?: map) -> map, http.put(url: str, options?: map) -> map, http.patch(url: str, options?: map) -> map, http.delete(url: str, options?: map) -> map |
other methods |
http.fetch(method: str, url: str, options?: map) -> map |
any method |
Options: headers (map), query (map, appended to the URL), json (sends JSON),
form (sends a URL-encoded form), body (raw text), timeout (ms, default
30000).
The result is { status, ok, headers, body, json }: ok is true for 2xx,
json is the decoded body when the response is JSON (else null). A status such as
404 or 500 is not an error (check ok); network failures, timeouts and invalid
certificates raise HTTPError. Responses are limited to 50 MB.
// no-check
let res = http.get("https://api.example.com/users", { query: { page: 2 }, headers: { authorization: "Bearer {token}" } })
if res.ok
print(res.json)
let created = http.post("https://api.example.com/users", { json: { name: "Ana" } })
print(created.status)
db
SQLite, PostgreSQL and MySQL/MariaDB with one API; see the
database guide.
| Function |
Description |
db.open(url: str) -> connection |
a connection: sqlite:app.db, sqlite::memory:, postgres://..., mysql://... |
db.drivers: array |
drivers compiled into this Korr |
conn.exec(sql: str, params?: array \| map) -> map |
{ affected, last_id } |
conn.query(sql: str, params?: array \| map) -> array / conn.one(sql: str, params?: array \| map) -> ?map / conn.value(sql: str, params?: array \| map) -> any |
rows / first row / first value |
conn.transaction(f: fn) -> any |
commit on success, rollback on error |
conn.migrate(dir: str) -> array |
apply the *.sql files in dir that have not run yet, in name order; returns the names applied. See Migrations. |
conn.close() -> null |
close |
log
Levelled, structured logging to stderr (default), stdout or a file.
| Function |
Description |
log.debug(msg: str, fields?: map) -> null, log.info(msg: str, fields?: map) -> null, log.warn(msg: str, fields?: map) -> null, log.error(msg: str, fields?: map) -> null |
write a line if the level is enabled |
log.level(name?: str) -> str |
get or set the minimum level: debug, info (default), warn, error, off |
log.format(name: str) -> null |
output format: "text" (default) or "json" |
log.output(target: str) -> null |
"stderr", "stdout" or a file path (appended, folders created) |
Defaults can be set with the environment variables KORR_LOG_LEVEL and
KORR_LOG_FORMAT.
log.info("server started", { port: 8080, mode: "dev" })
// 2026-11-28T14:24:46.638Z INFO server started port=8080 mode=dev
log.format("json")
log.warn("disk low", { free_mb: 120 })
// {"time":"2026-11-28T14:24:46.638Z","level":"warn","msg":"disk low","free_mb":120}
re
Regular expressions with guaranteed linear-time matching (a hostile pattern or
input cannot freeze your server). Write patterns in raw 'single-quoted' strings so
backslashes and {n} need no escaping. Syntax: Rust regex (Perl-like: \d, \w,
\s, [a-z], +, *, ?, {2,4}, (...), (?<name>...), (?i) for
case-insensitive).
| Function |
Result |
re.test(pattern: str, text: str) -> bool |
bool |
re.find(pattern: str, text: str) -> ?str |
first match text or null |
re.find_all(pattern: str, text: str) -> array |
array of match texts |
re.match(pattern: str, text: str) -> ?map |
{ text, start, end, groups, named } or null |
re.match_all(pattern: str, text: str) -> array |
array of matches |
re.replace(pattern: str, text: str, replacement: str \| fn) -> str |
replacement is a string ($1, ${name}) or fn(match) => str |
re.split(pattern: str, text: str) -> array |
array of parts |
re.escape(text: str) -> str |
pattern that matches text literally |
print(re.test('^\d{4}-\d{2}-\d{2}$', "2026-11-28")) // true
let m = re.match('(?<user>[\w.]+)@(?<host>[\w.]+)', "mail ana@korr.dev")
print(m.named.user, m.named.host) // ana korr.dev
print(re.replace('\s+', " too many spaces ", " ").trim()) // too many spaces
path
| Function |
Example |
path.join(...parts: str) -> str |
path.join("a", "b/../c", "d.txt") gives "a/c/d.txt" |
path.normalize(p: str) -> str |
removes . and .. |
path.abs(p: str) -> str |
absolute, normalised path |
path.is_abs(p: str) -> bool |
bool |
path.basename(p: str) -> str / path.dirname(p: str) -> str |
"file.txt" / "a/b" |
path.ext(p: str) -> str / path.stem(p: str) -> str |
".txt" / "file" |
path.sep: str |
"/" (or "\\" on Windows) |
cli
Arguments and options for command-line programs, with a generated --help.
See CLI apps for a full example.
| Function |
Description |
cli.parse(spec: map, argv?: array) -> map |
parses os.args() (or argv) and returns { option: value, ..., argument: value }. On --help it prints the usage and exits; on a mistake it prints the error and the usage and exits with code 2 (with exit: false in the spec it returns { help } or throws a UsageError instead) |
cli.usage(spec: map) -> str |
the help text for a spec |
The spec is a map: name (default: the script name), about, options and
args. Each option is { short, type, default, required, help } (type is
"bool" (default), "str", "int" or "float"; bool options are flags), or just
a help string. args lists positional arguments in order: "name" (required),
"name?" (optional), "name..." (the rest, as an array). Options accept
--name value, --name=value, -n value, -n5 and combined flags -vq;
-- ends the options.
term
Text styling and facts about the terminal. Styles are added only when standard
output is a terminal and the NO_COLOR environment variable is not set (or when
FORCE_COLOR is set), so output piped to a file stays plain.
| Function |
Description |
term.red(text: any) -> str, term.green(text: any) -> str, term.yellow(text: any) -> str, term.blue(text: any) -> str, term.magenta(text: any) -> str, term.cyan(text: any) -> str, term.white(text: any) -> str, term.gray(text: any) -> str, term.black(text: any) -> str |
colored text |
term.color(text: any, name: str) -> str |
colored text by color name |
term.bold(text: any) -> str, term.dim(text: any) -> str, term.italic(text: any) -> str, term.underline(text: any) -> str |
styled text |
term.strip(text: str) -> str |
text without color and style codes |
term.is_tty() -> bool |
true when standard output is a terminal |
term.colors() -> bool |
true when styles are being applied |
term.width() -> int |
terminal width in columns (COLUMNS, default 80) |
csv
| Function |
Description |
csv.parse(text: str, options?: map) -> array |
array of arrays; with { header: true } an array of maps. Handles quoted fields, "" escapes and newlines inside quotes. |
csv.encode(rows: array, options?: map) -> str |
text from arrays or maps (maps write a header row) |
Option sep changes the separator ({ sep: ";" }).
let rows = csv.parse("name,city\nAna,Bandung\n", { header: true })
print(rows[0].city) // Bandung
print(csv.encode([{ name: "Budi", city: "Jakarta, ID" }]))