DEV Community

Cover image for Choosing a JavaScript engine binding for Kotlin: the requirements and the spike
Yonto Player
Yonto Player

Posted on

Choosing a JavaScript engine binding for Kotlin: the requirements and the spike

Picking a JavaScript engine binding for a Kotlin app looks like a library choice. For Yonto Player it was more, because everything a plugin does goes through it. So before I looked at a candidate I wrote down what the binding had to do, then checked each one in a throwaway spike. This post is about the list, the spike, what the chosen binding gave us, and what it costs.

Here I only cover one question: given that plugins run on QuickJS, which binding to use, and how the runtime is hosted.

Two requirements, written down first

Yonto Player is an Android TV, phone and tablet app that plays your own library, and its sources are small JavaScript plugins that talk to a server's API. Two facts turned into hard requirements.

1. It must run in plain JVM unit tests. The repo's adapters are tested on the JVM, with a mock web server standing in for the real one. A binding that only loads on a device would make the plugin runtime the one part we could not test the same way as everything else.

2. Host calls must suspend, not block. A plugin asks the host to fetch things, and a good plugin asks for several at once, with Promise.all over a few awaited host calls. If a host call blocks the engine's thread until it returns, three calls run one after another and "concurrent" is only a word. The host is Kotlin and coroutines, so the natural shape is a host function that is itself suspend, and an engine that can park a promise until it finishes.

Everything else was negotiable.

The spike

I checked three candidates against the two requirements, in September 2026, and wrote a small throwaway test for the one that looked right. quickjs-kt (1.0.15 at the time) met both. The other two I looked at did not meet both requirements for this use at that time, and they were built for other jobs, so I will leave them out of the rest of this post.

For the binding that passed, the first test evaluated 1 + 1 in a JVM unit test and asserted 2. That was the first proof that the library loads and evaluates on the JVM: its JVM artifact ships natives for macOS, Linux and Windows, so developer machines and CI need no extra setup.

The second test mattered more. It registered a host function that sleeps, awaited it from JavaScript, then ran three under one Promise.all. Each slept 300 ms: overlapping calls total about 300 ms, serial ones about 900 ms.

In a JVM unit test the three took about 304 ms. It shows the one thing I needed to know, which is that the calls genuinely overlap.

What a suspending host function looks like

What made requirement 2 work is a registration call for functions whose body can suspend. Here is a simplified sketch of how the host side is shaped, not the app's exact code.

// Simplified sketch with generic names, not the app's exact code.
interface HostScope {
    fun function(name: String, body: (List<Any?>) -> Any?)
    fun asyncFunction(name: String, body: suspend (List<Any?>) -> Any?)
}

fun registerHost(scope: HostScope) {
    scope.asyncFunction("host_sleep") { args ->
        delay((args[0] as Number).toLong())   // suspends, the engine's thread is free
        null
    }
}

// Platform side: hand each registration to the engine's own binding calls.
class EngineScope(private val engine: QuickJs) : HostScope {
    override fun function(name: String, body: (List<Any?>) -> Any?) =
        engine.function<Any?>(name) { args -> body(args.toList()) }

    override fun asyncFunction(name: String, body: suspend (List<Any?>) -> Any?) =
        engine.asyncFunction<Any?>(name) { args -> body(args.toList()) }
}
Enter fullscreen mode Exit fullscreen mode

The host functions are flat, with names like host_sleep, and a bootstrap script written in JavaScript shapes them into the object a plugin sees. That keeps the Kotlin surface small and lets the CLI run the same shaping text.

One runtime, hosted per platform

The app talks to a plugin runtime through a small interface: list what the plugin exported, and call a method with arguments as JSON to get JSON back. The shared code declares the factory (createRuntime in this post) as an expect function, and the platform provides the actual one. In the repo the implementation lives in a shared source set rather than in each app, so there is one runtime and one set of tests for it.

Each runtime runs its JavaScript on a dispatcher that it hands to the engine when it creates it. That is what let the host own the limits. A plugin call gets a memory ceiling (64 MB by default) and a time budget for the JavaScript it runs (20 seconds, which the plugin reference also documents). Time spent waiting on a host call does not count against that budget, because the call suspends, and a call that never finishes is still ended at 85 seconds, as the reference says. A runaway while (true) is ended by the engine's interrupt, which only an engine-level hook can do.

A contract test lives in the shared code and runs on every target against whatever createRuntime gives it, so the JVM is one of them.

One engine in the CLI too

The second thing the choice bought is less obvious. Authors write plugins on their own computers with a Node command line tool. If it ran the plugin in Node's own engine, a plugin could pass on a laptop and misbehave on a television, because two engines can agree on every global name and still differ in what regular expressions and string functions do.

So the CLI runs the plugin on QuickJS as well, compiled to WebAssembly. It uses the same host bootstrap text as the device, the same memory and time limits, and an interrupt handler for the time budget rather than a Promise.race, which cannot stop a loop that never yields. "It passes on my machine" and "it works on a television" end up close to the same statement, not the same one, because there is one known difference in the list of globals (below).

Requirement 2 applies here too. The WebAssembly library has an easy way to make a host call that pauses the whole runtime until it finishes. That fails requirement 2, because the host calls then run in sequence. In a short spike, three 50 ms host calls under one Promise.all took over 120 ms that way. The variant that returns a pending promise and settles it later took about 52 ms for the same three, and that is the one the CLI uses.

I did not want to take it on trust that two builds of QuickJS agree. A recorded list of the global names the device's engine offers lives in the CLI's conformance folder, and a test (both are in the public plugins repository) compares it with the CLI's list in both directions. The one known difference is Atomics, which the Kotlin binding's build enables and the published WebAssembly build does not. The test names it, so a second difference fails the test.

The costs

  • Native code. The engine is a native library per ABI. In the spike the arm64 one was 903 KB and the armeabi-v7a one was 642 KB, and the app ships those two ABIs only. They are stored uncompressed, so unlike dex code they do not shrink.
  • A recent toolchain. The binding needs a recent Kotlin and a high compile SDK, so the repo has to stay current to take its releases.
  • Handle discipline in the CLI. In the WebAssembly engine every handle has to be disposed, and a leak aborts the process at teardown rather than raising a JavaScript error. It wants a scoped helper from the first line.
  • Two packages to keep in step. The CLI's fidelity depends on a WebAssembly build tracking the Kotlin binding's engine build. The globals test turns a mismatch into a failing test.

They are the price of testing the plugin runtime like everything else in the repo, and of giving plugin authors the engine their plugin will meet.

Takeaway

Write the requirements first and make them testable. For me that was a 1 + 1 test and a three-calls-under-Promise.all test.

Read more

Top comments (0)