Integrating the kernel
Basthon's console and notebook are built on Basthon-Kernel, which can be used by any web page or platform (Capytale does): it runs the user's code in the browser and reports what happens through events. This guide shows how to integrate it; the JavaScript API reference describes every class and method.
Info
This page is in English, for integrators. The rest of the documentation is in French.
Quick start
The @basthon/browser-bundle package is the kernel ready for a web page: a bundle.js script and the files it loads (kernels, WebAssembly modules...). Get it from npm and serve its lib/ directory with your page, e.g. as basthon/:
npm pack @basthon/browser-bundle
tar xzf basthon-browser-bundle-*.tgz
mv package/lib basthonThe bundle is configured by global variables set before it loads, then it creates a kernel loader (window.basthonKernelLoader) and shows a loading screen until the kernel is started:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<script>
// where the bundle's files are, and the kernel to load
window.basthonRoot = "basthon";
window.basthonKernel = "python3";
</script>
<script src="basthon/bundle.js" defer></script>
</head>
<body>
<textarea id="code">
name = input("Your name? ")
print("Hello", name)
6 * 7</textarea>
<button id="run">Run</button>
<pre id="output"></pre>
<script type="module">
const output = document.getElementById("output");
// the kernel, once started
const kernel = await window.basthonKernelLoader.kernelStarted();
kernel.addEventListener("eval.output", (data) => {
output.textContent += data.content;
});
kernel.addEventListener("eval.input", (data) => {
data.resolve(window.prompt(data.content.prompt ?? ""));
});
kernel.addEventListener("eval.finished", (data) => {
const value = data.result?.["text/plain"];
if (value != null) output.textContent += `Out: ${value}\n`;
});
kernel.addEventListener("eval.error", (data) => {
output.textContent += `(error: ${data.error.name})\n`;
});
document.getElementById("run").addEventListener("click", () => {
const code = document.getElementById("code").value;
kernel.execute({ code });
});
</script>
</body>
</html>The bundle's global variables:
| Variable | Default | Role |
|---|---|---|
basthonRoot | "./" | URL of the bundle's files |
basthonKernel | "python3" | the language: python3, sql, ocaml, javascript, xcas, c or r |
basthonLegacy | false | run Python in the main thread (legacy kernel) instead of a worker |
basthonEphemeralAPI | "https://api.basthon.fr/ephemeral" | Basthon's ephemeral API (see Inputs) |
Loading a kernel
With a bundler (webpack, Vite...), use the npm packages instead of the bundle: @basthon/kernel-loader loads the kernel of a language, whose package (@basthon/kernel-python3, @basthon/kernel-ocaml...) is imported dynamically, in its own chunk.
import { KernelLoader } from "@basthon/kernel-loader";
const loader = new KernelLoader({ rootPath: "assets", language: "python3" });
// initializes the kernel and shows the loading screen until it is started
loader.showLoader("Loading Basthon...");
const kernel = await loader.kernelStarted();rootPath is the URL where your bundler's output is served: the kernels' workers and WebAssembly modules are emitted there by the bundler. Python's own files (Basthon's Python packages) must also be copied from @basthon/kernel-python3/lib/dist/ to <rootPath>/<version>/python3/. The webpack configuration of browser-bundle (packages/browser-bundle/bundler/ in the repository) is a complete example, with the Node.js polyfills the kernels need (crypto, path, buffer...).
Without showLoader, initialize the kernel yourself: await (await loader.kernelAvailable()).init(). See KernelLoader and its options, KernelLoaderOptions.
Running code
kernel.execute({ code }) runs code, then the kernel reports through its own events: listen to them with kernel.addEventListener. Several kernels can run on the same page, each one only hears its own events. The promise returned by execute is resolved at the end of the evaluation, even if it failed.
| Event | Dispatched when | Data |
|---|---|---|
eval.output | the code prints | stream ("stdout" or "stderr"), content: the text |
eval.display | the code displays something | display_type and content (see Displays) |
eval.clear-output | the code clears its output | content.wait |
eval.input | the code waits for an input | content.prompt, content.password, resolve(answer) |
eval.input-cancel | the kernel gave up waiting for an input | the eval.input data |
eval.finished | the evaluation succeeded | execution_count, result: a MIME bundle ({"text/plain": ...}), if the code has a value |
eval.error | the evaluation failed | execution_count, error: a KernelError (name, value, traceback) |
The fields of the request's data are copied to the events of its evaluation: add your own ones (e.g. an id, a cell) to know which evaluation an event belongs to.
kernel.addEventListener("eval.output", (data) => console.log(data.cell, data.content));
kernel.execute({ code: "print(1)", cell: 3 });To do something before each evaluation (e.g. save the user's work), set kernel.beforeEval: an asynchronous function receiving the request's data, that the evaluation waits for.
Astuce
The error of a failed evaluation is already printed on stderr (an eval.output event) when its displayed field is true.
A kernel runs one evaluation at a time: wait for eval.finished or eval.error, or for execute's promise, before the next request. kernel.restart() stops a running evaluation and loses the user's variables (the files and modules are kept).
Inputs
When the code waits for an input (input() in Python, scanf in C...), an eval.input event is dispatched: answer it by calling its resolve with the text typed by the user. A pending input can also be interrupted (kernel.interruptPendingInput(), a KeyboardInterrupt in Python) or ended (kernel.endPendingInput(), an EOFError in Python).
The kernel runs in a worker, which must wait for the answer while the code runs. Without SharedArrayBuffer (a page that is not cross-origin isolated), the answer goes through Basthon's ephemeral API (api.basthon.fr), encrypted with a key that never leaves the browser. Set basthonEphemeralAPI (or the ephemeralAPI option) to use your own deployment of basthon-api.
Displays
The data of an eval.display event is one of:
- a MIME bundle (
display_type"multiple"):contentmaps MIME types ("text/plain","text/html","image/png"in base64,"image/svg+xml"...) to their content. Display the richest one you support. HTML comes from the user's code: render it in a sandboxed iframe (withoutallow-same-origin), not in your page; - a kernel iframe (
display_type"kernel-iframe"):content.htmlis a page to display in a sandboxed iframe, which communicates with the kernel (p5 sketches, interactive matplotlib figures, tkinter windows...). Once the iframe is loaded, transfercontent.portto it:iframe.contentWindow.postMessage(port, "*", [port]).
Files and modules
kernel.putFile(name, content) puts an auxiliary file in the kernel's virtual filesystem, kernel.putModule(name, content) installs a module (e.g. a Python module) and kernel.putRessource(name, content) chooses from the file's extension. They are put again after a restart. kernel.getFile(path) reads a file written by the code.
const response = await fetch("data.csv");
await kernel.putFile("data.csv", await response.arrayBuffer());Driving a kernel from Node.js
The @basthon/kernel-node package runs the kernels in Node.js and provides the basthon command. Its --json mode lets another program drive a kernel: once started, it writes {"ready": true}, then each line read is a request {"id": ..., "code": ..., "args": [...]} whose code is run as the body of an async function where Basthon is the kernel (the same API as in a page), and it answers {"id": ..., "value": ...} or {"id": ..., "error": ...}.