Skip to content

kernel-base/worker ​

The base of the kernels running in a worker (@basthon/kernel-base/worker): KernelMainBase on the main thread side, KernelWorkerBase in the worker, connected by expose (see "Writing a new kernel" in the contributors' documentation).

Classes ​

DOMNodeBus ​

Objects (e.g. HTML elements) exchanged by id between the worker's code and the main thread in legacy mode, where they share the same JS context but messages are serialized.

Extends ​

  • Map<number, any>

Constructors ​

Constructor ​
ts
new DOMNodeBus(entries?): DOMNodeBus;
Parameters ​
ParameterType
entries?readonly (readonly [number, any])[] | null
Returns ​

DOMNodeBus

Inherited from ​

Map<number, any>.constructor

Constructor ​
ts
new DOMNodeBus(iterable?): DOMNodeBus;
Parameters ​
ParameterType
iterable?Iterable<readonly [number, any], any, any> | null
Returns ​

DOMNodeBus

Inherited from ​

Map<number, any>.constructor

Methods ​

pop() ​
ts
pop(id): any;

Take an object out of the bus.

Parameters ​
ParameterTypeDescription
idnumberThe object's id (see push).
Returns ​

any

The object.

push() ​
ts
push(obj): number;

Put an object in the bus.

Parameters ​
ParameterTypeDescription
objanyThe object.
Returns ​

number

Its id, to get it back with pop.


KernelMainBase ​

The main thread side of the kernels that run in a worker (all of them): it starts the kernel's worker (an opaque origin worker, see SandboxedWorker, with a proxy worker to fetch Basthon's files), talks to it through comlink and a message port, and turns its messages into events. It also answers the worker's synchronous requests (inputs, kernel iframes' messages) through a SharedArrayBuffer or the ephemeral API, and opens the camera and the audio contexts it asks for.

Each language extends it (kernel.ts of its package) and implements at least language, languageName, moduleExts and newWorker.

Extends ​

Type Parameters ​

Type ParameterDescription
Type extends KernelWorkerBaseThe class of the kernel's worker.

Constructors ​

Constructor ​
ts
new KernelMainBase<Type>(options): KernelMainBase<Type>;
Parameters ​
ParameterTypeDescription
optionsKernelOptionsThe kernel's options.
Returns ​

KernelMainBase<Type>

Overrides ​

KernelBase.constructor

Properties ​

PropertyModifierTypeDefault valueDescriptionInherited from
_execution_countprotectednumber0-KernelBase._execution_count
_filesprotectedMap<string, ArrayBuffer>...-KernelBase._files
_modulesprotectedMap<string, ArrayBuffer>...-KernelBase._modules
_optionsprotectedKernelOptionsundefined-KernelBase._options
_pendingInput?protectedPromiseDelegate<InputAnswer>undefined-KernelBase._pendingInput
_runningDataprotectedany{}-KernelBase._runningData
beforeEvalpublic(data) => Promise<void>...Called by execute before each evaluation, that waits for it. Frontends set it to do what has to be done first (e.g. a backup of the code).KernelBase.beforeEval
confirmCamerapublic(data) => Promise<boolean>...Ask the user to let the running code use the camera, at each request (on top of the browser's permission, granted once for all the code run on the page). Frontends set their own dialog, window.confirm is the default.KernelBase.confirmCamera

Accessors ​

execution_count ​
Get Signature ​
ts
get execution_count(): number;

Number of evaluations since the kernel started (reset at each restart), as Jupyter's execution count.

Returns ​

number

Inherited from ​

KernelBase.execution_count

isReady ​
Get Signature ​
ts
get isReady(): boolean;

Is the kernel started and ready to run code?

Returns ​

boolean

Inherited from ​

KernelBase.isReady

remote ​
Get Signature ​
ts
get protected remote(): Remote<Type> | undefined;

The worker, through comlink (undefined when stopped).

Returns ​

Remote<Type> | undefined

Methods ​

_init() ​
ts
protected _init(): Promise<void>;

The kernel's own initialization, run once by init (to be overridden).

Returns ​

Promise<void>

Inherited from ​

KernelBase._init

_start() ​
ts
_start(): Promise<void>;

Start the kernel: set up the worker, the proxy worker, the synchronous communication (shared buffer, or the ephemeral API's keys) and initialize the worker.

Returns ​

Promise<void>

Overrides ​

KernelBase._start

_stop() ​
ts
_stop(): Promise<void>;

Stop the kernel: terminate the worker, stop the cameras and the audio contexts it opened.

Returns ​

Promise<void>

Overrides ​

KernelBase._stop

addEventListener() ​
Call Signature ​
ts
addEventListener<K>(eventName, callback): void;

Listen to an event of this kernel (see the events of KernelBase).

Type Parameters ​
Type Parameter
K extends keyof KernelEvents
Parameters ​
ParameterTypeDescription
eventNameKThe event's name (e.g. "eval.output").
callback(data) => voidCalled with the event's data.
Returns ​

void

Inherited from ​

KernelBase.addEventListener

Call Signature ​
ts
addEventListener(eventName, callback): void;

Listen to an event of this kernel (see the events of KernelBase).

Parameters ​
ParameterTypeDescription
eventNamestringThe event's name (e.g. "eval.output").
callback(_) => voidCalled with the event's data.
Returns ​

void

Inherited from ​

KernelBase.addEventListener

assetsURL() ​
ts
assetsURL(absolute?): string;

URL of the assets directory (see KernelOptions.rootPath).

Parameters ​
ParameterTypeDefault valueDescription
absolute?booleanfalseReturn an absolute URL.
Returns ​

string

Inherited from ​

KernelBase.assetsURL

ts
banner(): string;

The message displayed by consoles at startup.

Returns ​

string

Inherited from ​

KernelBase.banner

basthonRoot() ​
ts
basthonRoot(absolute?): string;

URL of the kernel's files: <assets>/<version>/<language>.

Parameters ​
ParameterTypeDefault valueDescription
absolute?booleanfalseReturn an absolute URL.
Returns ​

string

Inherited from ​

KernelBase.basthonRoot

cancelPendingInput() ​
ts
cancelPendingInput(): void;

Cancel a pending input on the kernel side (e.g. the kernel gave up waiting for the answer): the frontend is notified by an eval.input-cancel event (with the eval.input data) to close its input field.

Returns ​

void

Inherited from ​

KernelBase.cancelPendingInput

clone() ​
ts
clone(obj): any;

Copy a JSON-serializable object.

Parameters ​
ParameterTypeDescription
objanyThe object to copy.
Returns ​

any

Its copy.

Inherited from ​

KernelBase.clone

complete() ​
ts
complete(code): Promise<[string[], number] | []>;

Completions of the code at its end, by the worker (see KernelBase.complete).

Parameters ​
ParameterTypeDescription
codestringThe code before the cursor.
Returns ​

Promise<[string[], number] | []>

[completions, start], or [] if there is none.

Overrides ​

KernelBase.complete

dispatchEvent() ​
ts
protected dispatchEvent(eventName, data): void;

Dispatch an event of this kernel (see the events of KernelBase).

Parameters ​
ParameterTypeDescription
eventNamestringThe event's name (e.g. "eval.output").
dataanyThe event's data.
Returns ​

void

Inherited from ​

KernelBase.dispatchEvent

download() ​
ts
download(data, filename): void;

Download a file (the browser saves it, or asks where to).

Parameters ​
ParameterTypeDescription
datastring | Uint8Array<ArrayBuffer>The file's content: bytes or a data URL.
filenamestringThe name of the saved file.
Returns ​

void

Inherited from ​

KernelBase.download

endPendingInput() ​
ts
endPendingInput(): void;

End a pending input: there is nothing more to read (EOFError in Python), e.g. the program's stdin is closed.

Returns ​

void

Inherited from ​

KernelBase.endPendingInput

evalAsync() ​
ts
evalAsync(
   code, 
   outCallback, 
   errCallback, 
   data?
): Promise<any>;

Run code in the worker (see KernelBase.evalAsync).

Parameters ​
ParameterTypeDefault valueDescription
codestringundefinedThe code to run.
outCallback(_) => voidundefinedUnused: outputs come as worker's messages.
errCallback(_) => voidundefinedUnused: outputs come as worker's messages.
data?anynullThe evaluation's data.
Returns ​

Promise<any>

[result, executionCount].

Throws ​

A KernelError (already displayed) when the code fails.

Overrides ​

KernelBase.evalAsync

execute() ​
ts
execute(data): Promise<void>;

Run code in this kernel and dispatch the evaluation's events: eval.output while it runs, then eval.finished or eval.error.

Parameters ​
ParameterTypeDescription
dataEvalRequestThe request's data, with the code to run (its other fields are copied to the evaluation's events).
Returns ​

Promise<void>

Resolved at the end of the evaluation, even if it failed (see eval.error).

Inherited from ​

KernelBase.execute

getFile() ​
ts
getFile(path): Promise<Uint8Array<ArrayBufferLike>>;

Read a file of the kernel's (virtual) filesystem.

Parameters ​
ParameterTypeDescription
pathstringThe file's path (relative to the working directory or absolute).
Returns ​

Promise<Uint8Array<ArrayBufferLike>>

The file's content.

Inherited from ​

KernelBase.getFile

getUserModuleFile() ​
ts
getUserModuleFile(filename): Promise<Uint8Array<ArrayBufferLike>>;

Read a module installed by putModule.

Parameters ​
ParameterTypeDescription
filenamestringThe module's file name.
Returns ​

Promise<Uint8Array<ArrayBufferLike>>

The module's content.

Inherited from ​

KernelBase.getUserModuleFile

importLegacyWorker() ​
ts
protected importLegacyWorker(): Promise<void>;

Import the worker's code in the main thread (legacy kernel). Only the Python kernel has a legacy mode, the other ones throw an error.

Returns ​

Promise<void>

init() ​
ts
init(): Promise<void>;

Initialize the kernel (once) and start it. Wait for ready before running code.

Returns ​

Promise<void>

Throws ​

The initialization's error (the kernel can't be used).

Inherited from ​

KernelBase.init

inputAsync() ​
ts
inputAsync(
   prompt, 
   password?, 
   data?
): Promise<InputAnswer>;

Ask the frontend for an input: dispatch an eval.input event and wait for its answer (given to the event's resolve).

Parameters ​
ParameterTypeDefault valueDescription
promptstring | null | undefinedundefinedThe text displayed before the input.
password?booleanfalseHide the typed text.
data?anyundefinedThe evaluation's data (sent with the event).
Returns ​

Promise<InputAnswer>

The answer (see InputAnswer).

Inherited from ​

KernelBase.inputAsync

interruptPendingInput() ​
ts
interruptPendingInput(): void;

Interrupt a pending input: the running program stops (KeyboardInterrupt in Python) instead of getting an answer.

Returns ​

void

Inherited from ​

KernelBase.interruptPendingInput

isLegacy() ​
ts
isLegacy(): boolean;

Does the kernel run in the main thread (legacy kernel)?

Returns ​

boolean

language() ​
ts
language(): string;

The kernel's language, as used in URLs and file paths (lower case, e.g. "python3", "ocaml").

Returns ​

string

Inherited from ​

KernelBase.language

languageName() ​
ts
languageName(): string;

The kernel's language as displayed to the user (e.g. "Python 3").

Returns ​

string

Inherited from ​

KernelBase.languageName

moduleExts() ​
ts
moduleExts(): string[];

Extensions of the files installed as modules by putRessource (e.g. ["py"]), without the dot.

Returns ​

string[]

Inherited from ​

KernelBase.moduleExts

more() ​
ts
more(code): Promise<boolean>;

Does the code need more lines (see KernelBase.more), by the worker?

Parameters ​
ParameterTypeDescription
codestringThe lines typed so far.
Returns ​

Promise<boolean>

true if the code is incomplete.

Overrides ​

KernelBase.more

newWorker() ​
ts
protected newWorker(): Worker;

Create the kernel's worker, with the sandboxed: true option (an opaque origin worker). To be overridden.

Returns ​

Worker

The worker.

pendingInput() ​
ts
pendingInput(): boolean;

Is the running code waiting for an input?

Returns ​

boolean

Inherited from ​

KernelBase.pendingInput

postIFrameMessage() ​
ts
postIFrameMessage(key, message): void;

Relay a kernel iframe's message to the worker waiting for it (see waitIFrameMessage in the worker), e.g. the user's answer to a tkinter dialog: the worker can't read the iframe's port while it waits. Iframes may be untrusted: only keys made for them are accepted, and big messages are ignored.

Parameters ​
ParameterTypeDescription
keystringThe message's key.
messagestringThe message.
Returns ​

void

Overrides ​

KernelBase.postIFrameMessage

processWorkerMessage() ​
ts
protected processWorkerMessage(msg): Promise<void>;

Process a message of the worker: outputs, displays, inputs, downloads, validation logs, camera and audio requests...

Parameters ​
ParameterTypeDescription
msg{ content: any; data: any; type: string; }The message: its type, its content and the evaluation's data.
msg.contentany-
msg.dataany-
msg.typestring-
Returns ​

Promise<void>

ps1() ​
ts
ps1(): string;

The console's prompt for a new instruction.

Returns ​

string

Inherited from ​

KernelBase.ps1

ps2() ​
ts
ps2(): string;

The console's prompt for a continuation line (see more).

Returns ​

string

Inherited from ​

KernelBase.ps2

putFile() ​
ts
putFile(filename, content): Promise<void>;

Put a file in the worker's filesystem (see KernelBase.putFile).

Parameters ​
ParameterTypeDescription
filenamestringThe file's name.
contentArrayBufferThe file's content.
Returns ​

Promise<void>

Overrides ​

KernelBase.putFile

putModule() ​
ts
putModule(filename, content): Promise<void>;

Install a module in the worker (see KernelBase.putModule).

Parameters ​
ParameterTypeDescription
filenamestringThe module's file name.
contentArrayBufferThe module's content.
Returns ​

Promise<void>

Overrides ​

KernelBase.putModule

putRessource() ​
ts
putRessource(filename, content): Promise<void>;

Put a file as a module (putModule) if its extension is one of moduleExts, as an auxiliary file (putFile) otherwise.

Parameters ​
ParameterTypeDescription
filenamestringThe file's name.
contentArrayBufferThe file's content.
Returns ​

Promise<void>

Inherited from ​

KernelBase.putRessource

ready() ​
ts
ready(): Promise<void>;

Wait for the kernel to be ready (started).

Returns ​

Promise<void>

Throws ​

The error of the kernel's initialization or start.

Inherited from ​

KernelBase.ready

removeEventListener() ​
Call Signature ​
ts
removeEventListener<K>(eventName, callback): void;

Stop listening to an event of this kernel.

Type Parameters ​
Type Parameter
K extends keyof KernelEvents
Parameters ​
ParameterTypeDescription
eventNameKThe event's name.
callback(data) => voidThe callback given to addEventListener.
Returns ​

void

Inherited from ​

KernelBase.removeEventListener

Call Signature ​
ts
removeEventListener(eventName, callback): void;

Stop listening to an event of this kernel.

Parameters ​
ParameterTypeDescription
eventNamestringThe event's name.
callback(_) => voidThe callback given to addEventListener.
Returns ​

void

Inherited from ​

KernelBase.removeEventListener

resolvePendingInput() ​
ts
resolvePendingInput(): void;

Answer a pending input with an empty text.

Returns ​

void

Inherited from ​

KernelBase.resolvePendingInput

restart() ​
ts
restart(): Promise<void>;

Restart the kernel (stop then start): the user's variables are lost, the files and modules are kept.

Returns ​

Promise<void>

Inherited from ​

KernelBase.restart

safeKernel() ​
ts
safeKernel(): boolean;

Does the kernel run in an isolated worker (not legacy)?

Returns ​

boolean

Overrides ​

KernelBase.safeKernel

setRunningData() ​
ts
setRunningData(data): Promise<void>;

Set the running data (see KernelBase.setRunningData), also in the worker.

Parameters ​
ParameterTypeDescription
dataanyThe data to add.
Returns ​

Promise<void>

Overrides ​

KernelBase.setRunningData

setupWorker() ​
ts
protected setupWorker(): Promise<void>;

Create the worker (or import its code in legacy mode) and set up the comlink and message channels with it.

Returns ​

Promise<void>

start() ​
ts
start(): Promise<void>;

Start the kernel (after init or stop): reset the execution count and put the files and modules again.

Returns ​

Promise<void>

Inherited from ​

KernelBase.start

stop() ​
ts
stop(): void;

Stop the kernel: it is no longer ready once the call returns (the end of its stop is awaited by the next start).

Returns ​

void

Inherited from ​

KernelBase.stop

syncCommSupport() ​
ts
syncCommSupport(): boolean;

Can the worker wait synchronously for the main thread (the page is cross-origin isolated, so a SharedArrayBuffer is shared)? Otherwise, the ephemeral API is used.

Returns ​

boolean

userModules() ​
ts
userModules(): Promise<string[]>;

The modules installed by putModule.

Returns ​

Promise<string[]>

Their file names.

Inherited from ​

KernelBase.userModules

version() ​
ts
version(): string;

The kernel's version (Basthon's version, e.g. "0.87.0").

Returns ​

string

Inherited from ​

KernelBase.version

workerOptions() ​
ts
protected workerOptions(): any;

The options given to the worker's constructor (the kernel's options by default).

Returns ​

any


KernelWorkerBase ​

The worker side of a kernel: runs the user's code with the language's runtime and talks to the main thread (KernelMainBase) through comlink (calls such as eval) and a message port (outputs, displays, inputs, downloads...). Each language extends it (worker.ts of its package) and implements at least language, _eval, putFile, putModule and more.

In legacy mode, it runs in the main thread (same API).

Constructors ​

Constructor ​
ts
new KernelWorkerBase(options?): KernelWorkerBase;
Parameters ​
ParameterTypeDescription
options?anyThe kernel's options (see KernelMainBase.workerOptions): legacy runs in the main thread, the other ones are the language's.
Returns ​

KernelWorkerBase

Properties ​

PropertyModifierType
__eval_data__protectedany
_legacyprotected readonlyboolean
_optionsprotectedany
postMessage?protected{ (message, transfer): void; (message, options?): void; }

Methods ​

_eval() ​
ts
protected _eval(data, code): Promise<
  | {
[key: string]: string;
}
| undefined>;

Run code with the language's runtime. To be overridden.

Parameters ​
ParameterTypeDescription
dataanyThe evaluation's data.
codestringThe code to run.
Returns ​

Promise< | { [key: string]: string; } | undefined>

The result as a MIME bundle, or undefined if the code has no value.

Throws ​

The code's error (a KernelError already displayed if the kernel printed it).

_init() ​
ts
protected _init(): Promise<void>;

The kernel's own initialization (loading the runtime...), run once by init. To be overridden.

Returns ​

Promise<void>

addEvalPromise() ​
ts
protected addEvalPromise(promise): void;

Make the current evaluation wait for a promise before ending (e.g. a display that needs an asynchronous conversion).

Parameters ​
ParameterTypeDescription
promisePromise<void>The promise to wait for.
Returns ​

void

basthonRoot() ​
ts
basthonRoot(): string;

URL of the kernel's files: <assets>/<version>/<language>.

Returns ​

string

blobToDataURL() ​
ts
protected blobToDataURL(blob): Promise<string>;

Convert a blob to a data URL.

Parameters ​
ParameterTypeDescription
blobBlobThe blob.
Returns ​

Promise<string>

The data URL.

clearOutput() ​
ts
clearOutput(wait): void;

Clear the current output (an eval.clear-output event).

Parameters ​
ParameterTypeDescription
waitbooleanClear only when a new output arrives (no flickering).
Returns ​

void

clone() ​
ts
protected clone(data): any;

Copy a JSON-serializable object.

Parameters ​
ParameterTypeDescription
dataanyThe object.
Returns ​

any

Its copy.

complete() ​
ts
complete(code): Promise<[string[], number] | []>;

Completions of the code at its end.

Parameters ​
ParameterTypeDescription
codestringThe code before the cursor.
Returns ​

Promise<[string[], number] | []>

[completions, start], or [] if there is none.

createCanvas() ​
ts
createCanvas(width?, height?): OffscreenCanvas | HTMLCanvasElement;

Create a canvas (an OffscreenCanvas in a worker, an HTMLCanvasElement in legacy mode), live as soon as created so that event listeners can be set before it is displayed (see canvas/worker/live-canvas.ts).

Parameters ​
ParameterTypeDefault valueDescription
width?number0The canvas' width.
height?number0The canvas' height.
Returns ​

OffscreenCanvas | HTMLCanvasElement

The canvas.

display() ​
ts
display(element): void;

Display something in the frontend (an eval.display event): a canvas (as an image), a MIME bundle ({"text/html": ...}), or an HTML element in legacy mode.

Parameters ​
ParameterTypeDescription
elementanyWhat to display.
Returns ​

void

displayBlob() ​
ts
protected displayBlob(blob, data): Promise<void>;

Display a PNG image given as a blob (other types are ignored).

Parameters ​
ParameterTypeDescription
blobBlobThe image.
dataanyThe evaluation's data (the current one if null).
Returns ​

Promise<void>

displayCanvas() ​
ts
protected displayCanvas(canvas, data): Promise<void>;

Display a canvas as a still image (its current pixels).

Parameters ​
ParameterTypeDescription
canvasOffscreenCanvasThe canvas.
dataanyThe evaluation's data (the current one if null).
Returns ​

Promise<void>

displayKernelIFrame() ​
ts
displayKernelIFrame(iframeHTML, fallback?): MessagePort;

Display a kernel iframe: send its page and one end of a new message channel to the frontend, which renders the page in a sandboxed iframe and transfers the port to it.

The channel is a spare one, whose other end the main thread received while the worker was idle: Firefox (128 and 140 at least, not 158) holds the messages of a port transferred while the worker is busy (e.g. a figure updated by plt.pause in a loop) until the worker's task ends. A new channel is used when there is no spare one left.

Parameters ​
ParameterTypeDescription
iframeHTMLstringThe iframe's page.
fallback?Record<string, string>A MIME bundle displayed when the iframe can't be (e.g. a notebook opened from a file).
Returns ​

MessagePort

The kernel's end of the channel, to talk to the iframe.

displayLiveCanvas() ​
ts
protected displayLiveCanvas(canvas): Promise<void>;

Display a canvas in a canvas kernel iframe, where it is updated and receives the mouse and keyboard events (a PNG image of it is the fallback).

Parameters ​
ParameterTypeDescription
canvasOffscreenCanvas | HTMLCanvasElementThe canvas (see createCanvas).
Returns ​

Promise<void>

download() ​
ts
download(content, filename): void;

Download a file (the main thread only accepts bytes or a data URL).

Parameters ​
ParameterTypeDescription
contentstring | Uint8Array<ArrayBufferLike>The file's content.
filenamestringThe name of the saved file.
Returns ​

void

downloadSVGAsPNG() ​
ts
downloadSVGAsPNG(
   svg, 
   filename, 
   scale?
): void;

Download an SVG image as a PNG one, converted by the main thread (workers can't decode SVG images).

Parameters ​
ParameterTypeDefault valueDescription
svgstringundefinedThe SVG image.
filenamestringundefinedThe name of the saved file.
scale?number1The scale of the PNG image (1 for the SVG's size).
Returns ​

void

eval() ​
ts
eval(data, code): Promise<ExecuteResult>;

Run code (called by the main thread through comlink): _eval, then wait for the promises added during the evaluation.

Parameters ​
ParameterTypeDescription
dataanyThe evaluation's data (given to KernelBase.execute).
codestringThe code to run.
Returns ​

Promise<ExecuteResult>

The result or the error (also printed on stderr).

getRunningData() ​
ts
getRunningData(): any;

The running data (see setRunningData).

Returns ​

any

iframeMessageKey() ​
ts
iframeMessageKey(): string;

A new key for a message of a kernel iframe while the program waits for it (see waitIFrameMessage).

Returns ​

string

init() ​
ts
init(): Promise<void>;

Initialize the kernel (called by the main thread once the worker is set up).

Returns ​

Promise<void>

Throws ​

The initialization's error.

input() ​
ts
input(prompt, password?): string;

Ask the user for an input and wait for the answer (synchronously): through the shared buffer, the browser's prompt in legacy mode, or the ephemeral API.

Parameters ​
ParameterTypeDefault valueDescription
promptstring | null | undefinedundefinedThe text displayed before the input.
password?booleanfalseHide the typed text.
Returns ​

string

The answer.

Throws ​

InputInterruptedError if the input is interrupted, InputEOFError at the end of the input.

isLegacy() ​
ts
isLegacy(): boolean;

Does the worker run in the main thread (legacy kernel)?

Returns ​

boolean

language() ​
ts
language(): string;

The kernel's language, as used in URLs and file paths (lower case, e.g. "python3"). To be overridden.

Returns ​

string

legacyStart() ​
ts
legacyStart(): Promise<void>;

Start again a legacy kernel (its restart is lazy: the runtime is kept). To be overridden by the kernels with a legacy mode.

Returns ​

Promise<void>

legacyStop() ​
ts
legacyStop(): Promise<void>;

Stop a legacy kernel (see legacyStart).

Returns ​

Promise<void>

logValidation() ​
ts
logValidation(data): void;

Log a self-assessment validation (a validation.log event), with the current date if data has none.

Parameters ​
ParameterTypeDescription
dataanyThe validation's log.
Returns ​

void

more() ​
ts
more(code): Promise<boolean>;

Does the code need more lines to be complete (consoles then ask for a continuation line)? To be overridden.

Parameters ​
ParameterTypeDescription
codestringThe lines typed so far.
Returns ​

Promise<boolean>

true if the code is incomplete.

openAudio() ​
ts
openAudio(options?): MessagePort;

Ask the main thread to open an audio context, where the audio graph built in the worker is mirrored (see installWebAudio in audio/worker.ts).

Parameters ​
ParameterTypeDescription
options?AudioContextOptionsThe audio context's options.
Returns ​

MessagePort

The port of the mirroring.

openCamera() ​
ts
openCamera(constraints?): MessagePort;

Ask the main thread to open the camera (after the user's confirmation) (see CameraStream.open in camera/worker.ts).

Parameters ​
ParameterTypeDefault valueDescription
constraints?CameraConstraintstrueThe video constraints of getUserMedia.
Returns ​

MessagePort

The port where its frames are sent.

popDOMNode() ​
ts
popDOMNode(id): any;

Take an HTML element displayed in legacy mode (see display): the main thread gets it from its id.

Parameters ​
ParameterTypeDescription
idnumberThe element's id in the bus.
Returns ​

any

The element.

processMainThreadMessage() ​
ts
protected processMainThreadMessage(msg): Promise<void>;

Process a message of the main thread.

Parameters ​
ParameterTypeDescription
msg{ content: any; data: any; type: string; }The message (type and content).
msg.contentany-
msg.dataany-
msg.typestring-
Returns ​

Promise<void>

putFile() ​
ts
putFile(filename, content): void;

Put a file in the kernel's (virtual) filesystem, in its working directory. To be overridden.

Parameters ​
ParameterTypeDescription
filenamestringThe file's name.
contentArrayBufferThe file's content.
Returns ​

void

putModule() ​
ts
putModule(filename, content): void;

Install a module for the user's code (and load its dependencies). To be overridden.

Parameters ​
ParameterTypeDescription
filenamestringThe module's file name.
contentArrayBufferThe module's content.
Returns ​

void

ready() ​
ts
ready(): Promise<void>;

Wait for the kernel to be initialized.

Returns ​

Promise<void>

sendStderrStream() ​
ts
protected sendStderrStream(data, text): void;

Print text on stderr (an eval.output event).

Parameters ​
ParameterTypeDescription
dataanyThe evaluation's data.
textstringThe text.
Returns ​

void

sendStdoutStream() ​
ts
protected sendStdoutStream(data, text): void;

Print text on stdout (an eval.output event).

Parameters ​
ParameterTypeDescription
dataanyThe evaluation's data.
textstringThe text.
Returns ​

void

setCommPort() ​
ts
setCommPort(port): void;

Set the port of the messages exchanged with the main thread (outputs, displays, inputs...).

Parameters ​
ParameterTypeDescription
portMessagePortThe worker's end of the channel.
Returns ​

void

setEphemeralAPI() ​
ts
setEphemeralAPI(url): Promise<void>;

Set the URL of the ephemeral API.

Parameters ​
ParameterTypeDescription
urlstringThe URL.
Returns ​

Promise<void>

setFallbackKeyAndPass() ​
ts
setFallbackKeyAndPass(key, pass): Promise<void>;

Set the base key and the encryption key of the ephemeral API's answers (when SharedArrayBuffer is not available). Each input gets its own key (base key and a counter) so that a late answer can't reach a later input.

Parameters ​
ParameterTypeDescription
keystringThe base key (random, new at each start).
passUint8ArrayThe AES-GCM key (256 bits) the answers are encrypted with.
Returns ​

Promise<void>

setProxyPort() ​
ts
setProxyPort(port): void;

Set the port of the proxy worker that fetches Basthon's files for this opaque origin worker (see ProxyFetch).

Parameters ​
ParameterTypeDescription
portMessagePortA comlink endpoint of the proxy.
Returns ​

void

setRunningData() ​
ts
setRunningData(data): Promise<void>;

Set the running data (see KernelBase.setRunningData): replaced, not merged (the main thread merges them).

Parameters ​
ParameterTypeDescription
dataanyThe data.
Returns ​

Promise<void>

setSAB() ​
ts
setSAB(sab): void;

Set the buffer shared with the main thread for the synchronous communication (inputs, sleep): its first 4 bytes are a flag, the rest the answer.

Parameters ​
ParameterTypeDescription
sabSharedArrayBufferThe shared buffer.
Returns ​

void

sleep() ​
ts
sleep(duration): void;

Pause the program (an Atomics.wait with a shared buffer, an active wait otherwise).

Parameters ​
ParameterTypeDescription
durationnumberThe duration in seconds.
Returns ​

void

syncCommSupport() ​
ts
syncCommSupport(): boolean;

Can the worker wait synchronously for the main thread (a SharedArrayBuffer was given, see setSAB)? Otherwise, inputs go through the ephemeral API.

Returns ​

boolean

toplevelInput() ​
ts
toplevelInput(
   prompt, 
   password?, 
   data?
): Promise<string>;

Ask the user for an input and wait for the answer asynchronously (for the code run at the top level, which can be awaited: no synchronous communication needed).

Parameters ​
ParameterTypeDefault valueDescription
promptstring | null | undefinedundefinedThe text displayed before the input.
password?booleanfalseHide the typed text.
data?anyundefinedThe evaluation's data.
Returns ​

Promise<string>

The answer.

Throws ​

InputInterruptedError if the input is interrupted, InputEOFError at the end of the input.

version() ​
ts
version(): string;

The kernel's version (the same as the main thread's version()).

Returns ​

string

waitIFrameMessage() ​
ts
waitIFrameMessage(key): string | null;

Wait (synchronously) for the message that a kernel iframe posts with this key through the frontend (see KernelBase.postIFrameMessage): the iframe can't reach the worker while the program waits, e.g. for the answer of a tkinter dialog.

Parameters ​
ParameterTypeDescription
keystringThe message's key (see iframeMessageKey).
Returns ​

string | null

The message, or null when nothing came for a while (the caller waits again).

Throws ​

InputInterruptedError if the wait is interrupted.

Type Aliases ​

ExecuteResult ​

ts
type ExecuteResult = {
  data: any;
  error?: {
     name: string;
     traceback?: string;
     value: string;
  };
  result?: any;
  status: "ok" | "error";
};

Properties ​

data ​
ts
data: any;

error? ​
ts
error?: {
  name: string;
  traceback?: string;
  value: string;
};
name ​
ts
name: string;
traceback? ​
ts
traceback?: string;
value ​
ts
value: string;

result? ​
ts
result?: any;

status ​
ts
status: "ok" | "error";

Functions ​

expose() ​

ts
function expose(kwc): void;

Expose the kernel worker class to the main thread (see WorkerHost).

Parameters ​

ParameterTypeDescription
kwcanyThe kernel worker class.

Returns ​

void


loadScript() ​

ts
function loadScript(url): Promise<void>;

Load and run a (classic) script (see WorkerHost).

Parameters ​

ParameterTypeDescription
urlstringThe script's URL.

Returns ​

Promise<void>

References ​

DownloadError ​

Re-exports DownloadError


KernelError ​

Re-exports KernelError