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.

Getting started: a web app

scaffold a full-stack web app, a WebAssembly client plus an OpenResty server in one repository, with toku init --example web

A santoku web project is one repository with a client compiled to WebAssembly, a server under OpenResty, and the migrations both use. toku init --example web scaffolds a working todo app, called my-app here, and the pwa example moves its data into the browser.

Details
  • Everything here assumes toku is installed and its one-time toku setup has run. setup-toku.sh on https://santoku.dev/install does both, and toku doctor confirms it.
  • Get the rest of the toolchain one of two ways. Install it on your machine, or run toku from the container image that santoku-make ships, with your code mounted in.
  • The first cards cover both ways, and everything after them is the same either way.
  • Scaffold, build and start the project before you change anything.
  • As in the library and API scaffolds, the rock keeps the hyphen and module paths use an underscore. client/lib/my_app/core.lua is required as my_app.core.
  • The todo app has #tags, a tags page, a settings page and JSON export.
  • toku init --example web keeps the todos in the server's SQLite database, and the page calls the server for every read and write.
  • toku init --example pwa keeps them in a SQLite database in the browser that syncs to the server's. It adds a Sync button, a Sync settings tab, and a service worker so the app boots offline after a first visit.

Install the toolchain

A web project compiles Lua to WebAssembly and serves it from OpenResty, so its toolchain is larger than a library's. The toku setup lines run once, and the rest must be on PATH.

toku setup          mandatory, once; done by setup-toku.sh (the Install tab)
toku setup --resty  once; builds the managed OpenResty (or sh setup-toku.sh --resty)
toku setup --node   once; adds node 24.22.0 for the wasm client specs
                    (or sh setup-toku.sh --node; elsewhere it records a PATH node 24+)
wasm toolchain      nothing to install on x86_64 or arm64 Linux and macOS: the
                    first wasm build fetches wasi-sdk 34 and binaryen 133, both
                    sha256-pinned, into $XDG_DATA_HOME/toku/wasm
                    (~/.local/share/toku/wasm by default). Elsewhere, put clang 18
                    or newer with a wasm32 target, wasm-ld, llvm-ar and wasm-opt
                    on PATH; toku then fetches only the WASI sysroot
OPENRESTY_DIR       optional: set it only to use your own OpenResty instead of the
                    managed one. It names the install prefix, such as
                    /usr/local/openresty, and that install's openresty must be on PATH
clang or gcc        builds C rocks for the host during dependency install
curl                the build vendors pinned assets over the network
luarocks            invoked by toku; the managed toolchain ships its own
git                 toku init runs git init unless told not to
ps                  toku start and toku test need it; setup-toku.sh checks for it.
                    On Debian, install procps
Illustrative: runs outside the browser.
Details
  • The first line is the mandatory one-time step, and setup-toku.sh from https://santoku.dev/install already ran it.
  • The second line gives toku a managed OpenResty. From then on every toku command puts it on PATH and sets OPENRESTY_DIR for itself, so you install and export nothing.
  • toku doctor then reports "web builds use: the managed openresty".
  • The third line adds the managed node that the client specs run on.
  • A missing tool fails the build at the first one it can't find, and the error comes from that tool instead of from toku.
  • A first build is slow, because the client's C dependencies compile for wasm32 and the server's compile natively. Later builds are incremental.

Run toku in a container

setup-toku.sh --container builds the toku-web and toku-lib images that santoku-make ships, and installs the toku-web and toku-lib commands. toku-web runs toku in its image with the current directory mounted at the same path.

Shell
$ curl -fsSL https://santoku.dev/setup-toku.sh | sh -s -- --container
$ export PATH="$HOME/.local/share/toku/rocks/bin:$PATH"
$ toku-web test
$ toku-web -p 8080:8080 -- start --iterate
$ curl -fsSL https://santoku.dev/setup-toku.sh | sh -s -- --check --container
Shell, by hand
$ for f in toku-web.dockerfile toku-container.sh toku-web.sh; do
>   curl -fsSLO https://releases.santoku.dev/santoku-make/13.1.0-1/$f
> done
$ chmod +x toku-container.sh toku-web.sh
$ docker build -t toku-web -f toku-web.dockerfile .

$ ./toku-web.sh -- build
$ ./toku-web.sh -- test
$ ./toku-web.sh -p 8080:8080 -- start
$ ./toku-web.sh -p 8081:8081 -- test --iterate
Illustrative: runs outside the browser.
Details
  • --container needs only podman or docker: no compiler, BLAS or other host tools. It picks podman when podman is on PATH, else docker.
  • It fetches toku-container.sh, toku-lib.sh, toku-web.sh, toku-lib.dockerfile and toku-web.dockerfile for santoku-make 13.1.0-1 from https://releases.santoku.dev/santoku-make/13.1.0-1/ into $XDG_DATA_HOME/toku/container/13.1.0-1.
  • It builds both images, links toku-web and toku-lib into $XDG_DATA_HOME/toku/rocks/bin, the native install's bin directory, and prints the PATH line.
  • A rerun skips an image whose dev.santoku.make label names that santoku-make, and rebuilds one whose label doesn't. So a newer setup-toku.sh rebuilds the images. --rebuild rebuilds them anyway.
  • --check --container checks that both images carry that santoku-make and both commands link to its wrappers. It changes nothing.
  • The wrapper keeps toku's download and built-rock caches in a named volume per image and santoku-make version, toku-web-cache-<version> for toku-web, mounted at /opt/toku/cache. A second run reuses the rocks the first built.
  • toku-web passes its arguments to toku. With a --, the arguments before it go to podman or docker run and the ones after it go to toku.
  • Publish the server's port to reach it from the host, as in toku-web -p 8080:8080 -- start --iterate. The server must listen on all interfaces.
  • A project whose nginx conf listens on a BIND address takes -e BIND=0.0.0.0.
  • Containers on one network reach each other by name. Put --network NET --name NAME before the -- for each app and its database, after podman network create NET.
  • nginx resolves a name through its resolver directive and never reads /etc/hosts. A conf that connects by name needs resolver local=on, which reads the container's /etc/resolv.conf.
  • host.containers.internal reaches the host from tools that read /etc/hosts, such as curl. Under docker the wrapper adds that name with --add-host host.containers.internal:host-gateway.
  • Your code stays on your machine, and toku runs in the container. Only the tooling lives there, so the build tree lands in your working directory as it would locally.
  • toku init --here names the project after your directory.
  • To set up by hand, download toku-web.dockerfile, toku-container.sh and toku-web.sh for your santoku-make version from https://releases.santoku.dev/santoku-make/<version>/. Mark the scripts executable, build the image once, then use the wrapper anywhere you would type toku.
  • toku-web.sh is a one-line shim that execs toku-container.sh beside it, so both need chmod +x. Running sh toku-web.sh doesn't avoid it, since the exec still needs toku-container.sh to be executable.
  • Rootless podman nested in another container can give the inner container the outer /proc. There toku start and toku test stop with "ps can't see this process", because ps can't find toku's own pid. Drop volumes = ["/proc:/proc"] from the inner containers.conf, run the outer container with --security-opt unmask=/proc/*, and install catatonit in it for --init.
  • Podman keeps file ownership yours automatically. Docker doesn't, so pass -u if root-owned build output would bother you.
  • toku-web is the image for anything with a client directory. A library project wants the smaller toku-lib: https://santoku.dev/start-lib#start-lib--run-toku-in-a-container
  • The image provisions toku with setup-toku.sh --resty --node. Its SANTOKU_MAKE_VERSION, SANTOKU_CLI_VERSION, SETUP_TOKU_VERSION and SETUP_TOKU_SHA256 build args pin the versions.
  • Since santoku-make 10.2.0, toku release writes those pins into the published dockerfiles: the make version it releases, the newest santoku-cli on luarocks.org that accepts that make, and the setup-toku.sh that https://santoku.dev/setup-toku.sh serves, with its sha256. The copies in the santoku-make repo hold no pins and stop with "unreleased dockerfile".
  • The image build stops when any rock is installed twice, then runs toku --version and toku doctor.
  • So the image carries the same managed OpenResty, with brotli, and the same node as a native install. It also carries the WebAssembly toolchain, fetched at image build.
  • The image carries the label dev.santoku.make with its santoku-make version. The wrapper refuses an image whose label differs from its own version, and prints the build command that replaces it.
  • Each build tree records the santoku-make that last configured it in build/<env>/make.version. When host toku and the image differ in version on one project, toku warns: <dir> was last built by santoku-make <old>; this is <new>.
  • The image sets TOKU_FG=1, which keeps start in the foreground. Under --rm, toku is the container's main process. If start put OpenResty in the background and exited, the container would stop with the server. Nothing would report an error, and the published port would never answer.
  • In a container you build yourself, set TOKU_FG or pass --fg.
  • The wrapper runs the container with --init, so an init process reaps the server's exited workers and toku test can stop its test server. Pass --init to any container you run toku in by hand.
  • Since santoku-make 7.11.6, toku test also stops its test server in a container without --init. The stop treats an exited server that nothing reaped as stopped. Before, it waited 20 s and failed with server did not exit within 20s of SIGTERM.
  • toku test --iterate runs in the container as it does natively. -p for the test port lets a browser on the host follow it.
  • Before the double dash come the wrapper's own flags, then runtime flags.
  • -c docker or -c podman forces a runtime. Without it, the wrapper tries podman, then docker.
  • -g <flag> passes a global flag to the runtime, ahead of run, as TOKU_CONTAINER_GLOBAL does.
  • On a host where podman fails with an sd-bus error, build with podman --cgroup-manager=cgroupfs build. Run with ./toku-web.sh -g --cgroup-manager=cgroupfs --cgroups=disabled -- test.
  • -n prints the command it would run and exits.
  • -u "$(id -u):$(id -g)" passes through to docker and keeps the output yours.
  • -i <image> overrides the image name, as TOKU_IMAGE does.
  • -p publishes a port. toku start serves on 8080 and the test server on 8081.

The toku-web-deployment image

toku-web-deployment is the runtime base image for a built web tree: debian:bookworm-slim with ca-certificates and the managed OpenResty at /opt/toku/openresty, on PATH. Its default CMD runs ./run.sh --fg.

Shell
$ for f in toku-web-deployment.dockerfile toku-deploy-setup.sh; do
>   curl -fsSLO https://releases.santoku.dev/santoku-make/13.1.0-1/$f
> done
$ docker build -t toku-web-deployment -f toku-web-deployment.dockerfile .
make.prod.lua
local fs = require("santoku.fs")
local tbl = require("santoku.table")

return tbl.merge(
  { env = { minify = true, nginx = { domain = "example.com" } } },
  fs.runfile("make.common.lua"))
Dockerfile
FROM toku-web AS builder
WORKDIR /app
COPY . .
RUN toku build --env prod

FROM toku-web-deployment
USER 0
COPY --from=builder /app/build/prod /app/build/prod
RUN toku-deploy-setup /app/build/prod
USER 10001:0
WORKDIR /app/build/prod/dist
Shell
$ podman run -d -p 8080:8080 -v my-app-data:/app/build/prod/dist/data my-app
$ podman run -d -p 8080:8080 -v /srv/my-app:/app/build/prod/dist/data:U my-app
Dockerfile (with a native library)
FROM toku-web-deployment
USER 0
RUN apt-get update \
    && apt-get -y install --no-install-recommends libopenblas0-pthread liblapacke \
    && rm -rf /var/lib/apt/lists/*
USER 10001:0
Illustrative: runs outside the browser.
Details
  • toku-web is a build image, and serving the built tree needs none of its toolchain.
  • The OpenResty is the one that setup-toku --resty builds. WORKDIR is /app, and the default CMD is sh -c "umask 002; exec ./run.sh --fg".
  • The image installs no procps. run.sh needs ps only for --reload, so add procps to reload a server there.
  • It takes the same SETUP_TOKU_VERSION, SETUP_TOKU_SHA256 and SANTOKU_CLI_VERSION build args as toku-web. It purges the compilers once OpenResty is built, and keeps only /opt/toku/openresty.
  • The rendered nginx.conf names the paths of that OpenResty and its brotli module. So the runtime must carry the same build as the image that built the tree.
  • Download toku-web-deployment.dockerfile and toku-deploy-setup.sh from https://releases.santoku.dev/santoku-make/<version>/, the version that built your toku-web, and build in that directory. The dockerfile copies toku-deploy-setup.sh out of the build context.
  • toku build --env prod in the Dockerfile loads make.prod.lua in place of make.lua. Both web scaffolds ship make.prod.lua, which sets minify = true over make.common.lua.
  • make.lua sets minify = false for the local debug build.
  • make.prod.lua merges its overrides over make.common.lua. tbl.merge keeps every key the first table sets and fills the rest from make.common.lua.
  • A make.prod.lua that returns only the overrides stops the build with bad argument #1 to 'gsub', since the project has no name.
  • It carries a non-root system user worker (uid 10001, gid 0, no home, nologin) and ends with USER 10001:0. The nginx master, its workers and the privileged agent that runs the WAL checkpointer then share one uid.
  • A platform that assigns its own uid keeps gid 0, and the group bits below cover it.
  • As root, nginx would run its workers as nobody and the agent as root. The workers then couldn't open the database that the agent created.
  • apt still works, but the package lists are stripped. Run apt-get update before any apt-get install, and remove the lists afterwards.
  • A downstream image adds the built tree, one toku-deploy-setup call under USER 0, then USER 10001:0 and a WORKDIR at the dist directory.
  • toku-deploy-setup takes the build tree, and dist defaults to <build-tree>/dist. It deletes the .o, .a and .link install intermediates and applies the arbitrary-uid permission convention. It marks run.sh executable, points the access and error logs at stdout and stderr, and runs ldconfig.
  • toku-deploy-setup also creates <dist>/data with group 0 and mode 2770. Group 0 can write it, and the setgid bit keeps new files in group 0.
  • SQLite creates the database and its -wal and -shm files with mode 0644 whatever the umask. Only the uid that created them can write them, so keep one uid per volume across restarts.
  • The scaffold's DB_FILE defaults to data/<module>.db, so the database lands there.
  • The scaffold's nginx.mustache puts the temp paths of nginx under temp/, and nginx-fg.conf writes its pid to temp/server.pid. The rest of the dist dir stays read-only.
  • Mount the volume over the data directory. Under podman and docker, an empty named volume starts as a copy of the image's data dir, owner and mode included.
  • A bind mount needs a host directory with group 0 and group write. Podman's :U suffix also works, since it chowns the directory to the container's uid.
  • The Dockerfile with a native library adds one downstream, the BLAS and LAPACK that santoku-matrix links. It switches to USER 0, updates the package lists first, strips them again and switches back.
  • santoku-sqlite needs no system library, since it links its own SQLite.
  • Since santoku-make 7.10.0, run.sh counts the CPUs the container may use at each start, so podman run --cpus 2 starts 2 nginx workers. A WORKERS value set at build time pins the count instead: https://santoku.dev/santoku-make#santoku-make--worker-count-at-start

Build-time configuration

WORKERS, DOMAIN and any other variable the descriptor reads belong in the builder stage, because toku build reads them when it renders nginx.conf. The same variables in the runtime stage have no effect.

Dockerfile (builder stage)
FROM toku-web AS builder
WORKDIR /app
COPY . .
RUN WORKERS=4 toku build --env prod
Illustrative: runs outside the browser.
Details
  • The generated run.sh exports only the values baked in at render time, then execs openresty against a static config. Nothing re-renders when the container starts.
  • The worker count is the one value run.sh works out at start, from the container's CPUs, while make.common.lua leaves nginx.workers unset.
  • Since santoku-make 8.0.1, toku build with no server running runs no openresty. So the builder stage needs no file and no account that the config names.
  • make.prod.lua and the full Dockerfile are in the toku-web-deployment card: https://santoku.dev/start-web#start-web--the-toku-web-deployment-image

Scaffold a web project

toku init --example web scaffolds a todo app that builds and runs unmodified. It keeps the todos in the server's SQLite database, and the page reaches them through POST /api/<name>.

$ toku init --example web my-app
Initialized empty Git repository in /home/you/my-app/.git/
warning: copyright is not set, so this project is all rights reserved with no notice; set it in make.common.lua
warning: license is not set, so this project is all rights reserved; set it in make.common.lua
Created my-app from the web example: A web app

Next steps:
  cd my-app
  toku start             # Build and start the development server
  toku start --iterate   # The same, then rebuild and reload it on each edit
  toku test              # Run the specs beside it
  toku build --env prod  # Build the minified page to deploy

$ find my-app -type f -not -path "*/.git/*" | sort
my-app/.gitignore
my-app/client/bin/bundle.lua
my-app/client/lib/my_app/async.lua
my-app/client/lib/my_app/core.lua
my-app/client/lib/my_app/main.lua
my-app/client/lib/my_app/templates.tk.lua
my-app/client/lib/my_app/todos.lua
my-app/client/static/index.html
my-app/make.common.lua
my-app/make.lua
my-app/make.prod.lua
my-app/res/client/partials/settings.mustache
my-app/res/client/partials/todo_settings.mustache
my-app/res/client/partials/toolbar.mustache
my-app/res/client/todo-app.html
my-app/res/server/migrations/0.0.1.sql
my-app/res/server/nginx.mustache
my-app/res/server/nginx/pages.mustache
my-app/server/lib/my_app/migrations.tk.lua
my-app/server/lib/my_app/store.lua
my-app/server/lib/my_app/web/api.lua
my-app/server/lib/my_app/web/db.lua
my-app/server/lib/my_app/web/init.lua
my-app/server/lib/my_app/web/init_worker.lua
my-app/server/lib/my_app/web/status.lua
my-app/server/nginx.tk.conf
my-app/server/test/res/browser.lua
my-app/server/test/res/shadow.lua
my-app/server/test/spec/db_file.lua
my-app/server/test/spec/latest.browser.lua
my-app/server/test/spec/my_app.lua
my-app/server/test/spec/page.browser.lua
my-app/server/test/spec/status.lua
my-app/server/test/spec/store.lua
Illustrative: runs outside the browser.
Details
  • #tags in a todo's text become links that filter the list with ?tag=.
  • /tags lists every tag with its count, and /settings holds the list's settings.
  • toku init --example pwa, three cards down, keeps the todos in the browser instead: https://santoku.dev/start-web#start-web--scaffold-a-pwa-project
  • The next two cards say what each file does and how the server holds its database.
  • The listing is santoku-make 13.1.0-1's.
  • toku init runs git init unless you pass git = false through the API.
  • --here scaffolds into the current directory, which must be empty. --here takes the project name from the directory, so toku init rejects it beside a project name.

The web scaffold's files

store.lua holds the queries as a builder that returns { read = {...}, write = {...} }, and api.lua serves each method at POST /api/<name>. The listing says what every other file does.

client/bin/bundle.lua               the one page: requires main.lua
client/lib/my_app/main.lua          defines the todo-app component with santoku.web.app.define
client/lib/my_app/todos.lua         the todo-app component: its state, actions and start, and
                                    the routes /, /tags and /settings on a query-mode
                                    santoku.web.router that restores scroll
client/lib/my_app/async.lua         the app's one santoku.async module, over
                                    santoku.web.async
client/lib/my_app/core.lua          core.<name>(...) posts to /api/<name>; core.view keeps
                                    only the latest call
client/lib/my_app/templates.tk.lua  loader.templates over res/client
client/static/index.html            the document: a todo-app element and the page's CSS inline
res/client/todo-app.html            the page markup
res/client/partials/*.mustache      the settings panel, its todo controls and the toolbar
res/server/migrations/0.0.1.sql     the todos, settings and todos_tags tables
res/server/nginx.mustache           the nginx config: POST /api/<name>, the hashed assets,
                                    a 204 for /favicon.ico with no log line, and the
                                    page routes from nginx/pages.mustache
res/server/nginx/pages.mustache     index.html for /, /tags and /settings
server/lib/my_app/store.lua         reads view, list, settings, tags and export; writes
                                    add, toggle, remove, set, clear_done and retag
server/lib/my_app/migrations.tk.lua embeds res/server/migrations at build time
server/lib/my_app/web/init.lua      santoku.resty.sqlite's init, in the next card
server/lib/my_app/web/init_worker.lua
                                    santoku.resty.sqlite's init_worker
server/lib/my_app/web/db.lua        the store, served by santoku.resty.sqlite
server/lib/my_app/web/status.lua    a write's result to an HTTP status
server/lib/my_app/web/api.lua       POST /api/<name> calls store.<name>, 404 otherwise
server/nginx.tk.conf                renders res/server/nginx.mustache with the hashed
                                    index.html
server/test/res/browser.lua         launches Chromium for a browser spec and prints what the
                                    page reported when a test fails
server/test/res/shadow.lua          the Chromium specs' queries, click point and typing
                                    inside a component's shadow root
server/test/spec/store.lua          the store over open_memory()
server/test/spec/db_file.lua        the test server keeps its database in its own run
                                    directory, apart from the one toku start's server writes
server/test/spec/status.lua         every write status and the HTTP status it gets
server/test/spec/my_app.lua         the API over HTTP, including empty lists as [] and a
                                    failing write's 500
server/test/spec/page.browser.lua   adds, tags, filters and removes a todo in Chromium,
                                    checks that a setting changed while the page loads holds,
                                    that Back restores the list's scroll, and that a failed
                                    export shows its error on the page
server/test/spec/latest.browser.lua holds two view answers in Chromium and checks that the
                                    older one, answering last, doesn't replace the newer
Illustrative: runs outside the browser.
Details
  • store.lua is a function of an open database that prepares its statements and returns the read and write tables.
  • The server serves it through santoku.resty.sqlite. server/test/spec/store.lua flattens the same builder with db.store over open_memory(), so it tests the code the server runs.
  • Both run each write method in a transaction, so a write method holds no begin or commit of its own. A write returns true and its values. A write that raises rolls back and returns nil and "failed: " plus the error.
  • core.lua turns a call such as core.view(tag, all) into POST /api/view with the arguments as a JSON array. api.lua calls the store method of that name and answers with its results as a JSON array. Its writes table names the write methods, whose leading true it drops.
  • Since santoku-make 7.11.2, api.lua turns a JSON null argument into nil, so [null,false] reaches the store as view(nil, false).
  • Since santoku-make 7.11.3, api.lua encodes an empty list as []. On an empty database, view answers "todos":[] and "top":[], and an empty object stays {}.
  • api.lua marks the store's list fields (todos, top, all, tags) and the list results of list, tags, add, remove and set with cjson.array_mt. A new list-valued field needs its name added there.
  • A name the store lacks gets 404.
  • Since santoku-make 7.11.2, the page renders from one read, view(tag, all). It returns the settings, the todos for the tag, the top 10 tags, and every tag when all is true.
  • todos.lua calls view at start, on a page restored from the back-forward cache, and on each route change outside /settings.
  • Each write returns what the page draws next. add returns the row and the top tags, remove returns the top tags, set returns the list, and clear_done returns a fresh view.
  • Since santoku-make 9.2.0, async.lua is the app's one santoku.async module, built over santoku.web.async. Every other client module requires my_app.async: https://santoku.dev/santoku#santoku--santoku-async
  • core.view runs through async.latest. Since santoku-make 9.2.0, a newer view aborts the fetch in flight, and the older call never returns.
  • Since santoku-make 9.2.0, core.lua posts through santoku.web.http, the app's one client, and a write's POST makes one attempt.
  • Since santoku-make 7.12.0, todos.lua shows an unhandled error on the page. Its start listens for unhandledrejection and error with dom.listen("window", ...), and the template renders the message in a #error paragraph.
  • Since santoku-make 9.1.0, every todos.lua handler gets the handle c after s.
  • Since santoku-make 9.2.0, work that no action starts runs in a task and ends with c.commit(). A route change runs in santoku.web.async's task(fn), and the reload after a page restore runs in async.spawn(fn).
  • Since santoku-make 9.1.0, start registers each listener's stop function with c.on_stop, so the state table holds plain data only.
  • Since santoku-make 9.1.0, main.lua calls santoku.web.app.define once with the todo-app spec that todos.lua returns, and the spec names its template as template = tpl.todo_app.
  • index.html holds the todo-app element. The component renders into an open shadow root, and since santoku-make 10.0.0, app.page in its sheets brings the document's inline CSS into it.
  • todos.lua creates its own router, since define starts one only for components that set scope.
  • The router runs with scroll = true. Each route handler returns the promise of its task, which resolves after its render. So Back scrolls to the saved position once the list is drawn.
  • The component's start loads the list and calls routes.wait()() after that render, so a reload restores the scroll position too.
  • status.lua maps a write that returns nil and a status to the HTTP status in https://santoku.dev/start-web#start-web--the-server-s-database. api.lua then answers with { "status": ... }.
  • The page shows only #status until its first view comes back. That view then overwrites nothing typed while the page loads.
  • templates.tk.lua reads res/client with santoku.web.mustache.loader at build time and returns loader.templates("res/client", { readfile = readfile }). The client ships the compiled templates.
  • loader.templates compiles res/client/todo-app.html as the entry todo_app. It includes the partials by path key, such as {{> partials.toolbar.mustache}}.
  • The pwa example swaps in its own settings and toolbar partials.
  • page.browser.lua and latest.browser.lua drive Chromium through santoku-cdp, which make.common.lua lists in server.test.dependencies. TOKU_CHROMIUM names the browser command, and the toku-web image sets it.
  • Since santoku-make 7.11.3, toku test skips every *.browser.lua spec when TOKU_CHROMIUM is unset. It warns with the skipped specs and the fix, and the test line counts them, as in 4 specs ok, 2 skipped.
  • Under CI, or when a toku test PATH names the spec or its own directory, such as toku test server/test/spec, the browser specs run anyway. Without TOKU_CHROMIUM they then fail with "browser specs need TOKU_CHROMIUM set to a Chromium command; the toku-web image sets it".
  • Any non-empty CI value counts, which covers the CI=true that hosted pipelines set.
  • The page's elements sit in todo-app's open shadow root. A spec reaches the root with document.querySelector('todo-app').shadowRoot.
  • fs.runfile("test/res/shadow.lua")("todo-app") gives the Chromium specs a query, a click point and typing inside that component's root.
  • test/res/browser.lua launches Chromium, opens a page and watches its log. When a test fails, it prints the page reported: and the page's error:, exception:, netfail: and http lines, and the failed expression stays in the error.
  • Paths in the listing are relative to my-app.

The server's database since santoku-make 7.7.0

web/init.lua, web/init_worker.lua and web/db.lua run the server's SQLite database through santoku.resty.sqlite, with a connection in each nginx worker. The web, pwa and api examples all lay them down.

server/lib/my_app/web/init.lua
local env = require("santoku.env")
local migrate = require("santoku.migrate")
local sqlite = require("santoku.resty.sqlite")
local migrations = require("my_app.migrations")

sqlite.init({
  file = env.var("DB_FILE", "data/my_app.db"),
  writer = env.var("DB_WRITER", "local"),
  migrate = function (db)
    migrate(db, migrations)
  end,
  retry_dict = "sqlite_retry",
})

require("my_app.web.db")
server/lib/my_app/web/init_worker.lua
require("santoku.resty.sqlite").init_worker()
server/lib/my_app/web/db.lua
return require("santoku.resty.sqlite").store(require("my_app.store"))
Illustrative: runs outside the browser.
Details
  • The three scaffolds also share web/status.lua, and each supplies its own store.lua builder.
  • santoku.resty.sqlite comes from santoku-resty: https://santoku.dev/santoku-resty
  • init.lua calls init in the master with the database file, the write mode, the migrations and the retry dict. Then it requires web/db.lua, so the store is registered before nginx forks.
  • The master opens no database, so no SQLite handle crosses the fork.
  • init_worker.lua calls init_worker, which migrates each worker on a setup connection and opens the worker's connection. In nginx's privileged agent, init_worker runs the checkpointer that empties the WAL once writes stop.
  • web/db.lua returns the store, one flat module of the builder's read and write methods, which every handler requires.
  • DB_FILE names the database, data/my_app.db by default, relative to the dist dir. So toku start writes build/default/dist/data/my_app.db.
  • run.sh creates data beside logs and temp, and a deployed image mounts its volume there: https://santoku.dev/start-web#start-web--the-toku-web-deployment-image
  • The test server runs in build/default/test/run, so it writes build/default/test/run/data/my_app.db. Spec rows then stay out of the database you browse.
  • DB_WRITER picks the write mode. local, the default, runs every method on the worker's own connection. single sends every write to worker 0 over santoku.resty.ring.
  • single needs santoku-resty built against the nginx headers that setup-toku.sh installs. local needs none.
  • The retry dict is the sqlite_retry lua_shared_dict that nginx.mustache declares. A write that has waited 2 ms takes a ticket there, so the waiting writes of the workers take the lock in turn.
  • nginx.mustache names DB_FILE and DB_WRITER with env, since a worker sees no other variable.
  • A write method returns its results, or nil and a status. status.lua maps the status to an HTTP status, as the table shows.
Write statusHTTP status
"full"503
"timeout" or "lost"504
"failed: ..."500
"committed: ...", a write that landed with a result too large to return200
none, a nil with no status404
  • A read method raises instead, which nginx answers with 500.
  • santoku-make's own suite scaffolds an API project and checks these files, as the table shows.
CheckPass condition
a fresh start and a reload on an empty database, 12 timesno error in the log and one migration, each time
a 20000-write loopthe WAL returns to 0 bytes
a start with an unknown DB_WRITERthe start fails
20 writes queued behind a held lockall succeed, and in local mode the dict's head is at or past its tail
  • These scaffold files run on santoku-resty 2.10.0 and santoku-sqlite 6.2.0.

Scaffold a PWA project

toku init --example pwa scaffolds the same todo app with the todos in an OPFS-backed SQLite database in a dedicated worker. A service worker lets the app boot offline after a first visit.

$ toku init --example pwa my-app
$ find my-app -type f -not -path "*/.git/*" | sort
my-app/.gitignore
my-app/client/bin/bundle.lua
my-app/client/lib/my_app/async.lua
my-app/client/lib/my_app/core.lua
my-app/client/lib/my_app/db.lua
my-app/client/lib/my_app/main.lua
my-app/client/lib/my_app/migrations.tk.lua
my-app/client/lib/my_app/store.lua
my-app/client/lib/my_app/sync.lua
my-app/client/lib/my_app/sync_view.lua
my-app/client/lib/my_app/templates.tk.lua
my-app/client/lib/my_app/todos.lua
my-app/client/static/index.html
my-app/client/static/serviceworker.tk.js
my-app/client/test/spec/my_app.lua
my-app/client/test/spec/store.lua
my-app/make.common.lua
my-app/make.lua
my-app/make.prod.lua
my-app/res/client/migrations/0.0.1.sql
my-app/res/client/partials/settings.mustache
my-app/res/client/partials/todo_settings.mustache
my-app/res/client/partials/toolbar.mustache
my-app/res/client/todo-app.html
my-app/res/server/migrations/0.0.1.sql
my-app/res/server/nginx.mustache
my-app/res/server/nginx/pages.mustache
my-app/server/lib/my_app/migrations.tk.lua
my-app/server/lib/my_app/store.lua
my-app/server/lib/my_app/web/api.lua
my-app/server/lib/my_app/web/db.lua
my-app/server/lib/my_app/web/init.lua
my-app/server/lib/my_app/web/init_worker.lua
my-app/server/lib/my_app/web/status.lua
my-app/server/nginx.tk.conf
my-app/server/test/res/browser.lua
my-app/server/test/res/shadow.lua
my-app/server/test/spec/db_file.lua
my-app/server/test/spec/my_app.lua
my-app/server/test/spec/offline.browser.lua
my-app/server/test/spec/page.browser.lua
my-app/server/test/spec/status.lua
my-app/server/test/spec/sync_page.browser.lua
Illustrative: runs outside the browser.
Details
  • The page talks to the worker through santoku.web.sqlite.proxy.
  • Since santoku-make 7.11.2, both sides sync the todos table with santoku.sqlite.sync. POST /api/sync carries the client's changes, and the server answers with the changes the client hasn't seen.
  • The page adds a Sync button, and /settings gets a Todos tab and a Sync tab with automatic sync on a timer.
  • Since santoku-make 7.11.2, automatic sync also runs at startup when a sync is due, 1.5 s after a write, and when the network comes back or the tab becomes visible.
  • --example needs santoku-cli 8.0.0 and santoku-make 13.0.0.
  • The next card says what each file does.

The pwa scaffold's files

In the pwa example the store and its migrations move to the client: a worker serves the store.lua builder, extended by sync.lua. The listing says what every file does.

client/bin/bundle.lua               the one page: main.lua in a window, db.lua in the worker
client/lib/my_app/main.lua          defines todo-app from todos.lua with sync_view.lua's
                                    additions
client/lib/my_app/core.lua          the proxy to the worker, the service worker registration
                                    and update, and sync, which posts the outbox to
                                    /api/sync until nothing is left
client/lib/my_app/db.lua            the worker: opens /my_app.db on OPFS, migrates it and
                                    serves db.store(sync(db, store(db)), { raise = true })
client/lib/my_app/store.lua         the same builder the web server serves
client/lib/my_app/sync.lua          santoku.sqlite.sync on todos; adds outbox, inbox,
                                    sync_due and sync_settings to the builder
client/lib/my_app/sync_view.lua     the page's Sync button and tab, the timer, and the
                                    syncs at startup, after a write, online and on show
client/static/serviceworker.tk.js   the service worker, rendered at build time
client/test/spec/my_app.lua         the store plus sync over open_memory(), against a
                                    server engine in the same process
res/client/partials/settings.mustache
                                    the Todos and Sync tabs
res/server/migrations/0.0.1.sql     the server's todos table
res/server/nginx/pages.mustache     the web routes plus /settings/todos, /settings/sync
                                    and /serviceworker.js
server/lib/my_app/store.lua         santoku.sqlite.sync on todos; the sync write applies
                                    the push and answers the request
server/lib/my_app/web/api.lua       POST /api/sync, and 404 for any other /api/<name>
server/test/spec/my_app.lua         the sync endpoint over HTTP, including a client's own
                                    rows staying out of its answers and changes as []
server/test/spec/offline.browser.lua
                                    loads the app once, then boots /, /settings/sync, /tags
                                    and /?tag=x with the network and the HTTP cache off, in
                                    Chromium
server/test/spec/sync_page.browser.lua
                                    opens the Sync tab and syncs in Chromium, with the zone
                                    set to Asia/Kolkata, and checks the time it shows
Illustrative: runs outside the browser.
Details
  • The worker flattens the builder with db.store and raise = true. The client specs flatten it the same way over open_memory(), so they test the code the worker runs.
  • migrations.tk.lua is one template on both sides. It embeds res/client/migrations in the client build and res/server/migrations in the server build.
  • A write that fails raises in the worker, so the proxy returns nil and "failed: ...". core.lua wraps every call in err.checkok, which returns the values or raises that error on the page.
  • The santoku.web.sqlite.proxy card on https://santoku.dev/santoku-web covers how arguments and results cross to the worker.
  • main.lua hands the sync_view.lua table to todos.lua. That table adds the Sync action, the auto-sync timer, the settings tab and the sync settings to the page.
  • Since santoku-make 7.11.2, client sync.lua and server store.lua each call santoku.sqlite.sync's create on the todos table, with body and done as the synced columns: https://santoku.dev/santoku-sqlite/sync
  • The module's triggers stamp every insert, update and delete with a hybrid logical clock (hlc). remove and clear_done delete rows, and each delete syncs as a tombstone.
  • outbox returns the client's request and push(server) as JSON. core.lua posts it to /api/sync.
  • The server's sync write applies the push, then answers respond(request, push). The answer leaves out the rows that push won, so a client never gets its own rows back.
  • A pushed row that lost comes back in the same answer, as the server's winner.
  • inbox acks the push and applies the answer. core.lua repeats the exchange while the answer has more or the client holds changes it hasn't pushed.
  • The first exchange with a server only pulls, because the client learns the server's replica id from that answer.
  • The newer hlc wins a conflict, and a delete wins a tie. Applying a change moves the client's clock past it, so an edit made after a sync beats what the sync brought, whatever the device's clock says.
  • An edit made while a sync is in flight goes out on the next exchange.
  • The todos table's after_apply rebuilds the tags of each row a sync changes or deletes.
  • sync_due is true when the client holds unpushed changes, or its last sync is older than the interval setting.
  • The Sync tab shows the time of the last sync from the client's own clock.
  • Since santoku-make 7.11.3, that time reads in the browser's zone. sync.lua formats it with santoku.utc.format(t, "%Y-%m-%d %H:%M:%S", true), whose local time comes from JavaScript's Date in the wasm build.
  • SQLite's localtime modifier doesn't work there, since the browser build of santoku-sqlite omits it. Node's WASI build, which runs the client specs, keeps UTC, so sync_page.browser.lua checks the zone in Chromium.
  • Since santoku-make 7.11.3, the server's sync answer encodes changes and fetched as JSON arrays, [] when empty.
  • The PWA scaffold needs santoku-sqlite 6.6.0, which santoku-web 9.0.0's sqlite worker requires.
  • serviceworker.tk.js renders /serviceworker.js with santoku.web.pwa.sw. It precaches the app's routes and the hashed bundle.js and bundle.wasm.
  • The service worker names its cache from the hashed index.html, bundle.js and bundle.wasm. A changed build then installs a new worker and drops the old cache.
  • client.stable keeps a copy at the plain /serviceworker.js, which nginx/pages.mustache serves with no-cache and core.lua registers.
  • When a new worker installs under a page that an older worker controls, core.lua posts it skip_waiting. core.lua reloads the page when the new worker takes control, so an open tab runs the new build.
  • A first install reloads nothing.
  • core.lua passes proxy an opts table and sets its on_restart. A page restored from the back-forward cache then reloads once the new worker is ready.

Add a rock dependency

make.common.lua keeps a dependency list per side: client.dependencies, server.dependencies and server.test.dependencies. Add a rock to every side that requires it.

client = {
  dependencies = {
    "lua == 5.1",
    "santoku >= 6.0.0, < 7.0.0",
    "santoku-web >= 13.0.0, < 14.0.0",
    "santoku-markdown >= 2.2.5, < 3.0.0",
  },
},
server = {
  dependencies = { ... },
  test = {
    dependencies = {
      "santoku-cdp >= 0.4.8, < 0.5.0",
    },
  },
},
Illustrative: runs outside the browser.
Details
  • client.dependencies is for the WebAssembly client, server.dependencies for the OpenResty server, and server.test.dependencies for rocks that only the server specs use.
  • The server.test.dependencies rocks install under build/<env>/test/server, where nginx can't load them. A rock that a handler requires goes in server.dependencies.
  • Each side installs into its own tree, and neither side sees the rocks in toku's own tree.
  • Find the current version of a rock with toku luarocks search, such as toku luarocks search santoku-markdown, and pin it to that major version.
  • The server and its specs need no entry for cjson. Server specs run under OpenResty's LuaJIT with OpenResty's lualib on the path, which carries cjson, so the scaffold's page.browser.lua requires it as is.
  • Since santoku-make 7.10.0, each tree's luarocks config lists toku's cache first, then the servers the luarocks config names. A private server in the system luarocks config then serves its rocks to every tree.

Add Tailwind CSS since santoku-make 7.10.0

Set client.tailwind in make.common.lua to build a Tailwind stylesheet from the templates. toku fetches the tailwindcss binary, builds and minifies the stylesheet, and ships it as a hashed /index.css.

make.common.lua (env.client)
tailwind = { input = "res/client/index.css", sources = { "res/client" } },
res/client/index.css
@import "tailwindcss";
client/static/index.html (head)
<link rel="stylesheet" href="/index.49e48e032508.css">
res/client/todo-app.html (excerpt)
<h1 class="text-2xl font-bold"><a href="/">my-app</a></h1>
Illustrative: runs outside the browser.
Details
  • The scaffold's CSS is inline in index.html, and no scaffold sets client.tailwind.
  • Write res/client/index.css, set client.tailwind, and link /index.css from client/static/index.html.
  • With sources = { "res/client" }, tailwind scans the component template and the partials for class names, and an edit to any of them rebuilds the stylesheet.
  • todo-app's sheets start with app.page, so the linked stylesheet reaches its shadow root.
  • A pwa project also adds hashed("index.css") to the precache list in client/static/serviceworker.tk.js, or the app boots offline without its styles.
  • tailwindcss ships for x86_64 and arm64 Linux with glibc and for macOS. Elsewhere, Android included, the build stops and names the platform.
  • The keys, the fetch and the errors: https://santoku.dev/santoku-make#santoku-make--tailwind-css-with-client-tailwind

The dev loop

toku start --iterate is the day-to-day loop for a web project. It serves, then after each rebuild reloads the dev server and reruns the specs, all of them or only the spec file you edited.

Shell, the loop to leave running
$ toku start --iterate
Shell, the spec-only loop
$ toku test --iterate --show-logs
Shell, the commands the loop composes
$ toku build
$ toku start
  serving   http://127.0.0.1:8080/
  build     up to date              0.1s
  start     server                  0.3s
  log       build/default/toku.log
$ toku test
$ toku test server
$ toku test server/test/spec/page.browser.lua
$ toku stop
$ toku start --fg
Illustrative: runs outside the browser.
Details
  • Leave the loop running in one pane and edit in another.
  • Since santoku-make 10.2.1, the spec server runs beside the dev server. Ctrl-C stops the loop, the server and the spec server.
  • toku test --iterate --show-logs is the spec-only loop. It builds, starts a test server, runs the suites and prints the server's log lines, then repeats when a file the build reads changes.
  • --show-logs prints the access and error log lines the test server wrote during each run, after the server specs. Between runs the loop waits for changes and prints a line that says it's waiting.
  • An edit to a file the build reads rebuilds what depends on it, restarts the test server and reruns the suites. An edit to one spec reruns that spec alone.
  • A cycle prints the plain specs' lines, then runs the .browser.lua specs on a test browser line. It prints no stop line, since the next cycle restarts the test server.
  • A loop with no terminal runs under setsid toku test --iterate --show-logs, and kill -INT -- -PGID ends it.
  • An edit to a file nothing reads prints iterate nothing reads <file>, so nothing reruns. No suite runs.
  • A change to make.lua or make.common.lua, or a file created or deleted under a watched directory, reloads the project before the next run. A new page, spec or migration joins the build without a restart.
  • A failing run keeps the test server up for the next one.
  • nginx serves pages with Cache-Control no-cache, so a browser reload after a run gets the new bundle.
  • Since santoku-make 10.2.1, both --iterate loops poll the watched files by stat every 0.5 s. They see edits on any mount, including a macOS bind mount under podman machine.
  • Since santoku-make 10.2.0, both --iterate loops also watch each local_deps entry's lib, bin, deps and res directories and its make.lua and make.common.lua. An edit there reinstalls that local dep.
  • Since santoku-make 10.2.0, the loop reruns the descriptor after each change. When its values differ, the project reloads, so nginx.conf and every file built from descriptor data is rebuilt before the server reloads.
  • Since santoku-make 10.2.0, toku start renders nginx.conf and nginx-fg.conf with dev additions, and toku build renders them without. The dist keeps whichever ran last, so build the tree you deploy with toku build.
  • The dev additions are a second error log, logs/toku-errors.log, at level error, a Cache-Control: no-cache header on every response, and a 500 page that shows the error nginx logged for that request, with its file, line and traceback.
  • Since santoku-make 10.2.1, a location with its own header_filter_by_lua_block or body_filter_by_lua_block also gets the dev 500 page. toku start runs its dev filter code first inside that block.
  • A header_filter_by_lua_file, header_filter_by_lua, body_filter_by_lua_file or body_filter_by_lua directive stops toku start with an error that says to use the _block form.
  • A location with its own more_set_headers gets no Cache-Control: no-cache header.
  • The test server's nginx.conf in build/<env>/test/run always carries the dev additions except the no-cache header, so specs see the app's own Cache-Control.
  • toku start --iterate prints each new entry of logs/toku-errors.log on a server line: the level, the message, the traceback and the request. A lua_modules path in the message names the server/lib, lib or local_deps file it was installed from.
  • Since santoku-cli 6.0.4, toku start --iterate --show-logs also prints each new logs/access.log line on an access line and each new logs/error.log line on a server line.
  • --show-logs leaves out error.log's [error], [crit], [alert] and [emerg] entries, since the toku-errors.log entry already prints each of them once.
  • toku start --show-logs without --iterate is a usage error.
  • Under toku start, each page bundle starts with a dev reporter, and toku build leaves it out. A browser-side Lua error with a traceback, an uncaught exception or an unhandled rejection shows on the page and goes to /__toku/client-error. The dev nginx.conf logs that request, so the terminal prints "client error on <page>" with the client/lib file and line.
  • Since santoku-make 10.2.0, each --iterate loop records its pid in build/<env>/toku.pid. A toku build, test, start or second loop in that build tree stops at once with "<command> (pid N) already loops in <dir>". Stop the loop, or run the command in another checkout.
  • Run the commands the loop composes against the fresh scaffold before you change anything.
  • Don't pipe toku start. It puts OpenResty in the background, and the pipe never closes.
  • toku stop stops the server, and the test server when a run left it up.
  • toku test runs its own test server. It restarts the test server and stops it again when the suites finish.
  • Since santoku-make 7.7.0, a server you started for a browser keeps running through a test run. The test server listens on its own ports.
  • Since santoku-make 7.9.0, a run prints one line per phase, as in the code: deps, build, start, test, check and stop, each with a count and a time.
  • Since santoku-make 9.0.0, a run first prints a select line with the count of specs that run and the specs it skips. The .browser.lua specs run after every plain spec, on a test browser line.
  • The full output, with the [make], Test: and luacheck lines, goes to build/default/toku.log. -v streams it to the terminal as well.
  • A failure marks its phase failed, names each failing spec with its error, prints the last 40 lines of that phase and exits nonzero.
  • Client specs compile to WebAssembly and run under the managed node. They can require any module under client/lib.
  • toku start serves on 8080 and the test server on 8081. toku start takes no port flag.
  • Since santoku-make 7.9.0, toku start prints serving http://127.0.0.1:8080/ as soon as the server is up.
  • toku start --fg and the toku-web image print that line too, before OpenResty takes over the terminal.
  • nginx listens on IPv4 only, so use 127.0.0.1 where localhost resolves to ::1 first.
  • toku build renders the client wasm and the server tree. Since santoku-make 7.7.0 it runs no specs and no luacheck, and only toku test does.
  • client.test settings reach only the client spec tree.
  • toku start builds, then runs OpenResty against the dist.
  • toku test runs the client and server suites. toku test test, toku test client or toku test server runs one suite, and a spec's own path runs that spec.
  • The web example ships no client specs, so toku test client stops there with "client (command line) selects no spec". The pwa example ships client/test/spec/my_app.lua.
  • toku start --fg runs in the foreground with the error log on stderr.

The sqlite worker's handlers since santoku-make 7.7.0

santoku.web.pwa.wrap_events defines Module.start and Module.on_message, the handlers that the client's sqlite worker uses to talk to the main thread. The build puts it in the page glue.

pre_js = { "res/pre.js" },
Illustrative: runs outside the browser.
Details
  • wrap_events must run inside the page glue before the wasm module starts.
  • A page whose client tree holds santoku-web gets wrap_events in its glue, ahead of the client.pre_js files.
  • A project scaffolded before santoku-make 7.7.0 has client/res/pre.tk.js, a one-line template that holds the wrap_events JavaScript. It also has the client.pre_js line below in make.lua.
  • Delete both, because a client.pre_js file that sets Module.start stops the build with an error that names the file.
  • The client's Lua reaches the browser as one merged chunk linked into bundle.wasm.
  • minify.chunk picks whether that chunk ships as source or as bytecode. The default, "smallest", builds both and ships the smaller, as https://santoku.dev/santoku-make covers.

Going to production

The service worker

santoku.web.pwa.sw is a build-time generator that returns the service worker's JavaScript as a string. Put it in client/static as a .tk.js template, as toku init --example pwa does.

<%
  local sw = require("santoku.web.pwa.sw")
  return sw({
    nonce = hashed("index.568b57e86a93.html") .. "-" .. hashed("bundle.606e713e9c93.js") .. "-" .. hashed("bundle.f4c2e4986607.wasm"),
    precache = {
      "/", "/tags", "/settings", "/settings/todos", "/settings/sync",
      hashed("bundle.606e713e9c93.js"), hashed("bundle.f4c2e4986607.wasm"),
    },
    no_cache = { "^/api/" },
  })
%>
Illustrative: runs outside the browser.
Details
  • toku init --example pwa ships the template below as client/static/serviceworker.tk.js, and a web project can copy it.
  • In client/static, the rendered output is a served file.
  • sw isn't a runtime module. Under client/lib it becomes a Lua module that nobody fetches, and the app builds cleanly and never goes offline.
  • precache lists everything the app needs to boot with no network: its routes, and hashed("bundle.js") and hashed("bundle.wasm"), which the build resolves to the hashed names.
  • The scaffold's CSS is inline, so there's no /index.css to list.
  • A precache entry that 404s makes install throw, and the worker never activates.
  • The scaffold's offline.browser.lua turns the network and the HTTP cache off, so it fails when a route or asset the app boots from is missing from precache.
  • The nonce names the cache, so build it from the same hashed names. A new build then installs a new worker and drops the old cache, and an unchanged build leaves every client's cache alone.
  • no_cache lists paths never served from cache.
  • The worker needs a stable url, so make.common.lua lists it in client.stable, which keeps a copy at the plain /serviceworker.js.
  • res/server/nginx/pages.mustache serves that copy with location = /serviceworker.js and Cache-Control no-cache. core.lua registers it with js.navigator.serviceWorker:register("/serviceworker.js").

The document and manifest

santoku.web.pwa.index renders the document that the service worker serves for the path /. Build the two together: hand the HTML to sw as index_html, and point the document at the worker with sw.

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

local app_html = index({
  title = "my-app",
  description = "...",
  theme_color = "#1e293b",
  manifest = "/manifest.26e55a5b2d51.json",
  sw = "/serviceworker.js",
  initial = true,
  head = [=[<meta name="bundle-js" content="/bundle.606e713e9c93.js">
            <script src="/bundle.606e713e9c93.js"></script>]=],
})
Illustrative: runs outside the browser.
Details
  • Both renders need the same app_html, so build it once where both can reach it. Put the index(...) call in a helper under res/, and load it from the serviceworker template with fs.runfile(depend(fs.join(root_dir, "res/app_html.lua"))).
  • The depend call makes an edit to the helper rebuild serviceworker.js.
  • initial = true is required, since only that branch emits the script that registers the worker.
  • With csp = true, the policy comes from the hashes of the inline scripts present in the output, so it must run after any transforms.
  • manifest points at a rendered manifest.json.
  • Tie any file you add to the public directory here to client_env.static_files_ok, so hashing doesn't race it.
  • Point sw at a stable url, never at the hashed worker file. pwa.index hashes the inline registration script for the CSP.
  • If that url is itself a hashed asset, the asset-hash pass rewrites it afterwards. The declared hash then no longer matches, and the browser silently blocks the page's own scripts.
  • Serve the worker from a fixed location in res/server/nginx.mustache, such as location = /sw.js { try_files /{{{sw}}} =404; }. Put sw = hashed("serviceworker.js") in the context that server/nginx.tk.conf builds.
  • A service worker needs a stable url anyway, because its scope and update checks are keyed off it.