JSVM
Version 0.2.0 · Owners: @benallfree
PocketOne's JS engine for pb_hooks and pb_migrations. It runs the same JS API as PocketBase ($app, onX,
routerAdd, cronAdd, $http, $security, ...) on QuickJS, with one VM per app:
- Real globals. Every hook file runs in the app's one global scope, so top-level helpers, constants and state are
visible to every handler. No more
require()inside each handler. - ES modules.
*.pb.mjs(and TypeScript*.pb.ts/*.pb.mts) hook files and modules useimport/export, including top-levelawait;*.pb.jsand*.pb.cjsstay scripts withrequire(). Both share the same module instances. - TypeScript.
.ts,.mtsand.ctshooks, migrations and modules run directly (types stripped by esbuild, linked into the binary), with error positions in your.tssource. - Async. Handlers can be
async. Every Go function has an.async(...)twin that runs off the VM and returns a promise, so one app serves other requests while it waits:await $app.findRecordById.async("posts", id). - Timers.
setTimeout,setInterval,clearTimeout,clearIntervalandqueueMicrotask, as in browsers and Node.js. A timer set while serving a request is cleared once the request is answered or its client goes away. - Cancellation. Go contexts, as in PocketBase:
TimeoutContextand$app.withContext(ctx), plusCancelContextfor stopping work for any other reason. A Go function that takes acontext.Contextgets one, andfn.async(ctx, ...args)rejects as soon asctxends. - Hard limits per app. A memory cap (JS heap plus Go objects JS holds), a CPU and a wall-clock budget per task, and caps on queued tasks and async calls. A runaway script stops with an error; other apps in the process keep running.
- Real error positions. Stack traces name
pb_hooks/<file>:<line>.
Every PocketOne app runs on it: a standalone app or an instance on a multisite host, whatever the runtime. PocketBase's
own plugins/jsvm (goja) is for pure PocketBase compatibility only: jsvm: goja under app: in pocketone.yaml (or
--jsvm goja) runs a standalone app on it, with pages, $mcp, $apiTokens, $bulkmail and JS contracts off.
Install · Configure · Use · Integrations · Example
Install
The engine is pure Go (QuickJS translated to Go by modernc.org/libquickjs,
the way PocketBase uses modernc.org/sqlite), so it needs no cgo: CGO_ENABLED=0 builds and cross-compiles work as with
stock PocketBase. In your own Go build, register it where you'd register plugins/jsvm:
jsvm.MustRegister(app, jsvm.Config{HooksDir: "pb_hooks", MigrationsDir: "pb_migrations"})
The module is pocketone.dev/ext/jsvm.
Configure
Config takes PocketBase's jsvm fields (HooksDir, HooksWatch, HooksFilesPattern, MigrationsDir,
MigrationsFilesPattern, TypesDir; HooksPoolSize is accepted and ignored) plus:
OnInit func(rt js.Runtime): add globals after everything else is set up.VM: the limits.MemoryLimit(JS heap plus the Go objects JS holds, default 64 MiB),TaskBudget(JS time per stretch, default 5 s),TaskWall(wall time per stretch, sync Go calls included, default 30 s),AwaitLimit(a whole async handler, awaits included, default 15 min),WaitTimeout(a handler's synchronous part, queue wait included, default 30 s),QueueSize,MaxAsync,MaxTimers(timers pending at once, default 1024),MaxPumpDepth. A stretch is the JS between twoawaits, so time spent awaiting an.asynccall counts only towardAwaitLimit. PastAwaitLimit, or when the HTTP request a handler serves ends (the client went away), the call fails and the handler stops at its nextawait: async calls it started are dropped when they finish and new ones throw. A detached promise outlives its handler. A timer belongs to the call that set it: each run is a task of its own (its ownTaskBudgetandTaskWall), it's cleared when that call is given up, and for a request also when the request is answered. Timers set at the top of a file run until cleared. Thepocketonebinary setsmemory,task_time,task_wallandawait_timeinpocketone.yaml'sapp: js_limits:(QuickJS hooks). Array methods that walk every index (join,indexOf,slice,forEach,concat,flat, ...) and arrays passed to Go throw aRangeErrorpastMemoryLimit / 16elements: QuickJS doesn't checkTaskBudgetinside those loops, and a sparse array (new Array(1e9)) or array-like costs no memory, so the cap is what stops them. No dense array that long fits inMemoryLimit.Extensions: values that extend it (below).
Use
Write hooks and migrations as in PocketBase's JS docs; they run unchanged. What's new:
// pb_hooks/main.pb.js
const cache = new Map()
routerAdd("GET", "/post/{slug}", async (e) => {
const slug = e.request.pathValue("slug")
if (!cache.has(slug)) {
cache.set(slug, await e.app.findFirstRecordByData.async("posts", "slug", slug))
}
return e.json(200, cache.get(slug))
})
-
Hook files run before the app opens its database, as in PocketBase, so a
$appquery at a file's top level fails. Read data inonBootstrapaftere.next(), or in a handler:let users = null onBootstrap((e) => { e.next() users = e.app.findCollectionByNameOrId("users") }) -
Globals live as long as the app's VM. A restart, a hooks reload or running out of memory starts a fresh one, so keep durable data in the database.
-
After an
await, other requests may have run: usee.app, not the global$app, and keep transactions short acrossawaits (they hold SQLite's write lock). -
Use
.asyncfor anything slow ($http.send,sleep, slow queries). Without it, other requests still run while a call waits, but they nest on one stack and wait on each other: under load, a plainsleep(100)served 19 requests a second whereawait sleep.async(100)served 481 (benchmark). -
process.envand a smallBuffer(from,toStringwith utf8, base64, hex) are there.
Cancelling Go calls
A Go function whose first parameter is a context.Context gets one from the engine; JS passes only the other
arguments (or a Go context of its own, such as e.request.context(), first). The context is cancelled when the
request or hook the call runs for is given up (its client went away, AwaitLimit passed) and when the VM closes,
so abandoned work stops instead of running on. Answering the request doesn't cancel it: background work keeps going.
To stop a call early, pass it a Go context of your own as its first argument. new TimeoutContext(seconds, [parent])
ends after a time; new CancelContext([parent]) ends when you call ctx.cancel([reason]), for any other reason (a
user pressed stop, another request said so). Make one the other's parent to stop at whichever comes first:
// a model call that gives up after a minute, even in background work after the response was sent
const ctx = new TimeoutContext(60)
try {
const reply = await callModel.async(ctx, prompt)
} finally {
ctx.cancel() // frees its timer
}
// stop it yourself, or after a minute, whichever comes first
const stop = new CancelContext()
const either = new TimeoutContext(60, stop)
// elsewhere: stop.cancel("the user pressed stop")
When the context ends, the promise rejects at once with its cause (context deadline exceeded, context canceled,
or context canceled: <reason>), and the Go function's context is cancelled with it. The context also ends
when the request is given up or the VM closes. A TimeoutContext runs on a Go timer, so it keeps working after the
request is answered, where setTimeout is refused.
App methods take no context argument: call them through $app.withContext(ctx), a copy of $app whose queries use
ctx (await $app.withContext(ctx).findRecordById.async("articles", id)). A Go function that takes no context
can't be stopped; give it one if it should be.
Modules: import and require
Name a file for what it is: .mjs is an ES module, .cjs is CommonJS. A plain .js file is CommonJS, so existing
PocketBase hooks run unchanged (inside node_modules, Node's rule applies: "type": "module" in the package's
package.json makes its .js files ES modules). TypeScript is written as ES modules, so .ts and .mts are ES
modules and .cts is the CommonJS exception.
| File | Runs as | Shares through |
|---|---|---|
pb_hooks/*.pb.mjs, *.pb.ts, *.pb.mts |
ES module: import, export, top-level await, import.meta |
export / import; its top-level names are private |
pb_hooks/*.pb.js, *.pb.cjs, *.pb.cts |
script in the app's one global scope, with require() |
globals |
pb_migrations/*.mjs, *.ts, *.mts |
ES module | each migration has its own scope either way |
pb_migrations/*.js, *.cjs, *.cts |
script in its own function scope |
All of them run in the app's one VM: scripts and modules share the global object (a module can read a script's globals) and one instance of every module.
// pb_hooks/lib/store.mjs
export const state = { hits: 0 }
export const bump = () => ++state.hits
// pb_hooks/main.pb.mjs
import { bump } from "./lib/store.mjs"
import legacy from "./lib/legacy.cjs" // CommonJS: module.exports is the default export
import { hello } from "some-package" // node_modules, CommonJS or ES
const { greeting } = await import("./lib/greeting.mjs") // top-level await: done before the app serves
routerAdd("GET", "/hit", (e) => e.json(200, { hits: bump() }))
importandrequire()resolve the same way: relative paths (.js,.mjs,.cjs,.jsonandindex.*tried in turn), thennode_modulespackages bypackage.jsonexports(theimportorrequirecondition) ormain.- A module loads once per app, however many files import or require it, so its state is shared by every request.
Importing a CommonJS module gives its
module.exportsas the default export, its keys as named exports, and the same instancerequire()returns. require()of an ES module returns its namespace (the same instanceimportgives), as in Node 22, as long as the module has no top-levelawait; for one that does, useawait import("./lib/x.mjs").
TypeScript
.ts, .mts and .cts files run as they are: esbuild strips the types when the file loads, and each file's source
map is kept, so an error names pb_hooks/main.pb.mts:12:5 in your source, not in the stripped code.
- There's no type checking at runtime. Check with
tsc --noEmitor your editor;types.d.tsandtsconfig.jsonin the project root type the whole JS API. - Imports may name the compiled file, as TypeScript's
NodeNextstyle does:import { add } from "./math.js"loadsmath.tswhen there's nomath.js. import typeand other type-only imports disappear, so a*.pb.ctsscript can use them and stay a script.- A
.ctsmodule may still be written withimport/export; it's turned into CommonJS.
Types
When the app starts, types.d.ts in the project root (the folder holding pb_hooks, next to pb_data and
pocketone.yaml) gets the declarations of the whole JS API, for your editor and tsc:
- PocketBase's API generated from PocketOne's core (its extra hooks included), by PocketBase's own generator.
- What this engine adds (
pocketone.d.ts):.asyncon every Go function, fully typed (await $app.findRecordById.async(...)is aPromise<core.Record>, and acontext.Contextfirst parameter is optional),CancelContext,require,process,Buffer,console,import.meta. - Each extension's own API, for the extensions on in that app (
$mcp,$apiTokens,$bulkmail,onContractsand the contracts' action hooks).
Beside it, the app writes a tsconfig.json when the folder has none, so your editor and tsc --noEmit work right
away. It's yours from then on: the app never overwrites it.
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022"],
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"skipLibCheck": true
},
"include": ["types.d.ts", "pb_hooks/**/*", "pb_migrations/**/*", "pb_pages/**/*"]
}
skipLibCheck skips two type errors inside PocketBase's own generated declarations. Commit both files: a fresh
checkout is then typed before the app first runs, and a diff in types.d.ts shows what an upgrade or a new extension
changed in the JS API. Empty hook files get a /// <reference path="../types.d.ts" /> line.
Config.TypesDir puts both somewhere else. With hooks embedded in the binary (Bundle) and
no TypesDir, neither is written. In a PocketOne checkout,
go generate in ext/jsvm regenerates the declarations after a core change (the TestTypes tests fail until you
do).
Integrations
Extensions plug in through Config.Extensions with the engine-neutral types in
ext/extkit/js. A value implements any of:
OnInit(rt): set up the VM.BindJS(app, rt): expose a Go API.TypeScript(): declare it for editors andtsc(appended totypes.d.ts).FilterTypes(decl): change the finished declarations (the sandbox declares what it hidesnever).OnCall(rt): wrap every handler call; an error refuses it.HTTPClient(rt): the client$http.senduses.HookFiles,MigrationFiles,Modules: hooks, migrations andrequire()modules from somewhere other than disk.OnLoad(rt, root, file, content): wrap loading each hook file.
js.Run(app, fn) runs Go code on the app's VM; a js.Func kept from JS can be called from any goroutine.
To make your extension's calls cancellable, give the Go function a ctx context.Context first parameter. JS passes
the other arguments and the engine fills in the context, which is cancelled when the request is given up.
In PocketBase's JS API, a context comes with the object you call: $app.withContext(ctx) returns a copy of $app
whose every call uses ctx, and $app.context() returns it. An extension API that page code can set a time limit on
or cancel follows the same convention, with withContext(ctx) and context(), so page code writes
$mine.withContext(deadline).completeAsync(...). $llm and $wasm work
this way:
// Go: n.Set("call", func(ctx context.Context, kind, op, opts string) (string, error) { ... })
const build = (ctx) => {
const callAsync = async (kind, op, o) => {
const s = JSON.stringify(o ?? {})
return JSON.parse(await (ctx == null ? n.call.async(kind, op, s) : n.call.async(ctx, kind, op, s)))
}
return Object.freeze({
withContext: (c) => build(c),
context: () => ctx ?? n.background, // n.background: context.Background(), as an unbound $app.context()
completeAsync: (o) => callAsync("text", "complete", o),
})
}
globalThis.$mine = build(null)
The same function called without .async gets the handler's context, so one Go function serves both. Under goja
(jsvm: goja), JS must pass the context itself, and CancelContext doesn't exist.
Bundle uses these to serve hooks and migrations embedded in the binary.
Example
// Command example serves example/pb_hooks with the jsvm extension: one QuickJS VM for the app, so the hook file's
// top-level helpers and state are visible to every handler.
//
// cd example && go run . serve
// curl http://127.0.0.1:8090/hello/world
package main
import (
"log"
"ganigeorgiev.com/pocketbase/pocketbase"
"pocketone.dev/ext/devusers"
"pocketone.dev/ext/jsvm"
)
func main() {
app := pocketbase.New()
devusers.Register(app)
jsvm.MustRegister(app, jsvm.Config{HooksDir: "pb_hooks", MigrationsDir: "pb_migrations"})
if err := app.Start(); err != nil {
log.Fatal(err)
}
}
How it works
- Each app's VM is owned by one goroutine, its loop; everything that touches the VM runs there. Go code elsewhere posts tasks and waits. A Go call made from JS that fires a hook runs it inline, so Go → JS → Go → JS works.
- Go values cross live through two QuickJS classes:
GoObject(property get/set/has/keys go to Go by reflection, with PocketBase's JS names) andGoFunc(calls go to Go). Each holds a handle into the VM's table; QuickJS's refcounting frees it as soon as JS drops it. - Memory: QuickJS caps its own heap. Go objects JS holds are charged to the same budget: a per-type estimate, and a reachability walk for fresh results of Go calls.
- QuickJS is modernc.org/libquickjs, Bellard's QuickJS translated to Go,
so there is no cgo. It runs about as fast as goja; deep recursion stops at
VM.StackSize(QuickJS stack slots, about one per call; default 5000) with "InternalError: stack overflow". - Benchmarks and the red team (27 attacks against 50 VMs in one process) are in the package's tests
(
ASYNCVM_BENCH=1,ASYNCVM_REDTEAM=1).
License
MIT
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.