Skip to content

Example: render a PDF on the server ​

A record as a PDF, made without a browser in the loop. In this example the page delivers the envelope to an endpoint that first validates it with the sandbox program, as in Example: validate on the server but with the form's own checks only (it registers no custom rules and sends no external data), then renders the sanitised values with the PDF program, datum-pdf-program.js. That is the same kernel the browser's PDF button runs, so the server's PDF has the same layout, page for page. The endpoint answers application/pdf with the bytes, and the page shows them in place and offers them as a file.

The page ​

There is no server behind these docs. The result under the code is answered by a stand-in in the browser that runs the same programs, from the same built files, over the same form. The endpoint files further down are what a real server runs.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Customer intake</title>
    <link rel="stylesheet" href="/datum/datum-form.css">
    <script type="module" src="/datum/datum-form.js"></script>
    <style>#record { width: 100%; height: 640px; border: 1px solid #c8ccd0; }</style>
  </head>
  <body>
    <datum-form id="intake" src="/forms/customer-intake.json" language-switcher></datum-form>

    <!-- Where the PDF the server answers with lands: offered as a file and shown in the page. -->
    <p><a id="save" hidden download="customer-intake.pdf">Save the PDF</a></p>
    <iframe id="record" title="The submission as a PDF" hidden></iframe>

    <script type="module">
      const form = document.getElementById("intake");
      form.dataSources = {
        countries: [
          { value: "CA", label: "Canada" },
          { value: "US", label: "United States" },
          { value: "MX", label: "Mexico" }
        ]
      };

      // The endpoint validates before anything else; a 422 carries codes, which these word.
      form.messages = {
        required: {
          default: "This field is required.",
          locales: { "fr-CA": "Ce champ est requis." }
        }
      };

      form.addEventListener("datum-submit", ({ detail }) => {
        if (!detail.accepted) return; // the form shows its own validation errors
        detail.waitUntil(deliver(detail));
      });

      // Deliver the envelope. What comes back is the PDF itself, application/pdf: the record as the
      // server rendered it, in the submission's language.
      async function deliver(detail) {
        try {
          const response = await fetch("/api/submissions/pdf", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify(detail.submission)
          });
          if (response.status === 422) {
            // { errors: [{ field, code }] }: the server's verdict, worded by the messages above.
            const { errors } = await response.json();
            form.setErrors(errors.map((e) => ({ componentId: e.field ?? undefined, code: e.code })));
            return;
          }
          if (!response.ok) throw new Error(response.statusText);
          const pdf = await response.blob();
          // The bytes as an address the page can show and offer: an iframe draws a PDF in place.
          const url = URL.createObjectURL(pdf);
          Object.assign(document.getElementById("record"), { src: url, hidden: false });
          Object.assign(document.getElementById("save"), { href: url, hidden: false });
        } catch {
          form.setErrors([{ code: "delivery.failed", message: "The form could not be sent. Try again." }]);
        }
      }
    </script>
  </body>
</html>
ResultThis page, running. Addresses under /forms//api/ are answered by the example.
What the page did

Nothing yet.

Enter a full name and submit. The form stays locked while the server renders, then the PDF appears under the form with a link to save it. The PDF is in English whatever language the form is switched to: the endpoint sends the form's root and the answers but no form translations, so the program has no other language's text to print. Submit with the name empty and nothing is sent, because the form refuses the submit and shows its own error on the field. A 422 comes only from a delivery that reaches the endpoint and fails its checks, which the page hands to setErrors.

The form here declares no PDF layout, so the kernel derives one from the form's components. A form designed in the builder's PDF workspace carries its layouts under pdf, and the endpoint passes them on unchanged.

The endpoint ​

Each file is complete. Its first lines say what to install and how to fetch the engine, a WASM build of a JavaScript engine (qjs-wasi.wasm), from its release page. Beside it the server keeps both programs from the bundle folder, datum-sandbox-program.js and datum-pdf-program.js, its copy of the form at forms/customer-intake.json, and the two fonts it embeds at fonts/DejaVuSans.ttf and fonts/DejaVuSans-Bold.ttf.

Python (FastAPI) ​

python
# main.py — the endpoint the page delivers to: the submission validated, then rendered as a PDF.
#   pip install fastapi uvicorn wasmtime
#   curl -LO https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
#   uvicorn main:app
#
# Two programs from beside the bundles, each run in a QuickJS of this process's own — QuickJS-ng's
# WebAssembly build, under wasmtime. datum-sandbox-program.js re-validates the envelope (see
# Validate on the server), and datum-pdf-program.js is the PDF kernel behind the browser's PDF
# button: the form's PDF layout laid out over the answers, the fonts embedded, the bytes written.
# The same program on any host, so the server's PDF is the browser's, byte for byte.
import base64
import json
import math
import tempfile
import threading
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path

from fastapi import FastAPI
from fastapi.responses import JSONResponse, Response
from wasmtime import Config, Engine, ExitTrap, Linker, Module, Store, Trap, WasiConfig

FORM = json.loads(Path("forms/customer-intake.json").read_text())


# The journey the answers were given through, from this server's own copy of the form: the
# envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
# kernel work the path out again from the values, as the browser did: an answer on a page the
# path skipped is judged hidden, and a form field one of the journey's own fields fills or works
# out counts as asked on that page. None named, or one the form does not have: null, and the
# answers are judged as the whole form, which asks for every required field.
def journey_of(submission: dict):
    named = (submission.get("journey") or {}).get("id")
    return next((j for j in FORM.get("journey", {}).get("journeys", []) if j["id"] == named), None)


# The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, compiled
# once and shared. Every request runs it afresh in a store of its own, so requests need no lock.
config = Config()
config.epoch_interruption = True  # the time budget: a run past its deadline traps
engine = Engine(config)
QJS = Module.from_file(engine, "qjs-wasi.wasm")
linker = Linker(engine)
linker.define_wasi()

# The clock every budget is kept by, one for all the runs at once: a tick every 50 ms; a run's
# deadline is its budget in ticks, plus one for the tick already under way when it started. The
# epoch it advances is the engine's, shared by every store on it, so no run may bump it for
# itself: a timer of the run's own, fired when its budget was spent, would advance the epoch under
# every other run in flight too, and cut short one that had set its deadline a tick earlier — a
# wrong verdict for a submission that was never judged. One clock, and no run can touch another.
TICK = 0.05


def clock() -> None:
    while True:
        time.sleep(TICK)
        engine.increment_epoch()


threading.Thread(target=clock, daemon=True).start()


class SandboxError(Exception):
    """A run that ended without an outcome: a limit cut it off, or a program or rule module would not load."""


def qjs(argv: list, request: str, seconds: float, memory: int) -> str:
    # One run: this directory mounted read-only as /app (the programs), the request on stdin, the
    # answer on stdout — all the run can reach; wasmtime hands it nothing else. The limits are
    # wasmtime's, at the browser's profile: the budget in seconds, the memory in bytes. Runaway
    # recursion exhausts the instance's own stack and traps, which ends the run too.
    out, err = [], []
    with tempfile.NamedTemporaryFile("w", suffix=".json") as stdin:
        stdin.write(request)
        stdin.flush()
        store = Store(engine)
        store.set_limits(memory_size=memory)
        store.set_epoch_deadline(math.ceil(seconds / TICK) + 1)
        wasi = WasiConfig()
        wasi.argv = ["qjs", "--std", *argv]  # --std: the std module, which reads stdin
        wasi.preopen_dir(".", "/app", fs_mutable=False)
        wasi.stdin_file = stdin.name
        wasi.stdout_custom = out.append
        wasi.stderr_custom = err.append
        store.set_wasi(wasi)
        try:
            linker.instantiate(store, QJS).exports(store)["_start"](store)
        except ExitTrap as exit:  # a throw: qjs printed it to stderr and exited 1
            if exit.code != 0:
                raise SandboxError(b"".join(err).decode().strip()) from exit
        except Trap as trap:  # "interrupt": the budget; "stack_overflow": the recursion
            raise SandboxError(f"{trap.trap_code}") from trap
    return b"".join(out).decode().rstrip("\n")


# Validation first, so the PDF prints the sanitized values: what the form defines, nothing else.
# Rules of the page's own register into this program too (see Validate on the server).
VALIDATE = ["-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));"]

# The PDF program, under the document profile: a PDF takes seconds and real memory. __datum_pdf
# answers with a promise; qjs runs the pending jobs once the script has run (the program's only
# timers are microtasks), so the answer is printed before it exits.
RENDER = ["-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));"]


# The fonts to embed, read from beside the bundles: the program has no file system. DejaVu Sans
# covers Latin, Greek, Cyrillic, Arabic and Hebrew; with no fonts, the standard 14 stand in.
def font(id, family, weight, file):
    data = base64.b64encode(Path("fonts", file).read_bytes()).decode("ascii")
    return {"id": id, "family": family, "weight": weight, "style": "normal", "data": data}


FONTS = [font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf")]

# What the Country select shows, resolved here: the program never fetches a data source.
COUNTRIES = [{"value": "CA", "label": "Canada"}, {"value": "US", "label": "United States"}, {"value": "MX", "label": "Mexico"}]

LOCALE = None  # None renders in the submission's language; "en" or "fr-CA" picks one
COMPACT = False  # object streams and a compressed cross-reference: smaller, slower to write

# Which of the form's PDF layouts prints. A form designed in the builder's PDF mode may
# carry several under FORM["pdf"]["layouts"] — an applicant copy, an internal summary, a government
# template to fill — each with an id. Name one here, e.g. "applicant-copy", and the request asks
# for it by id ("layoutId" below), whatever the answers. None leaves the choice to the form: the
# first layout, in its list's order, whose "when" holds on these validated values — the layout the
# person's own download printed — else FORM["pdf"]["defaultLayoutId"], the one marked default in
# the builder, else the first layout declared; a form with no layouts at all gets one derived from
# its tree, as this sample does. The response names the layout that printed ("layoutId").
# An id the form lacks derives one too, with a "layout.notFound" warning in the response. A template
# layout whose PDF this server keeps needs its bytes in the request, and the answers may choose
# another template than the default: ask the "build" op first and send its "layoutId" back with
# that layout's bytes. One submission, several PDFs: render once per id. A request may instead
# carry a whole layout object under "layout" — one kept outside the form — which then prints
# whatever the form declares, and whatever the answers.
LAYOUT_ID = None

app = FastAPI()


@app.post("/api/submissions/pdf")
def submit(envelope: dict):
    submission = envelope["submission"]
    locale = submission.get("locale", "en")
    # The journey, if the answers came through one: the path is worked out again from the values (see journey_of).
    context = {"formId": FORM["id"], "form": FORM["root"], "values": submission["values"], "locale": locale, "journey": journey_of(submission), "optionSnapshot": {"countries": COUNTRIES}}
    outcome = json.loads(qjs(VALIDATE, json.dumps(context), 0.25, 32 * 1024 * 1024))
    if outcome["errors"]:  # 422 with codes and fields, never text; the page's messages word them
        errors = [{"field": e.get("componentId"), "code": e["code"]} for e in outcome["errors"]]
        return JSONResponse(status_code=422, content={"errors": errors})
    request = {
        "abi": "4.0.0",
        "op": "document",
        "form": FORM["root"],
        "pdf": FORM.get("pdf"),  # the form's PDF layouts, as designed in the builder's PDF mode
        "values": outcome["values"],
        "locale": LOCALE or locale,
        "optionSnapshot": {"country": COUNTRIES},
        "fonts": FONTS,
        "options": {"compact": COMPACT},
        # The only time and identity the program ever sees: the same request gives the same bytes.
        "env": {"createdAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"), "documentId": str(uuid.uuid4())},
    }
    if LAYOUT_ID:  # a specific layout by id, whatever the answers; left out, the answers choose (see LAYOUT_ID)
        request["layoutId"] = LAYOUT_ID
    response = render(request)
    if not response["ok"]:  # {"code": "font" | "layout" | "template" | "internal", "message": ...}
        return JSONResponse(status_code=500, content={"error": response["error"]})
    return Response(
        content=base64.b64decode(response["bytes"]),
        media_type="application/pdf",
        headers={"Content-Disposition": 'attachment; filename="customer-intake.pdf"', "X-Page-Count": str(response["pageCount"])},
    )


def render(request: dict) -> dict:
    return json.loads(qjs(RENDER, json.dumps(request), 15, 256 * 1024 * 1024))

Java (Spring Boot) ​

java
// Application.java — the endpoint the page delivers to: the submission validated, then rendered as a PDF.
//   pom.xml beside it: Spring Boot, and Endive with its Maven plugin, which compiles the engine in.
//   curl -Lo src/main/resources/qjs-wasi.wasm https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
//   mvn spring-boot:run
//
// Two programs from beside the bundles, each run in a QuickJS of this process's own — QuickJS-ng's
// WebAssembly build, under Endive. datum-sandbox-program.js re-validates the envelope (see
// Validate on the server), and datum-pdf-program.js is the PDF kernel behind the browser's PDF
// button: the form's PDF layout laid out over the answers, the fonts embedded, the bytes written.
// The same program on any host, so the server's PDF is the browser's, byte for byte.
package datum;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import run.endive.runtime.ImportValues;
import run.endive.wasi.WasiExitException;
import run.endive.wasi.WasiOptions;
import run.endive.wasi.WasiPreview1;
import run.endive.wasm.types.MemoryLimits;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.node.ObjectNode;

@SpringBootApplication
@RestController
public class Application {

    static final JsonMapper JSON = JsonMapper.shared();
    static final JsonNode FORM = JSON.readTree(text("forms/customer-intake.json"));

    // The journey the answers were given through, from this server's own copy of the form: the
    // envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
    // kernel work the path out again from the values, as the browser did: an answer on a page the
    // path skipped is judged hidden, and a form field one of the journey's own fields fills or works
    // out counts as asked on that page. None named, or one the form does not have: null, and the
    // answers are judged as the whole form, which asks for every required field.
    static JsonNode journeyOf(JsonNode submission) {
        for (JsonNode journey : FORM.path("journey").path("journeys")) {
            if (journey.path("id").equals(submission.path("journey").path("id"))) {
                return journey;
            }
        }
        return null;  // set as JSON null: no journey
    }

    // The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, compiled once,
    // at build time, by Endive's plugin (see pom.xml) into the class Qjs — native code where the platform
    // has it, JVM bytecode where not. Every request runs it afresh in an instance of its own, so requests
    // need no lock. The module's own initial memory, which a limit must keep.
    static final int QJS_PAGES = Qjs.load().memorySection().get().getMemory(0).limits().initialPages();

    // What a run can reach: one in-memory directory holding the two programs, and nothing else — not this
    // directory, not the disk. Endive mounts any java.nio path, and Jimfs makes one.
    static final Path APP = programs();

    static Path programs() {
        try {
            var app = Files.createDirectories(Jimfs.newFileSystem(Configuration.unix()).getPath("/app"));
            for (var name : List.of("datum-sandbox-program.js", "datum-pdf-program.js")) {
                Files.copy(Path.of(name), app.resolve(name));
            }
            return app;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    static {
        // A JVM's first runs are slow until its JIT has compiled the runner's own setup, several times
        // over what they settle to: pay for that at start, not on the first requests.
        for (int i = 0; i < 3; i++) {
            try {
                qjs(List.of("-e", "0"), "", 30, 32 * 1024 * 1024);
            } catch (SandboxException ignored) {
                // the budget is wide; a failure here shows on the first request instead
            }
        }
    }

    /** A run that ended without an outcome: a limit cut it off, or a program or rule module would not load. */
    static class SandboxException extends Exception {
        SandboxException(String message) {
            super(message);
        }
    }

    static String qjs(List<String> argv, String request, double seconds, int memory) throws SandboxException {
        // One run: the programs mounted as /app, the request on stdin, the answer on stdout — all the run can
        // reach; Endive hands it nothing else. The limits are Endive's, at the browser's profile: the budget in
        // seconds — past it the run is interrupted, native or bytecode — and the memory in bytes. The budget
        // is this run's alone, a Future of its own cancelled at the timeout, so a run past it interrupts no
        // other: there is no engine-wide clock here, as there is under wasmtime (see main.py). Runaway
        // recursion exhausts the instance's own stack and traps, which ends the run too.
        var out = new ByteArrayOutputStream();
        var err = new ByteArrayOutputStream();
        var args = new ArrayList<>(List.of("qjs", "--std"));  // --std: the std module, which reads stdin
        args.addAll(argv);
        var options = WasiOptions.builder()
                .withArguments(args)
                .withDirectory("/app", APP)
                .withStdin(new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8)))
                .withStdout(out)
                .withStderr(err)
                .build();
        var worker = Executors.newSingleThreadExecutor();
        try (var wasi = WasiPreview1.builder().withOptions(options).build()) {
            var imports = ImportValues.builder().addFunction(wasi.toHostFunctions()).build();
            var run = worker.submit(() -> {
                // Building the instance runs _start: qjs's main, through to its exit.
                try (var instance = Qjs.builder()
                        .withImportValues(imports)
                        .withMemoryLimits(new MemoryLimits(QJS_PAGES, memory / 65536))
                        .build()) {
                    return null;
                }
            });
            try {
                run.get((long) (seconds * 1000), TimeUnit.MILLISECONDS);
            } catch (TimeoutException budget) {
                run.cancel(true);  // the interrupt that ends the run
                throw new SandboxException("interrupt");
            }
        } catch (ExecutionException failed) {
            var cause = failed.getCause();
            if (cause instanceof WasiExitException exit) {  // a throw: qjs printed it to stderr and exited 1
                if (exit.exitCode() != 0) {
                    throw new SandboxException(err.toString(StandardCharsets.UTF_8).strip());
                }
            } else {  // a trap: "call stack exhausted", "out of bounds memory access"
                throw new SandboxException(cause.getMessage());
            }
        } catch (InterruptedException interrupted) {
            Thread.currentThread().interrupt();
            throw new SandboxException("interrupted");
        } finally {
            worker.shutdownNow();
        }
        return out.toString(StandardCharsets.UTF_8).stripTrailing();
    }

    static String text(String file) {
        try {
            return Files.readString(Path.of(file));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    // Validation first, so the PDF prints the sanitized values: what the form defines, nothing else.
    // Rules of the page's own register into this program too (see Validate on the server).
    static final List<String> VALIDATE = List.of("-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));");

    // The PDF program, under the document profile: a PDF takes seconds and real memory. __datum_pdf
    // answers with a promise; qjs runs the pending jobs once the script has run (the program's only
    // timers are microtasks), so the answer is printed before it exits.
    static final List<String> RENDER = List.of("-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));");

    // The fonts to embed, read from beside the bundles: the program has no file system. DejaVu Sans
    // covers Latin, Greek, Cyrillic, Arabic and Hebrew; with no fonts, the standard 14 stand in.
    static Map<String, Object> font(String id, String family, int weight, String file) {
        return Map.of("id", id, "family", family, "weight", weight, "style", "normal", "data", base64("fonts/" + file));
    }

    static final List<Map<String, Object>> FONTS = List.of(font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf"));

    // What the Country select shows, resolved here: the program never fetches a data source.
    static final List<Map<String, String>> COUNTRIES = List.of(
            Map.of("value", "CA", "label", "Canada"), Map.of("value", "US", "label", "United States"), Map.of("value", "MX", "label", "Mexico"));

    // The instant as the program takes it, to the second: the same request gives the same bytes.
    static final DateTimeFormatter CREATED_AT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'.000Z'").withZone(ZoneOffset.UTC);

    static final String LOCALE = null;  // null renders in the submission's language; "en" or "fr-CA" picks one
    static final boolean COMPACT = false;  // object streams and a compressed cross-reference: smaller, slower to write

    // Which of the form's PDF layouts prints. A form designed in the builder's PDF mode may
    // carry several under FORM's "pdf" block — an applicant copy, an internal summary, a government
    // template to fill — each with an id. Name one here, e.g. "applicant-copy", and the request asks
    // for it by id ("layoutId" below), whatever the answers. null leaves the choice to the form: the
    // first layout, in its list's order, whose "when" holds on these validated values — the layout
    // the person's own download printed — else its "defaultLayoutId", the one marked default in the
    // builder, else the first layout declared; a form with no layouts at all gets one derived from
    // its tree, as this sample does. The response names the layout that printed ("layoutId"). An id the form lacks derives one too, with a "layout.notFound" warning in the response.
    // A template layout whose PDF this server keeps needs its bytes in the request, and the answers
    // may choose another template than the default: ask the "build" op first and send its "layoutId"
    // back with that layout's bytes. One submission, several PDFs: render once per id. A request may
    // instead carry a whole layout object under "layout" — one kept outside the form — which then
    // prints whatever the form declares, and whatever the answers.
    static final String LAYOUT_ID = null;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    record FieldError(String field, String code) {}

    @PostMapping("/api/submissions/pdf")
    public ResponseEntity<?> submit(@RequestBody JsonNode envelope) throws SandboxException {
        var submission = envelope.path("submission");
        var locale = submission.path("locale").asString("en");
        var context = JSON.createObjectNode()
                .put("formId", FORM.path("id").asString())
                .set("form", FORM.path("root"))
                .set("values", submission.path("values"))
                .put("locale", locale)
                .set("optionSnapshot", JSON.valueToTree(Map.of("countries", COUNTRIES)))  // the lists a choice's data source holds, by source id
                .set("journey", journeyOf(submission));  // the path, worked out again from the values (see journeyOf)
        var outcome = JSON.readTree(qjs(VALIDATE, JSON.writeValueAsString(context), 5, 32 * 1024 * 1024));
        if (!outcome.path("errors").isEmpty()) {  // 422 with codes and fields, never text; the page's messages word them
            var errors = new ArrayList<FieldError>();
            for (JsonNode e : outcome.path("errors")) {
                errors.add(new FieldError(e.path("componentId").asString(null), e.path("code").asString()));
            }
            return ResponseEntity.status(422).body(Map.of("errors", errors));
        }
        var request = JSON.createObjectNode()
                .put("abi", "4.0.0")
                .put("op", "document")
                .set("form", FORM.path("root"))
                .set("pdf", FORM.get("pdf"))  // the form's PDF layouts, as designed in the builder's PDF mode
                .set("values", outcome.path("values"))
                .put("locale", LOCALE != null ? LOCALE : locale)
                .set("optionSnapshot", JSON.valueToTree(Map.of("country", COUNTRIES)))
                .set("fonts", JSON.valueToTree(FONTS))
                .set("options", JSON.valueToTree(Map.of("compact", COMPACT)))
                // The only time and identity the program ever sees: the same request gives the same bytes.
                .set("env", JSON.valueToTree(Map.of("createdAt", CREATED_AT.format(Instant.now()), "documentId", UUID.randomUUID().toString())));
        if (LAYOUT_ID != null) {  // a specific layout by id, whatever the answers; left out, the answers choose (see LAYOUT_ID)
            request.put("layoutId", LAYOUT_ID);
        }
        var response = render(request);
        if (!response.path("ok").asBoolean()) {  // {"code": "font" | "layout" | "template" | "internal", "message": ...}
            return ResponseEntity.status(500).body(Map.of("error", response.path("error")));
        }
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"customer-intake.pdf\"")
                .header("X-Page-Count", String.valueOf(response.path("pageCount").asInt()))
                .body(Base64.getDecoder().decode(response.path("bytes").asString()));
    }

    static JsonNode render(ObjectNode request) throws SandboxException {
        return JSON.readTree(qjs(RENDER, JSON.writeValueAsString(request), 15, 256 * 1024 * 1024));
    }

    static String base64(String file) {
        try {
            return Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of(file)));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
xml
<!-- pom.xml — beside Application.java. Spring Boot for the endpoint; Endive, the Bytecode Alliance's
     WebAssembly runtime for the JVM, for the engine: its Maven plugin compiles qjs-wasi.wasm at build
     time — to native code through Redline (Cranelift, the code generator behind wasmtime) for the six
     platforms it knows, and to JVM bytecode as the fallback for any other — into the class datum.Qjs,
     packaged in the jar. No native library to install, no JNI: the jar runs wherever a JDK does. Redline
     is experimental in Endive 1.1.0; the bytecode runs the same program the same way, more slowly. -->
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.1.1</version>
  </parent>
  <groupId>example</groupId>
  <artifactId>intake</artifactId>
  <version>1.0.0</version>
  <properties>
    <!-- The native runner uses the Panama FFM API, so Java 25; on 17 to 24, redline-runner-jffi-experimental instead. -->
    <java.version>25</java.version>
    <endive.version>1.1.0</endive.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>
    <!-- Endive: the WASI layer (stdin, stdout, the mount) and the runner for the native code. -->
    <dependency>
      <groupId>run.endive</groupId>
      <artifactId>wasi</artifactId>
      <version>${endive.version}</version>
    </dependency>
    <dependency>
      <groupId>run.endive</groupId>
      <artifactId>redline-runner-experimental</artifactId>
      <version>${endive.version}</version>
    </dependency>
    <!-- An in-memory file system: the one directory a run is given. -->
    <dependency>
      <groupId>com.google.jimfs</groupId>
      <artifactId>jimfs</artifactId>
      <version>1.3.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <!-- The native runner is a restricted API: without this the JDK warns at the first run. -->
          <jvmArguments>--enable-native-access=ALL-UNNAMED</jvmArguments>
        </configuration>
      </plugin>
      <plugin>
        <groupId>run.endive</groupId>
        <artifactId>endive-compiler-maven-plugin</artifactId>
        <version>${endive.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <name>datum.Qjs</name>
              <wasmFile>src/main/resources/qjs-wasi.wasm</wasmFile>
              <redlineExperimental>true</redlineExperimental>
              <!-- QuickJS's interpreter loop, JS_CallInternal, is too big for one JVM method: the bytecode
                   fallback interprets that one function. The native code has no such limit. -->
              <interpreterFallback>WARN</interpreterFallback>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

C# (ASP.NET Core) ​

csharp
// Program.cs — the endpoint the page delivers to: the submission validated, then rendered as a PDF.
//   intake.csproj beside it: ASP.NET Core, and Wasmtime, the .NET embedding of wasmtime.
//   curl -LO https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
//   dotnet run
//
// Two programs from beside the bundles, each run in a QuickJS of this process's own — QuickJS-ng's
// WebAssembly build, under wasmtime. datum-sandbox-program.js re-validates the envelope (see
// Validate on the server), and datum-pdf-program.js is the PDF kernel behind the browser's PDF
// button: the form's PDF layout laid out over the answers, the fonts embedded, the bytes written.
// The same program on any host, so the server's PDF is the browser's, byte for byte.
using System.Text.Json;
using System.Text.Json.Nodes;
using Wasmtime;

var form = JsonNode.Parse(File.ReadAllText("forms/customer-intake.json"))!;

// The journey the answers were given through, from this server's own copy of the form: the
// envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
// kernel work the path out again from the values, as the browser did: an answer on a page the
// path skipped is judged hidden, and a form field one of the journey's own fields fills or works
// out counts as asked on that page. None named, or one the form does not have: null, and the
// answers are judged as the whole form, which asks for every required field.
JsonNode? JourneyOf(JsonNode submission) =>
    form["journey"]?["journeys"]?.AsArray().FirstOrDefault(journey => (string?)journey!["id"] == (string?)submission["journey"]?["id"]);

// The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, compiled
// once, now, and shared (the Sandbox class below). Every request runs it afresh in a store of its
// own, so requests need no lock.
var sandbox = new Sandbox();

// Validation first, so the PDF prints the sanitized values: what the form defines, nothing else.
// Rules of the page's own register into this program too (see Validate on the server).
string[] validate = ["-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));"];

// The PDF program, under the document profile: a PDF takes seconds and real memory. __datum_pdf
// answers with a promise; qjs runs the pending jobs once the script has run (the program's only
// timers are microtasks), so the answer is printed before it exits.
string[] render = ["-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));"];

// The fonts to embed, read from beside the bundles: the program has no file system. DejaVu Sans
// covers Latin, Greek, Cyrillic, Arabic and Hebrew; with no fonts, the standard 14 stand in.
static object Font(string id, string family, int weight, string file) =>
    new { id, family, weight, style = "normal", data = Convert.ToBase64String(File.ReadAllBytes(Path.Combine("fonts", file))) };

object[] fonts = [Font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), Font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf")];

// What the Country select shows, resolved here: the program never fetches a data source.
object[] countries = [new { value = "CA", label = "Canada" }, new { value = "US", label = "United States" }, new { value = "MX", label = "Mexico" }];

string? pdfLocale = null;  // null renders in the submission's language; "en" or "fr-CA" picks one
var compact = false;  // object streams and a compressed cross-reference: smaller, slower to write

// Which of the form's PDF layouts prints. A form designed in the builder's PDF mode may
// carry several under the form's "pdf" block — an applicant copy, an internal summary, a government
// template to fill — each with an id. Name one here, e.g. "applicant-copy", and the request asks
// for it by id ("layoutId" below), whatever the answers. null leaves the choice to the form: the
// first layout, in its list's order, whose "when" holds on these validated values — the layout the
// person's own download printed — else its "defaultLayoutId", the one marked default in the
// builder, else the first layout declared; a form with no layouts at all gets one derived from its
// tree, as this sample does. The response names the layout that printed ("layoutId"). An
// id the form lacks derives one too, with a "layout.notFound" warning in the response. A template
// layout whose PDF this server keeps needs its bytes in the request, and the answers may choose
// another template than the default: ask the "build" op first and send its "layoutId" back with
// that layout's bytes. One submission, several PDFs: render once per id. A request may instead
// carry a whole layout object under "layout" — one kept outside the form — which then prints
// whatever the form declares, and whatever the answers.
string? layoutId = null;

var app = WebApplication.CreateBuilder(args).Build();

app.MapPost("/api/submissions/pdf", (JsonNode envelope, HttpContext http) =>
{
    var submission = envelope["submission"]!;
    var locale = (string?)submission["locale"] ?? "en";
    // The journey, if the answers came through one: the path is worked out again from the values (see JourneyOf).
    var context = JsonSerializer.Serialize(new { formId = form["id"], form = form["root"], values = submission["values"], locale, journey = JourneyOf(submission), optionSnapshot = new { countries } });
    var outcome = JsonNode.Parse(sandbox.Run(validate, context, 0.25, 32 * 1024 * 1024))!;
    if (outcome["errors"]!.AsArray().Count > 0)  // 422 with codes and fields, never text; the page's messages word them
    {
        var errors = outcome["errors"]!.AsArray().Select(e => new { field = (string?)e!["componentId"], code = (string?)e["code"] });
        return Results.Json(new { errors }, statusCode: 422);
    }
    var request = new Dictionary<string, object?>
    {
        ["abi"] = "4.0.0",
        ["op"] = "document",
        ["form"] = form["root"],
        ["pdf"] = form["pdf"],  // the form's PDF layouts, as designed in the builder's PDF mode
        ["values"] = outcome["values"],
        ["locale"] = pdfLocale ?? locale,
        ["optionSnapshot"] = new { country = countries },
        ["fonts"] = fonts,
        ["options"] = new { compact },
        // The only time and identity the program ever sees: the same request gives the same bytes.
        ["env"] = new { createdAt = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'.000Z'"), documentId = Guid.NewGuid().ToString() }
    };
    if (layoutId != null)  // a specific layout by id, whatever the answers; left out, the answers choose (see layoutId)
    {
        request["layoutId"] = layoutId;
    }
    var response = Render(request);
    if (!(bool)response["ok"]!)  // {"code": "font" | "layout" | "template" | "internal", "message": ...}
    {
        return Results.Json(new { error = response["error"] }, statusCode: 500);
    }
    http.Response.Headers["X-Page-Count"] = ((int)response["pageCount"]!).ToString();
    return Results.File(Convert.FromBase64String((string)response["bytes"]!), "application/pdf", "customer-intake.pdf");
});

app.Run();

JsonNode Render(Dictionary<string, object?> request) =>
    JsonNode.Parse(sandbox.Run(render, JsonSerializer.Serialize(request), 15, 256 * 1024 * 1024))!;

/// <summary>A run that ended without an outcome: a limit cut it off, or a program or rule module would not load.</summary>
class SandboxException(string message) : Exception(message);

/// <summary>The engine, compiled once as the process starts, and one run of it per request.</summary>
class Sandbox
{
    readonly Engine engine = new(new Config().WithEpochInterruption(true));  // the time budget: a run past its deadline traps
    readonly Module qjs;
    readonly Linker linker;

    // The clock every budget is kept by, one for all the runs at once: a tick every 50 ms; a run's
    // deadline is its budget in ticks, plus one for the tick already under way when it started. The
    // epoch it advances is the engine's, shared by every store on it, so no run may bump it for
    // itself: a timer of the run's own, fired when its budget was spent, would advance the epoch under
    // every other run in flight too, and cut short one that had set its deadline a tick earlier — a
    // wrong verdict for a submission that was never judged. One clock, and no run can touch another.
    static readonly TimeSpan Tick = TimeSpan.FromSeconds(0.05);
    readonly Timer clock;

    public Sandbox()
    {
        qjs = Module.FromFile(engine, "qjs-wasi.wasm");
        linker = new Linker(engine);
        linker.DefineWasi();
        clock = new Timer(_ => engine.IncrementEpoch(), null, Tick, Tick);
    }

    public string Run(string[] argv, string request, double seconds, long memory)
    {
        // One run: this directory mounted read-only as /app (the programs), the request on stdin, the
        // answer on stdout — all the run can reach; wasmtime hands it nothing else. The limits are
        // wasmtime's, at the browser's profile: the budget in seconds, the memory in bytes. Runaway
        // recursion exhausts the instance's own stack and traps, which ends the run too. WASI's
        // standard streams are files here: the request goes in as one, the answer comes back as one.
        var stdin = Path.GetTempFileName();
        var stdout = Path.GetTempFileName();
        var stderr = Path.GetTempFileName();
        try
        {
            File.WriteAllText(stdin, request);
            string[] args = ["qjs", "--std", .. argv];  // --std: the std module, which reads stdin
            using var store = new Store(engine);
            store.SetLimits(memorySize: memory);
            store.SetEpochDeadline((ulong)Math.Ceiling(seconds / Tick.TotalSeconds) + 1);
            store.SetWasiConfiguration(new WasiConfiguration()
                .WithArgs(args)
                .WithPreopenedDirectory(".", "/app", WasiDirectoryPermissions.Read, WasiFilePermissions.Read)
                .WithStandardInput(stdin)
                .WithStandardOutput(stdout)
                .WithStandardError(stderr));
            try
            {
                linker.Instantiate(store, qjs).GetFunction("_start")!.Invoke();
            }
            catch (WasmtimeException exit) when (exit.ExitCode is int code)  // a throw: qjs printed it to stderr and exited 1
            {
                if (code != 0)
                {
                    throw new SandboxException(File.ReadAllText(stderr).Trim());
                }
            }
            catch (TrapException trap)  // Interrupt: the budget; StackOverflow: the recursion
            {
                throw new SandboxException(trap.Type.ToString());
            }
            return File.ReadAllText(stdout).TrimEnd('\n');
        }
        finally
        {
            File.Delete(stdin);
            File.Delete(stdout);
            File.Delete(stderr);
        }
    }
}
xml
<!-- intake.csproj — beside Program.cs. ASP.NET Core for the endpoint; Wasmtime, the Bytecode Alliance's
     .NET embedding of wasmtime, for the engine: the runtime main.py runs under, as a NuGet package that
     carries its native library for Windows, macOS and Linux on x64 and arm64. Nothing else to install. -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Wasmtime" Version="44.0.0" />
  </ItemGroup>
</Project>

Node.js (Express) ​

js
// main.mjs — the endpoint the page delivers to: the submission validated, then rendered as a PDF.
//   qjs.mjs beside it: the engine, one process per run — Node 22 or later, nothing to install for it.
//   npm install express
//   curl -LO https://github.com/quickjs-ng/quickjs/releases/download/v0.16.2/qjs-wasi.wasm
//   node main.mjs
//
// Two programs from beside the bundles, each run in a QuickJS of this process's own — QuickJS-ng's
// WebAssembly build, under node:wasi. datum-sandbox-program.js re-validates the envelope (see
// Validate on the server), and datum-pdf-program.js is the PDF kernel behind the browser's PDF
// button: the form's PDF layout laid out over the answers, the fonts embedded, the bytes written.
// The same program on any host, so the server's PDF is the browser's, byte for byte.
import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { copyFileSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";

import express from "express";

const FORM = JSON.parse(readFileSync("forms/customer-intake.json", "utf8"));

// The journey the answers were given through, from this server's own copy of the form: the
// envelope names it (submission.journey.id) and nothing more. Handed to the sandbox, it has the
// kernel work the path out again from the values, as the browser did: an answer on a page the
// path skipped is judged hidden, and a form field one of the journey's own fields fills or works
// out counts as asked on that page. None named, or one the form does not have: null, and the
// answers are judged as the whole form, which asks for every required field.
const journeyOf = (submission) => FORM.journey?.journeys?.find((journey) => journey.id === submission.journey?.id) ?? null;

// The engine: qjs-wasi.wasm, QuickJS-ng's own WebAssembly build from its release page, on V8 with
// node:wasi (qjs.mjs) — nothing to install. Every request runs it in a process of its own, so requests
// need no lock and share nothing: V8 has no store to hang a limit on, as wasmtime has, so the
// operating system draws the line instead, and the flag and the timeout below are that process's.
const RUNNER = fileURLToPath(new URL("qjs.mjs", import.meta.url));

// What a run can reach: one directory holding the two programs, and nothing else — not this
// directory, not the disk. Node's WASI mounts a directory read-write and does not promise the
// sandbox wasmtime's does, so a run is started in a directory of its own with nothing else in it.
const APP = programs();

function programs() {
  const app = mkdtempSync(join(tmpdir(), "datum-"));
  for (const name of ["datum-sandbox-program.js", "datum-pdf-program.js"]) {
    copyFileSync(name, join(app, name));
  }
  // Gone with the process: at its exit, and on the signals that would otherwise end it without one.
  process.on("exit", () => rmSync(app, { recursive: true, force: true }));
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => process.exit());
  return app;
}

/** A run that ended without an outcome: a limit cut it off, or a program or rule module would not load. */
class SandboxError extends Error {}

function qjs(argv, request, seconds, memory) {
  // One run: a process started in the programs' directory, which it mounts as /app, the request on
  // its stdin, the answer on its stdout — all the run can reach; the runner hands it nothing else.
  // The limits are the process's, at the browser's profile: the memory in bytes, as the pages V8
  // lets the module's memory grow to, and the budget in seconds, a timeout that ends the process —
  // this run's alone, so a run past it interrupts no other: there is no engine-wide clock here, as
  // there is under wasmtime (see main.py). The budget counts the process's own start and the
  // module's compilation, a fifth of a second: it is a bound on a runaway rule, not a latency to
  // meet. Runaway recursion ends the run too: QuickJS's own stack check throws, and V8 traps the
  // instance's stack if it does not.
  return new Promise((resolve, reject) => {
    const flags = ["--wasm-max-mem-pages=" + memory / 65536, "--disable-warning=ExperimentalWarning"];
    const run = spawn(process.execPath, [...flags, RUNNER, ...argv], { cwd: APP, timeout: seconds * 1000 });
    const out = [];
    const err = [];
    run.stdout.on("data", (chunk) => out.push(chunk));
    run.stderr.on("data", (chunk) => err.push(chunk));
    run.stdin.on("error", () => {});  // a run that ended before reading its request: what ended it is on stderr
    run.stdin.end(request);
    run.on("error", reject);
    run.on("close", (code, signal) => {
      if (signal !== null) {  // the budget: the timeout ended the process
        reject(new SandboxError("interrupt"));
      } else if (code !== 0) {  // a throw: qjs printed it to stderr and exited 1
        reject(new SandboxError(Buffer.concat(err).toString().trim()));
      } else {
        resolve(Buffer.concat(out).toString().trimEnd());
      }
    });
  });
}

// Validation first, so the PDF prints the sanitized values: what the form defines, nothing else.
// Rules of the page's own register into this program too (see Validate on the server).
const VALIDATE = ["-I", "/app/datum-sandbox-program.js", "-e", "print(__datum_run(std.in.readAsString()));"];

// The PDF program, under the document profile: a PDF takes seconds and real memory. __datum_pdf
// answers with a promise; qjs runs the pending jobs once the script has run (the program's only
// timers are microtasks), so the answer is printed before it exits.
const RENDER = ["-I", "/app/datum-pdf-program.js", "-e", "__datum_pdf(std.in.readAsString()).then((json) => print(json));"];

// The fonts to embed, read from beside the bundles: the program has no file system. DejaVu Sans
// covers Latin, Greek, Cyrillic, Arabic and Hebrew; with no fonts, the standard 14 stand in.
function font(id, family, weight, file) {
  return { id, family, weight, style: "normal", data: readFileSync(join("fonts", file)).toString("base64") };
}

const FONTS = [font("dejavu-sans", "sans-serif", 400, "DejaVuSans.ttf"), font("dejavu-sans-bold", "sans-serif", 700, "DejaVuSans-Bold.ttf")];

// What the Country select shows, resolved here: the program never fetches a data source.
const COUNTRIES = [{ value: "CA", label: "Canada" }, { value: "US", label: "United States" }, { value: "MX", label: "Mexico" }];

const LOCALE = null;  // null renders in the submission's language; "en" or "fr-CA" picks one
const COMPACT = false;  // object streams and a compressed cross-reference: smaller, slower to write

// Which of the form's PDF layouts prints. A form designed in the builder's PDF mode may
// carry several under FORM.pdf.layouts — an applicant copy, an internal summary, a government
// template to fill — each with an id. Name one here, e.g. "applicant-copy", and the request asks
// for it by id ("layoutId" below), whatever the answers. null leaves the choice to the form: the
// first layout, in its list's order, whose "when" holds on these validated values — the layout the
// person's own download printed — else FORM.pdf.defaultLayoutId, the one marked default in the
// builder, else the first layout declared; a form with no layouts at all gets one derived from its
// tree, as this sample does. The response names the layout that printed (layoutId). An
// id the form lacks derives one too, with a "layout.notFound" warning in the response. A template
// layout whose PDF this server keeps needs its bytes in the request, and the answers may choose
// another template than the default: ask the "build" op first and send its layoutId back with
// that layout's bytes (a server running @datum/engine can ask selectPdfLayoutForValues(FORM,
// outcome.values) instead). One submission, several PDFs: render once per id. A request may
// instead carry a whole layout object under "layout" — one kept outside the form — which then
// prints whatever the form declares, and whatever the answers.
const LAYOUT_ID = null;

const app = express();
app.use(express.json());

app.post("/api/submissions/pdf", async (req, res) => {
  const { submission } = req.body;
  const locale = submission.locale ?? "en";
  // The journey, if the answers came through one: the path is worked out again from the values (see journeyOf).
  const context = { formId: FORM.id, form: FORM.root, values: submission.values, locale, journey: journeyOf(submission), optionSnapshot: { countries: COUNTRIES } };
  const outcome = JSON.parse(await qjs(VALIDATE, JSON.stringify(context), 5, 32 * 1024 * 1024));
  if (outcome.errors.length > 0) {  // 422 with codes and fields, never text; the page's messages word them
    const errors = outcome.errors.map((e) => ({ field: e.componentId ?? null, code: e.code }));
    return res.status(422).json({ errors });
  }
  const request = {
    abi: "4.0.0",
    op: "document",
    form: FORM.root,
    pdf: FORM.pdf,  // the form's PDF layouts, as designed in the builder's PDF mode
    values: outcome.values,
    locale: LOCALE ?? locale,
    optionSnapshot: { country: COUNTRIES },
    fonts: FONTS,
    options: { compact: COMPACT },
    // The only time and identity the program ever sees: the same request gives the same bytes.
    env: { createdAt: new Date().toISOString(), documentId: randomUUID() }
  };
  if (LAYOUT_ID) {  // a specific layout by id, whatever the answers; left out, the answers choose (see LAYOUT_ID)
    request.layoutId = LAYOUT_ID;
  }
  const response = await render(request);
  if (!response.ok) {  // {"code": "font" | "layout" | "template" | "internal", "message": ...}
    return res.status(500).json({ error: response.error });
  }
  res.set({ "Content-Type": "application/pdf", "Content-Disposition": 'attachment; filename="customer-intake.pdf"', "X-Page-Count": String(response.pageCount) });
  res.send(Buffer.from(response.bytes, "base64"));
});

app.listen(8000);

async function render(request) {
  return JSON.parse(await qjs(RENDER, JSON.stringify(request), 15, 256 * 1024 * 1024));
}
js
// qjs.mjs — one run of the engine, in a process of its own: qjs-wasi.wasm, QuickJS-ng's own
// WebAssembly build from its release page, on V8, with node:wasi for its system interface — nothing
// to install beside Node 22. The endpoint (main.mjs) starts one of these per request:
//   node --wasm-max-mem-pages=<pages> --disable-warning=ExperimentalWarning qjs.mjs <qjs arguments>
// The request comes in on stdin and the answer goes out on stdout; the directory the process was
// started in is mounted as /app, all the run can reach. The flag is the memory the module may grow
// to, per process. The warning silenced is node:wasi's own, that it is still marked experimental,
// so that stderr is the run's alone.
import { readFileSync } from "node:fs";
import { WASI } from "node:wasi";

const wasi = new WASI({
  version: "preview1",
  args: ["qjs", "--std", ...process.argv.slice(2)],  // --std: the std module, which reads stdin
  preopens: { "/app": "." },
  returnOnExit: true  // qjs's exit code comes back from start() below, and becomes this process's
});
const qjs = await WebAssembly.compile(readFileSync(new URL("qjs-wasi.wasm", import.meta.url)));
const instance = await WebAssembly.instantiate(qjs, wasi.getImportObject());
process.exitCode = wasi.start(instance);

What to notice ​

  • Validation first. The PDF prints the values the sandbox returned, not what was posted, so it never shows a key the form does not define.
  • The program has no file system. The endpoint reads the fonts and hands them over as base64, and resolves the Country select's options itself. With no fonts, the standard PDF fonts stand in.
  • The only time and identity. The request's env carries the creation time and a document id. The program reads no clock and makes no random numbers, so the same request gives the same bytes on every host.
  • The server's say. The language and the compactness of the file are constants of the endpoint (LOCALE, COMPACT). LAYOUT_ID names one of the form's layouts by id; left empty, the form chooses, by the first layout whose condition holds on the answers, else its default.
  • Two budgets. A validation run gets 32 MiB and a PDF run 256 MiB and 15 s. The validation time budget is 250 ms in the Python and C# files and 5 s in the Java and Node.js files.
  • Errors keep their shape. A 422 is the same error contract as validation. A failed render answers 500 with the kernel's code, such as font, layout or template.

Next ​

MIT licence. Your forms, your data, your keys.