santoku
santoku

santoku

A Lua framework for building applications end to end

Lua 5.1 from the build system to the server to the browser. Every example on this site runs in your browser. Edit one and run it.


santoku targets Lua 5.1, because 5.1 is the version its platforms actually share. LuaJIT implements 5.1 and OpenResty embeds LuaJIT, so server code, client code and the build harness all run the same language. Compiled to WebAssembly, the 5.1 core is smaller to embed, and its single number type sidesteps the integer and float split introduced in 5.3, which keeps numeric values crossing the JavaScript boundary simple. Support for newer versions is meant to come from compatibility shims layered over the 5.1 core rather than version branches in the tree; contributions and design ideas for that layer are welcome.

santoku-web

View on LuaRocks

browser runtime for Lua compiled to WebAssembly: val and js interop, promise await, and a batched DOM command buffer

santoku-web is the browser runtime for Lua compiled to WebAssembly. val and js marshal values across the boundary, async awaits promises in coroutines, and dom batches DOM access over a binary command buffer. Application code never writes JavaScript, and reaches the platform only through val, js and dom.

Details
  • The library's C core holds the TK_JS shims. clang compiles it to WebAssembly, targeting wasm32-wasip1, and santoku-make generates the page JS.
  • santoku-web's behaviour (APIs, and HTML that changes what an element does) uses only what is Baseline widely available, read per API member or BCD key. The one exception is Selection.getComposedRanges, on the editor paths that read a selection inside a shadow root, where no widely available API reads it.
  • Declarative CSS and HTML that a browser ignores when unsupported, such as @property, @starting-style and scrollbar-gutter, is allowed as a hint. santoku-web ships no feature detection, no polyfill and no fallback.
  • An app may target fewer browsers than santoku-web does and states its floor in its own docs. Current status per key: https://webstatus.dev.
  • toku lua test/res/gen-baseline.lua <web-features>/data.json in lua-santoku-web refreshes the denylist the baseline spec reads, and raises when a denied key or the exception has turned widely available.
Browser integrationModule
fetchsantoku.web.socket
the app's one HTTP clientsantoku.web.http
historysantoku.web.history
a scoped routersantoku.web.router
a page model with actions, and custom elementssantoku.web.app
mustache templates rendered as live DOM, on https://santoku.dev/santoku-web/templatessantoku.web.mustache
tasks, sleep, scopes and promises: the browser runtime for santoku.asyncsantoku.web.async
localStoragesantoku.web.storage
worker RPCsantoku.web.rpc
OPFS SQLitesantoku.web.sqlite
PWA scaffoldingsantoku.web.pwa.index, santoku.web.pwa.sw, santoku.web.pwa.manifest and santoku.web.pwa.csp
TLS streams under nodesantoku.web.stream
  • Since santoku-web 10.0.0, latest, debounce and atleast come from santoku.async over santoku.web.async, and a timer is spawn plus sleep: https://santoku.dev/santoku#santoku--santoku-async
  • This page runs on santoku-web. The tabs, the editors and the Run buttons are Lua that drives the DOM through these modules.
  • Cards with a Run button run live. The display-only cards show APIs that settle asynchronously, need a worker or a network, or target elements this page lacks.

Values and calls

santoku.web.val

val(x) marshals a Lua value to JavaScript and back, with typeof and live proxies. val.pack(x) sends a deep copy. val.global(name) returns a property of globalThis, and val.module(name) a property of the wasm runtime's Module object.

local val = require("santoku.web.val")
local v = val("hello")
print("typeof:", v:typeof():lua())
print("value:", v:lua())
print("number:", val(100.6):lua())
local source = { a = 1 }
local proxy = val(source)
proxy:set("b", 2)
print("b through proxy:", source.b)
local copy = val.pack({ { a = 1 }, { b = 2 } }):lua()
print("deep copy:", copy[1].a, copy[2].b)
return val(true):lua()
Details
  • Since santoku-web 4.0.0, val.module() with no name returns the Module object itself.
  • Since santoku-web 5.0.0, val.pack(x) and val.unpack(v) copy a whole value in one call into JavaScript. val(x, true), val.lua(v, true) and v:lua(true) raise an error that names the replacement.

The conversion matrix

Primitives copy by value. Tables proxy by default, and val.pack(t) sends a deep copy. val.lua converts one value from the unwrapped side, and val.unpack(v) copies plain objects and arrays into Lua tables.

local val = require("santoku.web.val")
local js = require("santoku.web.js")
print("string:", val("hi"):typeof():lua())
print("number:", val(42):lua())
print("boolean:", val(true):lua())
local source = { a = 1, b = "2" }
local proxy = val(source)
proxy:set("c", 3)
print("same table back:", proxy:lua() == source)
print("mutation visible:", source.c)
local o = js.Object:new()
o.a = 1
o.nested = js.Object:new()
o.nested.b = 2
local t = val.unpack(o)
print("val.unpack deep:", t.a, t.nested.b)
print("val.lua primitive:", val.lua(1))
return js.JSON:stringify(t)
Details
val.pack(x) receivesJavaScript gets
a table with a first element, or an empty tablean array of elements 1 to #t
any other tablea plain object; number keys become string keys
a stringthe same text, NUL bytes included
a JS value, nested or at the topthat same JS value
a Lua functionthe function proxy val(fn) gives
a thread, a userdata that isn't a JS value, a key that isn't a string or a numberan error that names the key path, such as .rows[2].owner
val.unpack(v) receivesLua gets
a plain object or an arraya table; array index 0 becomes element 1
null or undefinednil, so the key or the element is absent
a Date, Map, Promise, Uint8Array, function or class instancethe wrapper val.lua gives for a Promise, Uint8Array or function, and a bare val for the rest
a Lua value that isn't a JS valuethe same value
  • Both raise on a value nested deeper than 200 levels, which is how a cycle shows up.
CaseSince santoku-web 5.0.0
a __proto__ key in a packed tablestays an own property; 4.x set the object's prototype instead
a plain object with its own constructor keyunpacks as a table; 4.x returned a bare val. A class instance is still a bare val
a val.pack error whose key path has more than eight keysprints the first four and the last four. A 200-deep cycle prints .self.self.self.self ... 192 more ... .self.self.self.self
a Lua error raised under a JS frame, such as an __index error on a table proxy that JS reads, also from a getter inside val.unpackkeeps its message in Lua, and a JS catch around the read sees the same message
a table proxy made in one coroutineJS can read it, write it and stringify it while another coroutine runs, or after its coroutine finished. An error raises in the coroutine that uses the proxy

santoku.web.js

js.Name is an unwrapped JavaScript global. It forwards index, newindex and calls straight to JavaScript.

local js = require("santoku.web.js")
local val = require("santoku.web.val")
print("max:", js.Math:max(1, 3, 2))
print("json:", js.JSON:stringify({ a = { b = 1 } }))
local doc = val.unpack(js.JSON:parse("{\"results\":[{\"title\":\"Komodo\"}]}"))
print("parsed:", doc.results[1].title)
local m = js.Map:new()
m:set("k", 42)
print("map get:", m:get("k"))
print("instanceof Map:", m:instanceof(js.Map))
return js.JSON:stringify({ 1, 2, 3 })
Details
  • To decode JSON in the client, such as a fetch response body, parse it with js.JSON:parse. Then convert the result to Lua tables with val.unpack(x).

val get, set, call, new

get, set, call and new are the explicit handle API on a val. The example stores a Lua function on a JS object and calls it from JavaScript.

local val = require("santoku.web.val")
local obj = val.global("Object"):call(nil)
obj:set("a", 1)
print("a:", obj:get("a"):lua())
obj:set("square", function (_, n)
  return n * n
end)
print("square(20):", obj:get("square"):call(obj, 20):lua())
local m = val.global("Map"):new()
m:get("set"):call(m, "k", 2)
print("map get:", m:get("get"):call(m, "k"):lua())
return obj:get("a"):typeof():lua()

Callbacks and the this-first convention

A Lua function called from JavaScript receives this as its first argument. So a Promise executor is function (this, resolve, reject), and an event listener is function (_, ev).

local val = require("santoku.web.val")
local js = require("santoku.web.js")
local fn = function (a) return a + 4 end
print("direct call:", val(fn):lua()(2))
local obj = js.Object:new()
obj.square = function (_, n)
  return n * n
end
print("called from JS:", obj:square(20))
local ki = 0
js.Object:keys({ 1, 2, 3 }):forEach(function (_, k)
  print("js key:", k)
  ki = ki + 1
end)
return ki
Details
  • Called directly from Lua, the same function gets its arguments straight.
  • The rule runs the other way too. A call to a JS function proxy from Lua passes the first argument as this.
  • obj:method(x) supplies obj, but a bare function needs this explicitly. So resolve a promise with resolve(nil, value), as async.promise does: https://santoku.dev/santoku-web#santoku-web--promise-helpers
  • resolve(value) resolves with nothing.
  • setTimeout(fn, ms) without its window receiver treats fn as this. Call js.window:setTimeout(fn, ms) instead.

Arrays across the boundary

Lua is 1-indexed and JS is 0-indexed. Array proxies convert at the boundary, so JS index 0 is Lua element 1.

local val = require("santoku.web.val")
local js = require("santoku.web.js")
local a = val({ 1, 2, 3, 4 })
print("js index 0:", a:get(0):lua())
print("js index 3:", a:get(3):lua())
local target = {}
local t = val(target)
t:set(0, 10)
print("lua index 1:", target[1])
print("stringified:", js.JSON:stringify({ 1, 2, 3, 4 }))
return js.JSON:stringify({ 1, 2, 3, 4 })

val.bytes and Uint8Array

val.bytes(s) turns a Lua string into a Uint8Array, and :str() turns it back, for binary round trips.

local val = require("santoku.web.val")
local b = val.bytes("ABC")
print("instanceof Uint8Array:", b:instanceof(val.global("Uint8Array")))
print("back to string:", b:str())
print("empty:", "[" .. val.global("Uint8Array"):new():lua():str() .. "]")
local u = val.global("Uint8Array"):new({ 104, 105 })
return u:lua():str()

Operators, equality and tostring

Proxies carry metamethods. Equality applies JavaScript's == to the two values, arithmetic applies the JS operator, tostring forwards, and a BigInt becomes a Lua number.

local val = require("santoku.web.val")
local js = require("santoku.web.js")
local a = val.global("console"):lua()
local b = val.global("console"):lua()
print("same object:", a == b)
print("sum:", val(1) + val(2))
local five, two = js.Number:new(5), js.Number:new(2)
print("difference:", five - two, "less:", two < five)
local e = js.Error:new("boom")
print("tostring:", tostring(e):match("[^\n]*"))
print("bigint:", js.BigInt(nil, 1))
return tostring(e):match("[^\n]*")
Details
  • +, -, *, /, %, ^, < and <= on two wrapped JS values take their operands in the order written. So a - b is a minus b.
  • A BigInt outside the safe integer range raises "Conversion from bigint to number failed: too large or too small".

val.class

val.class(config, parent) builds a JS class from Lua. The config function receives the prototype, the optional parent is the class it extends, and instances answer instanceof up the chain.

local val = require("santoku.web.val")
local Parent = val.class(function (proto)
  proto.greet = function () return "parent" end
end)
local Child = val.class(function (proto)
  proto.kind = function () return "child" end
end, Parent)
local c = Child:new()
print("instanceof Child:", c:instanceof(Child))
print("instanceof Parent:", c:instanceof(Parent))
print("greet:", c:get("greet"):call(c):lua())
print("kind:", c:get("kind"):call(c):lua())
return c:typeof():lua()
Details
  • On a bare val, instanceof and typeof return a val. Call :lua() on the result before you test it in an if, since a val that holds false is still true to Lua.

Async

santoku.web.async since santoku-web 10.0.0

santoku.web.async is the browser runtime: now, sleep, spawn, scope, run, kill, task and promise. spawn(fn, ...) starts fn as a task, where p:await() and sleep block as straight-line code.

local js = require("santoku.web.js")
local async = require("santoku.web.async")
local Promise = js.Promise
async.spawn(function ()
  local ok, result = Promise:resolve(42):await()
  print("resolved:", ok, result)
  local ok2, e = Promise:reject("boom"):await()
  print("rejected:", ok2, e)
  local t0 = async.now()
  async.sleep(50)
  print("slept:", async.now() - t0 >= 50)
  local doubled = async.task(function ()
    local _, v = Promise:resolve(21):await()
    return v * 2
  end)
  print("returns a promise:", doubled:instanceof(Promise))
  print("task:", doubled:await())
end)
async.task(function ()
  error("load failed", 0)
end):catch(function (_, e)
  print("caught:", e)
end)
local s
async.spawn(function ()
  s = async.scope()
  async.run(s, function ()
    async.sleep(1000)
    print("never prints")
  end)
end)
async.kill(s)
Illustrative: runs outside the browser.
Details
  • Since santoku-web 10.0.0 the module isn't callable. async(fn) becomes async.task(fn) where a caller needs a promise, such as a router on_change hook or JavaScript, and async.spawn(fn) otherwise.
  • santoku.async builds latest, debounce, throttle, atleast and retry over this runtime: https://santoku.dev/santoku#santoku--santoku-async
FunctionBehavior
now()milliseconds on a monotonic clock
sleep(ms)blocks the calling task for ms milliseconds, and returns nothing
spawn(fn, ...)starts fn(...) as a task in the caller's scope, runs it to its first block, and returns nothing
task(fn, ...)starts fn(...) the same way, and returns a promise of fn's first value
scope()returns a new scope under the calling task's scope
run(s, fn, ...)calls fn(...) in the calling task inside s, and returns fn's values
kill(s)kills s and its child scopes
promise(fn)builds a promise from a completion callback, in the next card
  • A kill aborts each fetch the scope's tasks await and clears each sleep. A killed task never resumes, and the promise of a killed task resolves with nil.
  • :await() returns two values, ok and then the result.
  • An error in a task rejects the promise task returned, before the first block or after one. Neither spawn nor task raises in the code that calls it.
  • Handle the error with :catch(fn) on the promise, or with err.pcall inside the task. Since santoku 5.0.0 err.pcall can span a block.
  • An error in a spawned task, or in a task the library starts such as an app action, start or route, reaches the page as an unhandledrejection event. node exits non-zero.
  • The library adds no unhandledrejection listener.
CallError
p:await() or sleep outside a task"await called outside async context", or "sleep called outside async context"
p:await() in a coroutine that the task resumed itself"await called from a coroutine outside its async context"
p:await() before anything required santoku.web.async"await: require santoku.web.async before awaiting a promise"
  • Since santoku-web 4.5.0, a task resumes in the microtask where its promise settles, before any timer, message event or paint. Code that needs to yield to the page calls dom.painted() or async.sleep(ms).

Promise helpers

async.promise(fn) returns a promise and hands fn one completion callback. complete(true, v) resolves the promise, and complete(false, e) rejects it. js.Promise:resolve(v) builds a resolved promise.

local async = require("santoku.web.async")
local js = require("santoku.web.js")
local p = async.promise(function (complete)
  async.spawn(function ()
    async.sleep(50)
    complete(true, "done")
  end)
end)
async.spawn(function ()
  local ok, v = p:await()
  print("promise:", ok, v)
  local ok2, v2 = js.Promise:resolve(1):await()
  print("resolved:", ok2, v2)
end)
Illustrative: runs outside the browser.
Details
  • task(fn) also returns a promise, of fn's first value.

The DOM command buffer

DOM writes

Every dom write, such as dom.text or dom.attr, queues into a shared linear-memory buffer. The buffer hits the DOM once, on dom.flush() or at the end of the event dispatch that queued it.

local dom = require("santoku.web.dom")
dom.text("title", "hello")
dom.html("container", "<p>hi</p>")
dom.attr("title", "title", "a tooltip")
dom.attr("title", "title", nil)
dom.data("title", "sync", "dirty")
dom.style("title", "color", "teal")
dom.style("title", "--accent", "#f80")
dom.class_add("title", "active")
dom.class_rm("title", "hidden")
dom.insert_html("list", "beforeend", '<li id="item-1">first</li>')
dom.prop("item-1", "contentEditable", "true")
dom.prop("item-1", "hidden", false)
dom.focus("item-1", 3)
dom.blur("item-1")
dom.popover_show("menu")
dom.popover_hide("menu")
dom.modal_show("confirm")
dom.modal_close("confirm")
dom.scroll_to(0, 120)
dom.select("editor", 2, 5)
dom.reset("search")
dom.submit("search")
dom.remove_children("container")
dom.remove("item-1")
dom.flush()
Illustrative: runs outside the browser.
Details
  • Since santoku-web 4.1.0, the writes of a raw dom.on, dom.links or dom.popstate handler need no dom.flush().
  • Since santoku-web 4.5.0, a dom.listen callback flushes when it returns or raises. It flushes through the same call as a manual dom.flush(), so it honours a deferring or held dispatch.
  • A listener attached with raw addEventListener keeps its own dom.flush().
  • A dom.listen callback fired synchronously from Lua, such as by el:click(), also flushes the caller's queued writes.
  • An app action's writes still land at its commit. So writes it queues before an await wait for the commit after that await.
  • Writes from a timer or an async resume wait for dom.flush().
  • attr with a nil value removes the attribute.
  • style names that start with - set custom properties.
  • prop sets the property to a JS boolean when the value is a Lua boolean or the string "true" or "false". Any other value sets it to the string.
  • focus takes an optional caret offset.
  • Since santoku-web 4.0.0, a target is an element id, "body" or a dom handle. Handles: https://santoku.dev/santoku-web#santoku-web--handles-roots-and-templates
  • Since santoku-web 5.0.0, a target is also a { root, selector } table. Any other value raises "expected an id string, a dom handle or a { root, selector } table". Selector targets: https://santoku.dev/santoku-web#santoku-web--selector-targets
  • Since santoku-web 9.0.0, "document" is a target too, for document properties such as dom.prop("document", "title", t).
  • select(target, start, stop) selects the text between two character offsets inside the target once the flush has applied. stop defaults to start, and a negative offset raises.
  • reset(target) calls the form's reset() at the flush.
  • Since santoku-web 4.1.0, submit(target) sends a form natively at the flush through HTMLFormElement.prototype.submit. That fires no submit event and runs no constraint validation.
  • Since santoku-web 4.1.0, a flush whose work runs past 6 ms lands over several tasks. First come the ops that only touch nodes cloned in that flush and still detached, a slice per task.
  • Then the ops that touch the page land together in one task, so the page never shows part of a flush.
  • dom.read and dom.node finish a pending flush first, and a later flush lands after it.
  • A flush with a focus, blur, popover, modal, scroll, scroll_into_view, select, reset, submit, history or listener op lands before flush() returns.
  • modal_show and modal_close exist since santoku-web 6.0.0.
  • Since santoku-web 7.0.0, a modal_show dialog also closes on a backdrop click, through a cancel event and close(). Modal and popover rules: https://santoku.dev/santoku-web/components
  • Since santoku-web 7.0.0, dom.painted() waits in the caller's coroutine until the browser has painted every flush made before the call. It flushes nothing and returns nothing.
  • With no flush pending, dom.painted() waits for the next rendering update to end.
  • Since santoku-web 4.4.0, the flush at the end of an event dispatch lands before the dispatch returns. So a default action, such as following a link or sending a form, runs after those writes.

DOM reads

dom.read(query, ...) runs its queries at once and returns one result per query in order, with nil for a missing element.

local dom = require("santoku.web.dom")
local text, tip, sync, active = dom.read(
  { "text", "title" },
  { "attr", "title", "title" },
  { "data", "title", "sync" },
  { "has_class", "title", "active" }
)
print(text, tip, sync, active)
local rect, scroll = dom.read({ "rect", "title" }, { "scroll" })
print("rect:", rect[1], rect[2], rect[3], rect[4], rect[5], rect[6])
print("scroll:", scroll[1], scroll[2], scroll[3], scroll[4], scroll[5])
local cursor, hit, checked = dom.read(
  { "cursor", "editor" },
  { "element_at", 40, 200 },
  { "prop", "note-1", "checked" }
)
print(cursor, hit, checked)
local ds, fields, key, sel = dom.read(
  { "dataset", "title" },
  { "form", "search" },
  { "closest", "item-1", "data-key" },
  { "selection", "editor" }
)
print(ds.sync, fields.q, key, sel and sel.start)
Illustrative: runs outside the browser.
Details
  • Since santoku-web 4.1.0, read first applies every queued write and lookup. So dom.find followed by dom.read needs no flush in between.
  • Inside an event dispatch, read first applies the writes that a dom.flush() call already asked for.
  • Since santoku-web 4.0.0, reads take dom handles too, and the dataset, form, closest and selection queries exist.
  • Since santoku-web 5.0.0, a query's target is also a { root, selector } table: https://santoku.dev/santoku-web#santoku-web--selector-targets
  • rect, scroll and each entry of rects are lists in the order the Result column gives. So rect[1] is top and scroll[2] is scrollY.
QueryResult
rect{ top, left, bottom, right, width, height }
scroll{ scrollX, scrollY, innerWidth, innerHeight, scrollHeight, clientWidth }, with clientWidth since santoku-web 4.4.0
rectsa list of rects, one per line box, since santoku-web 4.4.0
indexthe 1-based position of the target's closest selector match among a root's matches, since santoku-web 4.4.0
location{ pathname, search, hash, state }, with state as JSON text, since santoku-web 4.4.0
cursorthe caret offset
element_atthe id of the closest data-id ancestor under a point
datasetthe element's data attributes as a table
forma form's fields, with a repeated name as a list and a file as its name
closestan attribute's value on the nearest ancestor that has it
selection{ start, stop, collapsed } for the text selection inside the element
attrsevery attribute of the element as a table by name, since santoku-web 4.4.0
{ "referrer" }document.referrer, since santoku-web 9.0.0
{ "focus", target }true when the focused element, followed through open shadow roots, is target or inside it, since santoku-web 9.0.0
{ "normalize", html }html parsed and serialized by the browser through a template element, since santoku-web 9.0.0
{ "zone", t }{ offset, abbr }: the UTC offset in seconds and the short zone name at instant t (seconds), for santoku.utc's zone_format and zone_date, since santoku-web 9.0.0
  • index takes { "index", target, selector, root }. root is optional and defaults to the target's document or shadow root.
  • index returns nil when no ancestor-or-self of the target matches inside root.

Navigation, dialogs and downloads since santoku-web 9.0.0

dom.go, dom.alert, dom.confirm and dom.download cover the page actions that once needed santoku.web.js.

local dom = require("santoku.web.dom")
if dom.confirm("Export the list?") then
  dom.download("todos.json", "[]", "application/json")
end
dom.go("/done", { replace = true })
Illustrative: runs outside the browser.
Details
CallEffect
dom.go(url)assigns location.href
dom.go(url, { replace = true })replaces the current history entry
dom.go(url, { target = "_blank" })opens a new window
dom.go(url, { target = "_top" })assigns the top frame's location
dom.download(name, text, type)saves text as a file named name with MIME type type
  • dom.go and dom.download run at the next flush, in order with the other commands. Any other target, or replace with a target, raises.
  • dom.alert(text) and dom.confirm(text) flush pending commands, show the browser dialog and return. confirm returns true or false.
  • They block the page like window.alert, so call them from a handler or an action.

dom.jump since santoku-web 4.3.0

dom.jump(target, force) scrolls the window so the target sits at the top of the screen. Without force it scrolls only when the target's top is above the screen.

local js = require("santoku.web.js")
local dom = require("santoku.web.dom")
local root = dom.root(js.document)
dom.jump({ root, "#results" })
dom.jump({ root, "#section-tabs" }, true)
dom.jump("page-top", true)
dom.flush()
Illustrative: runs outside the browser.
Details
  • Since santoku-web 5.0.0, target is an element id, a dom handle or a { root, selector } table, as in every other op. Selector targets: https://santoku.dev/santoku-web#santoku-web--selector-targets
  • For the first match under a root, pass { root, selector }.
  • A target with no element, or a selector with no match, leaves the window where it is.
  • jump reads the target's position when it's called, after the queued writes land.
  • jump rounds the target position to whole pixels and queues the scroll like any other write.
  • Use it after a render that replaced a list the reader had scrolled past.

Selector targets since santoku-web 5.0.0

{ root, selector } targets the first match of selector inside root, and { root, selector, n } the nth match from 1. Every dom write and dom.read query takes one as its target.

local dom = require("santoku.web.dom")
local js = require("santoku.web.js")
local root = dom.root(js.document:querySelector("job-search").shadowRoot)
dom.text({ root, "header h2" }, "Jobs")
dom.class_add({ root, "li.row", 2 }, "active")
dom.prop({ root, "input[name=q]" }, "value", "chef")
dom.focus({ root, "#q" })
dom.text({ "sidebar", ".count" }, "12")
dom.flush()
local q, fields, missing = dom.read(
  { "prop", { root, "input[name=q]" }, "value" },
  { "form", { root, "form" } },
  { "text", { root, ".absent" } }
)
print(q, fields.q, missing)
print(dom.node({ root, "header h2" }).textContent)
Illustrative: runs outside the browser.
Details
  • root is an element id or a dom handle. Inside a component, c.root is the root: dom.focus({ c.root, "#q" }).
  • A selector target is one buffered command. It allocates no handle and adds no crossing.
  • The lookup runs when the flush applies the op, after the writes queued before it.
  • A write whose selector has no match is skipped with the console warning "dom: nothing in the root matches:", and the rest of the flush applies.
  • A read whose selector has no match gives nil.
  • dom.node and dom.jump take the same table. dom.node returns the JS node, or nil when nothing matches.
  • dom.listen and dom.release take no selector target.
  • dom.find, dom.nth and dom.byid still return a handle. Use a handle for a node that's used many times or kept, and free it with dom.release.
Bad targetError
a root that's neither a string nor a number"a { root, selector } target needs an id string or a dom handle as its root"
a number root that's no handle"the root of a { root, selector } target is not a dom handle"
a missing selector, or one that's no string"a { root, selector } target needs a selector string"
an n that's no integer from 1"the position in a { root, selector, n } target must be an integer from 1"

dom.nth since santoku-web 4.4.0

dom.nth(root, selector, i) returns a handle to the i-th match of selector under root, counting from 1. Use it to write to one of many matches without a JS loop.

local dom = require("santoku.web.dom")
local n = dom.read({ "index", "word-7", "span[data-entity]", "editor" })
local h = dom.nth("editor", "span[data-entity]", n)
dom.class_add(h, "hover")
dom.release(h)
dom.flush()
Illustrative: runs outside the browser.
Details
  • root is a dom handle or id, as in dom.find.
  • The lookup happens at the next flush, after the writes queued before it.
  • A miss leaves the handle unbound, so its writes are skipped.
  • An i below 1 raises "expected a position from 1".
  • The index read query finds the i for a node: https://santoku.dev/santoku-web#santoku-web--dom-reads

dom.scroll_into_view since santoku-web 4.4.0

dom.scroll_into_view(target) scrolls the target into view with the browser's scrollIntoView defaults. It lands before flush() returns.

local js = require("santoku.web.js")
local dom = require("santoku.web.dom")
local top = dom.find(dom.root(js.document), "[data-ref=top]")
dom.scroll_into_view(top)
dom.release(top)
dom.flush()
Illustrative: runs outside the browser.
Details
  • target is an element id or a dom handle.
  • Use it after a render that adds the element, since the scroll runs after the writes queued before it.

dom.listen

dom.listen(id, event, fn, opts) attaches an event handler by element id, with window and body accepted as ids. opts passes addEventListener options.

local dom = require("santoku.web.dom")
local stop = dom.listen("item-1", "click", function ()
  dom.text("item-1", "clicked")
end)
dom.listen("window", "resize", function ()
  local scroll = dom.read({ "scroll" })
  print("viewport now:", scroll[3], scroll[4])
end)
dom.listen("body", "touchstart", function ()
  dom.class_add("body", "touch-active")
end, { passive = true })
dom.listen("document", "selectionchange", function ()
  print("selection moved")
end)
local host = require("santoku.web.js").document:querySelector("my-list")
local root = dom.root(host.shadowRoot)
local stop_shadow = dom.listen(root, "click", function (_, ev)
  print("clicked inside the shadow root:", ev.type)
end)
stop()
stop_shadow()
Illustrative: runs outside the browser.
Details
  • Handlers follow the this-first convention: https://santoku.dev/santoku-web#santoku-web--callbacks-and-the-this-first-convention
  • Since santoku-web 4.0.0, listen returns a stop function that removes the listener. A second call to stop does nothing.
  • Since santoku-web 4.0.0, listen returns nothing when no element has the id.
  • Since santoku-web 4.1.0, listen also takes "document" and a dom handle, such as a shadow root from dom.root or an element from dom.find.
  • listen resolves a handle when it runs, after the queued lookups land, so a dom.find needs no flush first.
  • Since santoku-web 4.4.0, listen applies queued writes before it looks up an id. So it finds an element that an unflushed dom.html wrote.
  • The stop function still removes the listener after dom.release frees the handle.
  • Since santoku-web 9.0.0, fn gets (this, ev, detail). detail is ev.detail decoded into Lua, so a listener for a c.emit event gets the table c.emit sent.
  • listen adds a plain addEventListener, so dom.on handlers on the same root still get the event.
  • Since santoku-web 10.0.0, fn runs in a spawned task, so a listener can block on an await or a sleep. Its writes after the block land with no dom.flush.
  • The event dispatch ends at fn's first block. Call ev:preventDefault(), ev:stopPropagation() and any other synchronous work before it, since after it they have no effect.

Handles, roots and templates since santoku-web 4.0.0

A dom handle is a number that names a node on the JS side. Handles let Lua target nodes that have no id or sit inside a shadow root.

local dom = require("santoku.web.dom")
local js = require("santoku.web.js")
local host = js.document:querySelector("my-list")
local root = dom.root(host.shadowRoot)
local list = dom.byid(root, "list")
local title = dom.find(root, "header h2")
dom.template("row", '<li class="row"><b>name</b>: <i>value</i></li>')
local frag, hs = dom.clone("row", { { 1 }, { 1, 1, 1 }, { 1, 3 } })
dom.attr(hs[1], "data-key", "a")
dom.text(hs[2], "alpha")
dom.text(hs[3], "one")
dom.insert(list, frag)
dom.text(title, "1 row")
dom.flush()
print(dom.node(hs[1]).className)
dom.remove(hs[1])
dom.release(title)
dom.flush()
Illustrative: runs outside the browser.
Details
  • dom.root(node) takes a JS node, such as a shadow root, and returns a handle.
  • dom.byid(root, id) and dom.find(root, selector) look inside that root and return a handle at once.
  • The lookup happens at the next flush. A miss leaves the handle unbound, so its writes are skipped.
  • A string id still targets the document.
  • dom.template(name, html) registers markup once. A second call with other markup under the same name raises.
  • dom.clone(name, paths) returns a handle for a fresh copy and a list with one handle per path. A path lists 1-based child node indexes, text nodes included.
  • dom.insert(parent, node, before) inserts or moves a node, ahead of the optional before handle.
  • dom.remove takes the node out, so it can go back in.
  • dom.release(h) frees a handle and stops a listener's dispatch. Later writes to it are skipped while the rest of the flush applies.
  • dom.node(h) returns the JS node as an unwrapped object, so dom.node(h).className reads a property and dom.node(h):focus() calls a method.
  • Since santoku-web 5.0.0, a selector target needs no handle: https://santoku.dev/santoku-web#santoku-web--selector-targets
  • Since santoku-web 4.1.0, two ops work on the run of siblings between two marker nodes, such as a pair of empty comments.
  • dom.range_html(start, stop, html) replaces what lies between the markers with the parsed html.
  • dom.range_move(start, stop, parent, before) moves start, stop and everything between them into parent ahead of before. before is required.
  • santoku.web.mustache uses the range ops for a raw hole beside elements.

Delegated data-action events since santoku-web 4.0.0

dom.on(root, event, fn, opts) puts one delegated listener on a root and returns its handle. An event reaches fn when an element between the target and the root has a data-action that names it.

local dom = require("santoku.web.dom")
local js = require("santoku.web.js")
local root = dom.root(js.document:querySelector("my-list").shadowRoot)
local out = dom.byid(root, "out")
dom.on(root, "click", function (action, el, ev)
  dom.text(out, action .. " " .. tostring(ev.key))
  dom.class_add(el, "done")
end)
dom.on(root, "submit", function (_, _, ev)
  dom.text(out, ev.form.q)
  dom.defer(function ()
    print("after the handler, before the flush")
  end)
  return true
end)
dom.on(root, "keydown", function (_, _, ev)
  if ev.keyboard.key == "Escape" then
    dom.text(out, "closed")
    return true
  end
end)
dom.flush()
Illustrative: runs outside the browser.
Details
  • A second dom.on for the same root and event replaces the first.
  • data-action holds space-separated entries. Each entry is an event:name pair, or a bare name, which means click, or submit on a form.
  • fn gets the action name, a handle for the action element and a decoded payload ev.
  • ev carries type, action, tag, key (the nearest data-key), value (the target control's value) and data (the action element's data attributes).
  • Since santoku-web 4.1.0, ev.checked is the checked state as a boolean when the target is a checkbox or radio input. It's nil for any other target.
Event or optionAdds to ev
a submitform (the fields, with a repeated name as a list) and submitter
a keyboard eventkeyboard { key, code, repeated, ctrl, meta, shift, alt }
a pasteclipboard { text, html }
an input eventinput { type, data, composing }
opts.selectionselection { start, stop, collapsed }
opts.htmlhtml, the root's markup
opts.margin (visible only)none; the IntersectionObserver rootMargin, "0px" when absent
a change on a file inputfiles, a list of { name, type, size, text }
opts.pointer (mouse and pointer events)x and y, the client coordinates
enter, leavetype, action, tag, key, data and el of the element entered or left; x and y with opts.pointer
  • Since santoku-web 9.0.0, dom.on(root, "enter", fn) and dom.on(root, "leave", fn) run data-action="enter:NAME leave:NAME" actions with mouseenter and mouseleave meaning, from one mouseover or mouseout listener on root.
  • A move between children of an element runs nothing for that element. One move runs every element it crosses, enter outermost first and leave innermost first.
  • Since santoku-web 9.0.0, dom.on(root, "visible", fn, { margin = "200px" }) keeps one IntersectionObserver for root and observes every element under root whose data-action lists visible:NAME, including ones a later render adds.
  • fn runs as for a click, with type "visible", each time such an element enters the viewport widened by margin. Releasing the listener disconnects the observer. A margin on any other event raises "dom.on: margin applies only to the visible event".
  • ev.event is the raw JS event, read only when Lua asks for it.
  • Returning true calls preventDefault.
  • A dispatch crosses into wasm once. The writes, dom.flush calls and history changes it makes go back as one flush when fn returns.
  • dom.defer(fn) runs fn after the handler inside the same dispatch, ahead of that flush. Outside a dispatch it queues a microtask.
  • The element handle stays valid until the next dispatch to the same listener.
  • Since santoku-web 4.1.0, an action event also carries ev.target, a handle for the node the event hit. It comes from composedPath()[0] at dispatch time, and it's held like the element handle.
  • The DOM clears ev.event.target inside a shadow root once dispatch ends. So code that runs later, such as an app action, reads ev.target instead.
  • dom.read({ "closest", ev.target, "data-href" }) gives the nearest data-href, or nil when the click landed outside every element that has one.

Apps and templates

santoku.web.app since santoku-web 4.0.0

app.mount(root, fn) runs a page from one state table. fn(h) gets the root and returns { state, actions, render, events }. mount returns unmount and the handle c.

Template
<button type="button" popovertarget="menu">Menu</button>
<ul id="menu" popover>...</ul>
Client
local app = require("santoku.web.app")
local async = require("santoku.web.async")
local dom = require("santoku.web.dom")
local js = require("santoku.web.js")
local state = { items = {} }
local unmount, c = app.mount("todo-app", function (h)
  local count = dom.byid(h, "count")
  return {
    state = state,
    actions = {
      add = function (s, _, ev)
        s.items[#s.items + 1] = ev.form.title
      end,
      clear = function (s)
        s.items = {}
      end,
      reveal = function (s, c)
        s.dim = true
        c.enter(function ()
          s.dim = false
        end)
      end,
      send = function (_, _, ev)
        if ev.form.title ~= "" then
          dom.submit(ev.el)
        end
      end,
    },
    render = function (s)
      dom.text(count, tostring(#s.items))
    end,
  }
end)
async.spawn(function ()
  local ok, res = js.window:fetch("/items.txt"):await()
  if ok then
    local _, text = res:text():await()
    state.items = { text }
    c.commit()
  end
end)
Illustrative: runs outside the browser.
Details
  • root is an element id, a dom handle or a JS node. h is the id or the handle as given, or a new handle for a JS node.
  • mount listens for click and submit plus every name in events. An events entry such as { "paste", prevent = true, html = true } also passes dom.on options.
  • { "visible", margin = "200px" } runs data-action="visible:NAME" actions as their elements scroll into view, inside the component's coroutine group, with a commit after, and never after disconnect.
  • { "enter", pointer = true } and "leave" run data-action="enter:NAME leave:NAME" actions as the pointer enters and leaves each element, with ev.el, ev.data, and ev.x and ev.y.
  • An event runs the action its data-action names as actions[name](state, c, ev), with ev.el the action element's handle. Data-action events: https://santoku.dev/santoku-web#santoku-web--delegated-data-action-events
  • An unknown action name raises "app: unknown action".
  • The action runs in a coroutine after the handler, so it can await, and it ends with a commit.
  • Since santoku-web 9.0.0, every handler gets the handle c after the state, and the framework writes no field on the state table. c.commit() calls that app's render(s, c) and then flushes, and no other app renders.
  • c.root is the root handle. c.emit, c.scope and the rest of c: https://santoku.dev/santoku-web/components
  • The render after an action is the same commit. So an action that calls c.commit() before an await shows its progress.
  • Run work that no action starts, such as a startup load or a timer, in async.spawn(fn), and end it with c.commit(). Async: https://santoku.dev/santoku-web#santoku-web--santoku-web-async
  • End a block that queues dom writes and never commits with dom.flush().
  • An error in an action skips the commit after it and reaches the page as an unhandledrejection event. Later actions still run.
  • mount prevents the default of a submit, a click on a link, and an events entry with prevent.
  • mount renders once and returns an unmount function that stops dispatch, and c. After unmount, c.commit() renders nothing and still flushes, and c.emit sends nothing.
  • Since santoku-web 4.1.0, an action that wants the browser's own submission after its check calls dom.submit(ev.el).
  • A menu is a popover panel opened by a popovertarget button, as in the template.
  • Since santoku-web 10.0.0, the element's departure kills its scope: every fetch its actions, start and route await is aborted, and the awaiting code never resumes. A latest keeps one call of a series in flight: https://santoku.dev/santoku-web#santoku-web--latest-in-components
  • Since santoku-web 9.0.0, c.enter(undim) fades new content in. Set the dimmed mark on the state before the call. c.enter calls c.commit(), waits for dom.painted(), calls undim() and calls c.commit() again.
  • c.enter waits in the caller's coroutine and returns nothing.
  • Since santoku-web 11.0.0, c.hash_jump(ev) serves in-page links: actions = { jump = function (_, c, ev) c.hash_jump(ev) end }. A second argument raises.
  • c.hash_jump reads the clicked link's href, such as #notes, and jumps with force to the first [id=notes] or a[name=notes] under c.root.
  • An href that isn't #name, or a link with no href, leaves the window where it is.
  • c.hash_jump escapes quotes and backslashes in the name, so any name makes a valid selector.

Components with app.define since santoku-web 4.3.0

app.define(spec) registers a custom element that mounts one app per element, renders spec.template and routes through one shared router.

local app = require("santoku.web.app")
local tpl = require("myapp.templates")

app.define({
  tag = "job-search",
  template = tpl.job_search,
  sheets = { app.page, app.stylesheet("a { color: teal }") },
  scope = { "q", "p" },
  state = function (attrs, scope)
    return { cur = scope.read(), ctx = attrs.context_path }
  end,
  route = function (s, c)
    s.cur = c.scope.read()
  end,
  actions = {
    search = function (s, c, ev)
      s.cur = c.scope.read(ev.form)
      c.scope.push(s.cur)
    end,
  },
})
Illustrative: runs outside the browser.
Details
  • Since santoku-web 9.0.0, spec.template is one entry of the table loader.templates builds: { name, compiled, style }. Its style becomes the element's own sheet.
  • define raises "app.define: spec.template must be a template" when spec.template is missing or names no compiled template.
Spec fieldUse
tagthe element name
templatethe template entry, such as tpl.job_search
state(attrs, scope)returns the state table, from the element's attributes and its scope
actions, eventsas in app.mount
derive(s, c)runs just before every template update, which define then runs
sheetsa list of constructed stylesheets, such as app.stylesheet(css) returns, adopted ahead of the template's own style, with app.page first to clone the page's sheets
scopea list of query names gives each element its own router scope. A name in it gives one scope that every element with that name uses
route(s, c, dir)runs in a coroutine on each scope change, then commits. c.scope.read() reads the new values
rewrite(s, c, k, ev)the S.links rewrite for links under the element
start(s, c)runs in a coroutine after the first render, then commits. c.on_stop(fn) in it registers each disconnect step
statesa list of state field names, each shown as the host attribute state-<name>
  • Since santoku-web 11.0.0, app.page as the first entry of sheets copies the page's stylesheet link and style elements into the start of the shadow root on each connect.
  • The browser applies those copies before every adopted sheet, so define raises when app.page comes anywhere but first in sheets.
  • Since santoku-web 11.0.0, derive(s, c) replaces render(s, c, update), and scope replaces keys and shared. scope is a list of plain query names, with name as its only named field. A shared spec writes scope = { "t", "q", "p", "o", name = "matcher" }.
Removed fieldWrite instead
page_sheets = truesheets = { app.page, ... }
empty = { "0" }treat the value as absent where the component reads it
{ "t", default = "deal" }"t", and c.scope.read().t or "deal" at each read
{ "keyword", "q" }, an alias list"keyword"
render(s, c, update)derive(s, c), with no update call
keys = { ... }scope = { ... }
drop = { "o" }"o" in the scope list, left out of the table a search writes
shared = "name"scope = { ..., name = "name" }
stop(s, c)c.on_stop(fn) from start
route(s, c, path, dir)route(s, c, dir), reading c.scope.read()
  • Lua can't count a function's parameters, so define can't see a stale route(s, c, path, dir). That route gets dir in the path slot, and its c.scope.read(path) raises "router: read takes a table or a function".
  • define raises a clear error on each removed field, on a scope that isn't a table, on a named scope field other than name, and on a key that isn't a plain string.
  • The handle c, the disconnect order and the authoring rules: https://santoku.dev/santoku-web/components
  • The shadow root is built once per element, so a moved element keeps it. Teardown empties the shadow root after the c.on_stop steps end, and the c.root handle stops working.
  • Since santoku-web 11.0.0, the c.on_stop steps run in order as one task at disconnect, while the view is still in the root. A step can await, and c still works.
  • The state table is the template's data. So a keyed list field of the state becomes a list object after the first render. Live views: https://santoku.dev/santoku-web/templates
  • spec.state gets attrs, a plain table of the element's attributes: https://santoku.dev/santoku-web/components
  • The render after a route and start is the same c.commit() as after an action.
  • route doesn't run for the URL the page loads with. spec.state reads that URL with scope.read().
  • Since santoku-web 7.0.0, at connect and before spec.state, define seeds the scope. Attributes named for the spec's keys win over the URL, which fills the rest. An empty or naked attribute seeds nothing.
  • The seed writes the canonical URL with one replace and runs no route. Each sharer seeds its own keys, and the last connect wins a shared key.
  • With the example's spec, <job-search q="chef"> on /jobs?p=2 reads { q = "chef", p = "2" }, and the URL becomes /jobs?q=chef&p=2.
  • A component that shows another component's state doesn't render when that state changes. The code that changes the state calls the reader's c.commit().
  • Or both components name one scope with scope.name. Then each one's route runs on a followed link and on Back and Forward.
  • scope.push from one sharer doesn't call the other sharers' route.
  • A scope without a name is called tag#N, where N counts that tag's elements.
  • Since santoku-web 4.4.0, specs that share a scope declare their own keys. Each gets a router view whose keys and read cover only those keys. Router: https://santoku.dev/santoku-web#santoku-web--santoku-web-router
  • A disconnect disposes that scope, except a shared one.
  • start of a scoped element holds the router's reload scroll until start returns. Router scroll: https://santoku.dev/santoku-web#santoku-web--santoku-web-router
  • S.links follows links under every scoped element in query mode.
app.router opts fieldDefault
mode, the history mode"query"
scroll, the router scroll flagtrue
  • Since santoku-web 11.0.0, the app's history always batches, and app.router raises on batch.
  • The router starts at the first scoped element. Since santoku-web 9.0.0, app.router(opts) sets its options once before that. A second call raises "app.router: called twice", and a call after the router starts raises "app.router: the router already runs".
  • define raises when spec.tag or spec.state is missing, when a spec with scope has no route, or when a scope without a name has no keys.
  • Since santoku-web 6.0.0, a second define of one tag raises.
  • When the page already holds elements with the tag, define registers the tag in a later task, one task per such tag. A tag with no element in the page registers at once.

latest in components since santoku-web 10.0.0

async.latest(fn) from the app's santoku.async module returns a callable for a series of calls where only the newest counts. A call kills the call before it, whose caller never resumes.

local app = require("santoku.web.app")
local dom = require("santoku.web.dom")
local http = require("santoku.web.http")
local async = require("myapp.async")
local tpl = require("myapp.templates")

local function jobs (q)
  return http.get("/api/jobs", { params = { q = q } })
end

app.define({
  tag = "job-list",
  template = tpl.job_list,
  states = { "stale" },
  state = function ()
    return { html = "", stale = false }
  end,
  start = function (_, c)
    c.search = async.latest(async.atleast(jobs, 125))
  end,
  actions = {
    search = function (s, c, ev)
      s.stale = true
      c.commit()
      local ok, resp = c.search(ev.form.q)
      s.stale = false
      if ok then
        s.html = resp.body()
        c.commit()
        dom.jump({ c.root, "#results" })
      end
    end,
  },
})
Illustrative: runs outside the browser.
Details
  • santoku-web 10.0.0 removed santoku.web.latest and its l.run(fn). latest comes from santoku.async: https://santoku.dev/santoku#santoku--santoku-async
  • l(...) runs fn(...) in the calling task inside a new scope, and returns fn's values. Call it inside a task, such as an action, route, start or a spawned task.
  • A kill aborts each fetch the call awaits and clears its sleeps, along with any task fn spawned. The killed caller needs no check for a cancelled result. A task promise of a killed caller resolves with nil.
  • l.cancel() kills the newest call and is safe to call any number of times. l.busy() is true while fn runs.
  • A call of l from inside fn of the same l raises "latest: this latest already runs on this coroutine". A call of another latest inside fn is a child of this call, so l.cancel() kills both.
  • An error in fn reaches the caller. err.pcall around the call catches it, before or after a block.
  • In a component, keep l on c, such as c.search = async.latest(fn) in start, never on s. The element's departure kills every call made from its handlers, so no c.on_stop is needed for a request.
  • Code after a call that a newer call kills doesn't run. A flag set before the call and cleared after it stays set, so reset it next to l.cancel().
  • The library writes nothing to s and doesn't jump. The app sets its own dim and error fields, commits, and calls dom.jump({ c.root, selector }).
  • async.latest(async.atleast(fn, ms)) holds a dim for at least ms milliseconds.

Utilities

Timers since santoku-web 10.0.0

A timer is spawn plus sleep. A cancellable timer is a latest, and debounce and atleast come from santoku.async. The app's async module builds all of them over santoku.web.async.

local async = require("myapp.async")
local http = require("santoku.web.http")
async.spawn(function ()
  async.sleep(100)
  print("fires once, 100ms later")
end)
local reminder = async.latest(function (ms)
  async.sleep(ms)
  print("reminder")
end)
async.spawn(reminder, 5000)
reminder.cancel()
local search = async.debounce(function (q)
  print("searching:", q)
end, 300)
async.spawn(search, "l")
async.spawn(search, "lua")
search.cancel()
async.spawn(function ()
  local ok, resp = async.atleast(http.get, 125)("/api/search", { params = { q = "lua" } })
  if ok then
    print("results after at least 125ms:", resp.body())
  end
end)
Illustrative: runs outside the browser.
Details
  • santoku-web 10.0.0 removed santoku.web.timer: set_timeout, clear_timeout, sleep, debounce, atleast and now.
RemovedReplacement
timer.set_timeout(fn, ms)async.spawn(function () async.sleep(ms) fn() end)
timer.clear_timeout(id)l.cancel() on a latest that sleeps, then calls fn
timer.sleep(ms)async.sleep(ms)
timer.debounce(fn, ms)async.debounce(fn, ms)
timer.atleast(fn, ms)async.atleast(fn, ms)
timer.now()async.now()
  • async.debounce(fn, ms) returns a callable with fn's signature. A call blocks the caller for ms, and a newer call kills the waiting one, whose caller never resumes. Spawn the call when the caller mustn't wait.
  • d.cancel() on a debounce kills the waiting call (since santoku 5.1.0). It replaces timer.clear_timeout on a debounced timer.
  • A sleep inside a component's handler or a latest call dies with that scope.
  • santoku.async: https://santoku.dev/santoku#santoku--santoku-async

santoku.web.storage since santoku-web 5.0.0

santoku.web.storage wraps localStorage. storage.set(k, v) stores v under k, and a nil v removes the key. storage.get(k) returns the stored string, or nil.

local storage = require("santoku.web.storage")
storage.set("theme", "dark")
print("stored:", storage.get("theme"))
storage.set("theme", nil)
print("removed:", storage.get("theme"))
Illustrative: runs outside the browser.
Details
  • set stores v as a string and returns nothing.
  • set raises "storage.set: no localStorage here" where the global has no localStorage, such as a worker. get raises "storage.get: no localStorage here".

Network

santoku.web.socket since santoku-web 10.0.0

santoku.web.socket is the browser backend for santoku.http. santoku.web.http is the app's one client over it, built once on the first require.

local http = require("santoku.web.http")
local async = require("santoku.web.async")
async.spawn(function ()
  local ok, resp = http.get("/api/items", { params = { page = 2 } })
  print("ok:", ok, "status:", resp.status)
  print("content type:", resp.headers["content-type"])
  print("body:", resp.body())
  local pok, presp = http.post("/api/items", { body = "{}" })
  print("one attempt:", pok, presp.status)
end)
Illustrative: runs outside the browser.
Details
  • Every module that requires santoku.web.http gets the same client, so a hook installed with http.on, such as santoku.web.version.install_hooks, reaches every request in the app.
  • Inside a task, the client's fetch, get and post block inline. They return ok plus a response with status, ok, headers by lowercased name and a body() reader.
  • The text body arrives before the call returns, and body() gives it on every call. A failure while it downloads is a failed request. Fetch a binary body with js.fetch.
  • ok is the Response's ok flag, so a 404 returns false plus the response. A fetch that fails returns false and a response with status 0 and error, the JS error.
  • A GET, HEAD, OPTIONS, PUT or DELETE retries a response with status 0, 429, 502, 503 or 504 up to 3 times, with a growing backoff. A POST or PATCH retries only with retry = true or a retry table.
  • Each fetch carries an AbortController that the library owns, so opts.signal isn't accepted. A kill of the scope the fetch runs in, from a component's departure or a newer call of a latest, aborts it, and the caller never resumes.
  • The backend exports fetch and sleep on their own. Its sleep is santoku.web.async's sleep, so a kill also clears a retry's backoff.

santoku.web.stream

santoku.web.stream is the push driver for TLS and TCP in a wasm build under node, with the contract santoku.socket.stream follows natively. santoku-imap runs over it.

local stream = require("santoku.web.stream")
stream.connect({
  host = "imap.example.com",
  port = 993,
  data = function (chunk) print("read", #chunk, "bytes") end,
  closed = function (reason) print("closed:", reason) end,
}, function (ok, conn)
  if not ok then
    return print("connect failed:", conn)
  end
  conn.write("A1 CAPABILITY\r\n")
end)
Illustrative: runs outside the browser.
Details
  • connect(opts, done) opens a TLS connection to opts.host and opts.port through node's tls module. With opts.tls = false it opens plain TCP through net.
  • connect calls done(true, conn), where conn has write and close, or done(false, reason).
OptionMeaning
host, portwhere to connect
tlsfalse for plain TCP
datagets every chunk as a Lua string, and is required
closed(reason)reports the end of an established connection
sslnamethe SNI name
verifyfalse accepts any certificate
  • Since santoku-web 11.0.0, connect loads net and tls through process.getBuiltinModule (Node 20.16 and later). Where that's missing, such as a browser, connect raises "stream: process.getBuiltinModule is missing, santoku.web.stream needs Node 20.16 or later".

History and routing

santoku.web.history

santoku.web.history gives navigation with mark tracking. Each entry's state carries a monotonic id, a path-to-id mark map and user data.

local make_history = require("santoku.web.history")
print("fresh visit:", make_history.arrived())
local history = make_history({
  mode = "query",
  batch = true,
})
history.push("/settings?tab=profile", { section = "profile" })
history.mark("/settings?tab=profile")
history.replace("/settings?tab=security")
history.on_popstate(function ()
  print("state id now:", history.get_current_id(), history.read())
end)
local walked = history.back_to("/")
print("walked back:", walked, history.mode)
Illustrative: runs outside the browser.
Details
  • back_to(path) walks the real history back to the path's mark when one is in reach, and replaces otherwise. It returns true for a walk and false for a replace.
  • set_data(data) replaces the current entry's data, and keeps its id, marks and URL.
  • The "/" mark never prunes, and other marks expire 10 entries back.
  • Since santoku-web 11.0.0, history raises on opts.anchors and opts.prune_distance.
  • Since santoku-web 5.0.0, require("santoku.web.history").arrived() returns true when the page's navigation entry is a fresh visit. It returns false for a reload, a back-forward visit or no entry.
  • back() steps back once and returns true. It returns false on an entry whose id is 0 or missing, such as the one the page loaded on.
  • push(nil, data) adds an entry that keeps the current URL. A router layer's entry leaves the URL unchanged this way.
  • stamped() reports whether the current entry carries an id. An entry the browser made itself, such as the page's first entry or a hash link's, carries none.
  • adopt(id, path) stamps the current entry in place, with no URL change. The entry gets id, empty data, and the marks of the last stamped entry this page saw, pruned at id.
  • adopt also adds a mark for path when path has none.
  • get_data() returns the current entry's data as a Lua table, or {} when it has none.
  • Since santoku-web 4.0.0, opts.mode picks where a path lives, as the table shows. h.mode reports the mode, h.read() returns the current key, and h.go(n) moves n entries.
opts.modeThe path livesh.read() returns
"hash", the defaultafter # in the URLthe hash's path
"query"as the real path and query, such as /jobs?q=chefthe path, query and fragment
  • Inside a santoku.web.dom event handler, history reads the URL and state from the snapshot the event carried. It queues pushState, replaceState and go in the DOM command buffer.
  • With opts.batch, a popstate carries that snapshot too when every dom.popstate listener on the page asked for batch. So a Back that the router handles crosses into Lua once.
  • Since santoku-web 4.4.0, history goes through the buffer outside a handler too. It reads with dom.read({ "location" }), which lands queued writes first, and flushes each write.
  • So an action that pushes, awaits without a commit, then replaces ends on the replaced entry, with one new entry.

santoku.web.router since santoku-web 3.3.0

router({ history = h }) returns R, which runs scoped routes over santoku.web.history for several apps on one page. R.scope(name, opts) returns a scope S with its own path, layers and guards.

local history = require("santoku.web.history")
local router = require("santoku.web.router")
local js = require("santoku.web.js")
local dom = require("santoku.web.dom")
local R = router({ history = history({ mode = "query", batch = true }), scroll = true })
local content = R.scope("content", { primary = true })
local jobs = R.scope("jobs", { keys = { "q", "p" } })
print("read:", jobs.read({ q = "chef", p = "0" }).q, jobs.keys[1])
local side = R.scope("side")
local done = R.wait()
local off = jobs.on_change(function (values, prev, dir)
  print("jobs:", values.q, values.p, dir)
end)
print("fresh arrival:", not R.saved())
done()
local dirty = false
content.guard(function ()
  if dirty then
    content.open("confirm", function () print("confirm closed") end)
    return "restore"
  end
end)
content.push("/jobs")
jobs.push({ q = "chef de partie", p = 1 })
side.push("/help")
print("one entry:", R.key(), R.depth())
local stop = jobs.links(js.document.body)
R.before_follow(function ()
  jobs.replace(jobs.path(), { y = js.window.scrollY })
end)
local stop_pager = jobs.links("pager", function (k, ev)
  if dom.read({ "closest", ev.nh, "data-keep" }) then
    return k .. "&p=1"
  end
end)
content.open("menu", function () print("content menu closed") end)
side.open("menu", function () print("side menu closed") end)
side.close("menu")
content.open("about", function () print("about closed") end, "menu")
content.dismiss("about")
stop()
stop_pager()
off()
side.dispose()
Illustrative: runs outside the browser.
Details
  • The scope with opts.primary carries its path as the URL's path, after the # in hash mode.
  • Every other scope rides in the query as name=path. The query leaves it out while it sits at opts.default, which defaults to "/".
  • Since santoku-web 4.0.0, opts.keys, a list of query keys, gives a scope a table path.
  • S.push({ q = "chef", p = 2 }) writes q=chef&p=2 in keys order, and leaves out nil and empty values.
  • S.path(), on_change and guards return the values as strings.
  • Since santoku-web 11.0.0, each keys entry is one plain query name. A table entry, such as an alias list or { "t", default = "deal" }, raises, and so does opts.empty.
  • An empty value means absent in both directions.
  • A scope with keys takes no primary or default.
  • Since santoku-web 4.3.0, S.read(src) returns a values table under each key.
  • src is a table or a function of a name, such as ev.form. With no src, S.read reads the scope's current values. A src of any other type raises.
  • S.read takes the first value for a key that isn't nil or "", across the sources in order.
  • On a scope without keys, S.read raises "router: read needs a scope with keys".
  • S.keys lists the keys in order. Treat it as read-only.
  • Each query key belongs to one scope, and a plain scope owns the key that is its name. R.scope raises on an overlap.
  • The router keeps the params no scope owns, and since santoku-web 9.0.0 it re-encodes them like the owned ones when it writes the URL.
  • Query mode encodes values the way URLSearchParams does, with a space as +. Hash mode percent-encodes only %, &, =, ?, #, + and whitespace, so a literal + writes as %2B.
  • Since santoku-web 9.0.0, the router decodes through santoku 4's str.from_query. A + reads as a space in both modes, and a % that starts no escape stays as it is.
  • Since santoku-web 4.4.0, opts.shared = true lets several components share one keyed scope. Each R.scope(name, opts) call with shared joins the scope and returns a view.
  • A view's keys and read cover only the keys that call declared. path, on_change, push and the rest act on the whole scope.
  • Each component declares its own keys plus the keys the components share. The scope owns the union, and calls with the same keys get the same view.
  • A join raises when the shared keys come in another order, when one call isn't shared, or when only one call declares keys.
  • A key a later join adds keeps the value the URL already holds for it.
  • Since santoku-web 11.0.0, R.scope raises on opts.drop. List such a param as a key, and leave it out of the table the next write gets.
  • S.dispose() frees the scope's name and query keys. It drops the scope's guards and layers, and doesn't run their close functions.
  • After S.dispose(), every later call on S raises "router: the scope was disposed".
  • In query mode a disposed scope's params stay in the URL, so a new scope with the same keys reads them back.
  • S.push(path, data) adds an entry. Pushes from different scopes in one turn merge into one entry and one Back step.
  • A turn ends with the microtask, or with the santoku.web.dom event dispatch the pushes ran in.
  • S.replace works on the scope's own path, and S.path() and S.data() read it.
  • Since santoku-web 11.0.0, a scope has no mark or back_to, and router raises on opts.read and opts.go. It reads and goes through opts.history.
  • Since santoku-web 11.0.0, S.read raises "router: read takes a table or a function" for any other source.
  • S.on_change(fn) calls fn(path, prev, dir, data) when a history move or a followed link changes that scope.
  • S.on_change(fn) returns a function that removes fn, and a handler can call it during a notify.
  • Layers (menus, sheets, dialogs) live on scopes, so two apps can both open a layer named menu. R has no open.
  • S.open(name, close, from) pushes one entry that keeps the current URL. So the first open on a page with no hash keeps the URL.
  • S.open returns false when the scope already has that layer open.
  • from names an open layer of the same scope, whose entry the new layer takes over.
  • The router keeps every scope's layers in one stack. So Back closes the top layer first, and a close also closes every layer above it, top first.
  • A layer's close function runs once, with no arguments, on every close path in the table. S.release and S.dispose don't run it.
Close pathEffect
Backsteps back past the top layer
S.dismiss(name)steps back past the layer the way Back does
S.close(name)steps back now and holds router calls until the step lands, so a push right after it lands above the page
a takeover through fromthe new layer takes over the entry
a followed linkcloses every open layer
a hash link or a write to location.hashcloses every open layer
  • S.release(name) keeps a layer's entry as a plain route entry and doesn't run its close.
  • S.is_open(name) reports whether the layer is open.
  • S.close, S.dismiss and S.release return false when the scope has no such open layer.
  • Since santoku-web 4.0.0, S.links(root), in query mode only, follows same-origin link clicks under root. S.links returns a function that stops it.
  • root is a dom handle or id, or a JS element or shadow root.
  • Since santoku-web 4.1.0, S.links(root, rewrite) calls rewrite(k, ev) for each link the router would follow.
  • k is the link's path and query, such as /?q=chef, and ev.nh is the link's handle for dom.read.
  • rewrite returns the path and query to follow, or nil to leave the click to the browser.
The browser keeps the click when
another handler already prevented the click's default
the click has a modifier key or another button
the link has a target other than _self, or a download attribute
the link goes to another origin
an element with a data-action for click holds the link
the link goes to another path while no scope is primary
the link changes a param no scope owns
the link only adds a fragment to the current page
  • A followed link closes every open layer and asks the guards with dir "link". Then it pushes one entry and calls on_change with dir "link" and no data.
  • Every scope the link's URL leaves out goes back to its default.
  • Back and Forward still report "back" and "forward".
  • Guards run on every history move the browser makes, and on a followed link.
  • A history move the browser makes is Back, Forward, R.back, R.go, or a hash link when no layer is open.
  • Guards never run on S.push, S.replace, S.open, S.close, S.dismiss or R.skip. A move that closes a layer skips them.
  • R.guard(fn) calls fn(dir, changed), with changed[name] = { path, prev } for each scope that changed.
  • S.guard(fn) calls fn(dir, c) only when its own scope changed.
Guard returnsOn a history moveOn a followed link
"restore"pushes a new entry with the old URLstops the link after its layers have closed: the router pushes nothing and no on_change runs
"stay"keeps the new URL while every scope keeps its old path, and no on_change runsstops the link the same way
  • Router calls a guard makes wait until the move settles. So a guard can't save state into the entry a link leaves.
  • A guard can open a layer before it returns "restore", and that layer lands one entry above the restored page.
  • Since santoku-web 4.1.0, R.before_follow(fn) calls fn(changed) after the guards let a followed link through, and before the router pushes its entry.
  • changed is the same table R.guard gets.
  • Router calls inside fn run at once. So S.replace(S.path(), data) there saves data, such as a scroll position, into the entry the link leaves.
  • Back to that entry brings the data back as S.data().
  • S.push, R.back and R.go need no hook, since the app calls them and can save first.
  • Since santoku-web 4.1.0, router({ history = h, scroll = true }) owns the window's scroll position.
  • A page has one window position and its scopes share each entry, so the router stores one position per entry.
  • The router sets history.scrollRestoration to "manual".
  • The router saves scrollY into the entry being left on a followed link (after the before_follow hooks), on S.push, and 200 ms after scrolling starts.
  • On Back and Forward the router scrolls to the saved position once every on_change handler has returned.
  • The router first waits for each handler that returns a promise. A handler that fetches before it renders returns its promise, such as the one async.task(fn) returns.
  • Since santoku-web 5.0.0, when a handler's promise rejects, the router skips that scroll and raises the error in a coroutine of its own. The page gets an unhandledrejection event.
  • S.replace keeps the saved position.
  • After a reload, the router scrolls to the position the entry saved, once per page. It waits until every component that asked it to wait has rendered.
  • Each component calls local done = R.wait() before its first render and done() after it.
  • The router scrolls one microtask after the last done(), so components that register in the same task all count.
  • A page with one component writes R.wait()() after its first render.
  • R.saved() reports whether a reloaded position is still waiting. So false before the first render means a fresh arrival.
  • Saving stays off until that scroll or the next push, and while a Back or Forward waits on its handlers.
  • A move that closes no layer and changes no scope has landed on a dead entry. A layer's entry after a reload is one, and so is a closed layer's entry reached by Forward.
  • On a dead entry the router keeps going in the direction of travel.
  • Since santoku-web 4.0.0, a move that changes only the URL's fragment in query mode isn't a dead entry. So Back and Forward across #section links stop there.
  • Back through dead entries keeps skipping, and a dead first entry steps off the page.
  • When Forward lands on the newest entry this page has made, the router steps back to the entry it came from.
  • After a reload the router can't know what lies ahead. So it keeps going forward, and stays put when nothing is there.
  • R.on_same(fn) replaces that skip with fn(dir). R.skip(n) moves n entries without settling the landing.
  • R.back() steps back and returns false on the first entry. R.go(n) moves n entries.
  • R.depth() returns the current entry id, and R.key() returns the composed URL key.

Workers and SQLite

santoku.web.rpc

rpc.client(port) returns a channel whose call(name, ...) runs a method on the other side of one persistent MessagePort. rpc.serve(port, handlers) answers those calls.

local rpc = require("santoku.web.rpc")
local js = require("santoku.web.js")
local async = require("santoku.web.async")
local worker = js.Worker:new("/worker.js")
local ch = js.MessageChannel:new()
rpc.register_port(worker, ch.port2)
local chan = rpc.client(ch.port1)
async.spawn(function ()
  local ok, sum = chan.call("add", 1, 2)
  if ok then
    print("sum:", sum)
  else
    print("call failed:", sum)
  end
end)
local function worker_side (port)
  rpc.serve(port, {
    add = function (a, b)
      async.sleep(10)
      return a + b
    end,
  })
end
Illustrative: runs outside the browser.
Details
  • call blocks the task it runs in until the reply comes, and returns true and the method's results, or nil and "status: detail". Call it inside a task.
StatusReturned when
failedthe method raised, the server has no method by that name, or a result can't be packed
lostchannel.lose(detail) ran before the reply came, or ran earlier
  • Since santoku-web 11.0.0, a call travels as santoku.pack bytes in one transferred ArrayBuffer, with a call id. One port carries every call, and each reply finds its caller by the id. rpc.call and its MessageChannel per call are gone.
  • Calls carry Lua values only: nil, booleans, numbers, strings, plain tables, and a userdata whose metatable sets __pack. A JS value in a call raises at the call with "it takes Lua values only". Pass a port or a stream through the setup message instead.
  • lose(detail) fails every pending call with "lost: detail", and every later call returns that status at once. santoku.web.sqlite.proxy calls it when its worker stops.
  • A killed caller abandons its call. The server may still run the method, and the channel drops its reply.
  • rpc.serve runs each message as a task, one at a time per port, in call order. A method can block on sleep or await, and the calls behind it wait.
  • rpc.server(handlers) returns answer(port, ev), which runs one call message inside the task that calls it. Use it to drain messages under your own lock, as the sqlite worker does.
  • A message that isn't packed values in an ArrayBuffer raises in answer.
  • register_port(worker, port) posts a port you made yourself to the worker as REGISTER_PORT, and returns at once. It's the one way to give a worker its port.
  • There's no call timeout. A call to a worker that never answers waits until lose runs.

santoku.web.sqlite

worker(db_path, opts, handler) opens an OPFS-backed SQLite file in a dedicated worker. It serves the closure table that handler returns over rpc. opts is optional.

require("santoku.web.sqlite.worker")("app.db", function (db)
  db.exec("create table if not exists items (id integer primary key, name text)")
  return {
    add = db.inserter("insert into items (name) values (?)"),
    name_of = db.getter("select name from items where id = ?"),
  }
end)
Illustrative: runs outside the browser.
Details
  • SQLite persists to OPFS through a SyncAccessHandle pool. The pool only exists in dedicated workers, so the database lives behind one.
  • worker opens the file under the cooperative OPFS lock, and calls handler(db) with the santoku.sqlite wrapper. handler returns the handlers table, and raises to fail.
  • An open that fails, a handler that raises, or a handler that returns anything but one table sends db_error to the proxy instead.
  • Since santoku-web 11.0.0, the ok argument and the true before the table are gone. A handler that still returns true, handlers fails the worker with that reason.
OptionMeaning
opts.initialCapacitysizes the pool, 6 handles by default
opts.verboselogs [sqlite-worker] lines
  • Calls that queue while the worker waits for the lock run as one batch under one lock. A batch gives the lock up between calls once it has held it for 50 ms.
  • santoku.web.sqlite.open(db_path, opts) is the open the worker runs, and grow(n) adds n handles to the pool.
  • The pool directory is always .opfs-sahpool. Since santoku-web 11.0.0, open raises on opts.directory and on opts that isn't a table or nil.
  • grow(n) takes the lock itself and awaits. Call grow from the handler builder or from your own async function, because a handler already holds the lock.
  • Since santoku-web 11.0.0, a handler runs as a task and can block on sleep or await. It keeps the lock while it waits, and the calls behind it wait too.
  • santoku.web.sqlite.coop is the lock between tabs. acquire() and release() bracket a database touch, and wrap(fn) runs fn between them.
  • on_reacquire(fn) runs fn when another tab held the lock since this tab did.
  • With santoku-sqlite 6.5.0, a tab lists the pool directory only after another tab added handles.
  • A tab on santoku-sqlite before 6.5.0 that adds handles isn't seen by 6.5.0 tabs until they reopen the pool.
  • The handler's functions receive and return Lua values only, by santoku.web.rpc's rules: https://santoku.dev/santoku-web#santoku-web--santoku-web-rpc

santoku.web.sqlite.proxy

proxy(bundle_path, opts) spawns the dedicated worker from the same bundle, and returns a core table and a readiness promise. A call on core becomes an RPC to the table your worker returned.

local proxy = require("santoku.web.sqlite.proxy")
local js = require("santoku.web.js")
local async = require("santoku.web.async")

local bundle_js = js.document:querySelector('meta[name="bundle-js"]').content
local opts = { verbose = false }
local core, ready = proxy(bundle_js, opts)

js.document.body:addEventListener("db-error", function (_, ev)
  print("database failed:", ev.detail.error)
end)

opts.on_restart = function ()
  async.spawn(function ()
    local ok, rows = core.list()
  end)
end

async.spawn(function ()
  local ok, e = ready:await()
  if not ok then
    print("no database:", e)
    return
  end
  local listed, rows = core.list()
  if not listed then
    print("list failed:", rows)
  end
end)
Illustrative: runs outside the browser.
Details
  • core is a santoku.async.proxy over an rpc channel. Arguments go forward, and a core call returns true and the method's values, or nil and "status: detail".
  • A method that raises returns nil and "failed: " with its error.
  • err.checkok(core.list()) returns the values or raises the status. local ok, rows = core.list() branches on ok.
  • Await the promise before you use core. It resolves when the worker signals ready, and ready:await() then returns true.
  • When the worker fails, the proxy adds a db-error class to document.body. It also dispatches a db-error CustomEvent that carries detail.error.
  • Hook the db-error event to show a database failure in your own UI.
  • Since santoku-web 4.0.0, the promise also rejects with the error when the worker reports db_error or fails to start. ready:await() then returns false and the message.
  • The proxy stops the worker on pagehide.
  • A core call that hasn't returned then returns nil and "lost: the database worker stopped when the page was hidden". So does every later call until a restore.
  • A worker that reports db_error or fails before it's ready also fails every call with lost.
  • Since santoku-web 4.1.0, a page restore from the back-forward cache starts a new worker. The proxy calls opts.on_restart() once that worker is ready.
  • Set opts.on_restart to reload what the page shows. The proxy reads it at the restore, so you can set it after proxy returns.
  • opts.verbose logs [proxy] lines to the console.
  • opts.on_worker_connection runs each time a worker signals ready, including after a restore.

PWA build

santoku.web.pwa.csp

santoku.web.pwa.csp builds a strict content security policy at build time. script_hashes collects the sha256 hashes of inline scripts, policy assembles the CSP around them, and meta wraps it in a tag.

local csp = require("santoku.web.pwa.csp")
local html = '<html><head><script>window.__boot = 1</script></head></html>'
local hashes = csp.script_hashes(html)
print("hash:", hashes[1])
print(csp.policy(hashes) .. "; upgrade-insecure-requests")
print(csp.meta(hashes, { "https://static.cloudflareinsights.com" }))
Details
  • policy allows self plus wasm-unsafe-eval for the runtime.
  • policy(hashes, sources) and meta(hashes, sources) add each string in the optional sources list to script-src, for a third-party script such as an analytics beacon (santoku-web 13.1.0). Append any other directive to the policy string.
  • Sibling templates render index.html, manifest.json and the service worker with precache and no_cache lists, in the next cards.

santoku.web.pwa.index

index(opts) renders a complete HTML document. The keys in the code are the common template slots.

local index = require("santoku.web.pwa.index")

index({
  title = ..., description = ...,
  lang = "en", charset = "utf-8", viewport = ...,
  head = ..., body = ..., plain = ...,
  manifest = "/manifest.26e55a5b2d51.json",
  ios_icon = ...,
  favicon_svg = ..., favicon_ico = ...,
  theme_color = ...,
  sw = "/serviceworker.js",
  initial = ...,
  broadcast_channel = ...,
  update_redirect = ..., update_redirect_delay = ...,
  verbose = ...,
  transforms = { html = ..., js = ..., css = ... },
  csp = true,
})
Illustrative: runs outside the browser.
Details
  • index silently ignores unknown keys, so a typo shows up as a missing tag instead of an error.
  • charset defaults to utf-8 and lang to en.
  • Since santoku-web 6.0.0, the default viewport lets the user zoom.
  • transforms and csp are handled in Lua, outside the template.
  • transforms runs your minifiers over the output.
  • csp = true injects a Content Security Policy meta tag, built from the hashes of the inline scripts actually present. It raises if the document has no head to inject into.
  • Since santoku-web 11.0.0, csp is true or false, and index raises on a table.
  • Since santoku-web 11.0.0, index takes one name per tag and raises on each removed slot.
Removed slotWrite instead
faviconfavicon_ico
iconios_icon
body_attrs, body_contentbody, the whole body element
base_href, keywords, ms_iconthe tag in head
sw_targetnothing, the body hears the service worker
  • The page gets a service worker script only when sw is set, and that script registers the worker only when initial is set.

santoku.web.pwa.sw

sw(opts) is a build-time generator that returns the service worker's JavaScript as a string. Write it to a served file from a template such as client/static/serviceworker.tk.js.

<%
  local sw = require("santoku.web.pwa.sw")
  return sw({
    nonce = build_id,
    precache = { "/index.49e48e032508.css", "/bundle.606e713e9c93.js" },
    no_cache = { "^/sync$", "^/api/", "^/v\\d+/" },
    index_html = app_html,
  })
%>
Illustrative: runs outside the browser.
Details
  • sw isn't a runtime module, and a require of it in client code does nothing useful.
  • sw reads only the options in the code, and silently ignores anything else you pass.
  • nonce changes the cache name, which forces a refill.
  • precache paths are normalized to start with a slash.
  • no_cache entries are JavaScript RegExp source, passed to new RegExp as written. A digit class is \d ("\\d" in Lua source), never the Lua pattern %d.
  • index_html is the document the worker serves for a GET of the path /, ahead of the no_cache check.
  • Every other path comes from the cache, then from the network. Offline, a path the cache lacks gets an empty 503.
  • The install step skips a precache path that matches a no_cache entry.
  • Since santoku-web 3.2.0, the returned script is minified. The rock's own build runs sw.js through santoku.make.build's minify_js, and keeps the nonce, precache, no_cache and index_html slots.

santoku.web.pwa.manifest

manifest(opts) renders a web app manifest as JSON, which makes an app installable. Render it to a served file, and point the document at it with index's manifest option.

local manifest = require("santoku.web.pwa.manifest")

manifest({
  name = ..., description = ..., id = ...,
  start_url = "/", scope = "/",
  display = "standalone",
  theme_color = ..., background_color = ...,
  orientation = ..., categories = { ... },
  handle_links = ..., launch_handler = ...,
  icons = { { src = "/icon-192.b5caeccd7a29.png", sizes = "192x192",
              type = "image/png", purpose = "any" } },
  screenshots = { ... },
})
Illustrative: runs outside the browser.
Details
  • manifest needs cjson available at build time.
  • Nothing in santoku-make reads a pwa block in your descriptor. These values reach the manifest only because your own template passes them here.
  • Since santoku-web 3.2.0, the output is compact JSON, with no whitespace outside strings.
  • Defaults: start_url and scope "/", display "standalone", theme_color "#000000", background_color "#ffffff", handle_links "preferred" and launch_handler { client_mode = "navigate-existing" }. short_name is always a copy of name.

Examples

Projects that toku init creates with this rock. The examples page shows their files.

  • An offline web app: The web app with its data in sqlite in the browser, synced to the server, and a service worker so it boots offline. toku init --example pwa my-app
  • A web app: A WebAssembly client and an OpenResty server in one repository, with the data in sqlite on the server. toku init --example web my-app