Skip to content

kernel-base ​

The base of all Basthon kernels, used by the frontends: a kernel runs the user's code (in a worker, or in the main thread for the legacy Python kernel), receives its input and dispatches its outputs as events (see KernelBase).

Classes ​

DownloadError ​

A kernel's start failed because a file it needs could not be downloaded (e.g. the network cut the download). Its name survives the transfer from the worker (unlike instanceof): the frontends can test it to show a network problem rather than an outdated browser.

Extends ​

  • Error

Constructors ​

Constructor ​
ts
new DownloadError(message): DownloadError;
Parameters ​
ParameterTypeDescription
messagestringWhat could not be downloaded, and why.
Returns ​

DownloadError

Overrides ​

Error.constructor


KernelBase ​

The API of all Basthon's kernels, used by the frontends (console, notebook...). A kernel is created (usually by a KernelLoader), started with init, then runs code with execute and reports through events:

EventDispatched whenData (besides the request's data)
eval.outputthe code printsstream ("stdout" or "stderr"), content: the text
eval.displaythe code displays somethingdisplay_type and content (see below)
eval.clear-outputthe code clears its outputcontent.wait
eval.inputthe code waits for an inputcontent.prompt, content.password, resolve(answer)
eval.input-cancelthe kernel gave up waiting for an inputthe eval.input data
eval.finishedthe evaluation succeededexecution_count, result (a MIME bundle, if any)
eval.errorthe evaluation failedexecution_count, error (a KernelError)
validation.loga self-assessment validation ran (Python)the validation's log

The data of an eval.display event is either a MIME bundle (display_type "multiple", content maps MIME types such as "text/html" or "image/png" to their content) or a kernel iframe (display_type "kernel-iframe", content.html is the iframe's page and content.port the MessagePort to transfer to it, e.g. p5 sketches and interactive matplotlib figures).

Each kernel has its own events, so several kernels can run side by side: listen to them with addEventListener.

Extended by ​

Constructors ​

Constructor ​
ts
new KernelBase(options): KernelBase;
Parameters ​
ParameterTypeDescription
optionsKernelOptionsThe kernel's options (copied).
Returns ​

KernelBase

Properties ​

PropertyModifierTypeDefault valueDescription
_execution_countprotectednumber0-
_filesprotectedMap<string, ArrayBuffer>...-
_modulesprotectedMap<string, ArrayBuffer>...-
_optionsprotectedKernelOptionsundefined-
_pendingInput?protectedPromiseDelegate<InputAnswer>undefined-
_runningDataprotectedany{}-
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).
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.

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

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

Is the kernel started and ready to run code?

Returns ​

boolean

Methods ​

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

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

Returns ​

Promise<void>

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

The kernel's own start, run by start (to be overridden).

Returns ​

Promise<void>

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

The kernel's own (asynchronous) stop, run by stop (to be overridden).

Returns ​

Promise<void>

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

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

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

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

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

string

ts
banner(): string;

The message displayed by consoles at startup.

Returns ​

string

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

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

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

string

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

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

Copy a JSON-serializable object.

Parameters ​
ParameterTypeDescription
objanyThe object to copy.
Returns ​

any

Its copy.

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

Completions of the code at its end (e.g. the names starting with the last word).

Parameters ​
ParameterTypeDescription
codestringThe code before the cursor.
Returns ​

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

[completions, start]: the completions and the position in code where they start, or [] if there is none.

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

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

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

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

Run code (prefer execute, that dispatches the evaluation's events).

Parameters ​
ParameterTypeDefault valueDescription
codestringundefinedThe code to run.
outCallback(_) => voidundefinedCalled with the text printed on stdout.
errCallback(_) => voidundefinedCalled with the text printed on stderr.
data?anynullThe request's data, passed with the events dispatched during the evaluation.
Returns ​

Promise<any>

[result, executionCount]: the result (a MIME bundle, or undefined when the code has no value) and the execution count.

Throws ​

KernelError when the code fails.

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).

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.

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.

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).

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).

interruptPendingInput() ​
ts
interruptPendingInput(): void;

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

Returns ​

void

language() ​
ts
language(): string;

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

Returns ​

string

languageName() ​
ts
languageName(): string;

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

Returns ​

string

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

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

Returns ​

string[]

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

Does the code need more lines to be complete (e.g. after def f(): in Python)? Used by consoles to ask for continuation lines.

Parameters ​
ParameterTypeDescription
sourcestringThe lines typed so far.
Returns ​

Promise<boolean>

true if the code is incomplete.

pendingInput() ​
ts
pendingInput(): boolean;

Is the running code waiting for an input?

Returns ​

boolean

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

Relay a kernel iframe's message to the worker waiting for it (e.g. the answer to a tkinter dialog): frontends call it for the iframes' {type: "iframe-message", key, message} messages.

Parameters ​
ParameterTypeDescription
keystringThe key of the message, given by the worker.
messagestringThe message.
Returns ​

void

ps1() ​
ts
ps1(): string;

The console's prompt for a new instruction.

Returns ​

string

ps2() ​
ts
ps2(): string;

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

Returns ​

string

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

Put a file in the kernel's (virtual) filesystem, in its working directory (an auxiliary file). The file is put again after a restart.

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

Promise<void>

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

Install a module for the user's code (e.g. a Python module, importable with import). The module is installed again after a restart.

Parameters ​
ParameterTypeDescription
filenamestringThe module's file name (its extension is one of moduleExts).
contentArrayBufferThe module's content.
Returns ​

Promise<void>

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>

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.

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

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

resolvePendingInput() ​
ts
resolvePendingInput(): void;

Answer a pending input with an empty text.

Returns ​

void

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>

safeKernel() ​
ts
safeKernel(): boolean;

Does the kernel run in a worker (isolated kernel), isolated from the page?

Returns ​

boolean

false for the main thread's kernels (legacy kernel).

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

Data given to the running code, kept across restarts (e.g. the user's random seed in Capytale). Merged with the previous data.

Parameters ​
ParameterTypeDescription
dataanyThe data to add (a JSON-serializable object).
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>

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

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

The modules installed by putModule.

Returns ​

Promise<string[]>

Their file names.

version() ​
ts
version(): string;

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

Returns ​

string


KernelError ​

An error raised by the evaluation of code (e.g. a Python exception), given by the eval.error event. name, value and traceback follow Jupyter's ename, evalue and traceback.

Extends ​

  • Error

Constructors ​

Constructor ​
ts
new KernelError(
   name, 
   value, 
   traceback?, 
   displayed?
): KernelError;
Parameters ​
ParameterTypeDefault valueDescription
namestringundefinedThe error's type (e.g. "ZeroDivisionError").
valuestringundefinedThe error's message.
traceback?stringundefinedThe error's traceback.
displayed?booleanfalseWas the error already shown to the user?
Returns ​

KernelError

Overrides ​

Error.constructor

Properties ​

PropertyModifierTypeDescription
displayedpublicbooleanWas the error already shown to the user (typically on stderr)? It should not be displayed again.
traceback?public readonlystringThe error's traceback, if any.
valuepublic readonlystringThe error's message (e.g. "division by zero").

Interfaces ​

KernelEvents ​

The events of a kernel and their data (see KernelBase).

Properties ​

PropertyType
eval.clear-outputEvalData & { content: { wait: boolean; }; }
eval.displayEvalData & { content: any; display_type: string; }
eval.errorEvalData & { error: any; execution_count: number; }
eval.finishedEvalData & { execution_count: number; result?: any; }
eval.inputEvalData & { content: { password: boolean; prompt: string | null | undefined; }; reject: (reason?) => void; resolve: (answer) => void; }
eval.input-cancelEvalData & { content: { password: boolean; prompt: string | null | undefined; }; reject: (reason?) => void; resolve: (answer) => void; }
eval.outputEvalData & { content: string; stream: "stdout" | "stderr"; }
validation.logany

KernelOptions ​

Options given to a kernel's constructor, common to all the kernels (some kernels have their own ones, e.g. Python3KernelOptions).

Properties ​

PropertyTypeDescription
ephemeralAPI?stringURL of Basthon's ephemeral API, through which the input's answers go (encrypted) when SharedArrayBuffer is not available. Default: "https://api.basthon.fr/ephemeral".
legacy?booleanRun the kernel in the main thread instead of a worker (the legacy kernel, Python only). Default: false (isolated kernel).
rootPathstringURL of the assets directory, where the kernels' files are installed (e.g. "assets"): a kernel's files are in <rootPath>/<version>/<language>/ (see KernelBase.basthonRoot).

Type Aliases ​

EvalRequest ​

ts
type EvalRequest = EvalData & {
  code: string;
};

What KernelBase.execute takes: the code to run and the evaluation's data.

Type Declaration ​

NameType
codestring

InputAnswer ​

ts
type InputAnswer = string | null | typeof END_OF_INPUT;

The answer to an input: the text typed by the user, null if the input was interrupted (see KernelBase.interruptPendingInput) or END_OF_INPUT at the end of the input (see KernelBase.endPendingInput).

Variables ​

END_OF_INPUT ​

ts
const END_OF_INPUT: {
  eof: true;
};

The answer to an input at the end of the input, e.g. when the program's standard input is closed (see KernelBase.endPendingInput): the program gets an EOFError in Python, EOF in C.

Type Declaration ​

NameTypeDefault value
eoftruetrue

VERSION ​

ts
VERSION: any;