API: stdlib
Generated from Geblang source declarations and docblocks.
async.http
Source: stdlib/async/http.gb
Function get
func get(string url): Task<any>
Starts an asynchronous HTTP GET request and resolves to the native HTTP response value.
Function post
func post(string url, any body): Task<any>
Starts an asynchronous HTTP POST request with the given body.
Function postJson
func postJson(string url, any body): Task<any>
Starts an asynchronous JSON POST request, encoding the body as JSON.
Function request
func request(string method, string url, any body): Task<any>
Starts an asynchronous HTTP request for the supplied method, URL, and body.
Function requestWithOptions
func requestWithOptions(dict<string, any> options): Task<any>
Starts an asynchronous HTTP request using the native HTTP options dictionary.
Function parseJson
func parseJson(any response): Task<any>
Parses an HTTP response body as JSON asynchronously.
async.io
Source: stdlib/async/io.gb
Function readText
func readText(string path): Task<string>
Reads a text file asynchronously and resolves to its full contents.
Function writeText
func writeText(string path, string text): Task<any>
Writes text to a file asynchronously, replacing any existing contents.
Function appendText
func appendText(string path, string text): Task<any>
Appends text to a file asynchronously.
Function readBytes
func readBytes(string path): Task<bytes>
Reads a file as bytes asynchronously.
Function writeBytes
func writeBytes(string path, bytes data): Task<any>
Writes bytes to a file asynchronously, replacing any existing contents.
Function appendBytes
func appendBytes(string path, bytes data): Task<any>
Appends bytes to a file asynchronously.
Function read
func read(any handle, int size): Task<any>
Reads up to size units from an open handle asynchronously.
Function readAll
func readAll(any handle): Task<any>
Reads all remaining data from an open handle asynchronously.
Function write
func write(any handle, any value): Task<any>
Writes a value to an open handle asynchronously.
Function writeln
func writeln(any handle, any value): Task<any>
Writes a value and newline to an open handle asynchronously.
Function flush
func flush(any handle): Task<any>
Flushes an open handle asynchronously when the handle supports flushing.
Function close
func close(any handle): Task<any>
Closes an open handle asynchronously.
Function stat
func stat(string path): Task<any>
Reads filesystem metadata for a path asynchronously.
Function listDir
func listDir(string path): Task<any>
Lists directory entries asynchronously.
async.net
Source: stdlib/async/net.gb
Function lookupHost
func lookupHost(string host): Task<any>
Resolves a host name asynchronously.
Function listenTcp
func listenTcp(string address): Task<any>
Starts a TCP listener asynchronously.
Function connectTcp
func connectTcp(string address): Task<any>
Opens a TCP connection asynchronously.
Function accept
func accept(any listener): Task<any>
Accepts the next TCP connection from a listener asynchronously.
Function read
func read(any conn, int size): Task<any>
Reads from a network connection asynchronously.
Function write
func write(any conn, any data): Task<any>
Writes data to a network connection asynchronously.
Function close
func close(any handle): Task<any>
Closes a network listener or connection asynchronously.
Function listenUdp
func listenUdp(string address): Task<any>
Starts a UDP listener asynchronously.
Function dialUdp
func dialUdp(string address): Task<any>
Opens a UDP connection asynchronously.
Function readFrom
func readFrom(any conn, int size): Task<any>
Reads a UDP datagram and sender address asynchronously.
Function writeTo
func writeTo(any conn, any data, string address): Task<any>
Writes a UDP datagram to an address asynchronously.
async.rate
Source: stdlib/async/rate.gb
Function throttle
func throttle(func fn, int ms): func
Returns a wrapper that invokes fn at most once per ms milliseconds.
Subsequent calls within the window return the result of the most
recent invocation without calling fn again. Useful for rate-limiting
handlers that fire on every keystroke / scroll / message.
let log = async.rate.throttle(func(string m): void {
io.println(m);
}, 200);
log("a"); log("b"); log("c"); only one io.println in 200ms
Function debounce
func debounce(func fn, int ms): func
Returns a wrapper that delays invocation until ms milliseconds have
passed since the last call. Repeated calls within that window cancel
prior pending invocations.
The wrapper returns a Task<any> that resolves to the value of fn
once it eventually runs, or null if a later call superseded it.
await it if you care about the result.
let save = async.rate.debounce(func(string text): void {
persist(text);
}, 300);
save("hello"); save("hello!"); save("hello world");
persist("hello world") runs 300ms after the last call
async.stream
Source: stdlib/async/stream.gb
Function jsonStream
func jsonStream(any source, any handler): Task<int>
Streams JSON values from a source through a handler asynchronously.
Function jsonReader
func jsonReader(any source): Task<any>
Creates a JSON streaming reader asynchronously.
Function yamlStream
func yamlStream(any source, any handler): Task<int>
Streams YAML values from a source through a handler asynchronously.
Function yamlReader
func yamlReader(any source): Task<any>
Creates a YAML streaming reader asynchronously.
Function xmlStream
func xmlStream(any source, any handler): Task<int>
Streams XML values from a source through a handler asynchronously.
Function xmlReader
func xmlReader(any source): Task<any>
Creates an XML streaming reader asynchronously.
Function csvStream
func csvStream(any source, any handler): Task<int>
Streams CSV rows from a source through a handler asynchronously.
Function csvReader
func csvReader(any source): Task<any>
Creates a CSV streaming reader asynchronously.
cli.color
Source: stdlib/cli/color.gb
Function isEnabled
func isEnabled(): bool
Returns true when color output is currently enabled (NO_COLOR unset or empty).
Function bold
func bold(string s): string
Function dim
func dim(string s): string
Function italic
func italic(string s): string
Function underline
func underline(string s): string
Function black
func black(string s): string
Function red
func red(string s): string
Function green
func green(string s): string
Function yellow
func yellow(string s): string
Function blue
func blue(string s): string
Function magenta
func magenta(string s): string
Function cyan
func cyan(string s): string
Function white
func white(string s): string
Function bgBlack
func bgBlack(string s): string
Function bgRed
func bgRed(string s): string
Function bgGreen
func bgGreen(string s): string
Function bgYellow
func bgYellow(string s): string
Function bgBlue
func bgBlue(string s): string
Function bgMagenta
func bgMagenta(string s): string
Function bgCyan
func bgCyan(string s): string
Function bgWhite
func bgWhite(string s): string
cli.command
Source: stdlib/cli/command.gb
Class Option
class Option
Describes a typed command-line option and converts it to cli.parseArgs schema data.
Field name
string name
Field kind
string kind
Field shortName
string shortName
Field helpText
string helpText
Field requiredFlag
bool requiredFlag
Field hasDefaultValue
bool hasDefaultValue
Field defaultValue
any defaultValue
Method Option
func Option(string name, string kind)
Method short
func short(string name): Option
Method help
func help(string text): Option
Method required
func required(): Option
Method default
func default(any value): Option
Method toSchema
func toSchema(): dict<string, any>
Class Command
class Command
Describes a command with options, parsing, help text, and required-argument validation.
Field name
string name
Field description
string description
Field options
list<any> options
Method Command
func Command(string name, string description)
Method option
func option(Option option): Command
Method schema
func schema(): dict<string, any>
Method parse
func parse(list<string> argv): dict<string, any>
Method help
func help(): string
Method requireParsed
func requireParsed(list<string> argv): dict<string, any>
Function newOption
func newOption(string name, string kind): Option
Creates a command option builder for the given long name and type.
Function newCommand
func newCommand(string name, string description): Command
Creates a command builder with a name and human-readable description.
config
Source: stdlib/config.gb
Function clone
func clone(dict<string, any> data): dict<string, any>
Returns a shallow copy of a configuration dictionary.
Function merge
func merge(dict<string, any> base, dict<string, any> overrides): dict<string, any>
Recursively merges override values into a copy of base.
Function defaults
func defaults(dict<string, any> values, dict<string, any> defaultValues): dict<string, any>
Applies default values first, then overlays explicit values.
Function layer
func layer(list<any> layers): dict<string, any>
Merges a list of configuration dictionaries from first to last.
Function has
func has(dict<string, any> data, string path): bool
Returns true when a dotted configuration path exists.
Function get
func get(dict<string, any> data, string path): any
Returns a required dotted configuration value or throws ValueError.
Function getOr
func getOr(dict<string, any> data, string path, any fallback): any
Returns a dotted configuration value, or fallback when any path segment is missing.
Function require
func require(dict<string, any> data, string path): any
Alias for get when call sites want to make required configuration explicit.
Class Config
class Config
Immutable-style wrapper around configuration dictionaries with dotted-path lookup helpers.
Field data
dict<string, any> data
Method Config
func Config(dict<string, any> data)
Method has
func has(string path): bool
Method require
func require(string path): any
Method get
func get(string path): any
Method getOr
func getOr(string path, any fallback): any
Method toDict
func toDict(): dict<string, any>
Function parse
func parse(string format, string text): Config
Parses a serde-supported document into a Config object.
datetime
Source: stdlib/datetime.gb
Class DateTime
class DateTime
Decorators: immutable
An immutable date-time value. Mutation returns a new instance (wither pattern).
Note: this is a reference source-module class — when import datetime;
the runtime returns the native datetime module (zone-aware parts via
datetime.now(zoneName?), datetime.partsInZone(unix, zone),
datetime.formatRFC3339(unix), datetime.formatHTTP(unix)). To use
this class explicitly, import the file path directly.
Field year
int year
Field month
int month
Field day
int day
Field hour
int hour
Field minute
int minute
Field second
int second
Method DateTime
func DateTime(int year, int month, int day, int hour, int minute, int second)
Method withYear
func withYear(int year): DateTime
Returns a new DateTime with the year replaced.
Method withMonth
func withMonth(int month): DateTime
Returns a new DateTime with the month replaced.
Method withDay
func withDay(int day): DateTime
Returns a new DateTime with the day replaced.
Method withHour
func withHour(int hour): DateTime
Returns a new DateTime with the hour replaced.
Method withMinute
func withMinute(int minute): DateTime
Returns a new DateTime with the minute replaced.
Method withSecond
func withSecond(int second): DateTime
Returns a new DateTime with the second replaced.
Method toString
func toString(): string
Returns an ISO 8601 formatted string representation.
functools
Source: stdlib/functools.gb
Function pipe
func pipe(list<func> fns): func
Returns a function that applies fns left-to-right.
pipe([f, g, h])(x) is equivalent to h(g(f(x))).
Function compose
func compose(list<func> fns): func
Returns a function that applies fns right-to-left.
compose([f, g, h])(x) is equivalent to f(g(h(x))).
Function partial
func partial(func fn, any ... bound): func
Returns a function that calls fn with bound prepended to its arguments.
partial(add, 1)(2) is equivalent to add(1, 2).
Function memoize
func memoize(func fn, int max = 128): func
Returns an LRU-cached wrapper of fn.
Cache keys are derived from the JSON representation of the call arguments,
so memoized functions must take JSON-serialisable arguments (primitives,
lists and dicts of primitives). When the cache reaches max entries the
least-recently-used entry is evicted.
http.server
Source: stdlib/http/server.gb
Function handle
func handle(dict<string, any> request): dict<string, any>
Function main
func main(list<string> args): int
mailer
Source: stdlib/mailer.gb
Class Attachment
class Attachment
File or in-memory attachment for an email message.
Field filename
string filename
Field content
any content
Field path
string path
Field contentType
string contentType
Field inline
bool inline
Field contentId
string contentId
Method Attachment
func Attachment(string filename, any content)
Method withContentType
func withContentType(string value): Attachment
Method asInline
func asInline(string cid): Attachment
Method toDict
func toDict(): dict<string, any>
Function attachmentFromPath
func attachmentFromPath(string path, string contentType): Attachment
Creates an attachment from a file path. The file is read when the message is sent or rendered.
Class Message
class Message
Email message with text, HTML, headers, and attachments.
Field from
string from
Field to
list<string> to
Field cc
list<string> cc
Field bcc
list<string> bcc
Field replyTo
string replyTo
Field subject
string subject
Field text
string text
Field html
string html
Field headers
dict<string, any> headers
Field attachments
list<Attachment> attachments
Method Message
func Message(string subject)
Method fromAddress
func fromAddress(string value): Message
Method toAddress
func toAddress(string value): Message
Method ccAddress
func ccAddress(string value): Message
Method bccAddress
func bccAddress(string value): Message
Method withReplyTo
func withReplyTo(string value): Message
Method withText
func withText(string value): Message
Method withHtml
func withHtml(string value): Message
Method withHeader
func withHeader(string name, string value): Message
Method attach
func attach(Attachment attachment): Message
Method toDict
func toDict(): dict<string, any>
Method render
func render(): string
Class SmtpTransport
class SmtpTransport
SMTP transport configuration.
Field config
dict<string, any> config
Method SmtpTransport
func SmtpTransport(string host, int port, string username, string password)
Method fromAddress
func fromAddress(string value): SmtpTransport
Method withStartTLS
func withStartTLS(bool enabled): SmtpTransport
Method withTLS
func withTLS(bool enabled): SmtpTransport
Method withHello
func withHello(string value): SmtpTransport
Method allowInsecureTLS
func allowInsecureTLS(bool enabled): SmtpTransport
Method toDict
func toDict(): dict<string, any>
Class Mailer
class Mailer
Mailer sends messages through a configured SMTP transport.
Field transport
SmtpTransport transport
Method Mailer
func Mailer(SmtpTransport transport)
Method send
func send(Message message): dict<string, any>
Method render
func render(Message message): string
Function smtpTransport
func smtpTransport(string host, int port, string username, string password): SmtpTransport
Convenience constructor for SMTP transports.
Function smtpMailer
func smtpMailer(string host, int port, string username, string password): Mailer
Convenience constructor for a Mailer using SMTP.
option
Source: stdlib/option.gb
Class Option
class Option<T>
A value that is either present (some = true) or absent (some = false).
Field some
bool some
Field value
T value
Method Option
func Option(bool some, T value)
Method isSome
func isSome(): bool
Returns true when a value is present.
Method isNone
func isNone(): bool
Returns true when no value is present.
Method unwrap
func unwrap(): T
Returns the wrapped value, or throws if absent.
Method unwrapOr
func unwrapOr(T fallback): T
Returns the wrapped value, or fallback if absent.
Method orNull
func orNull(): T
Returns the value or null.
Function some
func some<T>(T value): Option<T>
Returns an Option containing value.
Function none
func none<T>(): Option<T>
Returns an empty Option.
Function ofNullable
func ofNullable<T>(T value): Option<T>
Returns some(value) when value is not null, otherwise none().
pathlib
Source: stdlib/pathlib.gb
Class Path
class Path
Immutable-style path value with method chaining over native path functions.
Field raw
string raw
Method Path
func Path(string raw)
Method base
func base(): string
Returns the last element of the path.
Method dir
func dir(): Path
Returns all but the last element as a Path.
Method ext
func ext(): string
Returns the file name extension including the dot.
Method stem
func stem(): string
Returns the base name without extension.
Method withExt
func withExt(string newExt): Path
Returns the path with the extension replaced by newExt.
Method join
func join(string ... parts): Path
Joins additional segments to this path and returns a new Path.
Method abs
func abs(): Path
Returns the absolute version of this path.
Method parent
func parent(): Path
Returns the parent directory as a Path.
Method toString
func toString(): string
Returns the path as a plain string.
Method exists
func exists(): bool
Returns true when the path exists on the filesystem.
Method isDir
func isDir(): bool
Returns true when the path is an existing directory.
Method isFile
func isFile(): bool
Returns true when the path is an existing regular file.
Method glob
func glob(string pattern): list<Path>
Returns glob matches relative to this path as a list of Path values.
Function of
func of(string raw): Path
Creates a Path from a string.
Function join
func join(string ... parts): Path
Joins path segments into a Path.
redis
Source: stdlib/redis.gb
Class Client
class Client
Minimal Redis client for strings, lists, sets, hashes, counters, expiry, and raw commands.
Field conn
any conn
Method Client
func Client(string address)
Method command
func command(list<string> parts): any
Method ping
func ping(): bool
Method auth
func auth(string password): bool
Method select
func select(int database): bool
Method get
func get(string key): any
Method set
func set(string key, string value): bool
Method del
func del(string key): int
Method exists
func exists(string key): bool
Method expire
func expire(string key, int seconds): bool
Method incr
func incr(string key): int
Method ttl
func ttl(string key): int
Method lpush
func lpush(string key, string value): int
Method rpush
func rpush(string key, string value): int
Method lpop
func lpop(string key): any
Method rpop
func rpop(string key): any
Method lrange
func lrange(string key, int start, int stop): list<any>
Method sadd
func sadd(string key, string member): int
Method srem
func srem(string key, string member): int
Method sismember
func sismember(string key, string member): bool
Method smembers
func smembers(string key): list<any>
Method hset
func hset(string key, string field, string value): int
Method hget
func hget(string key, string field): any
Method hdel
func hdel(string key, string field): int
Method hgetAll
func hgetAll(string key): dict<string, any>
Method close
func close(): void
Function connect
func connect(string address): Client
Connects to a Redis server address and returns a Client.
result
Source: stdlib/result.gb
Class Result
class Result<T, E>
A value that is either a success (ok = true, value set) or a failure (ok = false, error set).
Field ok
bool ok
Field value
T value
Field error
E error
Method Result
func Result(bool ok, T value, E error)
Method isOk
func isOk(): bool
Returns true when this result represents success.
Method isErr
func isErr(): bool
Returns true when this result represents failure.
Method unwrap
func unwrap(): T
Returns the success value, or throws if this is an error.
Method unwrapOr
func unwrapOr(T fallback): T
Returns the success value, or fallback if this is an error.
Method unwrapErr
func unwrapErr(): E
Returns the error value, or throws if this is a success.
Function ok
func ok<T, E>(T value): Result<T, E>
Returns a success Result wrapping value.
Function err
func err<T, E>(E error): Result<T, E>
Returns a failure Result wrapping error.
schema.validator
Source: stdlib/schema/validator.gb
Class Validator
class Validator
Holds a schema definition and validates values against it.
Field schemaDict
dict<string, any> schemaDict
Method Validator
func Validator(dict<string, any> schemaDict)
Method validate
func validate(any value): dict<string, any>
Validates value and returns a Result.
Method isValid
func isValid(any value): bool
Returns true when value passes validation.
Method errors
func errors(any value): list<string>
Returns the list of error strings for a failed validation, or empty list.
Method fieldErrors
func fieldErrors(any value, string field): list<string>
Returns errors for a specific dotted-path prefix (e.g. "$.name").
Function of
func of(dict<string, any> schemaDict): Validator
Returns a Validator wrapping the given schema dict.
Function validate
func validate(any value, dict<string, any> schemaDict): dict<string, any>
Validates value directly and returns the result dict {valid, errors}.
testing.assertions
Source: stdlib/testing/assertions.gb
Function contains
func contains(string text, string needle): bool
Returns true when text contains needle.
Function startsWith
func startsWith(string text, string prefix): bool
Returns true when text starts with prefix.
Function endsWith
func endsWith(string text, string suffix): bool
Returns true when text ends with suffix.
Function isBlank
func isBlank(string text): bool
Returns true when text is empty after trimming whitespace.
time.scheduler
Source: stdlib/time/scheduler.gb
Class Timer
class Timer
A one-shot timer that runs fn once after ms milliseconds.
The callback runs on an async task. The timer can be cancelled before
it fires with timer.cancel(). After the timer fires (or is
cancelled), timer.done is true.
import time.scheduler as sched;
import io;
let t = sched.Timer(500, func(): void {
io.println("fired");
});
... do other work ...
await t.wait();
Field ms
int ms
Field cb
func cb
Field task
Task task
Field fired
bool fired
Method Timer
func Timer(int ms, func cb)
Method cancel
func cancel(): void
Cancels the timer. If it has not yet fired, the callback will not run.
Method wait
func wait(): Task<any>
Returns a Task that resolves once the timer fires or is cancelled.
Method didFire
func didFire(): bool
True once the callback has run (false if cancelled before firing).
Class Ticker
class Ticker
A repeating ticker that runs fn every ms milliseconds.
The first invocation happens after the first ms-millisecond delay
(not immediately). The ticker runs until ticker.stop() is called.
After stopping, ticker.ticks() reports how many times fn ran.
import time.scheduler as sched;
import io;
let ticker = sched.Ticker(100, func(): void {
io.println("tick");
});
await async.sleep(350);
ticker.stop();
io.println("fired " + (ticker.ticks() as string) + " times");
Field ms
int ms
Field cb
func cb
Field task
Task task
Field count
int count
Field stopped
bool stopped
Method Ticker
func Ticker(int ms, func cb)
Method stop
func stop(): void
Stops the ticker. Any in-flight tick completes; no further ticks fire.
Method ticks
func ticks(): int
How many times the callback has run so far.
Method wait
func wait(): Task<any>
Returns a Task that resolves once the ticker is stopped.
Class Interval
class Interval
Convenience: like Ticker(ms, fn) but also runs fn once
immediately, before starting the interval timer.
Use this for poll-on-startup-then-keep-polling patterns where you do not want to wait an entire interval for the first run.
let poll = sched.Interval(60000, func(): void {
refreshConfig();
});
...
poll.stop();
Field inner
Ticker inner
Method Interval
func Interval(int ms, func cb)
Method stop
func stop(): void
Method ticks
func ticks(): int
Method wait
func wait(): Task<any>
Function setTimeout
func setTimeout(int ms, func fn): Timer
Helper: run fn once after ms milliseconds. Returns the Timer so
the caller can cancel if needed.
let t = sched.setTimeout(1000, func(): void { io.println("hi"); });
Function setInterval
func setInterval(int ms, func fn): Ticker
Helper: run fn every ms milliseconds. Returns the Ticker so the
caller can stop it.
let t = sched.setInterval(1000, func(): void { tick(); });
web.auth
Source: stdlib/web/auth.gb
Function login
func login(any sessionStore, dict<string, any> response, dict<string, any> user, dict<string, any> options): dict<string, any>
Saves a user dictionary in the supplied session store and returns the updated response.
Function logout
func logout(any sessionStore, dict<string, any> response, dict<string, any> request): dict<string, any>
Clears the current user session through the supplied session store.
Function currentUser
func currentUser(any sessionStore, dict<string, any> request): dict<string, any>
Loads the current user dictionary from the supplied session store.
Function isAuthenticated
func isAuthenticated(any sessionStore, dict<string, any> request): bool
Returns true when the request has an authenticated user in the supplied session store.
Function userHasRole
func userHasRole(dict<string, any> user, string role): bool
Returns true when a user dictionary contains a role or roles list entry.
Function userHasPermission
func userHasPermission(dict<string, any> user, string permission): bool
Returns true when a user dictionary contains a permission or permissions list entry.
Class AuthGuard
class AuthGuard
Field sessionStore
any sessionStore
Field mode
string mode
Field value
string value
Method AuthGuard
func AuthGuard(any sessionStore, string mode, string value)
Method __invoke
func __invoke(dict<string, any> request): any
Function requireAuth
func requireAuth(any sessionStore): callable
Returns middleware that requires any authenticated user.
Function requireLogin
func requireLogin(any sessionStore, string loginPath): callable
Returns middleware that redirects anonymous users to the supplied login path.
Function requireRole
func requireRole(any sessionStore, string role): callable
Returns middleware that requires an authenticated user with the supplied role.
Function requirePermission
func requirePermission(any sessionStore, string permission): callable
Returns middleware that requires an authenticated user with the supplied permission.
Function csrfToken
func csrfToken(string secret): string
Creates a signed CSRF token payload.
Function withCsrf
func withCsrf(dict<string, any> response, string secret, dict<string, any> options): dict<string, any>
Writes a CSRF token cookie to a response.
Function clearCsrf
func clearCsrf(dict<string, any> response): dict<string, any>
Clears the CSRF cookie.
Function verifyCsrf
func verifyCsrf(dict<string, any> request, string secret): bool
Verifies a CSRF cookie against a submitted header or form token.
web.cache
Source: stdlib/web/cache.gb
Class RedisCacheStore
class RedisCacheStore
Cache store backed by Redis keys with JSON payloads and TTL expiry.
Field client
any client
Field prefix
string prefix
Field ttl
int ttl
Method RedisCacheStore
func RedisCacheStore(any client, string prefix, int ttl)
Method key
func key(string name): string
Method get
func get(string name): any
Method set
func set(string name, any value): bool
Method delete
func delete(string name): bool
Method has
func has(string name): bool
Function redisCacheStore
func redisCacheStore(any client, string prefix, int ttl): RedisCacheStore
Creates a Redis-backed cache store.
Class FileCacheStore
class FileCacheStore
Cache store backed by JSON files in a directory.
Field directory
string directory
Field ttl
int ttl
Method FileCacheStore
func FileCacheStore(string directory, int ttl)
Method path
func path(string name): string
Method get
func get(string name): any
Method set
func set(string name, any value): bool
Method delete
func delete(string name): bool
Method has
func has(string name): bool
Function fileCacheStore
func fileCacheStore(string directory, int ttl): FileCacheStore
Creates a file-backed cache store.
Class DatabaseCacheStore
class DatabaseCacheStore
Cache store backed by a database table with cache_key, data, and expiry columns.
Field conn
any conn
Field table
string table
Field ttl
int ttl
Method DatabaseCacheStore
func DatabaseCacheStore(any conn, string table, int ttl)
Method install
func install(): DatabaseCacheStore
Method get
func get(string name): any
Method set
func set(string name, any value): bool
Method delete
func delete(string name): bool
Method has
func has(string name): bool
Function databaseCacheStore
func databaseCacheStore(any conn, string table, int ttl): DatabaseCacheStore
Creates a database-backed cache store; call install() to create its table.
web.forms
Source: stdlib/web/forms.gb
Function bind
func bind(dict<string, any> request): dict<string, any>
Parses URL-encoded form data from a request body.
Function validate
func validate(dict<string, any> request, dict<string, any> rules): dict<string, any>
Validates request form data and returns a result with valid, errors, and data keys.
Function isValid
func isValid(dict<string, any> result): bool
Returns true when a form validation result is valid.
Function data
func data(dict<string, any> result): dict<string, any>
Returns parsed form data from a validation result.
Function fieldErrors
func fieldErrors(dict<string, any> result, string field): list<any>
Returns all validation errors for a field.
Function hasFieldError
func hasFieldError(dict<string, any> result, string field): bool
Returns true when a field has validation errors.
Function firstFieldError
func firstFieldError(dict<string, any> result, string field): string
Returns the first validation error for a field, or an empty string.
Function csrfField
func csrfField(string token): string
Builds an HTML hidden input for a CSRF token value.
Function withCsrf
func withCsrf(dict<string, any> response, string secret, dict<string, any> options): dict<string, any>
Adds a CSRF cookie to a response using web.auth.
Function verifyCsrf
func verifyCsrf(dict<string, any> request, string secret): bool
Returns true when a request passes web.auth CSRF verification.
Function redirectWithFlash
func redirectWithFlash(any sessionStore, dict<string, any> request, string location, string category, string message, dict<string, any> options): dict<string, any>
Creates a redirect response with a flash message saved to the session store.
Function redirectSuccess
func redirectSuccess(any sessionStore, dict<string, any> request, string location, string message, dict<string, any> options): dict<string, any>
Creates a redirect response with a success flash message.
Function redirectError
func redirectError(any sessionStore, dict<string, any> request, string location, string message, dict<string, any> options): dict<string, any>
Creates a redirect response with an error flash message.
web.http
Source: stdlib/web/http.gb
Class Request
class Request
Object wrapper for request dictionaries with query, form, JSON, header, parameter, and cookie helpers.
Field data
dict<string, any> data
Method Request
func Request(dict<string, any> data)
Method method
func method(): string
Method path
func path(): string
Method body
func body(): any
Method query
func query(): dict<string, any>
Method queryParam
func queryParam(string name): string
Method form
func form(): dict<string, any>
Method formValue
func formValue(string name): string
Method jsonBody
func jsonBody(): dict<string, any>
Method validate
func validate(dict<string, any> rules): dict<string, any>
Method validateForm
func validateForm(dict<string, any> rules): dict<string, any>
Method headers
func headers(): dict<string, any>
Method header
func header(string name): string
Method hasHeader
func hasHeader(string name): bool
Method params
func params(): dict<string, any>
Method param
func param(string name): string
Method paramDefault
func paramDefault(string name, string fallback): string
Method hasParam
func hasParam(string name): bool
Method cookies
func cookies(): dict<string, any>
Method cookie
func cookie(string name): string
Method toDict
func toDict(): dict<string, any>
Class Response
class Response
Object wrapper for response dictionaries with fluent header and cookie mutation helpers.
Field data
dict<string, any> data
Method Response
func Response(int status, any body)
Method header
func header(string name, string value): Response
Method statusCode
func statusCode(): int
Method body
func body(): any
Method headers
func headers(): dict<string, any>
Method headerValue
func headerValue(string name): string
Method hasHeader
func hasHeader(string name): bool
Method cookie
func cookie(string name, string value): Response
Method cookieOptions
func cookieOptions(string name, string value, dict<string, any> options): Response
Method toDict
func toDict(): dict<string, any>
Class Context
class Context
Per-request convenience object combining Request accessors with common response builders.
Field request
Request request
Method Context
func Context(dict<string, any> request)
Method method
func method(): string
Method path
func path(): string
Method body
func body(): any
Method query
func query(): dict<string, any>
Method queryParam
func queryParam(string name): string
Method form
func form(): dict<string, any>
Method formValue
func formValue(string name): string
Method jsonBody
func jsonBody(): dict<string, any>
Method validate
func validate(dict<string, any> rules): dict<string, any>
Method validateForm
func validateForm(dict<string, any> rules): dict<string, any>
Method header
func header(string name): string
Method hasHeader
func hasHeader(string name): bool
Method cookies
func cookies(): dict<string, any>
Method cookie
func cookie(string name): string
Method params
func params(): dict<string, any>
Method param
func param(string name): string
Method paramDefault
func paramDefault(string name, string fallback): string
Method hasParam
func hasParam(string name): bool
Method text
func text(any body): dict<string, any>
Method json
func json(any body): dict<string, any>
Method html
func html(any body): dict<string, any>
Method render
func render(string source, dict<string, any> data): dict<string, any>
Method status
func status(int code): dict<string, any>
Method redirect
func redirect(string location): dict<string, any>
Function request
func request(string method, string path): dict<string, any>
Builds a minimal request dictionary with method, path, parsed query parameters, and an empty body.
Function requestWithBody
func requestWithBody(string method, string path, any body): dict<string, any>
Builds a request dictionary with method, path, parsed query parameters, and body.
Function requestObject
func requestObject(dict<string, any> data): Request
Wraps a request dictionary in a Request object.
Function responseObject
func responseObject(int status, any body): Response
Creates a Response object with status and body.
Function context
func context(dict<string, any> request): Context
Wraps a request dictionary in a Context object.
Function validate
func validate(dict<string, any> request, dict<string, any> rules): dict<string, any>
Validates a request JSON body against schema rules.
Function validateForm
func validateForm(dict<string, any> request, dict<string, any> rules): dict<string, any>
Validates a request form body against schema rules.
Function text
func text(any body): dict<string, any>
Creates a 200 response dictionary with the supplied body.
Function response
func response(int status, any body): dict<string, any>
Creates a response dictionary with explicit status and body.
Function normalize
func normalize(any value): dict<string, any>
Normalizes strings, null, and response dictionaries into a response dictionary.
Function statusCode
func statusCode(dict<string, any> response): int
Returns the status code from a response dictionary, defaulting to 200.
Function body
func body(dict<string, any> response): any
Returns the body from a response dictionary, defaulting to an empty string.
Function responseFrom
func responseFrom(dict<string, any> data): Response
Wraps an existing response dictionary in a Response object.
Function headers
func headers(dict<string, any> response): dict<string, any>
Returns response headers, defaulting to an empty dictionary.
Function header
func header(dict<string, any> response, string name): string
Returns a response header value using case-insensitive lookup.
Function hasHeader
func hasHeader(dict<string, any> response, string name): bool
Returns true when a response header is present using case-insensitive lookup.
Function withHeader
func withHeader(dict<string, any> response, string name, string value): dict<string, any>
Adds or replaces a response header.
Function status
func status(int code): dict<string, any>
Creates an empty response dictionary with the supplied status code.
Function jsonResponse
func jsonResponse(any body): dict<string, any>
Creates a JSON response with status 200 and application/json content type.
Function jsonStatus
func jsonStatus(any body, int status): dict<string, any>
Creates a JSON response with an explicit status code.
Function jsonCreated
func jsonCreated(any body): dict<string, any>
Creates a JSON response with status 201.
Function jsonError
func jsonError(string message, int status): dict<string, any>
Creates a JSON error response with an error message and status code.
Function html
func html(any body): dict<string, any>
Creates an HTML response with status 200 and text/html content type.
Function htmlStatus
func htmlStatus(any body, int status): dict<string, any>
Creates an HTML response with an explicit status code.
Function render
func render(string source, dict<string, any> data): dict<string, any>
Renders a template string with data into an HTML response.
Function redirectStatus
func redirectStatus(string location, int status): dict<string, any>
Creates a redirect response with an explicit status code.
Function redirect
func redirect(string location): dict<string, any>
Creates a 302 redirect response with a Location header.
Function created
func created(any body): dict<string, any>
Creates a 201 Created response.
Function noContent
func noContent(): dict<string, any>
Creates a 204 No Content response.
Function badRequest
func badRequest(any body): dict<string, any>
Creates a 400 Bad Request response.
Function unauthorized
func unauthorized(any body): dict<string, any>
Creates a 401 Unauthorized response.
Function forbidden
func forbidden(any body): dict<string, any>
Creates a 403 Forbidden response.
Function notFound
func notFound(any body): dict<string, any>
Creates a 404 Not Found response.
Function withCookie
func withCookie(dict<string, any> response, string name, string value): dict<string, any>
Adds a simple Set-Cookie header to a response dictionary.
Function withCookieOptions
func withCookieOptions(dict<string, any> response, string name, string value, dict<string, any> options): dict<string, any>
Adds a Set-Cookie header using path, domain, maxAge, sameSite, secure, and httpOnly options.
Function deleteCookie
func deleteCookie(dict<string, any> response, string name): dict<string, any>
Adds an expired Set-Cookie header for the named cookie.
web.middleware
Source: stdlib/web/middleware.gb
Class CorsMiddleware
class CorsMiddleware
Field origin
string origin
Field methods
string methods
Field headers
string headers
Field credentials
bool credentials
Method CorsMiddleware
func CorsMiddleware(string origin, string methods, string headers, bool credentials)
Method __invoke
func __invoke(dict<string, any> request, dict<string, any> response): dict<string, any>
Class SecurityHeadersMiddleware
class SecurityHeadersMiddleware
Field headers
dict<string, any> headers
Method SecurityHeadersMiddleware
func SecurityHeadersMiddleware(dict<string, any> headers)
Method __invoke
func __invoke(dict<string, any> request, dict<string, any> response): dict<string, any>
Class RequestIdMiddleware
class RequestIdMiddleware
Field headerName
string headerName
Method RequestIdMiddleware
func RequestIdMiddleware(string headerName)
Method __invoke
func __invoke(dict<string, any> request, dict<string, any> response): dict<string, any>
Class AccessLogMiddleware
class AccessLogMiddleware
Field logger
any logger
Method AccessLogMiddleware
func AccessLogMiddleware(any logger)
Method __invoke
func __invoke(dict<string, any> request, dict<string, any> response): dict<string, any>
Function cors
func cors(string origin, string methods, string headers): callable
Adds CORS response headers.
Function corsCredentials
func corsCredentials(string origin, string methods, string headers): callable
Adds CORS response headers and allows credentials.
Function securityHeaders
func securityHeaders(): callable
Adds a conservative set of browser security response headers.
Function headers
func headers(dict<string, any> values): callable
Adds custom response headers.
Function requestId
func requestId(): callable
Adds or propagates an X-Request-ID response header.
Function requestIdHeader
func requestIdHeader(string name): callable
Adds or propagates a response header for the supplied request ID header name.
Function accessLog
func accessLog(any logger): callable
Logs method, path, and status after a response is produced.
web.router
Source: stdlib/web/router.gb
Function newRouter
func newRouter(): dict<string, any>
Creates a new router dictionary around a native web app.
Function fromApp
func fromApp(any app): dict<string, any>
Wraps an existing native web app as a router dictionary.
Function group
func group(dict<string, any> router, string prefix): dict<string, any>
Creates a router group that prefixes all registered routes.
Function use
func use(dict<string, any> router, callable middleware): dict<string, any>
Adds global response middleware. The middleware receives (request, response) and returns a response.
Function before
func before(dict<string, any> router, callable middleware): dict<string, any>
Adds global before middleware. The middleware receives request and returns null or a response.
Function after
func after(dict<string, any> router, callable middleware): dict<string, any>
Adds global response middleware. Alias of use for readability.
Function route
func route(dict<string, any> router, string method, string path, any handler): dict<string, any>
Registers a route handler for an HTTP method and path.
Function get
func get(dict<string, any> router, string path, any handler): dict<string, any>
Registers a GET route handler.
Function post
func post(dict<string, any> router, string path, any handler): dict<string, any>
Registers a POST route handler.
Function put
func put(dict<string, any> router, string path, any handler): dict<string, any>
Registers a PUT route handler.
Function patch
func patch(dict<string, any> router, string path, any handler): dict<string, any>
Registers a PATCH route handler.
Function delete
func delete(dict<string, any> router, string path, any handler): dict<string, any>
Registers a DELETE route handler.
Function options
func options(dict<string, any> router, string path, any handler): dict<string, any>
Registers an OPTIONS route handler.
Function mountWithOptions
func mountWithOptions(dict<string, any> router, any controller, dict<string, any> options): dict<string, any>
Mounts a controller by reading route, prefix, middleware, auth, and policy decorators.
Function mount
func mount(dict<string, any> router, any controller): dict<string, any>
Mounts a decorator-driven controller without extra middleware or policy options.
Function handle
func handle(dict<string, any> router, dict<string, any> request): dict<string, any>
Dispatches a request dictionary through the router and returns a response dictionary.
Function raw
func raw(dict<string, any> router): any
Returns the underlying native web app value for lower-level integrations.
web.session
Source: stdlib/web/session.gb
Function session
func session(dict<string, any> request, string secret): dict<string, any>
Reads a signed cookie-backed session dictionary from a request.
Function withSession
func withSession(dict<string, any> response, dict<string, any> data, string secret, dict<string, any> options): dict<string, any>
Writes a signed cookie-backed session dictionary to a response.
Function clearSession
func clearSession(dict<string, any> response): dict<string, any>
Clears the signed cookie-backed session cookie.
Class RedisSessionStore
class RedisSessionStore
Session store backed by Redis keys and opaque session-id cookies.
Field client
any client
Field prefix
string prefix
Field ttl
int ttl
Method RedisSessionStore
func RedisSessionStore(any client, string prefix, int ttl)
Method key
func key(string id): string
Method load
func load(dict<string, any> request): dict<string, any>
Method save
func save(dict<string, any> response, dict<string, any> data, dict<string, any> options): dict<string, any>
Method clear
func clear(dict<string, any> response, dict<string, any> request): dict<string, any>
Function redisSessionStore
func redisSessionStore(any client, string prefix, int ttl): RedisSessionStore
Creates a Redis-backed session store.
Class FileSessionStore
class FileSessionStore
Session store backed by JSON files in a directory.
Field directory
string directory
Field ttl
int ttl
Method FileSessionStore
func FileSessionStore(string directory, int ttl)
Method path
func path(string id): string
Method load
func load(dict<string, any> request): dict<string, any>
Method save
func save(dict<string, any> response, dict<string, any> data, dict<string, any> options): dict<string, any>
Method clear
func clear(dict<string, any> response, dict<string, any> request): dict<string, any>
Function fileSessionStore
func fileSessionStore(string directory, int ttl): FileSessionStore
Creates a file-backed session store.
Class DatabaseSessionStore
class DatabaseSessionStore
Session store backed by a database table with id, data, and expiry columns.
Field conn
any conn
Field table
string table
Field ttl
int ttl
Method DatabaseSessionStore
func DatabaseSessionStore(any conn, string table, int ttl)
Method install
func install(): DatabaseSessionStore
Method load
func load(dict<string, any> request): dict<string, any>
Method save
func save(dict<string, any> response, dict<string, any> data, dict<string, any> options): dict<string, any>
Method clear
func clear(dict<string, any> response, dict<string, any> request): dict<string, any>
Function databaseSessionStore
func databaseSessionStore(any conn, string table, int ttl): DatabaseSessionStore
Creates a database-backed session store; call install() to create its table.
Function flashes
func flashes(any sessionStore, dict<string, any> request): list<any>
Returns queued flash messages from a session store.
Function withFlash
func withFlash(any sessionStore, dict<string, any> response, dict<string, any> request, string category, string message, dict<string, any> options): dict<string, any>
Appends a flash message to the current session and saves it.
Function clearFlashes
func clearFlashes(any sessionStore, dict<string, any> response, dict<string, any> request, dict<string, any> options): dict<string, any>
Removes flash messages from the current session and saves it.
web.sse
Source: stdlib/web/sse.gb
Function comment
func comment(string text): string
Formats a raw SSE comment frame.
Function retry
func retry(int milliseconds): string
Formats an SSE retry frame in milliseconds.
Function data
func data(string body): string
Formats a data-only SSE message.
Function event
func event(string name, string body, dict<string, any> options): string
Formats an SSE message with event, id, retry, and data fields.
Function named
func named(string name, string body): string
Formats a named SSE event without extra options.
Function stream
func stream(list<any> frames): string
Joins a list of SSE frame strings.
Function withHeaders
func withHeaders(dict<string, any> response): dict<string, any>
Adds SSE headers to a response dictionary.
Function responseText
func responseText(string body): dict<string, any>
Creates an SSE response from a preformatted body.
Function response
func response(list<any> frames): dict<string, any>
Creates an SSE response from a list of frame strings.
Class EventStream
class EventStream
Source-level wrapper around a native HTTP stream handle for live SSE responses.
Field handle
any handle
Method EventStream
func EventStream(any handle)
Method write
func write(string frame): void
Method flush
func flush(): void
Method close
func close(): void
Function streaming
func streaming(any handler): dict<string, any>
Creates a streaming SSE response. The handler receives an SSE EventStream.
Function write
func write(EventStream stream, string frame): void
Writes a formatted SSE frame to a live SSE stream.
Function flush
func flush(EventStream stream): void
Flushes a live SSE stream.
Function close
func close(EventStream stream): void
Closes a live SSE stream.
web.testing
Source: stdlib/web/testing.gb
Class Client
class Client
Small test client for dispatching request dictionaries through a router.
Field app
dict<string, any> app
Method Client
func Client(dict<string, any> app)
Method request
func request(string method, string path): dict<string, any>
Method requestWithBody
func requestWithBody(string method, string path, any body): dict<string, any>
Method get
func get(string path): dict<string, any>
Method post
func post(string path, any body): dict<string, any>
Function client
func client(dict<string, any> app): Client
Creates a test client for a router dictionary.
Function hasStatus
func hasStatus(dict<string, any> response, int status): bool
Returns true when a response has the expected status code.
Function hasHeader
func hasHeader(dict<string, any> response, string name, string value): bool
Returns true when a response header exactly matches a value.
Function hasBody
func hasBody(dict<string, any> response, any body): bool
Returns true when a response body exactly matches a value.
web.validation
Source: stdlib/web/validation.gb
Function object
func object(dict<string, any> properties, list<any> required): dict<string, any>
Builds an object schema from property rules and a required-field list.
Function stringField
func stringField(): dict<string, any>
Builds a string field schema.
Function intField
func intField(): dict<string, any>
Builds an integer field schema.
Function numberField
func numberField(): dict<string, any>
Builds a numeric field schema accepting int, decimal, or float.
Function boolField
func boolField(): dict<string, any>
Builds a boolean field schema.
Function arrayOf
func arrayOf(dict<string, any> itemSchema): dict<string, any>
Builds an array/list field schema.
Function enumOf
func enumOf(list<any> values): dict<string, any>
Builds a field schema constrained to a fixed list of values.
Function validate
func validate(dict<string, any> data, dict<string, any> rules): dict<string, any>
Validates an arbitrary dictionary and includes the input data in the result.
Function json
func json(dict<string, any> request, dict<string, any> rules): dict<string, any>
Validates a request JSON body and includes parsed data in the result.
Function form
func form(dict<string, any> request, dict<string, any> rules): dict<string, any>
Validates a request form body and includes parsed data in the result.
Function isValid
func isValid(dict<string, any> validation): bool
Returns true when a validation result is valid.
Function errors
func errors(dict<string, any> validation): list<any>
Returns validation errors from a validation result.
Function data
func data(dict<string, any> validation): dict<string, any>
Returns validated data from a validation result.
Function errorResponseStatus
func errorResponseStatus(dict<string, any> validation, int status): dict<string, any>
Builds a JSON validation error response with an explicit status.
Function errorResponse
func errorResponse(dict<string, any> validation): dict<string, any>
Builds a JSON validation error response, defaulting to HTTP 422.
web.websocket
Source: stdlib/web/websocket.gb
Class Connection
class Connection
Source-level wrapper around a native WebSocket connection handle.
Field handle
any handle
Method Connection
func Connection(any handle)
Method sendText
func sendText(string message): void
Method readText
func readText(): string
Method sendJson
func sendJson(any value): void
Method readJson
func readJson(): dict<string, any>
Method sendBytes
func sendBytes(bytes data): void
Method readBytes
func readBytes(): bytes
Method close
func close(): void
Method echoText
func echoText(): void
Function upgrade
func upgrade(any handler): dict<string, any>
Creates a WebSocket upgrade response for a connection handler.
Function upgradeWithHeaders
func upgradeWithHeaders(any handler, dict<string, any> headers): dict<string, any>
Creates a WebSocket upgrade response with extra response headers.
Function connect
func connect(string url): Connection
Connects to a WebSocket URL.
Function connectWithHeaders
func connectWithHeaders(string url, dict<string, any> headers): Connection
Connects to a WebSocket URL with request headers.
Function sendText
func sendText(Connection conn, string message): void
Sends a text message.
Function readText
func readText(Connection conn): string
Reads a text message.
Function sendJson
func sendJson(Connection conn, any value): void
Sends a value as JSON text.
Function readJson
func readJson(Connection conn): dict<string, any>
Reads a JSON text message as a dictionary.
Function sendBytes
func sendBytes(Connection conn, bytes data): void
Sends bytes.
Function readBytes
func readBytes(Connection conn): bytes
Reads bytes.
Function close
func close(Connection conn): void
Closes a WebSocket connection.
Function echoText
func echoText(Connection conn): void
Runs a simple text echo loop until the client closes.