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-bundle

View on LuaRocks

bundles a Lua entry script and its dependencies into one C program, compiled native or to WebAssembly

santoku-bundle turns a Lua entry script and everything it requires into one generated C program, then compiles it. cc builds native executables, and clang with --target=wasm32-wasip1 builds WebAssembly. The library exports exactly one function, bundle(infile, outdir, opts).

Details
  • santoku-make links the WebAssembly output into a page or a node test. The wasm that runs this page is bundle output.
  • bundle is the last stage of the toku build flow. santoku-make calls it to ship native binaries, bundled test suites and web clients.
  • bundle finds dependencies by scanning the source text for string-literal require calls.
  • So dynamic requires need opts.mods, and unresolvable names need opts.ignores.
  • The cards cover the merge, the scanner and what it can't see, module resolution, C modules, bytecode and embedding, and the build-integration options.
  • The last cards show the calls that produce native toku binaries and this site.
  • Bundling needs the real filesystem and a C toolchain, so most examples are shown for reading.
  • A few in-page demos exercise the plain-Lua mechanisms that bundle builds on.

How bundle works

One call, three artifacts

bundle(infile, outdir, opts) scans, merges, generates C and compiles. The output prefix defaults to the entry basename with extensions stripped.

local bundle = require("santoku.bundle")
local sys = require("santoku.system")
local str = require("santoku.string")
local fs = require("santoku.fs")
local incdir = sys.sh({ "luarocks", "config", "variables.LUA_INCDIR" })()
local libdir = sys.sh({ "luarocks", "config", "variables.LUA_LIBDIR" })()
local libfile = sys.sh({ "luarocks", "config", "variables.LUA_LIBDIR_FILE" })()
local libname = str.stripprefix(fs.stripextension(libfile), "lib")
bundle("test/res/bundle/test.lua", "test/res/bundle/test", {
  flags = { "-I", incdir, "-L", libdir, "-l", libname, "-l", "m" }
})
print("compile command echoed by bundle, then three artifacts:")
print("test.lua", fs.exists("test/res/bundle/test/test.lua"))
print("test.c", fs.exists("test/res/bundle/test/test.c"))
print("test", fs.exists("test/res/bundle/test/test"))
return "merged lua, generated c, linked executable"
Illustrative: runs outside the browser.
Details
  • bundle prints the full compile command before it runs.
  • This is the anchor test from the repo. It links against the host Lua that luarocks config finds.

The package.preload layout

The merged Lua file has a fixed layout. It holds one package.preload assignment per discovered module, a require line for each opts.mods entry, then the entry source appended raw.

package.preload["demo.words"] = function ()
  return { pick = function () return "bundled" end }
end
package.preload["demo.app"] = function ()
  local words = require("demo.words")
  return "hello from a " .. words.pick() .. " module"
end
print(require("demo.app"))
print("bundle writes exactly this layout into <outdir>/<prefix>.lua:")
print("preload entries first, opts.mods requires next, entry source last")
return require("demo.app")
Illustrative: runs outside the browser.
Details
  • preload is stock Lua 5.1. Nothing here touches the filesystem, since it's all table assignment.

The require scanner in miniature

The real scanner is an lpeg grammar over raw source text. It matches the require keyword, optional parentheses and a string literal, and skips comments and string bodies.

local arr = require("santoku.array")
local src = arr.concat({
  "local arr = require(\"santoku.array\")",
  "local str = require \"santoku.string\"",
  "local required_elsewhere = 1",
  "-- require(\"santoku.commented\")",
  "local doc = \"call require(\\\"santoku.quoted\\\") yourself\"",
  "local dyn = require(\"santoku.\" .. \"joined\")",
}, "\n")
local naive = {}
for mod in src:gmatch("require%s*%(?%s*[\"']([%w%.]+)[\"']") do
  naive[#naive + 1] = mod
end
print("naive pattern finds: " .. arr.concat(naive, ", "))
print("the real grammar finds only: santoku.array, santoku.string")
print("it skips the comment and the string body, and required_elsewhere")
print("never matches because the keyword must end at a non-identifier")
print("the concatenation never reaches one literal, so it is invisible to both")
return naive
Details
  • The grammar guards the keyword against identifier characters.
  • The naive pattern below shows the literal-only idea. Its false positives show why the grammar skips comments and strings.

Finding modules

Blind spots and opts.mods

The scan is textual. It still bundles a require in dead code, and it can't see a require built from variables or concatenation. opts.mods forces modules in.

local bundle = require("santoku.bundle")
local fs = require("santoku.fs")
local arr = require("santoku.array")
fs.mkdirp("bin")
fs.writefile("bin/main.lua", arr.concat({
  "local name = \"myapp.backend.\" .. require(\"santoku.env\").var(\"BACKEND\", \"memory\")",
  "local backend = require(name)",
  "if false then require(\"myapp.debugview\") end",
  "backend.start()",
}, "\n"))
bundle("bin/main.lua", "build", {
  mods = { "myapp.backend.memory", "myapp.backend.sqlite" },
})
print("require(name) has no string literal, so the scan cannot see it")
print("require(\"myapp.debugview\") sits in dead code but is bundled anyway")
print("both backends ride in via mods and name resolves at runtime")
return fs.exists("build/main")
Illustrative: runs outside the browser.
Details
  • A require inside a function that never runs is bundled too. So a lazy require saves load time but no bundle size.
  • bundle resolves and preloads each opts.mods entry, and requires it ahead of the entry.
  • In make.lua descriptors, opts.mods surfaces as client.bundle_mods.
  • This docs site uses client.bundle_mods to make a fixed module list available to the snippets you can run in the page.

Unresolvable names and ignores

Any scanned name that resolves through neither path nor cpath is an error. opts.ignores exempts a name, which bundle then neither bundles nor recurses into.

local bundle = require("santoku.bundle")
local fs = require("santoku.fs")
local arr = require("santoku.array")
fs.mkdirp("bin")
fs.writefile("bin/tool.lua", arr.concat({
  "local dbg = require(\"debug\")",
  "print(dbg.traceback())",
}, "\n"))
bundle("bin/tool.lua", "build", {
  ignores = { "debug" },
})
print("debug is provided by luaL_openlibs in the generated C, so the")
print("require succeeds at runtime without a file ever being bundled")
return fs.exists("build/tool")
Illustrative: runs outside the browser.
Details
  • The classic case is debug, a Lua built-in with no file on LUA_PATH.
  • Every toku bundling flow passes ignores = { "debug" } by default.

Module resolution

Each scanned name goes through env.searchpath twice. opts.path, LUA_PATH by default, classifies it as a Lua module, then opts.cpath, LUA_CPATH by default, as a C module.

local bundle = require("santoku.bundle")
bundle("bin/main.lua", "build", {
  path = "build/lua_modules/share/lua/5.1/?.lua;build/lua_modules/share/lua/5.1/?/init.lua",
  cpath = "build/lua_modules/lib/lua/5.1/?.so",
})
print("santoku.fs found via path: read, merged, scanned recursively")
print("santoku.fs.posix found via cpath: linked, never scanned")
print("toku builds pass the project's own lua_modules tree here, so a")
print("bundle is hermetic: only what the build tree installed can ride in")
return "every module classified as lua or c"
Illustrative: runs outside the browser.
Details
  • bundle reads Lua modules and scans them recursively. It doesn't scan C modules.
  • A name that resolves nowhere raises the searchpath error.

C modules as linked symbols

A C module can't merge as source. Instead, bundle derives its luaopen symbol, declares it in the generated C, and registers it in package.preload before the entry runs.

local str = require("santoku.string")
local mods = { "santoku.fs.posix", "santoku.string.base", "santoku.web.val" }
for i = 1, #mods do
  local sym = "luaopen_" .. str.gsub(mods[i], "%.", "_")
  print(mods[i] .. "  ->  " .. sym)
end
print("generated C declares each: int luaopen_santoku_fs_posix(lua_State *L);")
print("then registers it in package.preload before the bytecode runs")
return "luaopen_" .. str.gsub(mods[1], "%.", "_")
Details
  • The symbol is luaopen_ plus the module name with dots swapped for underscores.
  • bundle also adds the objects of the module to the compile command.
  • Linking is static by default. When a .link file sits next to the resolved module, foo.link beside foo.so, bundle passes each of its lines instead.
  • bundle resolves relative paths in a .link file against its directory, and passes flags and absolute paths as written.
  • In santoku-bundle 3.2.2 and later, a module with no .link file links as it is, and the message names the target.
  • Then a native build links the shared object dynamically and prints "warning: no .link file, linking the shared object dynamically, so it must be present at runtime: <paths>".
  • A wasm build links the module object statically and prints a [bundle] line: "no .link file, linking the wasm module object statically with no extra inputs: <paths>".
  • opts.static = false links every shared object with no warning.
  • opts.link_c = false leaves the C inputs out of the command and only returns them.
  • With opts.wasm, or a cc or flag that names wasm32, a native ELF input raises "cannot link a native ELF object into a wasm bundle".
  • When a .requires file sits next to a C module, bundle adds each module it lists. So the C-level dependencies of a C module come along with no list by hand.

Bytecode and embedding

Bytecode with opts.luac

opts.luac precompiles the merged Lua to bytecode before embedding. The stripped bytecode ships, which shrinks the binary and skips the parse at startup.

local bundle = require("santoku.bundle")
local fs = require("santoku.fs")
bundle("bin/main.lua", "build", {
  luac = true,
  binary = true,
})
print("main.lua", fs.exists("build/main.lua"))
print("main.luac", fs.exists("build/main.luac"))
print("main.c", fs.exists("build/main.c"))
print("main", fs.exists("build/main"))
print("four artifacts now: merge, bytecode, generated C, executable")
return fs.exists("build/main")
Illustrative: runs outside the browser.
Details
  • true uses "<luac> -s -o %output %input". <luac> is the first of luac5.1 and luac on PATH whose -v reports 5.1.
  • With neither on PATH, bundle raises "no Lua 5.1 luac found on PATH".
  • A string is a template. bundle substitutes %input and %output, splits the result on whitespace and executes it, so keep spaces out of the paths.

The chunk the program loads

opts.chunk, opts.encode and opts.load control what the generated program loads. santoku-make uses them to ship either source or re-encoded bytecode in a web page.

local bundle = require("santoku.bundle")
bundle("bin/main.lua", "build", {
  chunk = "build/main.min.lua",
  luac = true,
  encode = true,
  load = "my_loadbuffer",
  flags = { "-O2", "src/my_loader.c", "-llua", "-lm" },
})
print("[bundle] encode: <luac bytes> -> <encoded bytes> bytes, decode check ok")
return "the program decodes the chunk, then calls my_loadbuffer"
Illustrative: runs outside the browser.
Details
  • opts.chunk names a prepared chunk file that replaces the merged Lua as the input to luac. It can't combine with opts.minify.
  • opts.encode re-encodes the luac output into a smaller form. encode needs luac.
  • At build time, encode decodes the result again and stops the build when the round trip differs.
  • The generated program decodes the chunk before it loads it.
  • opts.load names the C function the program loads the chunk with, in place of luaL_loadbuffer.
  • That function has the same signature: int f(lua_State *, const char *, size_t, const char *).
  • bundle declares the function, and your flags must link it.

The luac template, live

The string form of opts.luac is a santoku.string interp template. This snippet runs the same substitution that bundle performs.

local str = require("santoku.string")
local cmd = str.interp("build/lua-5.1.5/bin/luac -s -o %output %input", {
  input = "build/main.lua",
  output = "build/main.luac",
})
print(cmd)
return cmd

base64 vs binary embedding

By default, bundle embeds the bytecode as a base64 C string, and generated C decodes it at program start. binary = true writes a raw byte array instead, loaded directly with luaL_loadbuffer.

local str = require("santoku.string")
local arr = require("santoku.array")
local chunk = "print('hello from inside the executable')"
local b64 = str.to_base64(chunk)
print(b64)
print("roundtrip ok: " .. tostring(str.from_base64(b64) == chunk))
local bytes = {}
for i = 1, 12 do
  bytes[#bytes + 1] = str.format("0x%02x", str.byte(chunk, i))
end
print(arr.concat(bytes, ",") .. ", ...")
print("binary = true writes that byte array into the generated C")
return b64
Details
  • The byte array has 16 bytes per generated line.
  • The snippet runs the same transformations in the page with santoku.string.

Build options

Baked-in environment variables

opts.env is a list of {name, value} pairs. They become setenv calls at the very top of the generated main, before the Lua state exists.

local bundle = require("santoku.bundle")
bundle("bin/main.lua", "build", {
  env = {
    { "LOG_LEVEL", "info" },
    { "TK_MYAPP_WASM", "1" },
  },
})
print("generated main begins:")
print("  setenv(\"LOG_LEVEL\", \"info\", 1);")
print("  setenv(\"TK_MYAPP_WASM\", \"1\", 1);")
print("values are compiled into the binary: build-variant flags, not secrets")
return "environment fixed at compile time"
Illustrative: runs outside the browser.
Details
  • The wasm test flow bakes the WASM flag of the project into every bundled spec this way.

State lifecycles with close

With opts.close omitted, the generated program registers an atexit handler that closes the lua_State. true closes the state explicitly at the end of main. false never closes it.

local bundle = require("santoku.bundle")
bundle("bin/main.lua", "build", {})
print("close omitted: atexit(__tk_bundle_atexit) closes the state")
bundle("bin/main.lua", "build", { close = true })
print("close true: lua_close(L) at the end of main")
bundle("bin/main.lua", "build", { close = false })
print("close false: never closed; main returns and the state lives on")
return "pick the lifecycle to match the runtime"
Illustrative: runs outside the browser.
Details
  • wasm test bundles pass false, so the state outlives main.
  • A web page keeps the default. The atexit of the web libc never runs its handler, so the state stays open and keeps handling browser events.
  • That's how this page keeps running.

minify and the return value

opts.minify runs minify_lua from santoku-lpeg over the merged Lua and writes <outprefix>.min.lua, which luac then compiles. true uses the defaults, and a table passes minify_lua options.

local bundle = require("santoku.bundle")
local r = bundle("bin/main.lua", "build", {
  minify = { fields = false, shake = false },
  luac = true,
  link_c = false,
})
print(r.lua, r.chunk, r.encoded)
print("renamed names:", r.minify.names)
return #r.c_inputs
Illustrative: runs outside the browser.
Details
  • A keep function receives the C inputs and returns the names to keep.
  • bundle raises when live code uses introspection and renaming is on.
  • bundle also raises when minify_lua drops fields or shake for dynamic code, and names the option to set false.
  • bundle returns { lua, chunk, encoded, minify, c_inputs }:
  • lua: the merged Lua path.
  • chunk: the chunk the program loads, which is the luac output, else the minified or merged Lua.
  • encoded: the encoded chunk path, when opts.encode is set.
  • minify: the report from minify_lua.
  • c_inputs: the C inputs that bundle linked or, with link_c = false, left for the caller.

.d sidecars with opts.deps

opts.deps writes a make-style dependency file next to the output. The file holds the target and every resolved Lua and C source, then a second rule that makes the .d file depend on the entry.

local bundle = require("santoku.bundle")
local fs = require("santoku.fs")
bundle("bin/main.lua", "build", {
  deps = true,
})
print(fs.readfile("build/main.d"))
print("line one: build/main: every resolved source file")
print("line two: build/main.d: bin/main.lua")
return fs.exists("build/main.d")
Illustrative: runs outside the browser.
Details
  • depstarget overrides the target name.
  • The santoku-make engine folds target .. ".d" sidecars into staleness. So an edit to any bundled module restales the executable on the next toku build.

The compile command

opts.cc defaults to the CC environment variable, then plain cc. bundle prints the full command before it runs, so you can reproduce a failed build by hand.

local bundle = require("santoku.bundle")
bundle("bin/main.lua", "build", {
  cc = "musl-gcc",
  flags = { "-static", "-O2", "-I", "/usr/include/lua5.1", "-llua5.1", "-lm" },
})
print("echoed before execution:")
print("musl-gcc build/main.c -static -O2 -I /usr/include/lua5.1 -llua5.1 -lm")
print("  <each module's .link lines or .so> -o build/main")
return "one self-contained binary"
Illustrative: runs outside the browser.
Details
  • The command is cc, the generated .c file, opts.flags in order, the C inputs, then -o and the output path.
  • The C inputs are the .link lines of each module, else its shared object.

In the toku build

How this page is built

The web project layer of santoku-make bundles each client page with this call form. The entry of this site, client/bin/bundle.tk.lua, is one line: return require("docs.main").

local bundle = require("santoku.bundle")
local wasm = require("santoku.make.wasm")
local fs = require("santoku.fs")
local wasm_build = "build/client/pages"
local post = "build/client/bundler-post/bundle"
local pre = fs.readfile("build/client/vendor/codejar-global.js")
local function page (out, lua_dir, source, chunk)
  local b = bundle(wasm_build .. "/bin/bundle.lua", fs.dirname(out), {
    cc = wasm.toolchain().cc,
    luac = not source and wasm.luac(fs.dirname(out)) or nil,
    encode = not source,
    chunk = chunk,
    minify = not chunk and wasm.bundle_minify({ fields = false, shake = false }, lua_dir, "web", pre) or nil,
    binary = true,
    link_c = false,
    ignores = { "debug" },
    path = wasm_build .. "/lua_modules/share/lua/5.1/?.lua",
    cpath = wasm_build .. "/lua_modules/lib/lua/5.1/?.so",
    flags = wasm.get_bundle_flags(lua_dir, "web", {}, {}),
  })
  wasm.finalize(out, lua_dir, {
    pre = pre, chunk = b.chunk, encoded = b.encoded, source = source, inputs = b.c_inputs,
  })
  return b
end
local r = page(post, wasm_build .. "/lua-5.1.5", true)
local alt = fs.join(fs.dirname(post), "bc", fs.basename(post))
page(alt, wasm_build .. "/bc/lua-5.1.5", false, r.chunk)
return wasm.pick(post, alt)
Illustrative: runs outside the browser.
Details
  • The scanner follows that literal into the client modules it requires, including the generated search index.
  • The flags from get_bundle_flags make clang emit a relocatable wasm32 object (-r, -nostdlib).
  • link_c = false keeps the C modules out of that compile, and bundle returns them as c_inputs.
  • finalize(post, lua_dir, opts) then links the object and opts.inputs against the web Lua build and its small libc.
  • finalize keeps only the stdlib functions that the chunk or C strings name, runs wasm-opt, and writes the page JS beside the .wasm.
  • opts.pre is the client.pre_js text that finalize puts inside that JS. Here it's the vendored editor.
  • With minify.chunk = "smallest", the default, the layer builds the page twice.
  • One build ships source on a Lua with the parser. The other ships the same chunk as re-encoded bytecode under bc/.
  • wasm.pick keeps the build with the smaller brotli size.

Lua 5.1.5 per profile

santoku.make.wasm builds Lua 5.1.5 itself. setup_lua fetches the lua.org tarball with a pinned sha256, patches the source for a profile, and compiles it into lua-5.1.5/lib/liblua.a.

local wasm = require("santoku.make.wasm")
local make = require("santoku.make")
local arr = require("santoku.array")
local m = make()
local lua_dir, lua_ok = wasm.setup_lua(m.target, "build/client/pages", "web")
m.build({ lua_ok }, 1)
print(wasm.toolchain().kind)
print(arr.concat(wasm.get_bundle_flags(lua_dir, "web", {}, {}), " "))
print(wasm.luac("build/client/bundler-post"))
return lua_dir
Illustrative: runs outside the browser.
Details
  • setup_lua compiles with the wasm toolchain.
  • The web profile, for pages, drops io and os. It also drops the debug library unless the descriptor sets lua_runtime.hook.
  • The web profile keeps the parser, except when minify.chunk = "bytecode" and lua_runtime.parser is unset. Then a page runs only precompiled bytecode.
  • The default "smallest" builds its bytecode page on a second, parserless Lua under bc/.
  • The node profile, for wasm test specs, keeps the parser and the standard libraries.
  • wasm.luac returns the luac command that bundle runs. The host toku luac compiles the merged source.
  • The result is then rewritten to the 32-bit size_t layout that wasm32 Lua reads.

toku install --bundled

The library project layer bundles every script in bin/ into a standalone executable. The compiler is $CC, else cc, with the flags toku derives.

local bundle = require("santoku.bundle")
local fs = require("santoku.fs")
local str = require("santoku.string")
for fp in fs.files("bin") do
  if str.match(fp, "%.lua$") then
    bundle(fp, "build/bundled", {
      ignores = { "debug" },
      path = "build/lua_modules/share/lua/5.1/?.lua",
      cpath = "build/lua_modules/lib/lua/5.1/?.so",
      outprefix = fs.stripextensions(fs.basename(fp)),
    })
  end
end
print("this loop is what toku install --bundled runs after install-deps")
print("with --wasm it emits <name>.js plus a sh wrapper that execs the managed node")
return "standalone tools from bin/ scripts"
Illustrative: runs outside the browser.
Details
  • debug is always ignored.
  • Each executable is copied to bin/ under --prefix, else $PREFIX, else $HOME/.local, and gets chmod +x.
  • No Lua modules sit on disk, and no LUA_PATH is needed.
  • Lua links statically, since the managed toolchain ships only liblua.a. So readelf -d lists libc, libm and the system libraries your dependencies link.

Bundled test suites under node

When a project builds for wasm, toku test bundles every spec against the node Lua profile. It runs the result under the node that toku setup --node recorded.

local bundle = require("santoku.bundle")
local wasm = require("santoku.make.wasm")
local lua_dir = "build/default-wasm/test/lua-5.1.5"
local js = "test/bundler-post/test/spec/santoku/bundle.js"
local out_dir = "test/bundler-post/test/spec/santoku"
local r = bundle("test/bundler-pre/test/spec/santoku/bundle.lua", out_dir, {
  cc = wasm.toolchain().cc,
  luac = wasm.luac(out_dir),
  encode = true,
  outprefix = "bundle.606e713e9c93.js",
  close = false,
  link_c = false,
  ignores = { "debug" },
  env = { { "TK_BUNDLE_WASM", "1" } },
  flags = wasm.get_bundle_flags(lua_dir, "node", {}, {}),
})
wasm.finalize_node(js, lua_dir, false, {
  chunk = r.chunk, encoded = r.encoded, inputs = r.c_inputs,
})
print("<managed node> test/bundler-post/test/spec/santoku/bundle.js runs the suite:")
print("the same specs, compiled to wasm, testing the target for real")
return "toku test, but the suite itself is a wasm program"
Illustrative: runs outside the browser.
Details
  • get_bundle_flags(lua_dir, "node") links the WASI build of Lua with its process-clock emulation.
  • finalize_node(out, lua_dir, browser, opts) links the object with opts.inputs, the c_inputs that bundle returned.
  • finalize_node inlines the wasm into one runnable .js that starts it under node:wasi, or a browser runner when browser is true.
  • That WASI instance preopens the highest readable ancestor of the working directory, so specs read fixtures normally.
  • close = false leaves the state open, and the baked env pair lets specs branch on the wasm build.