Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

chore: require explicit member accessibility (#11020)

Shahmir Varqha629919ab4365
diff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.json
index a42e9b30b0..c19b2bc8bb 100644
--- a/frontend/.oxlintrc.json
+++ b/frontend/.oxlintrc.json
@@ -66,7 +66,6 @@
"react/rule-suppression": "off",
"react/set-state-in-effect": "off",
"react/todo": "off",
- "typescript/explicit-member-accessibility": "off",
"vitest/no-standalone-expect": [
"error",
{ "additionalTestBlockFunctions": ["beforeEach"] }
diff --git a/frontend/src/__mocks__/common.ts b/frontend/src/__mocks__/common.ts
index c56d82871a..6f9d28d3d7 100644
--- a/frontend/src/__mocks__/common.ts
+++ b/frontend/src/__mocks__/common.ts
@@ -101,9 +101,9 @@ export const SetupMocks = {
const unobserve = vi.fn();
const disconnect = vi.fn();
global.ResizeObserver = class MockResizeObserver {
- observe = observe;
- unobserve = unobserve;
- disconnect = disconnect;
+ public observe = observe;
+ public unobserve = unobserve;
+ public disconnect = disconnect;
} as unknown as typeof ResizeObserver;
return { observe, unobserve, disconnect };
},
diff --git a/frontend/src/__tests__/CellStatus.test.tsx b/frontend/src/__tests__/CellStatus.test.tsx
index bdf8e8b8e7..1f510e9929 100644
--- a/frontend/src/__tests__/CellStatus.test.tsx
+++ b/frontend/src/__tests__/CellStatus.test.tsx
@@ -57,7 +57,7 @@ describe("CellStatusComponent", () => {
beforeEach(() => {
global.Date = class extends Date {
- static override now() {
+ public static override now() {
return mockDate.getTime();
}
} as typeof Date;
diff --git a/frontend/src/__tests__/setup.ts b/frontend/src/__tests__/setup.ts
index 4dce4f9ece..98179c69e0 100644
--- a/frontend/src/__tests__/setup.ts
+++ b/frontend/src/__tests__/setup.ts
@@ -9,29 +9,29 @@ import "blob-polyfill";
// if we need to test ResizeObserver functionality
// we can use a library like "resize-observer-polyfill"
globalThis.ResizeObserver ??= class {
- observe(_target: Element) {
+ public observe(_target: Element) {
/* noop */
}
- unobserve(_target: Element) {
+ public unobserve(_target: Element) {
/* noop */
}
- disconnect() {
+ public disconnect() {
/* noop */
}
} as never;
// mock implementation because jsdom doesn't support IntersectionObserver
globalThis.IntersectionObserver ??= class {
- observe(_target: Element) {
+ public observe(_target: Element) {
/* noop */
}
- unobserve(_target: Element) {
+ public unobserve(_target: Element) {
/* noop */
}
- disconnect() {
+ public disconnect() {
/* noop */
}
- takeRecords() {
+ public takeRecords() {
return [];
}
} as never;
diff --git a/frontend/src/components/data-table/column-summary/chart-spec-model.tsx b/frontend/src/components/data-table/column-summary/chart-spec-model.tsx
index b590dad59d..452d8a1db5 100644
--- a/frontend/src/components/data-table/column-summary/chart-spec-model.tsx
+++ b/frontend/src/components/data-table/column-summary/chart-spec-model.tsx
@@ -137,14 +137,14 @@ export class ColumnChartSpecModel<T> {
private legacySourceName: "data_0" | "source_0";
private readonly fieldTypes: FieldTypes;
- readonly stats: Record<ColumnName, Partial<ColumnHeaderStats>>;
- readonly binValues: Record<ColumnName, BinValues>;
- readonly valueCounts: Record<ColumnName, ValueCounts>;
+ public readonly stats: Record<ColumnName, Partial<ColumnHeaderStats>>;
+ public readonly binValues: Record<ColumnName, BinValues>;
+ public readonly valueCounts: Record<ColumnName, ValueCounts>;
private readonly opts: {
includeCharts: boolean;
};
- constructor(
+ public constructor(
data: T[] | string,
fieldTypes: FieldTypes,
stats: Record<ColumnName, Partial<ColumnHeaderStats>>,
diff --git a/frontend/src/components/dependency-graph/elements.ts b/frontend/src/components/dependency-graph/elements.ts
index fda8261f9e..abf457317b 100644
--- a/frontend/src/components/dependency-graph/elements.ts
+++ b/frontend/src/components/dependency-graph/elements.ts
@@ -225,7 +225,7 @@ export class VerticalElementsBuilder implements ElementsBuilder {
};
}
- createElements(
+ public createElements(
cellIds: CellId[],
cellAtoms: Atom<CellData>[],
variables: Variables,
@@ -311,7 +311,7 @@ export class TreeElementsBuilder implements ElementsBuilder {
};
}
- createElements(
+ public createElements(
cellIds: CellId[],
cellAtoms: Atom<CellData>[],
variables: Variables,
diff --git a/frontend/src/components/editor/ai/staged-cell-submission.ts b/frontend/src/components/editor/ai/staged-cell-submission.ts
index 381d42b14e..7369cad68f 100644
--- a/frontend/src/components/editor/ai/staged-cell-submission.ts
+++ b/frontend/src/components/editor/ai/staged-cell-submission.ts
@@ -14,13 +14,13 @@ interface SubmissionAttempt {
export class StagedCellSubmissionController {
private activeAttempt: SubmissionAttempt | null = null;
- cancel() {
+ public cancel() {
if (this.activeAttempt) {
this.activeAttempt.cancelled = true;
}
}
- async run<T>({ prepare, submit, onError }: SubmissionCallbacks<T>) {
+ public async run<T>({ prepare, submit, onError }: SubmissionCallbacks<T>) {
if (this.activeAttempt !== null) {
return;
}
diff --git a/frontend/src/components/editor/ai/transport/chat-transport.tsx b/frontend/src/components/editor/ai/transport/chat-transport.tsx
index 4862494408..91122f94ec 100644
--- a/frontend/src/components/editor/ai/transport/chat-transport.tsx
+++ b/frontend/src/components/editor/ai/transport/chat-transport.tsx
@@ -15,7 +15,7 @@ export class StreamingChunkTransport<
> extends DefaultChatTransport<UI_MESSAGE> {
private onChunkReceived: (chunk: UIMessageChunk) => void;
- constructor(
+ public constructor(
options: HttpChatTransportInitOptions<UI_MESSAGE>,
onChunkReceived: (chunk: UIMessageChunk) => void,
) {
diff --git a/frontend/src/components/editor/connections/database/as-code.ts b/frontend/src/components/editor/connections/database/as-code.ts
index f136a28f23..dab7decdea 100644
--- a/frontend/src/components/editor/connections/database/as-code.ts
+++ b/frontend/src/components/editor/connections/database/as-code.ts
@@ -36,7 +36,7 @@ abstract class CodeGenerator<T extends DatabaseConnection["type"]> {
protected orm: ConnectionLibrary;
protected secrets: SecretContainer;
- constructor(
+ public constructor(
connection: Extract<DatabaseConnection, { type: T }>,
orm: ConnectionLibrary,
secrets: SecretContainer,
@@ -46,7 +46,7 @@ abstract class CodeGenerator<T extends DatabaseConnection["type"]> {
this.secrets = secrets;
}
- get imports(): Set<string> {
+ public get imports(): Set<string> {
const imports = new Set<string>(this.generateImports());
switch (this.orm) {
case "sqlalchemy":
@@ -67,7 +67,7 @@ abstract class CodeGenerator<T extends DatabaseConnection["type"]> {
protected abstract generateImports(): string[];
- abstract generateConnectionCode(): string;
+ public abstract generateConnectionCode(): string;
}
const makePrivate = (name: string) => `_${name}`;
@@ -75,14 +75,14 @@ const makePrivate = (name: string) => `_${name}`;
class SecretContainer {
private secrets: Record<string, string> = {};
- get imports(): Set<string> {
+ public get imports(): Set<string> {
if (Object.keys(this.secrets).length === 0) {
return new Set<string>();
}
return new Set<string>(["import os"]);
}
- print(
+ public print(
varName: string,
secretKeyOrValue: string | number | boolean,
defaultValue?: string | undefined,
@@ -119,7 +119,7 @@ class SecretContainer {
return `"${secretKeyOrValue}"`;
}
- printInFString(
+ public printInFString(
varName: string,
secretKeyOrValue: string | number | undefined | boolean,
defaultValue?: string | undefined,
@@ -171,7 +171,7 @@ class SecretContainer {
* f"db://sample:[email protected]"
* ```
*/
- printPassword(
+ public printPassword(
password: string | undefined,
passwordPlaceholder: string,
inFString: boolean,
@@ -187,11 +187,11 @@ class SecretContainer {
: printMethod(variableName || "password", passwordPlaceholder, password);
}
- getSecrets(): Record<string, string> {
+ public getSecrets(): Record<string, string> {
return this.secrets;
}
- formatSecrets(): string {
+ public formatSecrets(): string {
if (Object.keys(this.secrets).length === 0) {
return "";
}
@@ -203,11 +203,11 @@ class SecretContainer {
}
class PostgresGenerator extends CodeGenerator<"postgres"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return [];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const ssl = this.connection.ssl
? ", connect_args={'sslmode': 'require'}"
: "";
@@ -235,11 +235,11 @@ class PostgresGenerator extends CodeGenerator<"postgres"> {
}
class MySQLGenerator extends CodeGenerator<"mysql"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return [];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const ssl = this.connection.ssl
? ", connect_args={'ssl': {'ssl-mode': 'preferred'}}"
: "";
@@ -267,11 +267,11 @@ class MySQLGenerator extends CodeGenerator<"mysql"> {
}
class SQLiteGenerator extends CodeGenerator<"sqlite"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return [];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const database = this.connection.database
? this.secrets.printInFString("database", this.connection.database)
: "";
@@ -289,11 +289,11 @@ class SQLiteGenerator extends CodeGenerator<"sqlite"> {
}
class SnowflakeGenerator extends CodeGenerator<"snowflake"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return ["from snowflake.sqlalchemy import URL"];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const { authType, account, database, warehouse, schema, role } =
this.connection;
const baseParams: Record<string, string | undefined> = {
@@ -422,11 +422,11 @@ class BigQueryGenerator extends CodeGenerator<"bigquery"> {
);
}
- generateImports(): string[] {
+ public generateImports(): string[] {
return this.credential.kind === "path" ? [] : ["import json"];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const project = this.secrets.printInFString(
"project",
this.connection.project,
@@ -451,11 +451,11 @@ class BigQueryGenerator extends CodeGenerator<"bigquery"> {
}
class DuckDBGenerator extends CodeGenerator<"duckdb"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return [];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const database = this.secrets.printInFString(
"database",
this.connection.database || ":memory:",
@@ -469,11 +469,11 @@ class DuckDBGenerator extends CodeGenerator<"duckdb"> {
}
class MotherDuckGenerator extends CodeGenerator<"motherduck"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return [];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const database = this.secrets.printInFString(
"database",
this.connection.database,
@@ -497,11 +497,11 @@ class MotherDuckGenerator extends CodeGenerator<"motherduck"> {
}
class ClickHouseGenerator extends CodeGenerator<"clickhouse_connect"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return ["import clickhouse_connect"];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const password = this.secrets.printPassword(
this.connection.password,
"CLICKHOUSE_PASSWORD",
@@ -530,11 +530,11 @@ ${formatUrlParams(params, (inner) => ` ${inner}`)},
}
class TimeplusGenerator extends CodeGenerator<"timeplus"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return [];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const password = this.secrets.printPassword(
this.connection.password,
"TIMEPLUS_PASSWORD",
@@ -555,11 +555,11 @@ class TimeplusGenerator extends CodeGenerator<"timeplus"> {
}
class ChDBGenerator extends CodeGenerator<"chdb"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return ["import chdb"];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const database =
this.secrets.print("database", this.connection.database) || '""';
@@ -570,13 +570,13 @@ class ChDBGenerator extends CodeGenerator<"chdb"> {
}
class TrinoGenerator extends CodeGenerator<"trino"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return this.connection.async_support
? ["import aiotrino"]
: ["import trino.sqlalchemy"];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const trinoExtension = this.connection.async_support ? "aiotrino" : "trino";
const schema = this.connection.schema ? `/${this.connection.schema}` : "";
@@ -614,7 +614,7 @@ class PyIcebergGenerator extends CodeGenerator<"iceberg"> {
);
}
- generateImports(): string[] {
+ public generateImports(): string[] {
if (Object.keys(this.getCatalogOptions()).length === 0) {
return ["from pyiceberg.catalog import load_catalog"];
}
@@ -635,7 +635,7 @@ class PyIcebergGenerator extends CodeGenerator<"iceberg"> {
}
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const name = `"${this.connection.name}"`;
const options = this.getCatalogOptions();
if (Object.keys(options).length === 0) {
@@ -705,12 +705,12 @@ class PyIcebergGenerator extends CodeGenerator<"iceberg"> {
}
class DataFusionGenerator extends CodeGenerator<"datafusion"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
// To trigger installation of ibis-datafusion
return ["from datafusion import SessionContext"];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
if (this.connection.sessionContext) {
return dedent(`
ctx = SessionContext()
@@ -727,11 +727,11 @@ class DataFusionGenerator extends CodeGenerator<"datafusion"> {
}
class PySparkGenerator extends CodeGenerator<"pyspark"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return ["from pyspark.sql import SparkSession"];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
if (this.connection.host || this.connection.port) {
const host = this.secrets.printInFString("host", this.connection.host);
const port = this.secrets.printInFString("port", this.connection.port);
@@ -747,11 +747,11 @@ class PySparkGenerator extends CodeGenerator<"pyspark"> {
}
class RedshiftGenerator extends CodeGenerator<"redshift"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return ["import redshift_connector"];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const host = this.secrets.print("host", this.connection.host);
const port = this.secrets.print("port", this.connection.port);
const database = this.secrets.print("database", this.connection.database);
@@ -819,11 +819,11 @@ ${formatUrlParams(params, (inner) => ` ${inner}`)},
}
class DatabricksGenerator extends CodeGenerator<"databricks"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
return [];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const useFString = this.orm !== "ibis";
const accessToken = this.secrets.printPassword(
@@ -883,14 +883,14 @@ class DatabricksGenerator extends CodeGenerator<"databricks"> {
}
class SupabaseGenerator extends CodeGenerator<"supabase"> {
- generateImports(): string[] {
+ public generateImports(): string[] {
if (this.connection.disable_client_pooling) {
return ["from sqlalchemy.pool import NullPool"];
}
return [];
}
- generateConnectionCode(): string {
+ public generateConnectionCode(): string {
const password = this.secrets.printPassword(
this.connection.password,
"SUPABASE_PASSWORD",
@@ -921,7 +921,7 @@ class SupabaseGenerator extends CodeGenerator<"supabase"> {
class CodeGeneratorFactory {
public secrets = new SecretContainer();
- createGenerator(
+ public createGenerator(
connection: DatabaseConnection,
orm: ConnectionLibrary,
): CodeGenerator<DatabaseConnection["type"]> {
diff --git a/frontend/src/components/editor/connections/storage/as-code.ts b/frontend/src/components/editor/connections/storage/as-code.ts
index 82f6d7caf2..f596a861f5 100644
--- a/frontend/src/components/editor/connections/storage/as-code.ts
+++ b/frontend/src/components/editor/connections/storage/as-code.ts
@@ -26,14 +26,14 @@ export const StorageLibraryDisplayNames: Record<StorageLibrary, string> = {
class SecretContainer {
private secrets: Record<string, string> = {};
- get imports(): Set<string> {
+ public get imports(): Set<string> {
if (Object.keys(this.secrets).length === 0) {
return new Set<string>();
}
return new Set<string>(["import os"]);
}
- print(varName: string, value: string | undefined): string {
+ public print(varName: string, value: string | undefined): string {
if (value === undefined || value === "") {
return "";
}
@@ -46,7 +46,7 @@ class SecretContainer {
return `"${escapePythonString(value)}"`;
}
- formatSecrets(): string {
+ public formatSecrets(): string {
if (Object.keys(this.secrets).length === 0) {
return "";
}
diff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsx
index 3d53062ebb..96f1a1e933 100644
--- a/frontend/src/components/editor/file-tree/requesting-tree.tsx
+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx
@@ -55,7 +55,7 @@ export class RequestingTree {
renameFileOrFolder: EditRequests["sendRenameFileOrFolder"];
};
- constructor(callbacks: {
+ public constructor(callbacks: {
getRoots: EditRequests["getFileRoots"];
listFiles: EditRequests["sendListFiles"];
createFileOrFolder: EditRequests["sendCreateFileOrFolder"];
@@ -71,7 +71,7 @@ export class RequestingTree {
private onChange: (data: FileTreeNode[]) => void = Functions.NOOP;
private path = new PathBuilder("/");
- initialize = async (
+ public initialize = async (
onChange: (data: FileTreeNode[]) => void,
): Promise<void> => {
this.onChange = onChange;
@@ -102,7 +102,7 @@ export class RequestingTree {
this.emitChange();
};
- expand(id: string): Promise<boolean> {
+ public expand(id: string): Promise<boolean> {
return this.requestDirectory(id);
}
@@ -149,11 +149,11 @@ export class RequestingTree {
}
}
- getRoots(): readonly FileRoot[] {
+ public getRoots(): readonly FileRoot[] {
return this.roots;
}
- async reveal(node: FileTreeNode): Promise<boolean> {
+ public async reveal(node: FileTreeNode): Promise<boolean> {
const relative = relativePath(node.path as FilePath, node.rootPath);
if (relative === null) {
return false;
@@ -190,7 +190,7 @@ export class RequestingTree {
return true;
}
- async copy(id: string, newName: string): Promise<void> {
+ public async copy(id: string, newName: string): Promise<void> {
const node = this.getMutableNode(id);
if (!node) {
return;
@@ -206,7 +206,7 @@ export class RequestingTree {
}
}
- async rename(id: string, name: string): Promise<void> {
+ public async rename(id: string, name: string): Promise<void> {
const node = this.getMutableNode(id);
if (!node) {
return;
@@ -222,7 +222,7 @@ export class RequestingTree {
}
}
- async move(fromIds: string[], parentId: string | null): Promise<void> {
+ public async move(fromIds: string[], parentId: string | null): Promise<void> {
const targetParentId = parentId ?? this.getPrimaryRootId();
const parent = this.delegate.find(targetParentId);
if (!parent?.data.isDirectory) {
@@ -253,7 +253,7 @@ export class RequestingTree {
await this.refreshPaths([...refreshPaths]);
}
- async createFile({
+ public async createFile({
name,
parentId,
type = "file",
@@ -278,7 +278,10 @@ export class RequestingTree {
}
}
- async createFolder(name: string, parentId: string | null): Promise<void> {
+ public async createFolder(
+ name: string,
+ parentId: string | null,
+ ): Promise<void> {
const parent = this.getParentNode(parentId);
if (!parent) {
return;
@@ -295,7 +298,7 @@ export class RequestingTree {
}
}
- async delete(id: string): Promise<void> {
+ public async delete(id: string): Promise<void> {
const node = this.getMutableNode(id);
if (!node) {
return;
@@ -309,7 +312,7 @@ export class RequestingTree {
}
}
- refreshAll = async (ids: string[]): Promise<void> => {
+ public refreshAll = async (ids: string[]): Promise<void> => {
const paths = [
...this.roots.map((root) => root.path),
...ids
@@ -325,7 +328,7 @@ export class RequestingTree {
);
};
- refreshPath = async (path: FilePath): Promise<void> => {
+ public refreshPath = async (path: FilePath): Promise<void> => {
await this.refreshPaths([path]);
};
diff --git a/frontend/src/components/editor/navigation/clipboard.ts b/frontend/src/components/editor/navigation/clipboard.ts
index 5e890dcda4..79aa1f58b8 100644
--- a/frontend/src/components/editor/navigation/clipboard.ts
+++ b/frontend/src/components/editor/navigation/clipboard.ts
@@ -257,7 +257,7 @@ const toastPasteFailed = () => {
class ClipboardItemBuilder {
private items: Record<string, string | Blob> = {};
- add(mimeType: string, value: string | object) {
+ public add(mimeType: string, value: string | object) {
// Skip if the browser doesn't support the mime type
if (!ClipboardItem.supports(mimeType)) {
Logger.warn(`ClipboardItem does not support ${mimeType}`);
@@ -275,7 +275,7 @@ class ClipboardItemBuilder {
return this;
}
- build() {
+ public build() {
return new ClipboardItem(this.items);
}
}
diff --git a/frontend/src/components/editor/output/ansi-reduce.ts b/frontend/src/components/editor/output/ansi-reduce.ts
index 76f6a4a448..5423a66c02 100644
--- a/frontend/src/components/editor/output/ansi-reduce.ts
+++ b/frontend/src/components/editor/output/ansi-reduce.ts
@@ -42,7 +42,7 @@ export class TerminalBuffer {
}
/** Write a visible character at the current cursor position. */
- writeChar(ch: string) {
+ public writeChar(ch: string) {
this.ensureLine(this.cursor.row);
const line = this.lines[this.cursor.row];
const padded = line.padEnd(this.cursor.col, " ");
@@ -52,7 +52,7 @@ export class TerminalBuffer {
}
/** Write a string of visible characters at the current cursor position (optimized batch write). */
- writeString(str: string) {
+ public writeString(str: string) {
if (str.length === 0) {
return;
}
@@ -67,7 +67,7 @@ export class TerminalBuffer {
}
/** Handle simple control characters (\n, \r, \t, \b, \v). */
- control(ch: string) {
+ public control(ch: string) {
switch (ch) {
case "\n":
this.cursor.row++;
@@ -95,7 +95,7 @@ export class TerminalBuffer {
* Supports cursor movement and line erasing.
* For other sequences (like color codes), preserve them by writing to the buffer.
*/
- handleEscape(seq: string) {
+ public handleEscape(seq: string) {
const match = TerminalBuffer.ESCAPE_REGEX.exec(seq);
if (!match) {
// If it doesn't match the cursor movement pattern, it might be:
@@ -172,7 +172,7 @@ export class TerminalBuffer {
}
/** Return the final rendered buffer as a single string. */
- render(): string {
+ public render(): string {
return this.lines.join("\n");
}
}
@@ -187,7 +187,7 @@ export class AnsiParser {
"gu",
);
- parse(input: string): { type: "text" | "escape"; value: string }[] {
+ public parse(input: string): { type: "text" | "escape"; value: string }[] {
const tokens: { type: "text" | "escape"; value: string }[] = [];
let lastIndex = 0;
@@ -221,7 +221,7 @@ export class AnsiReducer {
* Process the entire input string (replaces any previous state).
* Use this for one-time processing or when starting fresh.
*/
- reduce(input: string): string {
+ public reduce(input: string): string {
this.reset();
this.append(input);
return this.render();
@@ -231,7 +231,7 @@ export class AnsiReducer {
* Append new input to the existing buffer (for streaming/incremental updates).
* This is efficient for streaming scenarios - only processes the new chunk.
*/
- append(input: string): void {
+ public append(input: string): void {
const tokens = this.parser.parse(input);
// Fast path: if only one text token (no ANSI codes), handle directly
@@ -260,14 +260,14 @@ export class AnsiReducer {
* Reset the buffer and cursor to initial state.
* Use this when you want to start processing fresh input.
*/
- reset(): void {
+ public reset(): void {
this.buffer = new TerminalBuffer();
}
/**
* Get the current rendered output without processing new input.
*/
- render(): string {
+ public render(): string {
return this.buffer.render();
}
@@ -375,7 +375,7 @@ export class StatefulOutputMessage implements OutputMessage {
return this._data;
}
- static create(message: StringOutputMessage): StatefulOutputMessage {
+ public static create(message: StringOutputMessage): StatefulOutputMessage {
const ansiReducer = new AnsiReducer();
ansiReducer.append(message.data);
return new StatefulOutputMessage(
@@ -399,7 +399,7 @@ export class StatefulOutputMessage implements OutputMessage {
this._data = this.ansiReducer.render();
}
- appendData(chunk: string): StatefulOutputMessage {
+ public appendData(chunk: string): StatefulOutputMessage {
this.ansiReducer.append(chunk);
return new StatefulOutputMessage(
this.mimetype,
@@ -409,7 +409,7 @@ export class StatefulOutputMessage implements OutputMessage {
);
}
- toJSON(): StringOutputMessage {
+ public toJSON(): StringOutputMessage {
return {
mimetype: this.mimetype,
channel: this.channel,
diff --git a/frontend/src/components/slides/__tests__/minimap-actions.test.tsx b/frontend/src/components/slides/__tests__/minimap-actions.test.tsx
index 1790b33394..803eead566 100644
--- a/frontend/src/components/slides/__tests__/minimap-actions.test.tsx
+++ b/frontend/src/components/slides/__tests__/minimap-actions.test.tsx
@@ -46,21 +46,21 @@ beforeAll(() => {
};
}
global.IntersectionObserver ??= class {
- observe() {
+ public observe() {
/* noop */
}
- unobserve() {
+ public unobserve() {
/* noop */
}
- disconnect() {
+ public disconnect() {
/* noop */
}
- takeRecords() {
+ public takeRecords() {
return [];
}
- root = null;
- rootMargin = "";
- thresholds = [];
+ public root = null;
+ public rootMargin = "";
+ public thresholds = [];
} as unknown as typeof IntersectionObserver;
});
diff --git a/frontend/src/components/slides/__tests__/minimap.test.ts b/frontend/src/components/slides/__tests__/minimap.test.ts
index 0c96297f3a..60d5a60947 100644
--- a/frontend/src/components/slides/__tests__/minimap.test.ts
+++ b/frontend/src/components/slides/__tests__/minimap.test.ts
@@ -42,28 +42,28 @@ describe("useVisibleCellIds", () => {
mutationObserveSpy = vi.fn();
global.IntersectionObserver = class MockIntersectionObserver {
- constructor(
+ public constructor(
callback: IntersectionObserverCallback,
_options?: IntersectionObserverInit,
) {
intersectionCallback = callback;
}
- observe = observeSpy;
- unobserve = vi.fn();
- disconnect = intersectionDisconnectSpy;
- root = null;
- rootMargin = "";
- thresholds = [0];
- takeRecords = vi.fn(() => []);
+ public observe = observeSpy;
+ public unobserve = vi.fn();
+ public disconnect = intersectionDisconnectSpy;
+ public root = null;
+ public rootMargin = "";
+ public thresholds = [0];
+ public takeRecords = vi.fn(() => []);
} as unknown as typeof IntersectionObserver;
global.MutationObserver = class MockMutationObserver {
- constructor(callback: MutationCallback) {
+ public constructor(callback: MutationCallback) {
mutationCallback = callback;
}
- observe = mutationObserveSpy;
- disconnect = mutationDisconnectSpy;
- takeRecords = vi.fn(() => []);
+ public observe = mutationObserveSpy;
+ public disconnect = mutationDisconnectSpy;
+ public takeRecords = vi.fn(() => []);
} as unknown as typeof MutationObserver;
});
diff --git a/frontend/src/components/slides/__tests__/slide-scroll-hint.test.tsx b/frontend/src/components/slides/__tests__/slide-scroll-hint.test.tsx
index bc47a3be4f..4eaac6cdd6 100644
--- a/frontend/src/components/slides/__tests__/slide-scroll-hint.test.tsx
+++ b/frontend/src/components/slides/__tests__/slide-scroll-hint.test.tsx
@@ -76,12 +76,12 @@ describe("SlideScrollContainer", () => {
vi.stubGlobal(
"ResizeObserver",
class MockResizeObserver {
- callback: ResizeObserverCallback;
- observe = vi.fn();
- unobserve = vi.fn();
- disconnect = vi.fn();
+ public callback: ResizeObserverCallback;
+ public observe = vi.fn();
+ public unobserve = vi.fn();
+ public disconnect = vi.fn();
- constructor(callback: ResizeObserverCallback) {
+ public constructor(callback: ResizeObserverCallback) {
this.callback = callback;
resizeObservers.push(this);
}
@@ -90,9 +90,9 @@ describe("SlideScrollContainer", () => {
vi.stubGlobal(
"MutationObserver",
class MockMutationObserver {
- observe = vi.fn();
- disconnect = vi.fn();
- takeRecords = vi.fn(() => []);
+ public observe = vi.fn();
+ public disconnect = vi.fn();
+ public takeRecords = vi.fn(() => []);
},
);
});
diff --git a/frontend/src/core/ai/context/__tests__/registry.test.ts b/frontend/src/core/ai/context/__tests__/registry.test.ts
index 0c125a4fe1..9d57d6e13f 100644
--- a/frontend/src/core/ai/context/__tests__/registry.test.ts
+++ b/frontend/src/core/ai/context/__tests__/registry.test.ts
@@ -44,9 +44,9 @@ const mockAttachment2: FileUIPart = {
// Concrete implementation of AIContextProvider for testing
class MockContextProvider extends AIContextProvider<MockContextItem> {
- readonly title = "Mock Items";
- readonly mentionPrefix = "@";
- readonly contextType = "mock";
+ public readonly title = "Mock Items";
+ public readonly mentionPrefix = "@";
+ public readonly contextType = "mock";
private items: MockContextItem[] = [
{
@@ -72,57 +72,60 @@ class MockContextProvider extends AIContextProvider<MockContextItem> {
},
];
- getItems(): MockContextItem[] {
+ public getItems(): MockContextItem[] {
return this.items;
}
- formatContext(item: MockContextItem): string {
+ public formatContext(item: MockContextItem): string {
return `Mock: ${item.name} (${item.data.value})`;
}
- formatCompletion(item: MockContextItem): Completion {
+ public formatCompletion(item: MockContextItem): Completion {
return this.createBasicCompletion(item);
}
// Method to add items for testing
- addItem(item: MockContextItem): void {
+ public addItem(item: MockContextItem): void {
this.items.push(item);
}
// Method to clear items for testing
- clearItems(): void {
+ public clearItems(): void {
this.items = [];
}
}
// Test provider that supports attachments
class AttachmentContextProvider extends AIContextProvider<MockContextItem> {
- readonly title = "Attachment Items";
- readonly mentionPrefix = "@";
- readonly contextType = "attachment";
+ public readonly title = "Attachment Items";
+ public readonly mentionPrefix = "@";
+ public readonly contextType = "attachment";
private items: MockContextItem[];
private attachments: FileUIPart[];
- constructor(items: MockContextItem[] = [], attachments: FileUIPart[] = []) {
+ public constructor(
+ items: MockContextItem[] = [],
+ attachments: FileUIPart[] = [],
+ ) {
super();
this.items = items;
this.attachments = attachments;
}
- getItems(): MockContextItem[] {
+ public getItems(): MockContextItem[] {
return this.items;
}
- formatContext(item: MockContextItem): string {
+ public formatContext(item: MockContextItem): string {
return `Attachment: ${item.name} (${item.data.value})`;
}
- formatCompletion(item: MockContextItem): Completion {
+ public formatCompletion(item: MockContextItem): Completion {
return this.createBasicCompletion(item);
}
- override async getAttachments(
+ public override async getAttachments(
items: MockContextItem[],
): Promise<FileUIPart[]> {
// Return attachments for items that need them
@@ -142,9 +145,9 @@ interface FileContextItem extends AIContextItem {
// Another mock provider with different prefix and type
class FileContextProvider extends AIContextProvider<FileContextItem> {
- readonly title = "Files";
- readonly mentionPrefix = "@";
- readonly contextType = "file";
+ public readonly title = "Files";
+ public readonly mentionPrefix = "@";
+ public readonly contextType = "file";
private items: FileContextItem[] = [
{
@@ -163,26 +166,26 @@ class FileContextProvider extends AIContextProvider<FileContextItem> {
},
];
- getItems(): FileContextItem[] {
+ public getItems(): FileContextItem[] {
return this.items;
}
- formatCompletion(item: FileContextItem): Completion {
+ public formatCompletion(item: FileContextItem): Completion {
return this.createBasicCompletion(item);
}
- formatContext(item: FileContextItem): string {
+ public formatContext(item: FileContextItem): string {
return `File: ${item.uri}\nDescription: ${item.description}`;
}
}
// Second mock provider with the same context type as MockContextProvider
class SecondaryMockProvider extends AIContextProvider<MockContextItem> {
- readonly title = "Secondary Mock Items";
- readonly mentionPrefix = "@";
- readonly contextType = "mock";
+ public readonly title = "Secondary Mock Items";
+ public readonly mentionPrefix = "@";
+ public readonly contextType = "mock";
- getItems(): MockContextItem[] {
+ public getItems(): MockContextItem[] {
return [
{
type: "mock",
@@ -194,11 +197,11 @@ class SecondaryMockProvider extends AIContextProvider<MockContextItem> {
];
}
- formatContext(item: MockContextItem): string {
+ public formatContext(item: MockContextItem): string {
return `Secondary: ${item.name}`;
}
- formatCompletion(item: MockContextItem): Completion {
+ public formatCompletion(item: MockContextItem): Completion {
return this.createBasicCompletion(item);
}
}
diff --git a/frontend/src/core/ai/context/providers/cell-output.ts b/frontend/src/core/ai/context/providers/cell-output.ts
index e28ca69022..6e51c41b48 100644
--- a/frontend/src/core/ai/context/providers/cell-output.ts
+++ b/frontend/src/core/ai/context/providers/cell-output.ts
@@ -80,16 +80,16 @@ function isMediaMimetype(
}
export class CellOutputContextProvider extends AIContextProvider<CellOutputContextItem> {
- readonly title = "Cell Outputs";
- readonly mentionPrefix = "@";
- readonly contextType = "cell-output";
+ public readonly title = "Cell Outputs";
+ public readonly mentionPrefix = "@";
+ public readonly contextType = "cell-output";
private store: JotaiStore;
- constructor(store: JotaiStore) {
+ public constructor(store: JotaiStore) {
super();
this.store = store;
}
- getItems(): CellOutputContextItem[] {
+ public getItems(): CellOutputContextItem[] {
const notebook = this.store.get(notebookAtom);
const items: CellOutputContextItem[] = [];
@@ -116,7 +116,7 @@ export class CellOutputContextProvider extends AIContextProvider<CellOutputConte
return items;
}
- formatCompletion(item: CellOutputContextItem): Completion {
+ public formatCompletion(item: CellOutputContextItem): Completion {
const { cellOutput: data, cellName, cellCode } = item.data;
return {
@@ -224,7 +224,7 @@ export class CellOutputContextProvider extends AIContextProvider<CellOutputConte
};
}
- formatContext(item: CellOutputContextItem): string {
+ public formatContext(item: CellOutputContextItem): string {
const { cellOutput: data, cellName, cellId, cellCode } = item.data;
const contextData = {
@@ -253,7 +253,7 @@ export class CellOutputContextProvider extends AIContextProvider<CellOutputConte
}
/** Get attachments for cell output items that have shouldDownloadImage=true */
- override async getAttachments(
+ public override async getAttachments(
items: CellOutputContextItem[],
): Promise<FileUIPart[]> {
const cellId = items[0].data.cellId;
diff --git a/frontend/src/core/ai/context/providers/datasource.ts b/frontend/src/core/ai/context/providers/datasource.ts
index 8261125c3c..9c282673c7 100644
--- a/frontend/src/core/ai/context/providers/datasource.ts
+++ b/frontend/src/core/ai/context/providers/datasource.ts
@@ -46,13 +46,16 @@ export interface DatasourceContextItem extends AIContextItem {
const CONTEXT_TYPE = "datasource";
export class DatasourceContextProvider extends AIContextProvider<DatasourceContextItem> {
- readonly title = "Datasource";
- readonly mentionPrefix = "@";
- readonly contextType = CONTEXT_TYPE;
+ public readonly title = "Datasource";
+ public readonly mentionPrefix = "@";
+ public readonly contextType = CONTEXT_TYPE;
private connectionsMap: ConnectionsMap;
private dataframes: DataTable[];
- constructor(connectionsMap: ConnectionsMap, tablesMap: DatasetTablesMap) {
+ public constructor(
+ connectionsMap: ConnectionsMap,
+ tablesMap: DatasetTablesMap,
+ ) {
super();
this.connectionsMap = connectionsMap;
this.dataframes = [...tablesMap.values()].filter(
@@ -60,7 +63,7 @@ export class DatasourceContextProvider extends AIContextProvider<DatasourceConte
);
}
- getItems(): DatasourceContextItem[] {
+ public getItems(): DatasourceContextItem[] {
return [...this.connectionsMap.values()]
.map((connection): DatasourceContextItem | null => {
let description = "Database schema.";
@@ -92,7 +95,7 @@ export class DatasourceContextProvider extends AIContextProvider<DatasourceConte
.filter(Boolean);
}
- formatContext(item: DatasourceContextItem): string {
+ public formatContext(item: DatasourceContextItem): string {
const data = item.data;
// Remove certain fields that are not needed in the context
const { name, display_name, source, ...filteredDatasource } =
@@ -117,7 +120,7 @@ export class DatasourceContextProvider extends AIContextProvider<DatasourceConte
});
}
- formatCompletion(item: DatasourceContextItem): Completion {
+ public formatCompletion(item: DatasourceContextItem): Completion {
const datasource = item.data;
const dataConnection = datasource.connection;
diff --git a/frontend/src/core/ai/context/providers/error.ts b/frontend/src/core/ai/context/providers/error.ts
index fba69aa186..06de858797 100644
--- a/frontend/src/core/ai/context/providers/error.ts
+++ b/frontend/src/core/ai/context/providers/error.ts
@@ -95,17 +95,17 @@ function errorContextName(entry: CellErrorEntry): string {
const errorsTxt = new PluralWord("error", "errors");
export class ErrorContextProvider extends AIContextProvider<ErrorContextItem> {
- readonly title = "Errors";
- readonly mentionPrefix = "@";
- readonly contextType = "error";
+ public readonly title = "Errors";
+ public readonly mentionPrefix = "@";
+ public readonly contextType = "error";
private store: JotaiStore;
- constructor(store: JotaiStore) {
+ public constructor(store: JotaiStore) {
super();
this.store = store;
}
- getItems(): ErrorContextItem[] {
+ public getItems(): ErrorContextItem[] {
const errors = getCellErrorEntries(this.store);
if (errors.length === 0) {
@@ -141,7 +141,7 @@ export class ErrorContextProvider extends AIContextProvider<ErrorContextItem> {
return items;
}
- formatCompletion(item: ErrorContextItem): Completion {
+ public formatCompletion(item: ErrorContextItem): Completion {
if (item.data.type === "all-errors") {
const errorCount = item.data.errors.length;
return {
@@ -201,7 +201,7 @@ export class ErrorContextProvider extends AIContextProvider<ErrorContextItem> {
};
}
- formatContext(item: ErrorContextItem): string {
+ public formatContext(item: ErrorContextItem): string {
const entries =
item.data.type === "all-errors" ? item.data.errors : [item.data.error];
diff --git a/frontend/src/core/ai/context/providers/file.ts b/frontend/src/core/ai/context/providers/file.ts
index 7f77b551bf..99ba697c5c 100644
--- a/frontend/src/core/ai/context/providers/file.ts
+++ b/frontend/src/core/ai/context/providers/file.ts
@@ -38,14 +38,14 @@ const DEFAULT_FILE_SEARCH_CONFIG: FileSearchConfig = {
};
export class FileContextProvider extends AIContextProvider<FileContextItem> {
- readonly title = "Files";
- readonly mentionPrefix = "#";
- readonly contextType = "file";
+ public readonly title = "Files";
+ public readonly mentionPrefix = "#";
+ public readonly contextType = "file";
private apiRequests: EditRequests & RunRequests;
private config: FileSearchConfig;
- constructor(
+ public constructor(
apiRequests: EditRequests & RunRequests,
config: FileSearchConfig = DEFAULT_FILE_SEARCH_CONFIG,
) {
@@ -58,7 +58,7 @@ export class FileContextProvider extends AIContextProvider<FileContextItem> {
* Create a dynamic completion source for file mentions
* This bypasses the standard registry system to enable dynamic searching
*/
- createCompletionSource(): CompletionSource {
+ public createCompletionSource(): CompletionSource {
return async (
context: CompletionContext,
): Promise<CompletionResult | null> => {
@@ -176,13 +176,13 @@ export class FileContextProvider extends AIContextProvider<FileContextItem> {
}
}
- getItems(): FileContextItem[] {
+ public getItems(): FileContextItem[] {
// Files are fetched dynamically, so return empty array
// This provider relies on dynamic fetching via createCompletionSource()
return [];
}
- formatCompletion(item: FileContextItem): Completion {
+ public formatCompletion(item: FileContextItem): Completion {
const { data, name } = item;
const icon = data.isDirectory ? "📁" : "📄";
@@ -254,7 +254,7 @@ export class FileContextProvider extends AIContextProvider<FileContextItem> {
};
}
- formatContext(item: FileContextItem): string {
+ public formatContext(item: FileContextItem): string {
const { data, name } = item;
return contextToXml({
type: this.contextType,
diff --git a/frontend/src/core/ai/context/providers/tables.ts b/frontend/src/core/ai/context/providers/tables.ts
index 46802d4aba..f63a520644 100644
--- a/frontend/src/core/ai/context/providers/tables.ts
+++ b/frontend/src/core/ai/context/providers/tables.ts
@@ -17,16 +17,16 @@ export interface TableContextItem extends AIContextItem {
}
export class TableContextProvider extends AIContextProvider<TableContextItem> {
- readonly title = "Tables";
- readonly mentionPrefix = "@";
- readonly contextType = "data";
+ public readonly title = "Tables";
+ public readonly mentionPrefix = "@";
+ public readonly contextType = "data";
private tablesMap: DatasetTablesMap;
- constructor(tablesMap: DatasetTablesMap) {
+ public constructor(tablesMap: DatasetTablesMap) {
super();
this.tablesMap = tablesMap;
}
- getItems(): TableContextItem[] {
+ public getItems(): TableContextItem[] {
return [...this.tablesMap.entries()].map(([tableName, table]) => ({
uri: this.asURI(tableName),
name: tableName,
@@ -36,7 +36,7 @@ export class TableContextProvider extends AIContextProvider<TableContextItem> {
}));
}
- formatContext(item: TableContextItem): string {
+ public formatContext(item: TableContextItem): string {
const { data } = item;
const { columns, source, num_rows, num_columns, name, variable_name } =
data;
@@ -90,7 +90,7 @@ export class TableContextProvider extends AIContextProvider<TableContextItem> {
});
}
- formatCompletion(item: TableContextItem): Completion {
+ public formatCompletion(item: TableContextItem): Completion {
const tableName = item.data.name;
const table = item.data;
return {
diff --git a/frontend/src/core/ai/context/providers/variable.ts b/frontend/src/core/ai/context/providers/variable.ts
index 16c4617101..3ddd60e1a5 100644
--- a/frontend/src/core/ai/context/providers/variable.ts
+++ b/frontend/src/core/ai/context/providers/variable.ts
@@ -16,20 +16,20 @@ export interface VariableContextItem extends AIContextItem {
}
export class VariableContextProvider extends AIContextProvider<VariableContextItem> {
- readonly title = "Variables";
- readonly mentionPrefix = "@";
- readonly contextType = "variable";
+ public readonly title = "Variables";
+ public readonly mentionPrefix = "@";
+ public readonly contextType = "variable";
private variables: Variables;
private tablesMap: DatasetTablesMap;
- constructor(variables: Variables, tablesMap: DatasetTablesMap) {
+ public constructor(variables: Variables, tablesMap: DatasetTablesMap) {
super();
this.variables = variables;
this.tablesMap = tablesMap;
}
- getItems(): VariableContextItem[] {
+ public getItems(): VariableContextItem[] {
const ignore = new Set(this.tablesMap.keys());
return Object.entries(this.variables).flatMap(([name, variable]) => {
@@ -51,7 +51,7 @@ export class VariableContextProvider extends AIContextProvider<VariableContextIt
});
}
- formatCompletion(item: VariableContextItem): Completion {
+ public formatCompletion(item: VariableContextItem): Completion {
const { data } = item;
const { variable } = data;
return {
@@ -66,7 +66,7 @@ export class VariableContextProvider extends AIContextProvider<VariableContextIt
};
}
- formatContext(item: VariableContextItem): string {
+ public formatContext(item: VariableContextItem): string {
const { data } = item;
const { variable } = data;
return contextToXml({
diff --git a/frontend/src/core/ai/context/registry.ts b/frontend/src/core/ai/context/registry.ts
index b317f32614..0174e8e947 100644
--- a/frontend/src/core/ai/context/registry.ts
+++ b/frontend/src/core/ai/context/registry.ts
@@ -36,35 +36,35 @@ export abstract class AIContextProvider<
T extends AIContextItem = AIContextItem,
> {
/** Human-readable title for this context type */
- abstract readonly title: string;
+ public abstract readonly title: string;
/** Prefix used for mentions (e.g., "@" for variables, "#" for files) */
- abstract readonly mentionPrefix: "@" | "#";
+ public abstract readonly mentionPrefix: "@" | "#";
/** Context type identifier used in ContextLocatorId */
- abstract readonly contextType: string;
+ public abstract readonly contextType: string;
/** Get all available items of this context type */
- abstract getItems(): T[];
+ public abstract getItems(): T[];
/** Format the context for inclusion in AI prompt */
- abstract formatContext(item: T): string;
+ public abstract formatContext(item: T): string;
/** Format completion */
- abstract formatCompletion(item: T): Completion;
+ public abstract formatCompletion(item: T): Completion;
/** Get attachments for context items (optional, async) */
- async getAttachments(_items: T[]): Promise<FileUIPart[]> {
+ public async getAttachments(_items: T[]): Promise<FileUIPart[]> {
// Default implementation returns no attachments
return [];
}
- asURI(id: string): ContextLocatorId {
+ public asURI(id: string): ContextLocatorId {
return `${this.contextType}://${id}` as ContextLocatorId;
}
/** Parse context IDs from input text using the provider's mention prefix */
- parseContextIds(input: string): ContextLocatorId[] {
+ public parseContextIds(input: string): ContextLocatorId[] {
// Match @type://id, e.g., @data://users
const regex = new RegExp(
`${this.mentionPrefix}([\\w-]+):\\/\\/([\\w./-]+)`,
@@ -112,7 +112,7 @@ export class AIContextRegistry<T extends AIContextItem> {
/**
* Register a new context provider
*/
- register<U extends AIContextItem>(
+ public register<U extends AIContextItem>(
provider: AIContextProvider<U>,
// oxlint-disable-next-line typescript/prefer-return-this-type
): AIContextRegistry<U | T> {
@@ -123,28 +123,28 @@ export class AIContextRegistry<T extends AIContextItem> {
/**
* Get all registered providers
*/
- getProviders(): Set<AIContextProvider<T>> {
+ public getProviders(): Set<AIContextProvider<T>> {
return this.providers;
}
/**
* Get a specific provider by type
*/
- getProvider(type: string): AIContextProvider | undefined {
+ public getProvider(type: string): AIContextProvider | undefined {
return [...this.providers].find(
(provider) => provider.contextType === type,
);
}
@Memoize()
- getAllItems(): T[] {
+ public getAllItems(): T[] {
return [...this.providers].flatMap((provider) => provider.getItems());
}
/**
* Parse context IDs from input across all providers
*/
- parseAllContextIds(input: string): ContextLocatorId[] {
+ public parseAllContextIds(input: string): ContextLocatorId[] {
return [...this.providers].flatMap((provider) =>
provider.parseContextIds(input),
);
@@ -167,7 +167,7 @@ export class AIContextRegistry<T extends AIContextItem> {
/**
* Resolve only the requested context items, querying each matching provider
*/
- resolveItems(contextIds: ContextLocatorId[]): T[] {
+ public resolveItems(contextIds: ContextLocatorId[]): T[] {
if (contextIds.length === 0) {
return [];
}
@@ -215,14 +215,14 @@ export class AIContextRegistry<T extends AIContextItem> {
/**
* Get context information for mentioned items
*/
- getContextInfo(contextIds: ContextLocatorId[]): T[] {
+ public getContextInfo(contextIds: ContextLocatorId[]): T[] {
return this.resolveItems(contextIds);
}
/**
* Format context for AI prompt inclusion
*/
- formatContextForAI(contextIds: ContextLocatorId[]): string {
+ public formatContextForAI(contextIds: ContextLocatorId[]): string {
const contextInfo = this.resolveItems(contextIds);
if (contextInfo.length === 0) {
@@ -240,7 +240,7 @@ export class AIContextRegistry<T extends AIContextItem> {
/**
* Get attachments for mentioned items
*/
- async getAttachmentsForContext(
+ public async getAttachmentsForContext(
contextIds: ContextLocatorId[],
): Promise<FileUIPart[]> {
const contextInfo = this.resolveItems(contextIds);
diff --git a/frontend/src/core/ai/ids/ids.ts b/frontend/src/core/ai/ids/ids.ts
index ce25b70355..2668b1ce7d 100644
--- a/frontend/src/core/ai/ids/ids.ts
+++ b/frontend/src/core/ai/ids/ids.ts
@@ -33,19 +33,19 @@ export type ShortModelId = TypedString<"ShortModelId">;
export type QualifiedModelId = `${ProviderId}/${ShortModelId}`;
export class AiModelId {
- readonly providerId: ProviderId;
- readonly shortModelId: ShortModelId;
+ public readonly providerId: ProviderId;
+ public readonly shortModelId: ShortModelId;
- constructor(providerId: ProviderId, shortModelId: ShortModelId) {
+ public constructor(providerId: ProviderId, shortModelId: ShortModelId) {
this.providerId = providerId;
this.shortModelId = shortModelId;
}
- get id(): QualifiedModelId {
+ public get id(): QualifiedModelId {
return `${this.providerId}/${this.shortModelId}`;
}
- static parse(id: string): AiModelId {
+ public static parse(id: string): AiModelId {
if (!id.includes("/")) {
const providerId = guessProviderId(id);
return new AiModelId(providerId, id as ShortModelId);
diff --git a/frontend/src/core/ai/model-registry.ts b/frontend/src/core/ai/model-registry.ts
index aee0032804..71db33982f 100644
--- a/frontend/src/core/ai/model-registry.ts
+++ b/frontend/src/core/ai/model-registry.ts
@@ -93,7 +93,7 @@ export class AiModelRegistry {
this.buildMaps();
}
- static getProviderInfo(providerId: ProviderId) {
+ public static getProviderInfo(providerId: ProviderId) {
const { providerMap } = getProviderMap();
return providerMap.get(providerId);
}
@@ -104,7 +104,10 @@ export class AiModelRegistry {
*
* Models should be in the format of `provider_id/short_model_id`.
*/
- static create(opts: { customModels?: string[]; displayedModels?: string[] }) {
+ public static create(opts: {
+ customModels?: string[];
+ displayedModels?: string[];
+ }) {
const { customModels = [], displayedModels = [] } = opts;
return new AiModelRegistry(
customModels.map((model) => AiModelId.parse(model).id),
@@ -196,23 +199,23 @@ export class AiModelRegistry {
return { modelsByProviderMap, modelsMap };
}
- getDisplayedModels() {
+ public getDisplayedModels() {
return this.displayedModels;
}
- getCustomModels() {
+ public getCustomModels() {
return this.customModels;
}
- getModelsByProvider(provider: ProviderId) {
+ public getModelsByProvider(provider: ProviderId) {
return this.modelsByProviderMap.get(provider) || [];
}
- getGroupedModelsByProvider() {
+ public getGroupedModelsByProvider() {
return this.modelsByProviderMap;
}
- getListModelsByProvider(): [ProviderId, AiModel[]][] {
+ public getListModelsByProvider(): [ProviderId, AiModel[]][] {
const modelsByProvider = this.getGroupedModelsByProvider();
const arrayModels = [...modelsByProvider.entries()];
const providerToOrderIdx = getProviderMap().providerToOrderIdx;
@@ -227,11 +230,11 @@ export class AiModelRegistry {
return arrayModels;
}
- getModelsMap() {
+ public getModelsMap() {
return this.modelsMap;
}
- getModel(qualifiedModelId: QualifiedModelId) {
+ public getModel(qualifiedModelId: QualifiedModelId) {
return this.modelsMap.get(qualifiedModelId);
}
}
diff --git a/frontend/src/core/ai/staged-cells.ts b/frontend/src/core/ai/staged-cells.ts
index abc8961bdc..b339c7a7e8 100644
--- a/frontend/src/core/ai/staged-cells.ts
+++ b/frontend/src/core/ai/staged-cells.ts
@@ -305,11 +305,11 @@ class StagedCellReconciler {
private readonly actions: StagedCellReconcilerActions;
private marimoImportCellId: CellId | null = null;
- constructor(actions: StagedCellReconcilerActions) {
+ public constructor(actions: StagedCellReconcilerActions) {
this.actions = actions;
}
- reconcile(completionCells: GeneratedCell[]) {
+ public reconcile(completionCells: GeneratedCell[]) {
for (const [idx, cell] of completionCells.entries()) {
if (idx < this.createdCells.length) {
const existingCell = this.createdCells[idx];
@@ -336,7 +336,7 @@ class StagedCellReconciler {
this.syncMarimoImport(completionCells);
}
- discard(stagedCells: StagedAICells) {
+ public discard(stagedCells: StagedAICells) {
for (const { cellId } of this.createdCells.toReversed()) {
if (stagedCells.has(cellId)) {
this.actions.deleteStagedCell(cellId);
@@ -350,17 +350,17 @@ class StagedCellReconciler {
this.marimoImportCellId = null;
}
- accept() {
+ public accept() {
for (const cellId of this.stagedCellIds()) {
this.actions.removeStagedCell(cellId);
}
}
- hasStagedCells(stagedCells: StagedAICells) {
+ public hasStagedCells(stagedCells: StagedAICells) {
return this.stagedCellIds().some((cellId) => stagedCells.has(cellId));
}
- stagedCellIds() {
+ public stagedCellIds() {
const cellIds = this.createdCells.map(({ cellId }) => cellId);
if (this.marimoImportCellId) {
cellIds.push(this.marimoImportCellId);
diff --git a/frontend/src/core/ai/tools/base.ts b/frontend/src/core/ai/tools/base.ts
index 6865107dae..ab5e73f089 100644
--- a/frontend/src/core/ai/tools/base.ts
+++ b/frontend/src/core/ai/tools/base.ts
@@ -26,12 +26,12 @@ export type StatusValue = "success" | "error" | "warning";
* );
*/
export class ToolExecutionError extends Error {
- readonly code: string;
- readonly isRetryable: boolean;
- readonly suggestedFix?: string;
- readonly meta?: Record<string, unknown>;
+ public readonly code: string;
+ public readonly isRetryable: boolean;
+ public readonly suggestedFix?: string;
+ public readonly meta?: Record<string, unknown>;
- constructor(
+ public constructor(
message: string,
code = "TOOL_ERROR",
isRetryable = false,
@@ -46,7 +46,7 @@ export class ToolExecutionError extends Error {
this.meta = meta;
}
- toStructuredString(): string {
+ public toStructuredString(): string {
const stringError = JSON.stringify({
message: this.message,
code: this.code,
diff --git a/frontend/src/core/ai/tools/edit-notebook-tool.ts b/frontend/src/core/ai/tools/edit-notebook-tool.ts
index 74aa589261..4093b9f345 100644
--- a/frontend/src/core/ai/tools/edit-notebook-tool.ts
+++ b/frontend/src/core/ai/tools/edit-notebook-tool.ts
@@ -76,13 +76,13 @@ export class EditNotebookTool implements AiTool<
EditNotebookInput,
ToolOutputBase
> {
- readonly name = "edit_notebook_tool";
- readonly description = description;
- readonly schema = editNotebookSchema;
- readonly outputSchema = toolOutputBaseSchema;
- readonly mode: CopilotMode[] = ["agent"];
+ public readonly name = "edit_notebook_tool";
+ public readonly description = description;
+ public readonly schema = editNotebookSchema;
+ public readonly outputSchema = toolOutputBaseSchema;
+ public readonly mode: CopilotMode[] = ["agent"];
- handler = async (
+ public handler = async (
{ edit }: EditNotebookInput,
toolContext: ToolNotebookContext,
): Promise<ToolOutputBase> => {
diff --git a/frontend/src/core/ai/tools/registry.ts b/frontend/src/core/ai/tools/registry.ts
index 780041f1e3..1e8e5be054 100644
--- a/frontend/src/core/ai/tools/registry.ts
+++ b/frontend/src/core/ai/tools/registry.ts
@@ -36,11 +36,11 @@ export class FrontendToolRegistry {
/** All registered tools */
private tools = new Map<string, StoredTool>();
- constructor(tools: StoredTool[] = []) {
+ public constructor(tools: StoredTool[] = []) {
this.tools = new Map(tools.map((tool) => [tool.name, tool]));
}
- has(toolName: string) {
+ public has(toolName: string) {
return this.tools.has(toolName);
}
@@ -52,7 +52,7 @@ export class FrontendToolRegistry {
return tool;
}
- async invoke<TName extends string>({
+ public async invoke<TName extends string>({
toolName,
rawArgs,
toolContext,
@@ -127,7 +127,7 @@ export class FrontendToolRegistry {
}
@Memoize()
- getToolSchemas(mode: CopilotMode): FrontendToolDefinition[] {
+ public getToolSchemas(mode: CopilotMode): FrontendToolDefinition[] {
const tools = [...this.tools.values()].filter((tool) =>
tool.mode.includes(mode),
);
diff --git a/frontend/src/core/ai/tools/run-cells-tool.ts b/frontend/src/core/ai/tools/run-cells-tool.ts
index d616bc43ae..e4ae77c8a9 100644
--- a/frontend/src/core/ai/tools/run-cells-tool.ts
+++ b/frontend/src/core/ai/tools/run-cells-tool.ts
@@ -54,10 +54,10 @@ export class RunStaleCellsTool implements AiTool<
EmptyToolInput,
RunStaleCellsOutput
> {
- readonly name = "run_stale_cells_tool";
- readonly description = description;
- readonly schema = z.object({});
- readonly outputSchema = toolOutputBaseSchema.extend({
+ public readonly name = "run_stale_cells_tool";
+ public readonly description = description;
+ public readonly schema = z.object({});
+ public readonly outputSchema = toolOutputBaseSchema.extend({
cellsToOutput: z
.record(
z.string(),
@@ -72,15 +72,15 @@ export class RunStaleCellsTool implements AiTool<
)
.optional(),
}) satisfies z.ZodType<RunStaleCellsOutput>;
- readonly mode: CopilotMode[] = ["agent"];
+ public readonly mode: CopilotMode[] = ["agent"];
private readonly postExecutionDelay: number;
- constructor(opts?: { postExecutionDelay?: number }) {
+ public constructor(opts?: { postExecutionDelay?: number }) {
this.postExecutionDelay = opts?.postExecutionDelay ?? POST_EXECUTION_DELAY;
}
- handler = async (
+ public handler = async (
_args: EmptyToolInput,
toolContext: ToolNotebookContext,
): Promise<RunStaleCellsOutput> => {
diff --git a/frontend/src/core/ai/tools/sample-tool.ts b/frontend/src/core/ai/tools/sample-tool.ts
index 0c00d3f883..1b7965c042 100644
--- a/frontend/src/core/ai/tools/sample-tool.ts
+++ b/frontend/src/core/ai/tools/sample-tool.ts
@@ -36,18 +36,18 @@ interface Output extends ToolOutputBase {
/** A sample frontend tool that demonstrates real tool output structure */
export class TestFrontendTool implements AiTool<Input, Output> {
- readonly name = "test_frontend_tool";
- readonly description = description;
- readonly schema = z.object({ name: z.string() });
- readonly outputSchema = toolOutputBaseSchema.extend({
+ public readonly name = "test_frontend_tool";
+ public readonly description = description;
+ public readonly schema = z.object({ name: z.string() });
+ public readonly outputSchema = toolOutputBaseSchema.extend({
data: z.object({
greeting: z.string(),
timestamp: z.string(),
}),
});
- readonly mode: CopilotMode[] = ["ask"];
+ public readonly mode: CopilotMode[] = ["ask"];
- async handler({ name }: Input): Promise<Output> {
+ public async handler({ name }: Input): Promise<Output> {
// Example: Validate input and throw ToolExecutionError on invalid data
if (!name.trim()) {
throw new ToolExecutionError(
diff --git a/frontend/src/core/codemirror/cells/debugger-decorations.ts b/frontend/src/core/codemirror/cells/debugger-decorations.ts
index 5b58eb3cc8..5dc34c6208 100644
--- a/frontend/src/core/codemirror/cells/debugger-decorations.ts
+++ b/frontend/src/core/codemirror/cells/debugger-decorations.ts
@@ -48,9 +48,12 @@ function createLineDecoration(
class CurrentLineHighlighter implements PluginValue {
private unsubscribe: () => void;
- decorations: DecorationSet;
+ public decorations: DecorationSet;
- constructor(view: EditorView, lineObservable: Observable<number | null>) {
+ public constructor(
+ view: EditorView,
+ lineObservable: Observable<number | null>,
+ ) {
this.decorations = createLineDecoration(view.state, lineObservable.get());
this.unsubscribe = lineObservable.sub((line) => {
this.decorations = createLineDecoration(view.state, line);
@@ -59,11 +62,11 @@ class CurrentLineHighlighter implements PluginValue {
});
}
- update(update: ViewUpdate) {
+ public update(update: ViewUpdate) {
this.decorations = this.decorations.map(update.changes);
}
- destroy() {
+ public destroy() {
this.unsubscribe();
}
}
@@ -88,7 +91,7 @@ export function debuggerLineHighlighter(
// --- Breakpoint gutter ------------------------------------------------------
class BreakpointMarker extends GutterMarker {
- override toDOM() {
+ public override toDOM() {
const dot = document.createElement("div");
dot.className = "cm-breakpoint-marker";
return dot;
@@ -130,7 +133,10 @@ function buildBreakpointMarkers(state: EditorState): RangeSet<GutterMarker> {
class BreakpointSync implements PluginValue {
private unsubscribe: () => void;
- constructor(view: EditorView, observable: Observable<ReadonlySet<number>>) {
+ public constructor(
+ view: EditorView,
+ observable: Observable<ReadonlySet<number>>,
+ ) {
const apply = (lines: ReadonlySet<number>) => {
view.dispatch({ effects: setBreakpointLines.of(lines) });
};
@@ -144,7 +150,7 @@ class BreakpointSync implements PluginValue {
this.unsubscribe = observable.sub(apply);
}
- destroy() {
+ public destroy() {
this.unsubscribe();
}
}
diff --git a/frontend/src/core/codemirror/cells/line-timing-decorations.ts b/frontend/src/core/codemirror/cells/line-timing-decorations.ts
index b4300a94d1..ca6be4add8 100644
--- a/frontend/src/core/codemirror/cells/line-timing-decorations.ts
+++ b/frontend/src/core/codemirror/cells/line-timing-decorations.ts
@@ -42,16 +42,16 @@ class LineTimerWidget extends WidgetType {
private readonly startedAtMs: number;
- constructor(startedAtMs: number) {
+ public constructor(startedAtMs: number) {
super();
this.startedAtMs = startedAtMs;
}
- override eq(other: LineTimerWidget): boolean {
+ public override eq(other: LineTimerWidget): boolean {
return other.startedAtMs === this.startedAtMs;
}
- override toDOM(): HTMLElement {
+ public override toDOM(): HTMLElement {
const el = document.createElement("span");
el.className = "cm-line-timer";
el.setAttribute("aria-hidden", "true");
@@ -68,7 +68,7 @@ class LineTimerWidget extends WidgetType {
return el;
}
- override destroy(dom: HTMLElement): void {
+ public override destroy(dom: HTMLElement): void {
const interval = LineTimerWidget.intervals.get(dom);
if (interval !== undefined) {
window.clearInterval(interval);
@@ -76,7 +76,7 @@ class LineTimerWidget extends WidgetType {
}
}
- override ignoreEvent(): boolean {
+ public override ignoreEvent(): boolean {
return true;
}
}
@@ -112,9 +112,9 @@ function createTimingDecorations(
class ActiveLineTimer implements PluginValue {
private unsubscribe: () => void;
- decorations: DecorationSet;
+ public decorations: DecorationSet;
- constructor(
+ public constructor(
view: EditorView,
infoObservable: Observable<ActiveLineInfo | null>,
) {
@@ -129,11 +129,11 @@ class ActiveLineTimer implements PluginValue {
});
}
- update(update: ViewUpdate) {
+ public update(update: ViewUpdate) {
this.decorations = this.decorations.map(update.changes);
}
- destroy() {
+ public destroy() {
this.unsubscribe();
}
}
diff --git a/frontend/src/core/codemirror/cells/traceback-decorations.ts b/frontend/src/core/codemirror/cells/traceback-decorations.ts
index 9599af6237..ce7b0b6fa0 100644
--- a/frontend/src/core/codemirror/cells/traceback-decorations.ts
+++ b/frontend/src/core/codemirror/cells/traceback-decorations.ts
@@ -91,9 +91,12 @@ function unfoldErrorLines(view: EditorView, errors: TracebackInfos) {
*/
class ErrorHighlighter implements PluginValue {
private unsubscribe: () => void;
- decorations: DecorationSet;
+ public decorations: DecorationSet;
- constructor(view: EditorView, errorsObservable: Observable<TracebackInfos>) {
+ public constructor(
+ view: EditorView,
+ errorsObservable: Observable<TracebackInfos>,
+ ) {
const errors = errorsObservable.get();
this.decorations = createErrorDecorations(view.state, errors);
unfoldErrorLines(view, errors);
@@ -113,11 +116,11 @@ class ErrorHighlighter implements PluginValue {
});
}
- update(update: ViewUpdate) {
+ public update(update: ViewUpdate) {
this.decorations = this.decorations.map(update.changes);
}
- destroy() {
+ public destroy() {
this.unsubscribe();
}
}
diff --git a/frontend/src/core/codemirror/code-lens/extension.ts b/frontend/src/core/codemirror/code-lens/extension.ts
index 66f306ac81..4a200d897d 100644
--- a/frontend/src/core/codemirror/code-lens/extension.ts
+++ b/frontend/src/core/codemirror/code-lens/extension.ts
@@ -56,12 +56,12 @@ class LensHoverController {
private showTimer: number | undefined;
private hideTimer: number | undefined;
- constructor(view: EditorView) {
+ public constructor(view: EditorView) {
this.view = view;
}
/** Pointer entered a lens icon */
- enterLens(spec: CodeLensSpec, icon: HTMLElement): void {
+ public enterLens(spec: CodeLensSpec, icon: HTMLElement): void {
this.clearTimers();
dismissEditorHoverTooltips(this.view, icon);
const hovered = this.view.state.field(codeLensHoverField, false);
@@ -76,7 +76,7 @@ class LensHoverController {
}
/** Pointer left a lens icon or the popover */
- leave(): void {
+ public leave(): void {
this.clearTimers();
this.hideTimer = window.setTimeout(() => {
this.hideTimer = undefined;
@@ -85,19 +85,19 @@ class LensHoverController {
}
/** Pointer entered the popover */
- enterPopover(): void {
+ public enterPopover(): void {
window.clearTimeout(this.hideTimer);
this.hideTimer = undefined;
}
- hide(): void {
+ public hide(): void {
this.clearTimers();
if (this.view.state.field(codeLensHoverField, false)) {
this.view.dispatch({ effects: setHoveredLens.of(null) });
}
}
- destroy(): void {
+ public destroy(): void {
this.clearTimers();
}
@@ -135,18 +135,18 @@ function dismissEditorHoverTooltips(
class CodeLensWidget extends WidgetType {
private readonly spec: CodeLensSpec;
- constructor(spec: CodeLensSpec) {
+ public constructor(spec: CodeLensSpec) {
super();
this.spec = spec;
}
- override eq(other: CodeLensWidget): boolean {
+ public override eq(other: CodeLensWidget): boolean {
// `pos` is captured by the DOM hover/click handlers, so a reused widget
// whose anchor moved must not be treated as equal
return specEquals(this.spec, other.spec);
}
- override toDOM(view: EditorView): HTMLElement {
+ public override toDOM(view: EditorView): HTMLElement {
const { spec } = this;
const element = document.createElement("span");
element.className = "mo-code-lens";
@@ -188,7 +188,7 @@ class CodeLensWidget extends WidgetType {
return element;
}
- override ignoreEvent(): boolean {
+ public override ignoreEvent(): boolean {
// The widget handles its own events
return true;
}
@@ -281,7 +281,7 @@ class CodeLensPlugin {
private readonly debounceMs = 300;
private readonly scheduleUpdate: DebouncedFunc<() => void>;
- constructor(view: EditorView, cellId: CellId, includeCache: boolean) {
+ public constructor(view: EditorView, cellId: CellId, includeCache: boolean) {
this.view = view;
this.cellId = cellId;
this.includeCache = includeCache;
@@ -297,7 +297,7 @@ class CodeLensPlugin {
this.scheduleUpdate();
}
- update(update: ViewUpdate) {
+ public update(update: ViewUpdate) {
// Recompute on edits, and when the cell's language changes (e.g. Python ->
// SQL) so stale Python-only icons are cleared even if the text is unchanged
const adapterChanged =
@@ -308,7 +308,7 @@ class CodeLensPlugin {
}
}
- destroy() {
+ public destroy() {
this.scheduleUpdate.cancel();
for (const unsubscribe of this.unsubscribes) {
unsubscribe();
diff --git a/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts b/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts
index 0ef862832f..ce148bfdab 100644
--- a/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts
+++ b/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts
@@ -22,11 +22,11 @@ vi.mock("../state", async (importOriginal) => {
class MockTransport implements Transport {
private readonly handlers = new Set<(message: JSONRPCMessage) => void>();
- readonly sent: JSONRPCMessage[] = [];
+ public readonly sent: JSONRPCMessage[] = [];
- connect = vi.fn().mockResolvedValue(undefined);
- close = vi.fn();
- send = vi.fn((message: JSONRPCMessage) => {
+ public connect = vi.fn().mockResolvedValue(undefined);
+ public close = vi.fn();
+ public send = vi.fn((message: JSONRPCMessage) => {
this.sent.push(message);
if (isRequest(message) && message.method === "initialize") {
queueMicrotask(() => {
@@ -39,14 +39,14 @@ class MockTransport implements Transport {
}
});
- onMessage(handler: (message: JSONRPCMessage) => void): () => void {
+ public onMessage(handler: (message: JSONRPCMessage) => void): () => void {
this.handlers.add(handler);
return () => {
this.handlers.delete(handler);
};
}
- emit(message: JSONRPCMessage) {
+ public emit(message: JSONRPCMessage) {
for (const handler of this.handlers) {
handler(message);
}
diff --git a/frontend/src/core/codemirror/copilot/__tests__/transport.test.ts b/frontend/src/core/codemirror/copilot/__tests__/transport.test.ts
index 4077b028be..96012e0ba3 100644
--- a/frontend/src/core/codemirror/copilot/__tests__/transport.test.ts
+++ b/frontend/src/core/codemirror/copilot/__tests__/transport.test.ts
@@ -8,24 +8,24 @@ vi.mock("@/utils/Logger", () => ({
}));
class FakeWebSocket {
- static readonly OPEN = 1;
- static readonly CLOSED = 3;
- static readonly instances: FakeWebSocket[] = [];
+ public static readonly OPEN = 1;
+ public static readonly CLOSED = 3;
+ public static readonly instances: FakeWebSocket[] = [];
- readonly sent: string[] = [];
- readyState = 0;
- readonly url: string;
+ public readonly sent: string[] = [];
+ public readyState = 0;
+ public readonly url: string;
private readonly listeners = new Map<
string,
Set<(event: Record<string, never>) => void>
>();
- constructor(url: string) {
+ public constructor(url: string) {
this.url = url;
FakeWebSocket.instances.push(this);
}
- addEventListener(
+ public addEventListener(
type: string,
listener: (event: Record<string, never>) => void,
) {
@@ -34,21 +34,21 @@ class FakeWebSocket {
this.listeners.set(type, listeners);
}
- send(frame: string) {
+ public send(frame: string) {
this.sent.push(frame);
}
- close() {
+ public close() {
this.readyState = FakeWebSocket.CLOSED;
this.emit("close");
}
- open() {
+ public open() {
this.readyState = FakeWebSocket.OPEN;
this.emit("open");
}
- fail() {
+ public fail() {
this.emit("error");
}
diff --git a/frontend/src/core/codemirror/copilot/language-server.ts b/frontend/src/core/codemirror/copilot/language-server.ts
index fe6d8e981c..11e80c36cd 100644
--- a/frontend/src/core/codemirror/copilot/language-server.ts
+++ b/frontend/src/core/codemirror/copilot/language-server.ts
@@ -117,7 +117,7 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
private lastOpenedDocument: DidOpenTextDocumentParams | undefined;
private copilotSettings: Record<string, unknown> = {};
- constructor(
+ public constructor(
options: ConstructorParameters<typeof LanguageServerClient>[0] & {
copilotSettings?: Record<string, unknown>;
},
@@ -140,7 +140,7 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
* Re-run the LSP initialize handshake and send configuration.
* Called by the transport's onReconnect callback after reconnecting.
*/
- async reInitialize(): Promise<void> {
+ public async reInitialize(): Promise<void> {
logger.log("#reInitialize: Re-initializing LSP connection");
this.initializePromise = this.initialize();
await this.initializePromise;
@@ -186,7 +186,7 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
return this.notify(method, params);
}
- override getInitializationOptions() {
+ public override getInitializationOptions() {
const info = {
name: "marimo",
version: "0.1.0",
@@ -208,7 +208,7 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
return !isCopilotEnabled();
}
- override async textDocumentDidOpen(
+ public override async textDocumentDidOpen(
params: DidOpenTextDocumentParams,
): Promise<boolean> {
if (this.isDisabled()) {
@@ -223,7 +223,7 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
return super.textDocumentDidOpen(params);
}
- override async textDocumentDidClose(
+ public override async textDocumentDidClose(
params: DidCloseTextDocumentParams,
): Promise<void> {
if (this.openDocumentCount === 0) {
@@ -233,14 +233,14 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
return super.textDocumentDidClose(params);
}
- override async textDocumentCompletion(
+ public override async textDocumentCompletion(
params: CompletionParams,
): Promise<CompletionList | CompletionItem[]> {
// Not used in Copilot
return [];
}
- override async textDocumentDidChange(
+ public override async textDocumentDidChange(
params: DidChangeTextDocumentParams,
): Promise<void> {
if (this.isDisabled()) {
@@ -304,17 +304,17 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
});
}
- override textDocumentHover(params: HoverParams): Promise<Hover> {
+ public override textDocumentHover(params: HoverParams): Promise<Hover> {
// Not used in Copilot
return Promise.resolve({ contents: [] });
}
// AUTH
- signOut() {
+ public signOut() {
return this._request("signOut", {});
}
- async signInInitiate() {
+ public async signInInitiate() {
logger.log("#signInInitiate: Starting sign-in flow");
try {
const result = await this._request("signIn", {});
@@ -326,7 +326,7 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
}
}
- async signInConfirm(params: GitHubCopilotSignInConfirmParams) {
+ public async signInConfirm(params: GitHubCopilotSignInConfirmParams) {
logger.log("#signInConfirm: Confirming sign-in");
try {
const result = await this._request("signInConfirm", params);
@@ -338,7 +338,7 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
}
}
- async signedIn() {
+ public async signedIn() {
try {
const { status } = await this._request("checkStatus", {});
logger.log("#checkStatus: Status check completed", { status });
@@ -375,7 +375,7 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
200,
);
- async getCompletion(
+ public async getCompletion(
params: InlineCompletionParams,
): Promise<InlineCompletionList | InlineCompletionItem[] | null> {
if (this.isDisabled()) {
diff --git a/frontend/src/core/codemirror/copilot/transport.ts b/frontend/src/core/codemirror/copilot/transport.ts
index ea384b0a5f..573be9dc37 100644
--- a/frontend/src/core/codemirror/copilot/transport.ts
+++ b/frontend/src/core/codemirror/copilot/transport.ts
@@ -38,7 +38,7 @@ export interface LazyWebsocketTransportOptions {
* Copilot-specific readiness checks, retries, and user-facing errors.
*/
export class LazyWebsocketTransport extends ReconnectingWebSocketTransport {
- constructor(options: LazyWebsocketTransportOptions) {
+ public constructor(options: LazyWebsocketTransportOptions) {
super({
getWsUrl: options.getWsUrl,
waitForConnection: options.waitForReady,
diff --git a/frontend/src/core/codemirror/find-replace/search-highlight.ts b/frontend/src/core/codemirror/find-replace/search-highlight.ts
index c314cac625..ac58c68e5d 100644
--- a/frontend/src/core/codemirror/find-replace/search-highlight.ts
+++ b/frontend/src/core/codemirror/find-replace/search-highlight.ts
@@ -90,15 +90,15 @@ const HighlightMargin = 250;
export const searchHighlighter = ViewPlugin.fromClass(
class {
- decorations: DecorationSet;
- readonly view: EditorView;
+ public decorations: DecorationSet;
+ public readonly view: EditorView;
- constructor(view: EditorView) {
+ public constructor(view: EditorView) {
this.view = view;
this.decorations = this.highlight(view.state.field(searchState));
}
- update(update: ViewUpdate) {
+ public update(update: ViewUpdate) {
const state = update.state.field(searchState);
if (
state !== update.startState.field(searchState) ||
@@ -110,7 +110,7 @@ export const searchHighlighter = ViewPlugin.fromClass(
}
}
- highlight(query: QueryType) {
+ public highlight(query: QueryType) {
if (!query.spec.valid) {
return Decoration.none;
}
diff --git a/frontend/src/core/codemirror/go-to-definition/underline.ts b/frontend/src/core/codemirror/go-to-definition/underline.ts
index f1b746810c..bf0e123f19 100644
--- a/frontend/src/core/codemirror/go-to-definition/underline.ts
+++ b/frontend/src/core/codemirror/go-to-definition/underline.ts
@@ -57,7 +57,7 @@ class MetaUnderlineVariablePlugin {
private hoveredRange: { from: number; to: number; position: number } | null;
private onClick: (view: EditorView) => void;
- constructor(view: EditorView, onClick: (view: EditorView) => void) {
+ public constructor(view: EditorView, onClick: (view: EditorView) => void) {
this.view = view;
this.commandClickMode = false;
this.hoveredRange = null;
@@ -69,13 +69,13 @@ class MetaUnderlineVariablePlugin {
window.addEventListener("mouseleave", this.windowBlur);
}
- update(_update: ViewUpdate) {
+ public update(_update: ViewUpdate) {
// We cannot add any transactions here (e.g. clearing underlines),
// otherwise CM fails with
// "Calls to EditorView.update are not allowed while an update is in progress"
}
- destroy() {
+ public destroy() {
window.removeEventListener("keydown", this.keydown);
window.removeEventListener("keyup", this.keyup);
window.removeEventListener("blur", this.windowBlur);
diff --git a/frontend/src/core/codemirror/keymaps/vim.ts b/frontend/src/core/codemirror/keymaps/vim.ts
index 77e7a7b615..65758d26b9 100644
--- a/frontend/src/core/codemirror/keymaps/vim.ts
+++ b/frontend/src/core/codemirror/keymaps/vim.ts
@@ -346,7 +346,7 @@ class CodeMirrorVimSync {
// noop
}
- addInstance(instance: EditorView) {
+ public addInstance(instance: EditorView) {
this.instances.add(instance);
const cm = getCM(instance);
@@ -376,11 +376,11 @@ class CodeMirrorVimSync {
});
}
- removeInstance(instance: EditorView) {
+ public removeInstance(instance: EditorView) {
this.instances.delete(instance);
}
- broadcastModeChange(
+ public broadcastModeChange(
originInstance: EditorView,
mode: string,
subMode?: string,
diff --git a/frontend/src/core/codemirror/language/languages/markdown.ts b/frontend/src/core/codemirror/language/languages/markdown.ts
index bdeb17a31b..dd934ef959 100644
--- a/frontend/src/core/codemirror/language/languages/markdown.ts
+++ b/frontend/src/core/codemirror/language/languages/markdown.ts
@@ -41,23 +41,23 @@ export const MARKDOWN_INITIAL_HIDE_CODE = true;
export class MarkdownLanguageAdapter implements LanguageAdapter<MarkdownLanguageAdapterMetadata> {
private parser = new MarkdownParser();
- readonly type = "markdown";
- readonly defaultCode = this.parser.defaultCode;
- readonly defaultMetadata: MarkdownLanguageAdapterMetadata =
+ public readonly type = "markdown";
+ public readonly defaultCode = this.parser.defaultCode;
+ public readonly defaultMetadata: MarkdownLanguageAdapterMetadata =
this.parser.defaultMetadata;
- static fromMarkdown(markdown: string) {
+ public static fromMarkdown(markdown: string) {
return MarkdownParser.fromMarkdown(markdown);
}
- transformIn(
+ public transformIn(
pythonCode: string,
): [string, number, MarkdownLanguageAdapterMetadata] {
const result = this.parser.transformIn(pythonCode);
return [result.code, result.offset, result.metadata];
}
- transformOut(
+ public transformOut(
code: string,
metadata: MarkdownLanguageAdapterMetadata,
): [string, number] {
@@ -65,11 +65,11 @@ export class MarkdownLanguageAdapter implements LanguageAdapter<MarkdownLanguage
return [result.code, result.offset];
}
- isSupported(pythonCode: string): boolean {
+ public isSupported(pythonCode: string): boolean {
return this.parser.isSupported(pythonCode);
}
- getExtension(
+ public getExtension(
_cellId: CellId,
_completionConfig: CompletionConfig,
hotkeys: HotkeyProvider,
diff --git a/frontend/src/core/codemirror/language/languages/python.ts b/frontend/src/core/codemirror/language/languages/python.ts
index 7376f4deed..a94c7e1176 100644
--- a/frontend/src/core/codemirror/language/languages/python.ts
+++ b/frontend/src/core/codemirror/language/languages/python.ts
@@ -261,25 +261,25 @@ const pyrightClient = once((_: LSPConfig) => {
export class PythonLanguageAdapter implements LanguageAdapter<{}> {
private parser = new PythonParser();
- readonly type = "python";
- readonly defaultCode = this.parser.defaultCode;
- readonly defaultMetadata = this.parser.defaultMetadata;
+ public readonly type = "python";
+ public readonly defaultCode = this.parser.defaultCode;
+ public readonly defaultMetadata = this.parser.defaultMetadata;
- transformIn(code: string): [string, number, {}] {
+ public transformIn(code: string): [string, number, {}] {
const result = this.parser.transformIn(code);
return [result.code, result.offset, result.metadata];
}
- transformOut(code: string, metadata: {}): [string, number] {
+ public transformOut(code: string, metadata: {}): [string, number] {
const result = this.parser.transformOut(code, metadata);
return [result.code, result.offset];
}
- isSupported(code: string): boolean {
+ public isSupported(code: string): boolean {
return this.parser.isSupported(code);
}
- getExtension(
+ public getExtension(
cellId: CellId,
completionConfig: CompletionConfig,
hotkeys: HotkeyProvider,
diff --git a/frontend/src/core/codemirror/language/languages/sql/completion-builder.ts b/frontend/src/core/codemirror/language/languages/sql/completion-builder.ts
index 486a3585c1..d6b53f7168 100644
--- a/frontend/src/core/codemirror/language/languages/sql/completion-builder.ts
+++ b/frontend/src/core/codemirror/language/languages/sql/completion-builder.ts
@@ -25,7 +25,7 @@ export class CompletionBuilder {
/**
* Add a table with its columns at the specified path
*/
- addTable(path: string[], table: DataTable): this {
+ public addTable(path: string[], table: DataTable): this {
const tableNamespace: SQLNamespace = {
self: tableToCompletion({
table: table,
@@ -44,7 +44,7 @@ export class CompletionBuilder {
/**
* Add a schema at the specified path
*/
- addSchema(path: string[], schema: DatabaseSchema): this {
+ public addSchema(path: string[], schema: DatabaseSchema): this {
const schemaObject: SQLNamespace = {
self: schemaToCompletion({
namespace: schema,
@@ -60,7 +60,7 @@ export class CompletionBuilder {
/**
* Add a database at the specified path
*/
- addDatabase(path: string[], database: Database): this {
+ public addDatabase(path: string[], database: Database): this {
const databaseObject: SQLNamespace = {
self: databaseToCompletion({
namespace: database,
@@ -90,14 +90,14 @@ export class CompletionBuilder {
/**
* Build the final schema
*/
- build(): SQLNamespace {
+ public build(): SQLNamespace {
return this.schema;
}
/**
* Reset for reuse
*/
- reset(): this {
+ public reset(): this {
this.schema = {};
return this;
}
diff --git a/frontend/src/core/codemirror/language/languages/sql/completion-store.ts b/frontend/src/core/codemirror/language/languages/sql/completion-store.ts
index 5846c9d0fb..3f6136b7e8 100644
--- a/frontend/src/core/codemirror/language/languages/sql/completion-store.ts
+++ b/frontend/src/core/codemirror/language/languages/sql/completion-store.ts
@@ -28,7 +28,7 @@ const datasetTableCompletionsAtom = atom((get) => {
class SQLCompletionStore {
private cache: LRUCache<DataSourceConnection, CachedSchema>;
- constructor() {
+ public constructor() {
this.cache = new LRUCache(10, {
create: (connection) => this.getConnectionSchema(connection),
});
@@ -121,7 +121,7 @@ class SQLCompletionStore {
* Returns the raw dialect of the connection passed from the backend,
* or null if the connection is not found
*/
- getInternalDialect(connectionName: ConnectionName): string | null {
+ public getInternalDialect(connectionName: ConnectionName): string | null {
const connection = this.getConnection(connectionName);
if (!connection) {
return null;
@@ -133,7 +133,7 @@ class SQLCompletionStore {
* Get the inferred SQL dialect for a connection
* If the connection is not found, return the standard SQL dialect.
*/
- getDialect(connectionName: ConnectionName): SQLDialect {
+ public getDialect(connectionName: ConnectionName): SQLDialect {
const connection = this.getConnection(connectionName);
if (!connection) {
return ModifiedStandardSQL;
@@ -141,7 +141,7 @@ class SQLCompletionStore {
return guessDialect(connection);
}
- getCompletionSource(connectionName: ConnectionName): SQLConfig | null {
+ public getCompletionSource(connectionName: ConnectionName): SQLConfig | null {
const connection = this.getConnection(connectionName);
if (!connection) {
return null;
diff --git a/frontend/src/core/codemirror/language/languages/sql/sql.ts b/frontend/src/core/codemirror/language/languages/sql/sql.ts
index b5da61be3b..602e032edc 100644
--- a/frontend/src/core/codemirror/language/languages/sql/sql.ts
+++ b/frontend/src/core/codemirror/language/languages/sql/sql.ts
@@ -99,21 +99,21 @@ function getLatestEngine(): ConnectionName {
*/
export class SQLLanguageAdapter implements LanguageAdapter<SQLLanguageAdapterMetadata> {
private parser = new SQLParser();
- readonly type = "sql";
- sqlModeEnabled: boolean;
+ public readonly type = "sql";
+ public sqlModeEnabled: boolean;
- constructor() {
+ public constructor() {
this.sqlModeEnabled = true;
}
- get defaultMetadata(): SQLLanguageAdapterMetadata {
+ public get defaultMetadata(): SQLLanguageAdapterMetadata {
return {
...this.parser.defaultMetadata,
engine: getLatestEngine() || DUCKDB_ENGINE,
};
}
- get defaultCode(): string {
+ public get defaultCode(): string {
const engine = getLatestEngine();
if (engine && engine !== DUCKDB_ENGINE) {
return `_df = mo.sql(f"""SELECT * FROM """, engine=${engine})`;
@@ -121,9 +121,9 @@ export class SQLLanguageAdapter implements LanguageAdapter<SQLLanguageAdapterMet
return this.parser.defaultCode;
}
- static fromQuery = (query: string) => SQLParser.fromQuery(query);
+ public static fromQuery = (query: string) => SQLParser.fromQuery(query);
- transformIn(
+ public transformIn(
pythonCode: string,
): [
sqlQuery: string,
@@ -143,7 +143,7 @@ export class SQLLanguageAdapter implements LanguageAdapter<SQLLanguageAdapterMet
return [result.code, result.offset, metadata];
}
- transformOut(
+ public transformOut(
code: string,
metadata: SQLLanguageAdapterMetadata,
): [string, number] {
@@ -151,11 +151,11 @@ export class SQLLanguageAdapter implements LanguageAdapter<SQLLanguageAdapterMet
return [result.code, result.offset];
}
- isSupported(pythonCode: string): boolean {
+ public isSupported(pythonCode: string): boolean {
return this.parser.isSupported(pythonCode);
}
- getExtension(
+ public getExtension(
_cellId: CellId,
_completionConfig: CompletionConfig,
_hotkeys: HotkeyProvider,
@@ -309,19 +309,19 @@ class DialectAwareQueryContextAnalyzer extends QueryContextAnalyzer {
private readonly analyzers = new Map<ParserDialects, QueryContextAnalyzer>();
private readonly analysisParser: NodeSqlParser;
- constructor(analysisParser: NodeSqlParser) {
+ public constructor(analysisParser: NodeSqlParser) {
super(analysisParser);
this.analysisParser = analysisParser;
}
- override getContext(
+ public override getContext(
sql: string,
opts: { state: EditorState },
): ReturnType<QueryContextAnalyzer["getContext"]> {
return this.getAnalyzer(opts.state).getContext(sql, opts);
}
- override clearCache(): void {
+ public override clearCache(): void {
for (const analyzer of this.analyzers.values()) {
analyzer.clearCache();
}
@@ -342,25 +342,25 @@ class DialectAwareSqlStructureAnalyzer extends SqlStructureAnalyzer {
private readonly analyzers = new Map<ParserDialects, SqlStructureAnalyzer>();
private readonly analysisParser: NodeSqlParser;
- constructor(analysisParser: NodeSqlParser) {
+ public constructor(analysisParser: NodeSqlParser) {
super(analysisParser);
this.analysisParser = analysisParser;
}
- override analyzeDocument(
+ public override analyzeDocument(
state: EditorState,
): ReturnType<SqlStructureAnalyzer["analyzeDocument"]> {
return this.getAnalyzer(state).analyzeDocument(state);
}
- override getStatementAtPosition(
+ public override getStatementAtPosition(
state: EditorState,
position: number,
): ReturnType<SqlStructureAnalyzer["getStatementAtPosition"]> {
return this.getAnalyzer(state).getStatementAtPosition(state, position);
}
- override getStatementsInRange(
+ public override getStatementsInRange(
state: EditorState,
from: number,
to: number,
@@ -368,7 +368,7 @@ class DialectAwareSqlStructureAnalyzer extends SqlStructureAnalyzer {
return this.getAnalyzer(state).getStatementsInRange(state, from, to);
}
- override clearCache(): void {
+ public override clearCache(): void {
for (const analyzer of this.analyzers.values()) {
analyzer.clearCache();
}
@@ -392,7 +392,7 @@ class CustomSqlParser extends NodeSqlParser {
private readonly VALIDATION_DELAY_MS = 300; // Wait 300ms after user stops typing
private isFocused = false; // Only validate if the editor is focused
- setFocusState(focused: boolean) {
+ public setFocusState(focused: boolean) {
this.isFocused = focused;
}
@@ -446,7 +446,7 @@ class CustomSqlParser extends NodeSqlParser {
});
}
- override async validateSql(
+ public override async validateSql(
sql: string,
opts: { state: EditorState },
): Promise<SqlParseError[]> {
@@ -470,7 +470,7 @@ class CustomSqlParser extends NodeSqlParser {
);
}
- override async parse(
+ public override async parse(
sql: string,
opts: { state: EditorState },
): Promise<NodeSqlParserResult> {
diff --git a/frontend/src/core/codemirror/lsp/__tests__/transports.test.ts b/frontend/src/core/codemirror/lsp/__tests__/transports.test.ts
index 7335b1bbc3..187a39bdfa 100644
--- a/frontend/src/core/codemirror/lsp/__tests__/transports.test.ts
+++ b/frontend/src/core/codemirror/lsp/__tests__/transports.test.ts
@@ -17,38 +17,38 @@ vi.mock("../../../runtime/config", () => ({
/** Minimal stand-in for the browser WebSocket used by `WebSocketTransport`. */
class FakeWebSocket {
- static readonly instances: FakeWebSocket[] = [];
- static readonly OPEN = 1;
+ public static readonly instances: FakeWebSocket[] = [];
+ public static readonly OPEN = 1;
- readyState = 0;
- readonly url: string;
+ public readyState = 0;
+ public readonly url: string;
private readonly listeners = new Map<string, Set<(event: unknown) => void>>();
- constructor(url: string) {
+ public constructor(url: string) {
this.url = url;
FakeWebSocket.instances.push(this);
}
- addEventListener(type: string, listener: (event: unknown) => void) {
+ public addEventListener(type: string, listener: (event: unknown) => void) {
const listeners = this.listeners.get(type) ?? new Set();
listeners.add(listener);
this.listeners.set(type, listeners);
}
- send() {
+ public send() {
// no-op
}
- close() {
+ public close() {
this.readyState = 3;
}
- open() {
+ public open() {
this.readyState = FakeWebSocket.OPEN;
this.emit("open", {});
}
- receive(message: unknown) {
+ public receive(message: unknown) {
this.emit("message", { data: JSON.stringify(message) });
}
diff --git a/frontend/src/core/codemirror/lsp/federated-lsp.ts b/frontend/src/core/codemirror/lsp/federated-lsp.ts
index d4ff924c17..cedd3dc648 100644
--- a/frontend/src/core/codemirror/lsp/federated-lsp.ts
+++ b/frontend/src/core/codemirror/lsp/federated-lsp.ts
@@ -18,12 +18,12 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
private readonly clients: ILanguageServerClient[] = [];
public readonly documentUri: string;
- constructor(clients: ILanguageServerClient[]) {
+ public constructor(clients: ILanguageServerClient[]) {
this.clients = clients;
this.documentUri = getLspDocumentUri();
}
- onNotification(
+ public onNotification(
listener: (n: {
jsonrpc: "2.0";
id?: null | undefined;
@@ -43,7 +43,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
};
}
- get clientCapabilities(): LSP.ClientCapabilities | undefined {
+ public get clientCapabilities(): LSP.ClientCapabilities | undefined {
const capabilities = this.clients
.map((client) => {
if (client.clientCapabilities) {
@@ -59,34 +59,34 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return mergeDictsIgnoreFalsey<LSP.ClientCapabilities>(capabilities);
}
- get ready(): boolean {
+ public get ready(): boolean {
return this.clients.some((client) => client.ready);
}
- set ready(value: boolean) {
+ public set ready(value: boolean) {
this.clients.forEach((client) => {
client.ready = value;
});
}
- get capabilities(): LSP.ServerCapabilities | null {
+ public get capabilities(): LSP.ServerCapabilities | null {
const capabilities = this.clients
.map((client) => client.capabilities)
.filter((c): c is LSP.ServerCapabilities => c !== null);
return mergeDictsIgnoreFalsey<LSP.ServerCapabilities>(capabilities);
}
- set capabilities(value: LSP.ServerCapabilities) {
+ public set capabilities(value: LSP.ServerCapabilities) {
this.clients.forEach((client) => {
client.capabilities = value;
});
}
- get initializePromise(): Promise<void> {
+ public get initializePromise(): Promise<void> {
return this.clients[0].initializePromise;
}
- set initializePromise(value: Promise<void>) {
+ public set initializePromise(value: Promise<void>) {
this.clients.forEach((client) => {
client.initializePromise = value;
});
@@ -104,19 +104,19 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return this.clients.filter((client) => client.hasCapability(method));
}
- hasCapability(method: string): boolean {
+ public hasCapability(method: string): boolean {
return this.clients.some((client) => client.hasCapability(method));
}
- async initialize(): Promise<void> {
+ public async initialize(): Promise<void> {
await Promise.all(this.clients.map((client) => client.initialize()));
}
- async close(): Promise<void> {
+ public async close(): Promise<void> {
await Promise.all(this.clients.map((client) => client.close()));
}
- async textDocumentDidChange(
+ public async textDocumentDidChange(
params: LSP.DidChangeTextDocumentParams,
): Promise<void> {
await Promise.all(
@@ -124,7 +124,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
);
}
- async completionItemResolve(
+ public async completionItemResolve(
item: LSP.CompletionItem,
): Promise<LSP.CompletionItem> {
const client = this.firstWithMethod("textDocument/completion");
@@ -134,7 +134,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return item;
}
- async textDocumentCodeAction(
+ public async textDocumentCodeAction(
params: LSP.CodeActionParams,
): Promise<(LSP.Command | LSP.CodeAction)[] | null> {
const client = this.firstWithMethod("textDocument/codeAction");
@@ -144,12 +144,14 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return null;
}
- async codeActionResolve(action: LSP.CodeAction): Promise<LSP.CodeAction> {
+ public async codeActionResolve(
+ action: LSP.CodeAction,
+ ): Promise<LSP.CodeAction> {
const client = this.firstWithMethod("textDocument/codeAction");
return client ? client.codeActionResolve(action) : action;
}
- async textDocumentRename(
+ public async textDocumentRename(
params: LSP.RenameParams,
): Promise<LSP.WorkspaceEdit | null> {
const client = this.firstWithMethod("textDocument/rename");
@@ -159,7 +161,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return null;
}
- async textDocumentPrepareRename(
+ public async textDocumentPrepareRename(
params: LSP.PrepareRenameParams,
): Promise<LSP.PrepareRenameResult | null> {
const client = this.firstWithMethod("textDocument/prepareRename");
@@ -169,7 +171,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return null;
}
- async textDocumentSignatureHelp(
+ public async textDocumentSignatureHelp(
params: LSP.SignatureHelpParams,
): Promise<LSP.SignatureHelp | null> {
const client = this.firstWithMethod("textDocument/signatureHelp");
@@ -180,7 +182,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
}
// Merge completions from all clients
- async textDocumentCompletion(
+ public async textDocumentCompletion(
params: LSP.CompletionParams,
): Promise<LSP.CompletionList | LSP.CompletionItem[] | null> {
const clients = this.clientsWithMethod("textDocument/completion");
@@ -191,7 +193,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return mergeCompletions(results);
}
- async textDocumentDefinition(
+ public async textDocumentDefinition(
params: LSP.DefinitionParams,
): Promise<LSP.Definition | LSP.LocationLink[] | null> {
const client = this.firstWithMethod("textDocument/definition");
@@ -201,7 +203,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return null;
}
- async textDocumentDidOpen(
+ public async textDocumentDidOpen(
params: LSP.DidOpenTextDocumentParams,
): Promise<boolean> {
const results = await Promise.all(
@@ -211,7 +213,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return results.some((result) => result !== false);
}
- async textDocumentDidClose(
+ public async textDocumentDidClose(
params: LSP.DidCloseTextDocumentParams,
): Promise<void> {
await Promise.all(
@@ -219,7 +221,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
);
}
- async textDocumentWillSave(
+ public async textDocumentWillSave(
params: LSP.WillSaveTextDocumentParams,
): Promise<void> {
await Promise.all(
@@ -227,7 +229,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
);
}
- async textDocumentWillSaveWaitUntil(
+ public async textDocumentWillSaveWaitUntil(
params: LSP.WillSaveTextDocumentParams,
): Promise<LSP.TextEdit[] | null> {
// This blocks the save, so query concurrently rather than paying the sum of
@@ -247,7 +249,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
return null;
}
- async textDocumentDidSave(
+ public async textDocumentDidSave(
params: LSP.DidSaveTextDocumentParams,
): Promise<void> {
await Promise.all(
@@ -255,7 +257,7 @@ export class FederatedLanguageServerClient implements ILanguageServerClient {
);
}
- async textDocumentHover(params: LSP.HoverParams): Promise<LSP.Hover> {
+ public async textDocumentHover(params: LSP.HoverParams): Promise<LSP.Hover> {
for (const client of this.clients) {
if (!client.hasCapability("textDocument/hover")) {
continue;
diff --git a/frontend/src/core/codemirror/lsp/notebook-lsp.ts b/frontend/src/core/codemirror/lsp/notebook-lsp.ts
index fdf31f018e..92780ecc27 100644
--- a/frontend/src/core/codemirror/lsp/notebook-lsp.ts
+++ b/frontend/src/core/codemirror/lsp/notebook-lsp.ts
@@ -42,7 +42,7 @@ class Snapshotter {
codes: Record<CellId, string>;
};
- constructor(
+ public constructor(
getNotebookCode: () => {
cellIds: CellId[];
codes: Record<CellId, string>;
@@ -226,7 +226,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
private latestDiagnosticsVersion: number | null = null;
private forwardedDiagnosticsVersion = 0;
- constructor(
+ public constructor(
client: ILanguageServerClient,
initialSettings: Record<string, unknown>,
getNotebookEditors: () => Record<
@@ -254,7 +254,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
this.snapshotter = new Snapshotter(this.getNotebookCode.bind(this));
}
- onNotification(
+ public onNotification(
listener: (n: {
jsonrpc: "2.0";
id?: null | undefined;
@@ -265,44 +265,44 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
return this.client.onNotification(listener);
}
- get ready(): boolean {
+ public get ready(): boolean {
return this.client.ready;
}
- set ready(value: boolean) {
+ public set ready(value: boolean) {
this.client.ready = value;
}
- get capabilities(): LSP.ServerCapabilities | null {
+ public get capabilities(): LSP.ServerCapabilities | null {
return this.client.capabilities;
}
- set capabilities(value: LSP.ServerCapabilities) {
+ public set capabilities(value: LSP.ServerCapabilities) {
this.client.capabilities = value;
}
- get initializePromise(): Promise<void> {
+ public get initializePromise(): Promise<void> {
return this.client.initializePromise;
}
- set initializePromise(value: Promise<void>) {
+ public set initializePromise(value: Promise<void>) {
this.client.initializePromise = value;
}
- get clientCapabilities() {
+ public get clientCapabilities() {
return this.client.clientCapabilities;
}
- async initialize(): Promise<void> {
+ public async initialize(): Promise<void> {
await this.client.initialize();
}
- close(): void {
+ public close(): void {
this.openCellDocumentCounts.clear();
this.client.close();
}
- hasCapability(method: string): boolean {
+ public hasCapability(method: string): boolean {
return this.client.hasCapability(method);
}
@@ -430,7 +430,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
* This ensures the caller uses the same lens that was sent to the server,
* avoiding race conditions if cells change between sync and subsequent operations.
*/
- async sync(): Promise<{
+ public async sync(): Promise<{
params: LSP.DidChangeTextDocumentParams;
lens: NotebookLens;
}> {
@@ -499,7 +499,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
});
}
- async textDocumentDefinition(
+ public async textDocumentDefinition(
params: LSP.DefinitionParams,
): Promise<LSP.Definition | LSP.LocationLink[] | null> {
// Get the cell document URI from the params
@@ -525,7 +525,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
});
}
- async textDocumentSignatureHelp(
+ public async textDocumentSignatureHelp(
params: LSP.SignatureHelpParams,
): Promise<LSP.SignatureHelp | null> {
const cellDocumentUri = params.textDocument.uri;
@@ -572,7 +572,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
*
* See textDocumentRename for a similar workaround that manually applies edits.
*/
- textDocumentCodeAction(
+ public textDocumentCodeAction(
params: LSP.CodeActionParams,
): Promise<(LSP.Command | LSP.CodeAction)[] | null> {
const disabledCodeAction = true;
@@ -582,7 +582,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
return this.client.textDocumentCodeAction(params);
}
- codeActionResolve(action: LSP.CodeAction): Promise<LSP.CodeAction> {
+ public codeActionResolve(action: LSP.CodeAction): Promise<LSP.CodeAction> {
return Promise.resolve(action);
}
@@ -646,7 +646,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
* LSP edit application flow. The trade-off is that we lose undo grouping
* across cells.
*/
- async textDocumentRename(
+ public async textDocumentRename(
params: LSP.RenameParams,
): Promise<LSP.WorkspaceEdit | null> {
// Get the cell document URI from the params
@@ -784,7 +784,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
};
}
- async completionItemResolve(
+ public async completionItemResolve(
params: LSP.CompletionItem,
): Promise<LSP.CompletionItem> {
// Used cached result to avoid jitter while typing in the same completion item
@@ -801,7 +801,7 @@ export class NotebookLanguageServerClient implements ILanguageServerClient {
return resolved;
}
- async textDocumentPrepareRename(
+ public async textDocumentPrepareRename(
params: LSP.PrepareRenameParams,
): Promise<LSP.PrepareRenameResult | null> {
// Get the cell document URI from the params
diff --git a/frontend/src/core/codemirror/misc/__tests__/dnd.test.ts b/frontend/src/core/codemirror/misc/__tests__/dnd.test.ts
index a02ec9d78a..9d3d87213a 100644
--- a/frontend/src/core/codemirror/misc/__tests__/dnd.test.ts
+++ b/frontend/src/core/codemirror/misc/__tests__/dnd.test.ts
@@ -66,11 +66,11 @@ describe("dnd", () => {
});
class DragEvent extends Event {
- dataTransfer: DataTransfer;
- clientX: number;
- clientY: number;
+ public dataTransfer: DataTransfer;
+ public clientX: number;
+ public clientY: number;
- constructor(
+ public constructor(
type: string,
{
dataTransfer,
@@ -86,14 +86,14 @@ class DragEvent extends Event {
}
class DataTransfer {
- data: Record<string, string> = {};
- _items: File[] = [];
+ public data: Record<string, string> = {};
+ public _items: File[] = [];
- setData(type: string, data: string) {
+ public setData(type: string, data: string) {
this.data[type] = data;
}
- get items() {
+ public get items() {
return {
add: (file: File) => {
this._items.push(file);
@@ -101,11 +101,11 @@ class DataTransfer {
};
}
- get files() {
+ public get files() {
return this._items;
}
- getData(type: string) {
+ public getData(type: string) {
return this.data[type];
}
}
diff --git a/frontend/src/core/codemirror/misc/__tests__/paste.test.ts b/frontend/src/core/codemirror/misc/__tests__/paste.test.ts
index 34f3f279f0..88b78d261d 100644
--- a/frontend/src/core/codemirror/misc/__tests__/paste.test.ts
+++ b/frontend/src/core/codemirror/misc/__tests__/paste.test.ts
@@ -320,17 +320,20 @@ def foo():
// Mock ClipboardEvent and DataTransfer
class MockDataTransfer {
private data: Record<string, string> = {};
- setData(format: string, data: string) {
+ public setData(format: string, data: string) {
this.data[format] = data;
}
- getData(format: string) {
+ public getData(format: string) {
return this.data[format];
}
}
class MockClipboardEvent extends Event {
- clipboardData: MockDataTransfer;
- constructor(type: string, init?: { clipboardData?: MockDataTransfer }) {
+ public clipboardData: MockDataTransfer;
+ public constructor(
+ type: string,
+ init?: { clipboardData?: MockDataTransfer },
+ ) {
super(type);
this.clipboardData = init?.clipboardData || new MockDataTransfer();
}
diff --git a/frontend/src/core/codemirror/reactive-references/extension.ts b/frontend/src/core/codemirror/reactive-references/extension.ts
index 42d2b438e2..d985aa86c8 100644
--- a/frontend/src/core/codemirror/reactive-references/extension.ts
+++ b/frontend/src/core/codemirror/reactive-references/extension.ts
@@ -50,7 +50,7 @@ class ReactiveReferencesPlugin {
// Debounced function to trigger highlighting
private readonly scheduleHighlighting: DebouncedFunc<() => void>;
- constructor(view: EditorView, cellId: CellId) {
+ public constructor(view: EditorView, cellId: CellId) {
this.view = view;
this.cellId = cellId;
@@ -67,13 +67,13 @@ class ReactiveReferencesPlugin {
this.scheduleHighlighting();
}
- update(update: ViewUpdate) {
+ public update(update: ViewUpdate) {
if (update.docChanged || update.focusChanged) {
this.scheduleHighlighting();
}
}
- destroy() {
+ public destroy() {
this.scheduleHighlighting.cancel();
this.variablesUnsubscribe();
}
diff --git a/frontend/src/core/codemirror/rtc/loro/awareness.ts b/frontend/src/core/codemirror/rtc/loro/awareness.ts
index 0fedc467af..86da62825f 100644
--- a/frontend/src/core/codemirror/rtc/loro/awareness.ts
+++ b/frontend/src/core/codemirror/rtc/loro/awareness.ts
@@ -208,7 +208,7 @@ export class RemoteCursorMarker implements LayerMarker {
private name: string;
private colorClassName: string;
- constructor(
+ public constructor(
left: number,
top: number,
height: number,
@@ -222,18 +222,18 @@ export class RemoteCursorMarker implements LayerMarker {
this.colorClassName = colorClassName;
}
- draw(): HTMLElement {
+ public draw(): HTMLElement {
const elt = document.createElement("div");
this.adjust(elt);
return elt;
}
- update(elt: HTMLElement): boolean {
+ public update(elt: HTMLElement): boolean {
this.adjust(elt);
return true;
}
- adjust(element: HTMLElement) {
+ public adjust(element: HTMLElement) {
element.style.left = `${this.left}px`;
element.style.top = `${this.top}px`;
element.style.height = `${this.height}px`;
@@ -241,7 +241,7 @@ export class RemoteCursorMarker implements LayerMarker {
element.style.setProperty("--rtc-name", `"${this.name}"`);
}
- eq(other: RemoteCursorMarker): boolean {
+ public eq(other: RemoteCursorMarker): boolean {
return (
this.left === other.left &&
this.top === other.top &&
@@ -364,7 +364,7 @@ export interface CursorPosition {
}
export class AwarenessPlugin implements PluginValue {
- sub: Subscription;
+ public sub: Subscription;
public view: EditorView;
public doc: LoroDoc;
public user: UserState;
@@ -373,7 +373,7 @@ export class AwarenessPlugin implements PluginValue {
private scopeId: ScopeId;
private getUserId?: () => Uid;
- constructor(
+ public constructor(
view: EditorView,
doc: LoroDoc,
user: UserState,
@@ -421,7 +421,7 @@ export class AwarenessPlugin implements PluginValue {
});
}
- update(update: ViewUpdate): void {
+ public update(update: ViewUpdate): void {
if (!update.selectionSet && !update.focusChanged && !update.docChanged) {
return;
}
@@ -450,7 +450,7 @@ export class AwarenessPlugin implements PluginValue {
}
}
- destroy(): void {
+ public destroy(): void {
this.sub?.();
this.awareness.setLocalState({
type: "delete",
@@ -460,13 +460,13 @@ export class AwarenessPlugin implements PluginValue {
}
}
export class RemoteAwarenessPlugin implements PluginValue {
- _awarenessListener?: AwarenessListener;
+ public _awarenessListener?: AwarenessListener;
public view: EditorView;
public doc: LoroDoc;
public awareness: Awareness<AwarenessState>;
private scopeId: ScopeId;
- constructor(
+ public constructor(
view: EditorView,
doc: LoroDoc,
awareness: Awareness<AwarenessState>,
@@ -493,7 +493,7 @@ export class RemoteAwarenessPlugin implements PluginValue {
this.awareness.addListener(listener);
}
- destroy(): void {
+ public destroy(): void {
if (this._awarenessListener) {
this.awareness.removeListener(this._awarenessListener);
}
diff --git a/frontend/src/core/codemirror/rtc/loro/sync.ts b/frontend/src/core/codemirror/rtc/loro/sync.ts
index 1494e2d717..e16b3a5e97 100644
--- a/frontend/src/core/codemirror/rtc/loro/sync.ts
+++ b/frontend/src/core/codemirror/rtc/loro/sync.ts
@@ -38,14 +38,14 @@ export const loroSyncPlugin = (
export const loroSyncAnnotation = Annotation.define();
export class LoroSyncPluginValue implements PluginValue {
- sub?: Subscription;
+ public sub?: Subscription;
private isInitDispatch = false;
private view: EditorView;
private doc: LoroDoc;
private docPath: string[];
private getTextFromDoc: (doc: LoroDoc) => LoroText;
- constructor(
+ public constructor(
view: EditorView,
doc: LoroDoc,
docPath: string[],
@@ -77,7 +77,7 @@ export class LoroSyncPluginValue implements PluginValue {
});
}
- onRemoteUpdate = (e: LoroEventBatch) => {
+ public onRemoteUpdate = (e: LoroEventBatch) => {
if (e.by === "local") {
return;
}
@@ -133,7 +133,7 @@ export class LoroSyncPluginValue implements PluginValue {
}
};
- update(update: ViewUpdate): void {
+ public update(update: ViewUpdate): void {
if (this.isInitDispatch) {
this.isInitDispatch = false;
return;
@@ -161,7 +161,7 @@ export class LoroSyncPluginValue implements PluginValue {
this.doc.commit();
}
- destroy(): void {
+ public destroy(): void {
this.sub?.();
this.sub = undefined;
}
diff --git a/frontend/src/core/codemirror/vim/cursor-visibility.ts b/frontend/src/core/codemirror/vim/cursor-visibility.ts
index b37a745ed5..d4503ce7b6 100644
--- a/frontend/src/core/codemirror/vim/cursor-visibility.ts
+++ b/frontend/src/core/codemirror/vim/cursor-visibility.ts
@@ -23,7 +23,7 @@ export class VimCursorVisibilityPlugin implements PluginValue {
private view: EditorView;
private abortController = new AbortController();
- constructor(options: VimCursorVisibilityPluginOptions) {
+ public constructor(options: VimCursorVisibilityPluginOptions) {
this.view = options.view;
this.view.dom.addEventListener(
"focus",
@@ -38,7 +38,7 @@ export class VimCursorVisibilityPlugin implements PluginValue {
this.update();
}
- update() {
+ public update() {
const vimCursorLayer = this.view.dom.querySelector(".cm-vimCursorLayer");
if (vimCursorLayer instanceof HTMLElement) {
// Hide all vim cursors when in command mode
@@ -52,7 +52,7 @@ export class VimCursorVisibilityPlugin implements PluginValue {
}
}
- destroy(): void {
+ public destroy(): void {
this.abortController.abort();
}
}
diff --git a/frontend/src/core/dom/ui-element.ts b/frontend/src/core/dom/ui-element.ts
index fccad48e32..ff4aa173a2 100644
--- a/frontend/src/core/dom/ui-element.ts
+++ b/frontend/src/core/dom/ui-element.ts
@@ -137,7 +137,7 @@ export function initializeUIElement() {
this.initialized = true;
}
- connectedCallback() {
+ public connectedCallback() {
this.init();
if (this.initialized) {
@@ -157,7 +157,7 @@ export function initializeUIElement() {
}
}
- disconnectedCallback() {
+ public disconnectedCallback() {
if (this.initialized) {
// Unregister everything
document.removeEventListener(
@@ -175,7 +175,7 @@ export function initializeUIElement() {
/**
* Reset the value of the child element to its initial value.
*/
- reset() {
+ public reset() {
const child = this.firstElementChild;
if (isCustomMarimoElement(child)) {
child.reset();
@@ -189,11 +189,11 @@ export function initializeUIElement() {
// We look for changes to the random-id attribute, which is effectively
// used like a React key. If the random-id changes, we need to unmount and
// remount its child.
- static get observedAttributes() {
+ public static get observedAttributes() {
return [RANDOM_ID_ATTR];
}
- attributeChangedCallback(
+ public attributeChangedCallback(
name: string,
oldValue: string | null,
newValue: string | null,
diff --git a/frontend/src/core/dom/uiregistry.ts b/frontend/src/core/dom/uiregistry.ts
index 223195ca52..ede1238e8a 100644
--- a/frontend/src/core/dom/uiregistry.ts
+++ b/frontend/src/core/dom/uiregistry.ts
@@ -45,12 +45,12 @@ interface UIElementEntry {
*/
export class UIElementRegistry {
// maps UIElement objectIds to entries.
- entries: Map<UIElementId, UIElementEntry>;
+ public entries: Map<UIElementId, UIElementEntry>;
/**
* Shared instance of UIElementRegistry since this must be a singleton.
*/
- static get INSTANCE(): UIElementRegistry {
+ public static get INSTANCE(): UIElementRegistry {
const KEY = "_marimo_private_UIElementRegistry";
if (!window[KEY]) {
window[KEY] = new UIElementRegistry();
@@ -62,11 +62,11 @@ export class UIElementRegistry {
this.entries = new Map();
}
- has(objectId: UIElementId): boolean {
+ public has(objectId: UIElementId): boolean {
return this.entries.has(objectId);
}
- set(objectId: UIElementId, value: ValueType): void {
+ public set(objectId: UIElementId, value: ValueType): void {
if (this.entries.has(objectId)) {
Logger.debug(
"UIElementRegistry overwriting entry for objectId.",
@@ -86,7 +86,7 @@ export class UIElementRegistry {
* @param objectId - id of the UIElement
* @param instance - the HTMLElement that the UIElement wraps
*/
- registerInstance(objectId: UIElementId, instance: HTMLElement) {
+ public registerInstance(objectId: UIElementId, instance: HTMLElement) {
const entry = this.entries.get(objectId);
if (entry === undefined) {
this.entries.set(objectId, {
@@ -109,7 +109,7 @@ export class UIElementRegistry {
* @param instance - the HTMLElement to remove
*
*/
- removeInstance(objectId: UIElementId, instance: HTMLElement) {
+ public removeInstance(objectId: UIElementId, instance: HTMLElement) {
const entry = this.entries.get(objectId);
// The UIElement can be removed from the registry before all
// instances are removed: UIElement removal is triggered
@@ -129,7 +129,7 @@ export class UIElementRegistry {
*
* @param cellId - stringified cellId
*/
- removeElementsByCell(cellId: CellId) {
+ public removeElementsByCell(cellId: CellId) {
const objectIds = [...this.entries.keys()].filter((objectId) =>
objectId.startsWith(`${cellId}-`),
);
@@ -145,12 +145,12 @@ export class UIElementRegistry {
* @param objectId - id of the UIElement
* @returns the value for `objectId`, or `undefined` if the object was not found.
*/
- lookupValue(objectId: UIElementId): ValueType {
+ public lookupValue(objectId: UIElementId): ValueType {
const entry = this.entries.get(objectId);
return entry === undefined ? undefined : entry.value;
}
- broadcastMessage(
+ public broadcastMessage(
objectId: UIElementId,
message: unknown,
buffers: readonly DataView[],
@@ -202,7 +202,7 @@ export class UIElementRegistry {
* @param objectId - id of the UIElement
* @param value - value to broadcast
*/
- broadcastValueUpdate(
+ public broadcastValueUpdate(
initiator: HTMLElement,
objectId: UIElementId,
value: ValueType,
diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.ts
index 25002b7995..df7835271e 100644
--- a/frontend/src/core/hotkeys/hotkeys.ts
+++ b/frontend/src/core/hotkeys/hotkeys.ts
@@ -510,13 +510,13 @@ export class HotkeyProvider implements IHotkeyProvider {
/**
* @param platform - See {@link HotkeyProviderOptions.platform}.
*/
- static create(platform?: Platform): HotkeyProvider {
+ public static create(platform?: Platform): HotkeyProvider {
return new HotkeyProvider(DEFAULT_HOT_KEY, { platform });
}
private hotkeys: Record<HotkeyAction, Hotkey>;
- constructor(
+ public constructor(
hotkeys: Record<HotkeyAction, Hotkey>,
options: HotkeyProviderOptions = {},
) {
@@ -525,11 +525,11 @@ export class HotkeyProvider implements IHotkeyProvider {
this.mod = this.platform === "mac" ? "Cmd" : "Ctrl";
}
- iterate(): HotkeyAction[] {
+ public iterate(): HotkeyAction[] {
return Objects.keys(this.hotkeys);
}
- getHotkey(action: HotkeyAction): ResolvedHotkey {
+ public getHotkey(action: HotkeyAction): ResolvedHotkey {
const { name, key, additionalKeywords } = this.hotkeys[action];
if (typeof key === "string") {
return {
@@ -553,15 +553,15 @@ export class HotkeyProvider implements IHotkeyProvider {
};
}
- getHotkeyDisplay(action: HotkeyAction): string {
+ public getHotkeyDisplay(action: HotkeyAction): string {
return this.hotkeys[action].name;
}
- isEditable(action: HotkeyAction): boolean {
+ public isEditable(action: HotkeyAction): boolean {
return this.hotkeys[action].editable !== false;
}
- getHotkeyGroups(): Record<HotkeyGroup, HotkeyAction[]> {
+ public getHotkeyGroups(): Record<HotkeyGroup, HotkeyAction[]> {
return Objects.groupBy(
Objects.entries(this.hotkeys),
([, hotkey]) => hotkey.group,
@@ -573,7 +573,7 @@ export class HotkeyProvider implements IHotkeyProvider {
export class OverridingHotkeyProvider extends HotkeyProvider {
private readonly overrides: Partial<Record<HotkeyAction, string | undefined>>;
- constructor(
+ public constructor(
overrides: Partial<Record<HotkeyAction, string | undefined>>,
options: HotkeyProviderOptions = {},
) {
@@ -581,7 +581,7 @@ export class OverridingHotkeyProvider extends HotkeyProvider {
this.overrides = overrides;
}
- override getHotkey(action: HotkeyAction): ResolvedHotkey {
+ public override getHotkey(action: HotkeyAction): ResolvedHotkey {
const base = super.getHotkey(action);
const override = this.overrides[action];
return {
diff --git a/frontend/src/core/islands/__tests__/bridge.test.ts b/frontend/src/core/islands/__tests__/bridge.test.ts
index d343c822c2..96328c05ac 100644
--- a/frontend/src/core/islands/__tests__/bridge.test.ts
+++ b/frontend/src/core/islands/__tests__/bridge.test.ts
@@ -38,12 +38,12 @@ vi.stubGlobal(
// Create a mock URL class that works as a constructor
class MockURL {
- href: string;
- constructor(url: string, base?: string | URL) {
+ public href: string;
+ public constructor(url: string, base?: string | URL) {
this.href = base ? `${base}/${url}` : url;
}
- static createObjectURL = vi.fn(() => "blob:mock-url");
- static revokeObjectURL = vi.fn();
+ public static createObjectURL = vi.fn(() => "blob:mock-url");
+ public static revokeObjectURL = vi.fn();
}
vi.stubGlobal("URL", MockURL);
diff --git a/frontend/src/core/islands/__tests__/test-utils.tsx b/frontend/src/core/islands/__tests__/test-utils.tsx
index 6178c23b69..324176e2e7 100644
--- a/frontend/src/core/islands/__tests__/test-utils.tsx
+++ b/frontend/src/core/islands/__tests__/test-utils.tsx
@@ -236,11 +236,11 @@ export class MockWorkerFactory implements WorkerFactory {
public workers: Worker[] = [];
private readonly mockWorker?: Worker;
- constructor(mockWorker?: Worker) {
+ public constructor(mockWorker?: Worker) {
this.mockWorker = mockWorker;
}
- create(): Worker {
+ public create(): Worker {
const worker = this.mockWorker || this.createMockWorker();
this.workers.push(worker);
return worker;
@@ -259,11 +259,11 @@ export class MockWorkerFactory implements WorkerFactory {
} as unknown as Worker;
}
- getCreatedWorkers(): Worker[] {
+ public getCreatedWorkers(): Worker[] {
return this.workers;
}
- terminateAll(): void {
+ public terminateAll(): void {
for (const worker of this.workers) {
worker.terminate();
}
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index c3f48cc750..f22960128d 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -72,7 +72,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
public initialized = new Deferred<void>();
- constructor(config: IslandsBridgeConfig = {}) {
+ public constructor(config: IslandsBridgeConfig = {}) {
this.store = config.store || defaultStore;
this.root = config.root || document;
@@ -120,7 +120,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
});
}
- async initializeApps(): Promise<void> {
+ public async initializeApps(): Promise<void> {
await this.enqueueAppTransition(async () => {
await this.workerReady.promise;
await this.startApps();
@@ -211,7 +211,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
}
}
- async stopSession(appId?: string): Promise<void> {
+ public async stopSession(appId?: string): Promise<void> {
await this.enqueueAppTransition(async () => {
const session = this.session;
if (session?.code === undefined || (appId && session.appId !== appId)) {
@@ -238,7 +238,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
/**
* Starts a new Python session for an app
*/
- async startSession(opts: {
+ public async startSession(opts: {
code: string;
appId: string;
sessionGeneration: number;
@@ -249,7 +249,9 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
/**
* Sets up a consumer for kernel messages
*/
- consumeMessages(consumer: (message: IslandsKernelMessage) => void): void {
+ public consumeMessages(
+ consumer: (message: IslandsKernelMessage) => void,
+ ): void {
this.messageConsumer = consumer;
this.rpc.proxy.send.consumerReady({});
}
@@ -258,7 +260,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
// RunRequests Implementation
// ============================================================================
- sendComponentValues: RunRequests["sendComponentValues"] = async (
+ public sendComponentValues: RunRequests["sendComponentValues"] = async (
request,
): Promise<null> => {
await this.putControlRequest({
@@ -269,11 +271,12 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendInstantiate: RunRequests["sendInstantiate"] = async (): Promise<null> => {
- return null;
- };
+ public sendInstantiate: RunRequests["sendInstantiate"] =
+ async (): Promise<null> => {
+ return null;
+ };
- sendFunctionRequest: RunRequests["sendFunctionRequest"] = async (
+ public sendFunctionRequest: RunRequests["sendFunctionRequest"] = async (
request,
): Promise<null> => {
await this.putControlRequest({
@@ -283,7 +286,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendModelValue: RunRequests["sendModelValue"] = async (request) => {
+ public sendModelValue: RunRequests["sendModelValue"] = async (request) => {
await this.putControlRequest({
type: "model",
...request,
@@ -295,7 +298,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
// EditRequests Implementation
// ============================================================================
- sendRun: EditRequests["sendRun"] = async (request): Promise<null> => {
+ public sendRun: EditRequests["sendRun"] = async (request): Promise<null> => {
const session = await this.getActiveSession();
await this.rpc.proxy.request.loadPackages({
appId: session.appId,
@@ -316,75 +319,75 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
// Not Implemented (Read-Only Mode)
// ============================================================================
- getUsageStats = throwNotImplemented;
- getEnvironmentInfo = throwNotImplemented;
- sendRename = throwNotImplemented;
- sendSave = throwNotImplemented;
- sendCopy = throwNotImplemented;
- sendRunScratchpad = throwNotImplemented;
- sendStdin = throwNotImplemented;
- sendInterrupt = throwNotImplemented;
- sendShutdown = throwNotImplemented;
- sendFormat = throwNotImplemented;
- sendDeleteCell = throwNotImplemented;
- sendInstallMissingPackages = throwNotImplemented;
- sendCodeCompletionRequest = throwNotImplemented;
- saveUserConfig = throwNotImplemented;
- saveAppConfig = throwNotImplemented;
- saveCellConfig = throwNotImplemented;
- sendRestart = throwNotImplemented;
- sendDocumentTransaction = throwNotImplemented;
- readCode = throwNotImplemented;
- readSnippets = throwNotImplemented;
- previewDatasetColumn = throwNotImplemented;
- previewSQLTable = throwNotImplemented;
- previewSQLTableList = throwNotImplemented;
- previewSQLSchemaList = throwNotImplemented;
- previewDataSourceConnection = throwNotImplemented;
- discoverDataSources = throwNotImplemented;
- validateSQL = throwNotImplemented;
- openFile = throwNotImplemented;
- getFileRoots = throwNotImplemented;
- sendListFiles = throwNotImplemented;
- sendSearchFiles = throwNotImplemented;
- sendPdb = throwNotImplemented;
- sendSetBreakpoints = throwNotImplemented;
- sendCreateFileOrFolder = throwNotImplemented;
- sendDeleteFileOrFolder = throwNotImplemented;
- sendCopyFileOrFolder = throwNotImplemented;
- sendRenameFileOrFolder = throwNotImplemented;
- sendUpdateFile = throwNotImplemented;
- sendFileDetails = throwNotImplemented;
- openTutorial = throwNotImplemented;
- getExportAvailability = throwNotImplemented;
- installExportRequirements = throwNotImplemented;
- exportAsHTML = throwNotImplemented;
- exportAsIPYNB = throwNotImplemented;
- exportAsMarkdown = throwNotImplemented;
- exportAsScript = throwNotImplemented;
- exportAsPDF = throwNotImplemented;
- autoExportAsHTML = throwNotImplemented;
- autoExportAsMarkdown = throwNotImplemented;
- autoExportAsIPYNB = throwNotImplemented;
- updateCellOutputs = throwNotImplemented;
- addPackage = throwNotImplemented;
- removePackage = throwNotImplemented;
- getPackageList = throwNotImplemented;
- getSandbox = throwNotImplemented;
- updateManifest = throwNotImplemented;
- syncSandbox = throwNotImplemented;
- getDependencyTree = throwNotImplemented;
- getRecentFiles = throwNotImplemented;
- getWorkspaceFiles = throwNotImplemented;
- getRunningNotebooks = throwNotImplemented;
- shutdownSession = throwNotImplemented;
- listSecretKeys = throwNotImplemented;
- writeSecret = throwNotImplemented;
- invokeAiTool = throwNotImplemented;
- clearCache = throwNotImplemented;
- getCacheInfo = throwNotImplemented;
- listStorageEntries = throwNotImplemented;
- downloadStorage = throwNotImplemented;
+ public getUsageStats = throwNotImplemented;
+ public getEnvironmentInfo = throwNotImplemented;
+ public sendRename = throwNotImplemented;
+ public sendSave = throwNotImplemented;
+ public sendCopy = throwNotImplemented;
+ public sendRunScratchpad = throwNotImplemented;
+ public sendStdin = throwNotImplemented;
+ public sendInterrupt = throwNotImplemented;
+ public sendShutdown = throwNotImplemented;
+ public sendFormat = throwNotImplemented;
+ public sendDeleteCell = throwNotImplemented;
+ public sendInstallMissingPackages = throwNotImplemented;
+ public sendCodeCompletionRequest = throwNotImplemented;
+ public saveUserConfig = throwNotImplemented;
+ public saveAppConfig = throwNotImplemented;
+ public saveCellConfig = throwNotImplemented;
+ public sendRestart = throwNotImplemented;
+ public sendDocumentTransaction = throwNotImplemented;
+ public readCode = throwNotImplemented;
+ public readSnippets = throwNotImplemented;
+ public previewDatasetColumn = throwNotImplemented;
+ public previewSQLTable = throwNotImplemented;
+ public previewSQLTableList = throwNotImplemented;
+ public previewSQLSchemaList = throwNotImplemented;
+ public previewDataSourceConnection = throwNotImplemented;
+ public discoverDataSources = throwNotImplemented;
+ public validateSQL = throwNotImplemented;
+ public openFile = throwNotImplemented;
+ public getFileRoots = throwNotImplemented;
+ public sendListFiles = throwNotImplemented;
+ public sendSearchFiles = throwNotImplemented;
+ public sendPdb = throwNotImplemented;
+ public sendSetBreakpoints = throwNotImplemented;
+ public sendCreateFileOrFolder = throwNotImplemented;
+ public sendDeleteFileOrFolder = throwNotImplemented;
+ public sendCopyFileOrFolder = throwNotImplemented;
+ public sendRenameFileOrFolder = throwNotImplemented;
+ public sendUpdateFile = throwNotImplemented;
+ public sendFileDetails = throwNotImplemented;
+ public openTutorial = throwNotImplemented;
+ public getExportAvailability = throwNotImplemented;
+ public installExportRequirements = throwNotImplemented;
+ public exportAsHTML = throwNotImplemented;
+ public exportAsIPYNB = throwNotImplemented;
+ public exportAsMarkdown = throwNotImplemented;
+ public exportAsScript = throwNotImplemented;
+ public exportAsPDF = throwNotImplemented;
+ public autoExportAsHTML = throwNotImplemented;
+ public autoExportAsMarkdown = throwNotImplemented;
+ public autoExportAsIPYNB = throwNotImplemented;
+ public updateCellOutputs = throwNotImplemented;
+ public addPackage = throwNotImplemented;
+ public removePackage = throwNotImplemented;
+ public getPackageList = throwNotImplemented;
+ public getSandbox = throwNotImplemented;
+ public updateManifest = throwNotImplemented;
+ public syncSandbox = throwNotImplemented;
+ public getDependencyTree = throwNotImplemented;
+ public getRecentFiles = throwNotImplemented;
+ public getWorkspaceFiles = throwNotImplemented;
+ public getRunningNotebooks = throwNotImplemented;
+ public shutdownSession = throwNotImplemented;
+ public listSecretKeys = throwNotImplemented;
+ public writeSecret = throwNotImplemented;
+ public invokeAiTool = throwNotImplemented;
+ public clearCache = throwNotImplemented;
+ public getCacheInfo = throwNotImplemented;
+ public listStorageEntries = throwNotImplemented;
+ public downloadStorage = throwNotImplemented;
// The kernel uses msgspec to parse control requests, which requires a 'type'
// field for discriminated union deserialization.
@@ -412,7 +415,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
/**
* Cleans up resources (for testing)
*/
- destroy(): void {
+ public destroy(): void {
// Future: terminate worker if we own it
}
}
diff --git a/frontend/src/core/islands/components/web-components.tsx b/frontend/src/core/islands/components/web-components.tsx
index 121941129a..26bf1ea3af 100644
--- a/frontend/src/core/islands/components/web-components.tsx
+++ b/frontend/src/core/islands/components/web-components.tsx
@@ -51,7 +51,7 @@ export class MarimoIslandElement extends HTMLElement {
public static readonly editorTagName = ISLAND_TAG_NAMES.CODE_EDITOR;
public static readonly styleNamespace = ISLAND_CSS_CLASSES.NAMESPACE;
- constructor() {
+ public constructor() {
super();
this.classList.add(MarimoIslandElement.styleNamespace);
}
@@ -59,7 +59,7 @@ export class MarimoIslandElement extends HTMLElement {
/**
* Gets the app ID from the element's data attribute
*/
- get appId(): string {
+ public get appId(): string {
const appId = this.getAttribute(ISLAND_DATA_ATTRIBUTES.APP_ID);
invariant(appId, "Missing data-app-id attribute");
return appId;
@@ -68,7 +68,7 @@ export class MarimoIslandElement extends HTMLElement {
/**
* Whether this island is reactive (has code sent to Python for execution)
*/
- get isReactive(): boolean {
+ public get isReactive(): boolean {
return this.getAttribute(ISLAND_DATA_ATTRIBUTES.REACTIVE) === "true";
}
@@ -76,7 +76,7 @@ export class MarimoIslandElement extends HTMLElement {
* Gets the cell ID by looking up the cell index in the notebook state.
* Returns undefined for non-reactive islands (they have no corresponding cell).
*/
- get cellId(): CellId | undefined {
+ public get cellId(): CellId | undefined {
if (!this.isReactive) {
return undefined;
}
@@ -95,7 +95,7 @@ export class MarimoIslandElement extends HTMLElement {
/**
* Gets the code for this island cell
*/
- get code(): string {
+ public get code(): string {
return extractIslandCodeFromEmbed(this);
}
@@ -115,7 +115,7 @@ export class MarimoIslandElement extends HTMLElement {
* which can happen inside a React render cycle. Rendering
* synchronously from there causes "unmount during render" warnings.
*/
- connectedCallback(): void {
+ public connectedCallback(): void {
const connectionGeneration = ++this.connectionGeneration;
this.addEventListener(
ISLAND_SOURCE_CHANGED_EVENT,
@@ -296,7 +296,7 @@ export class MarimoIslandElement extends HTMLElement {
/**
* Cleanup when element is removed from DOM
*/
- disconnectedCallback(): void {
+ public disconnectedCallback(): void {
this.removeEventListener(
ISLAND_SOURCE_CHANGED_EVENT,
this.handleSourceChanged,
diff --git a/frontend/src/core/islands/worker-factory.ts b/frontend/src/core/islands/worker-factory.ts
index 9541542747..a514888c85 100644
--- a/frontend/src/core/islands/worker-factory.ts
+++ b/frontend/src/core/islands/worker-factory.ts
@@ -39,7 +39,7 @@ export class DefaultWorkerFactory implements WorkerFactory {
private readonly url: string;
private readonly name: string;
- constructor(config: DefaultWorkerFactoryConfig = {}) {
+ public constructor(config: DefaultWorkerFactoryConfig = {}) {
this.url = config.workerUrl || this.getDefaultWorkerUrl();
this.name = config.workerName || getMarimoVersion();
}
@@ -47,7 +47,7 @@ export class DefaultWorkerFactory implements WorkerFactory {
/**
* Creates a new Pyodide worker
*/
- create(): Worker {
+ public create(): Worker {
return createModuleWorker(new URL(this.url, import.meta.url), {
name: this.name,
});
diff --git a/frontend/src/core/islands/worker/__tests__/controller.test.ts b/frontend/src/core/islands/worker/__tests__/controller.test.ts
index 1fc00ec518..5f6e71d6dc 100644
--- a/frontend/src/core/islands/worker/__tests__/controller.test.ts
+++ b/frontend/src/core/islands/worker/__tests__/controller.test.ts
@@ -5,7 +5,7 @@ import { describe, expect, it, vi } from "vitest";
import { ReadonlyWasmController } from "../controller";
class TestController extends ReadonlyWasmController {
- setPyodide(pyodide: PyodideInterface) {
+ public setPyodide(pyodide: PyodideInterface) {
this.pyodide = pyodide;
}
}
diff --git a/frontend/src/core/islands/worker/controller.ts b/frontend/src/core/islands/worker/controller.ts
index bcd546be7e..7d0e52b3ce 100644
--- a/frontend/src/core/islands/worker/controller.ts
+++ b/frontend/src/core/islands/worker/controller.ts
@@ -9,7 +9,7 @@ import type { JsonString } from "@/utils/json/base64";
import { Logger } from "../../../utils/Logger";
export class ReadonlyWasmController extends DefaultWasmController {
- override async bootstrap(opts: {
+ public override async bootstrap(opts: {
version: string;
pyodideVersion: string;
}): Promise<PyodideInterface> {
@@ -17,7 +17,10 @@ export class ReadonlyWasmController extends DefaultWasmController {
return pyodide;
}
- override async mountFilesystem(opts: { code: string; filename: string }) {
+ public override async mountFilesystem(opts: {
+ code: string;
+ filename: string;
+ }) {
const { code, filename } = opts;
// Write file
try {
@@ -34,7 +37,7 @@ export class ReadonlyWasmController extends DefaultWasmController {
return { code, filename };
}
- override async startSession(opts: {
+ public override async startSession(opts: {
code: string;
filename: string | null;
onMessage: (message: JsonString<NotificationPayload>) => void;
diff --git a/frontend/src/core/kernel/RuntimeState.ts b/frontend/src/core/kernel/RuntimeState.ts
index e16763d49a..4e4f116cb1 100644
--- a/frontend/src/core/kernel/RuntimeState.ts
+++ b/frontend/src/core/kernel/RuntimeState.ts
@@ -17,7 +17,7 @@ export class RuntimeState {
/**
* Shared instance of RuntimeState since this must be a singleton.
*/
- static get INSTANCE(): RuntimeState {
+ public static get INSTANCE(): RuntimeState {
const KEY = "_marimo_private_RuntimeState";
if (!window[KEY]) {
window[KEY] = new RuntimeState(UI_ELEMENT_REGISTRY);
@@ -31,7 +31,7 @@ export class RuntimeState {
private _sendComponentValues: RunRequests["sendComponentValues"] | undefined;
private uiElementRegistry: UIElementRegistry;
- constructor(uiElementRegistry: UIElementRegistry) {
+ public constructor(uiElementRegistry: UIElementRegistry) {
this.uiElementRegistry = uiElementRegistry;
}
@@ -45,7 +45,7 @@ export class RuntimeState {
/**
* Start listening for events from UIElements
*/
- start(sendComponentValues: RunRequests["sendComponentValues"]) {
+ public start(sendComponentValues: RunRequests["sendComponentValues"]) {
if (this.hasStarted) {
Logger.warn("RuntimeState already started");
return;
@@ -61,7 +61,7 @@ export class RuntimeState {
/**
* Stop listening for events from UIElements
*/
- stop() {
+ public stop() {
if (!this.hasStarted) {
Logger.warn("RuntimeState already stopped");
return;
diff --git a/frontend/src/core/lsp/__tests__/transport.test.ts b/frontend/src/core/lsp/__tests__/transport.test.ts
index d726eb1b00..e51c22d6f5 100644
--- a/frontend/src/core/lsp/__tests__/transport.test.ts
+++ b/frontend/src/core/lsp/__tests__/transport.test.ts
@@ -10,28 +10,28 @@ vi.mock("@/utils/Logger", () => ({
}));
class FakeWebSocket {
- static readonly CONNECTING = 0;
- static readonly OPEN = 1;
- static readonly CLOSING = 2;
- static readonly CLOSED = 3;
- static readonly instances: FakeWebSocket[] = [];
-
- readonly sent: string[] = [];
- readonly url: string;
- readonly protocols: string | string[] | undefined;
- readyState = FakeWebSocket.CONNECTING;
+ public static readonly CONNECTING = 0;
+ public static readonly OPEN = 1;
+ public static readonly CLOSING = 2;
+ public static readonly CLOSED = 3;
+ public static readonly instances: FakeWebSocket[] = [];
+
+ public readonly sent: string[] = [];
+ public readonly url: string;
+ public readonly protocols: string | string[] | undefined;
+ public readyState = FakeWebSocket.CONNECTING;
private readonly listeners = new Map<
string,
Set<(event: { data?: unknown }) => void>
>();
- constructor(url: string, protocols?: string | string[]) {
+ public constructor(url: string, protocols?: string | string[]) {
this.url = url;
this.protocols = protocols;
FakeWebSocket.instances.push(this);
}
- addEventListener(
+ public addEventListener(
type: string,
listener: (event: { data?: unknown }) => void,
) {
@@ -40,34 +40,34 @@ class FakeWebSocket {
this.listeners.set(type, listeners);
}
- send(frame: string) {
+ public send(frame: string) {
this.sent.push(frame);
}
- close() {
+ public close() {
this.readyState = FakeWebSocket.CLOSED;
this.emit("close", {});
}
- open() {
+ public open() {
this.readyState = FakeWebSocket.OPEN;
this.emit("open", {});
}
- fail() {
+ public fail() {
this.emit("error", {});
}
- disconnect() {
+ public disconnect() {
this.readyState = FakeWebSocket.CLOSED;
this.emit("close", {});
}
- receive(message: JSONRPCMessage) {
+ public receive(message: JSONRPCMessage) {
this.emit("message", { data: JSON.stringify(message) });
}
- messages(): JSONRPCMessage[] {
+ public messages(): JSONRPCMessage[] {
return this.sent.map((frame) => {
const message: unknown = JSON.parse(frame);
if (!isJSONRPCMessage(message)) {
diff --git a/frontend/src/core/lsp/transport.ts b/frontend/src/core/lsp/transport.ts
index b556a472c4..b1c8723e9f 100644
--- a/frontend/src/core/lsp/transport.ts
+++ b/frontend/src/core/lsp/transport.ts
@@ -100,7 +100,7 @@ export class ReconnectingWebSocketTransport implements Transport {
public onReconnect: (() => Promise<void>) | undefined;
- constructor(options: ReconnectingWebSocketTransportOptions) {
+ public constructor(options: ReconnectingWebSocketTransportOptions) {
this.options = {
...options,
retries: options.retries ?? 1,
@@ -109,7 +109,7 @@ export class ReconnectingWebSocketTransport implements Transport {
this.onReconnect = options.onReconnect;
}
- async connect(): Promise<void> {
+ public async connect(): Promise<void> {
if (this.isClosed) {
throw new Error("Transport is closed");
}
@@ -136,7 +136,7 @@ export class ReconnectingWebSocketTransport implements Transport {
return this.isClosed || generation !== this.connectionGeneration;
}
- send(message: JSONRPCMessage): void {
+ public send(message: JSONRPCMessage): void {
if (this.isClosed) {
return;
}
@@ -162,14 +162,14 @@ export class ReconnectingWebSocketTransport implements Transport {
this.reconnect();
}
- onMessage(handler: (message: JSONRPCMessage) => void): () => void {
+ public onMessage(handler: (message: JSONRPCMessage) => void): () => void {
this.messageHandlers.add(handler);
return () => {
this.messageHandlers.delete(handler);
};
}
- close(): void {
+ public close(): void {
if (this.isClosed) {
return;
}
diff --git a/frontend/src/core/network/CachingRequestRegistry.ts b/frontend/src/core/network/CachingRequestRegistry.ts
index dfbe7b7e67..65bc49a5a6 100644
--- a/frontend/src/core/network/CachingRequestRegistry.ts
+++ b/frontend/src/core/network/CachingRequestRegistry.ts
@@ -22,7 +22,7 @@ export class CachingRequestRegistry<REQ, RES> {
private toKey: ToKey<REQ>;
private cache: LRUCache<string, Promise<RES>>;
- static jsonStringifySortKeys<T>(): ToKey<T> {
+ public static jsonStringifySortKeys<T>(): ToKey<T> {
return (o: T) => {
if (typeof o !== "object" || o === null) {
return String(o);
@@ -31,7 +31,7 @@ export class CachingRequestRegistry<REQ, RES> {
};
}
- constructor(
+ public constructor(
delegate: DeferredRequestRegistry<REQ, RES>,
options: CachingOptions<REQ> = {},
) {
diff --git a/frontend/src/core/network/DeferredRequestRegistry.ts b/frontend/src/core/network/DeferredRequestRegistry.ts
index 625be8f77e..cd500473e6 100644
--- a/frontend/src/core/network/DeferredRequestRegistry.ts
+++ b/frontend/src/core/network/DeferredRequestRegistry.ts
@@ -27,7 +27,7 @@ export class DeferredRequestRegistry<REQ, RES> {
resolveExistingRequests?: () => RES;
};
- constructor(
+ public constructor(
operation: string,
makeRequest: (id: RequestId, req: REQ) => Promise<void>,
opts: {
@@ -42,7 +42,7 @@ export class DeferredRequestRegistry<REQ, RES> {
this.opts = opts;
}
- async request(opts: REQ): Promise<RES> {
+ public async request(opts: REQ): Promise<RES> {
if (this.opts.resolveExistingRequests) {
const result = this.opts.resolveExistingRequests();
for (const deferred of this.requests.values()) {
@@ -63,7 +63,7 @@ export class DeferredRequestRegistry<REQ, RES> {
return deferred.promise;
}
- resolve(requestId: RequestId, response: RES) {
+ public resolve(requestId: RequestId, response: RES) {
const entry = this.requests.get(requestId);
if (entry === undefined) {
return;
@@ -73,7 +73,7 @@ export class DeferredRequestRegistry<REQ, RES> {
this.requests.delete(requestId);
}
- reject(requestId: RequestId, error: Error) {
+ public reject(requestId: RequestId, error: Error) {
const entry = this.requests.get(requestId);
if (entry === undefined) {
return;
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index b49d4bfc00..b4c2fbf426 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -14,7 +14,7 @@ export class RuntimeManager {
private config: RuntimeConfig;
private lazy: boolean;
- constructor(config: RuntimeConfig, lazy = false) {
+ public constructor(config: RuntimeConfig, lazy = false) {
this.config = config;
this.lazy = lazy;
// Validate the URL on construction
@@ -32,15 +32,15 @@ export class RuntimeManager {
}
}
- get isLazy(): boolean {
+ public get isLazy(): boolean {
return this.lazy;
}
- get httpURL(): URL {
+ public get httpURL(): URL {
return new URL(this.config.url);
}
- get isSameOrigin(): boolean {
+ public get isSameOrigin(): boolean {
return this.httpURL.origin === window.location.origin;
}
@@ -51,7 +51,7 @@ export class RuntimeManager {
/**
* The base URL of the runtime.
*/
- formatHttpURL({
+ public formatHttpURL({
path = "",
searchParams,
restrictToKnownQueryParams = true,
@@ -105,7 +105,10 @@ export class RuntimeManager {
* An HTTP URL for requests made by browser navigation (e.g. anchor-click
* downloads), which cannot attach auth headers.
*/
- formatNavigableHttpURL(path: string, searchParams?: URLSearchParams): URL {
+ public formatNavigableHttpURL(
+ path: string,
+ searchParams?: URLSearchParams,
+ ): URL {
const url = this.formatHttpURL({ path, searchParams });
// Drop any token inherited from the current page's query params; re-add it
// only when cross-origin. Same-origin downloads authenticate via the
@@ -115,7 +118,7 @@ export class RuntimeManager {
return this.appendCrossOriginAuth(url);
}
- formatWsURL(path: string, searchParams?: URLSearchParams): URL {
+ public formatWsURL(path: string, searchParams?: URLSearchParams): URL {
// We don't restrict to known query parameters, since mo.query_params()
// can accept arbitrary parameters.
const url = this.formatHttpURL({
@@ -150,7 +153,7 @@ export class RuntimeManager {
/**
* The WebSocket URL of the runtime.
*/
- getWsURL(sessionId: SessionId): URL {
+ public getWsURL(sessionId: SessionId): URL {
return this.formatWsURL("/ws", this.getSessionSearchParams(sessionId));
}
@@ -160,7 +163,7 @@ export class RuntimeManager {
* can send headers, so auth travels in the Authorization header
* (see `headers()`) instead of the URL.
*/
- getSseURL(sessionId: SessionId): URL {
+ public getSseURL(sessionId: SessionId): URL {
const url = this.formatHttpURL({
path: "/sse",
searchParams: this.getSessionSearchParams(sessionId),
@@ -176,14 +179,14 @@ export class RuntimeManager {
/**
* The WebSocket Sync URL of the runtime, for real-time updates.
*/
- getWsSyncURL(sessionId: SessionId): URL {
+ public getWsSyncURL(sessionId: SessionId): URL {
return this.formatWsURL("/ws_sync", this.getSessionSearchParams(sessionId));
}
/**
* The WebSocket URL of the terminal.
*/
- getTerminalWsURL(size?: { rows: number; cols: number }): URL {
+ public getTerminalWsURL(size?: { rows: number; cols: number }): URL {
const url = this.formatWsURL("/terminal/ws");
if (size) {
url.searchParams.set("rows", String(size.rows));
@@ -195,7 +198,9 @@ export class RuntimeManager {
/**
* The URL of the copilot server.
*/
- getLSPURL(lsp: "pylsp" | "basedpyright" | "copilot" | "ty" | "pyrefly"): URL {
+ public getLSPURL(
+ lsp: "pylsp" | "basedpyright" | "copilot" | "ty" | "pyrefly",
+ ): URL {
if (lsp === "copilot") {
// For copilot, strip all query parameters except the auth token.
// Copilot doesn't understand arbitrary query params, but we still
@@ -211,14 +216,14 @@ export class RuntimeManager {
return this.formatWsURL(`/lsp/${lsp}`);
}
- getAiURL(path: "completion" | "chat"): URL {
+ public getAiURL(path: "completion" | "chat"): URL {
return this.formatHttpURL({ path: `/api/ai/${path}` });
}
/**
* The URL of the health check endpoint.
*/
- healthURL(): URL {
+ public healthURL(): URL {
return this.formatHttpURL({ path: "/health" });
}
@@ -234,7 +239,7 @@ export class RuntimeManager {
}
}
- async reconcileFromHealth(): Promise<boolean> {
+ public async reconcileFromHealth(): Promise<boolean> {
// Always healthy if WASM, Islands, or a static notebook (no server)
if (this.isServerless) {
return true;
@@ -261,7 +266,7 @@ export class RuntimeManager {
return response.ok;
}
- async probeHealth(): Promise<boolean> {
+ public async probeHealth(): Promise<boolean> {
// Always healthy if WASM, Islands, or a static notebook (no server)
if (this.isServerless) {
return true;
@@ -304,7 +309,7 @@ export class RuntimeManager {
}
}
- async init(options?: { disableRetryDelay?: boolean }) {
+ public async init(options?: { disableRetryDelay?: boolean }) {
Logger.debug("Initializing runtime...");
let retries = 0;
// This matches backoff logic elsewhere.
@@ -335,11 +340,11 @@ export class RuntimeManager {
/**
* Wait for the runtime to be healthy.
*/
- async waitForHealthy(): Promise<void> {
+ public async waitForHealthy(): Promise<void> {
return this.initialHealthyCheck.promise;
}
- headers(): KnownHeaders {
+ public headers(): KnownHeaders {
const headers: KnownHeaders = {
"Marimo-Session-Id": getSessionId(),
"Marimo-Server-Token": this.config.serverToken ?? "",
@@ -356,7 +361,7 @@ export class RuntimeManager {
return headers;
}
- sessionHeaders(): Pick<KnownHeaders, "Marimo-Session-Id"> {
+ public sessionHeaders(): Pick<KnownHeaders, "Marimo-Session-Id"> {
return {
"Marimo-Session-Id": getSessionId(),
};
diff --git a/frontend/src/core/static/virtual-file-tracker.ts b/frontend/src/core/static/virtual-file-tracker.ts
index 3a41553bc1..2eee3d10ce 100644
--- a/frontend/src/core/static/virtual-file-tracker.ts
+++ b/frontend/src/core/static/virtual-file-tracker.ts
@@ -13,7 +13,7 @@ export class VirtualFileTracker {
/**
* Shared instance of VirtualFileTracker since this must be a singleton.
*/
- static get INSTANCE(): VirtualFileTracker {
+ public static get INSTANCE(): VirtualFileTracker {
const KEY = "_marimo_private_VirtualFileTracker";
if (!window[KEY]) {
window[KEY] = new VirtualFileTracker();
@@ -21,13 +21,13 @@ export class VirtualFileTracker {
return window[KEY] as VirtualFileTracker;
}
- virtualFiles = new Map<CellId, Set<string>>();
+ public virtualFiles = new Map<CellId, Set<string>>();
private constructor() {
// Private
}
- track(message: Pick<CellMessage, "cell_id" | "output">): void {
+ public track(message: Pick<CellMessage, "cell_id" | "output">): void {
const output = message.output;
const cellId = message.cell_id;
if (!output) {
@@ -48,7 +48,7 @@ export class VirtualFileTracker {
}
}
- filenames(): string[] {
+ public filenames(): string[] {
const set = new Set<string>();
for (const files of this.virtualFiles.values()) {
files.forEach((file) => set.add(file));
@@ -57,7 +57,7 @@ export class VirtualFileTracker {
return [...set];
}
- removeForCellId(cellId: CellId): void {
+ public removeForCellId(cellId: CellId): void {
this.virtualFiles.delete(cellId);
}
}
diff --git a/frontend/src/core/wasm/__tests__/bridge.test.ts b/frontend/src/core/wasm/__tests__/bridge.test.ts
index e784022e36..9d1af4b844 100644
--- a/frontend/src/core/wasm/__tests__/bridge.test.ts
+++ b/frontend/src/core/wasm/__tests__/bridge.test.ts
@@ -35,8 +35,8 @@ vi.stubGlobal(
);
class MockURL extends URL {
- static override createObjectURL = vi.fn(() => "blob:mock-url");
- static override revokeObjectURL = vi.fn();
+ public static override createObjectURL = vi.fn(() => "blob:mock-url");
+ public static override revokeObjectURL = vi.fn();
}
vi.stubGlobal("URL", MockURL);
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index e3626f2bf2..c0fb07f73d 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -57,7 +57,7 @@ type SaveWorker = ReturnType<
>["proxy"]["request"];
export class PyodideBridge implements RunRequests, EditRequests {
- static get INSTANCE(): PyodideBridge {
+ public static get INSTANCE(): PyodideBridge {
const KEY = "_marimo_private_PyodideBridge";
if (!window[KEY]) {
window[KEY] = new PyodideBridge();
@@ -207,12 +207,14 @@ export class PyodideBridge implements RunRequests, EditRequests {
}
}
- attachMessageConsumer(consumer: (message: MessageEvent<string>) => void) {
+ public attachMessageConsumer(
+ consumer: (message: MessageEvent<string>) => void,
+ ) {
this.messageConsumer = consumer;
this.rpc.proxy.send.consumerReady({});
}
- sendRename: EditRequests["sendRename"] = async ({ filename }) => {
+ public sendRename: EditRequests["sendRename"] = async ({ filename }) => {
if (filename === null) {
return null;
}
@@ -227,7 +229,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendSave: EditRequests["sendSave"] = async (request) => {
+ public sendSave: EditRequests["sendSave"] = async (request) => {
if (!this.saveRpc) {
Logger.warn("Save RPC not initialized");
return null;
@@ -254,11 +256,11 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendCopy: EditRequests["sendCopy"] = async () => {
+ public sendCopy: EditRequests["sendCopy"] = async () => {
throwNotImplemented();
};
- sendStdin: EditRequests["sendStdin"] = async (request) => {
+ public sendStdin: EditRequests["sendStdin"] = async (request) => {
await this.rpc.proxy.request.bridge({
functionName: "put_input",
payload: request.text,
@@ -266,15 +268,15 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendPdb: EditRequests["sendPdb"] = async () => {
+ public sendPdb: EditRequests["sendPdb"] = async () => {
throwNotImplemented();
};
- sendSetBreakpoints: EditRequests["sendSetBreakpoints"] = async () => {
+ public sendSetBreakpoints: EditRequests["sendSetBreakpoints"] = async () => {
throwNotImplemented();
};
- sendRun: EditRequests["sendRun"] = async (request) => {
+ public sendRun: EditRequests["sendRun"] = async (request) => {
await this.rpc.proxy.request.loadPackages(request.codes.join("\n"));
await this.putControlRequest({
@@ -283,7 +285,9 @@ export class PyodideBridge implements RunRequests, EditRequests {
});
return null;
};
- sendRunScratchpad: EditRequests["sendRunScratchpad"] = async (request) => {
+ public sendRunScratchpad: EditRequests["sendRunScratchpad"] = async (
+ request,
+ ) => {
await this.rpc.proxy.request.loadPackages(request.code);
await this.putControlRequest({
@@ -292,18 +296,18 @@ export class PyodideBridge implements RunRequests, EditRequests {
});
return null;
};
- sendInterrupt: EditRequests["sendInterrupt"] = async () => {
+ public sendInterrupt: EditRequests["sendInterrupt"] = async () => {
if (this.interruptBuffer !== undefined) {
// 2 sends a SIGINT
this.interruptBuffer[0] = 2;
}
return null;
};
- sendShutdown: EditRequests["sendShutdown"] = async () => {
+ public sendShutdown: EditRequests["sendShutdown"] = async () => {
window.close();
return null;
};
- sendFormat: EditRequests["sendFormat"] = async (request) => {
+ public sendFormat: EditRequests["sendFormat"] = async (request) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "format",
payload: request,
@@ -311,7 +315,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FormatResponse;
};
- sendDeleteCell: EditRequests["sendDeleteCell"] = async (request) => {
+ public sendDeleteCell: EditRequests["sendDeleteCell"] = async (request) => {
await this.putControlRequest({
type: "delete-cell",
...request,
@@ -319,7 +323,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendInstallMissingPackages: EditRequests["sendInstallMissingPackages"] =
+ public sendInstallMissingPackages: EditRequests["sendInstallMissingPackages"] =
async (request) => {
this.putControlRequest({
type: "install-packages",
@@ -327,23 +331,22 @@ export class PyodideBridge implements RunRequests, EditRequests {
});
return null;
};
- sendCodeCompletionRequest: EditRequests["sendCodeCompletionRequest"] = async (
- request,
- ) => {
- // Because the Pyodide worker is single-threaded, sending
- // code completion requests while the kernel is running is useless
- // and runs the risk of choking the kernel
- const isRunning = store.get(notebookIsRunningAtom);
- if (!isRunning) {
- await this.rpc.proxy.request.bridge({
- functionName: "code_complete",
- payload: request,
- });
- }
- return null;
- };
+ public sendCodeCompletionRequest: EditRequests["sendCodeCompletionRequest"] =
+ async (request) => {
+ // Because the Pyodide worker is single-threaded, sending
+ // code completion requests while the kernel is running is useless
+ // and runs the risk of choking the kernel
+ const isRunning = store.get(notebookIsRunningAtom);
+ if (!isRunning) {
+ await this.rpc.proxy.request.bridge({
+ functionName: "code_complete",
+ payload: request,
+ });
+ }
+ return null;
+ };
- saveUserConfig: EditRequests["saveUserConfig"] = async (request) => {
+ public saveUserConfig: EditRequests["saveUserConfig"] = async (request) => {
await this.rpc.proxy.request.bridge({
functionName: "save_user_config",
payload: request,
@@ -361,7 +364,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
});
};
- saveAppConfig: EditRequests["saveAppConfig"] = async (request) => {
+ public saveAppConfig: EditRequests["saveAppConfig"] = async (request) => {
await this.rpc.proxy.request.bridge({
functionName: "save_app_config",
payload: request,
@@ -369,7 +372,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- saveCellConfig: EditRequests["saveCellConfig"] = async (request) => {
+ public saveCellConfig: EditRequests["saveCellConfig"] = async (request) => {
await this.putControlRequest({
type: "update-cell-config",
...request,
@@ -377,7 +380,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendRestart = async (): Promise<null> => {
+ public sendRestart = async (): Promise<null> => {
// Save first
const code = await this.readCode();
if (code.contents) {
@@ -388,7 +391,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- readCode: EditRequests["readCode"] = async () => {
+ public readCode: EditRequests["readCode"] = async () => {
if (!this.saveRpc) {
Logger.warn("Save RPC not initialized");
return { contents: "" };
@@ -397,7 +400,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return { contents };
};
- readSnippets: EditRequests["readSnippets"] = async () => {
+ public readSnippets: EditRequests["readSnippets"] = async () => {
const response = await this.rpc.proxy.request.bridge({
functionName: "read_snippets",
payload: undefined,
@@ -405,7 +408,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as Snippets;
};
- openFile: EditRequests["openFile"] = async ({ path }) => {
+ public openFile: EditRequests["openFile"] = async ({ path }) => {
const url = createShareableLink({
code: null,
baseUrl: window.location.origin,
@@ -414,7 +417,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendListFiles: EditRequests["sendListFiles"] = async (request) => {
+ public sendListFiles: EditRequests["sendListFiles"] = async (request) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "list_files",
payload: request,
@@ -422,7 +425,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FileListResponse;
};
- getFileRoots: EditRequests["getFileRoots"] = async () => {
+ public getFileRoots: EditRequests["getFileRoots"] = async () => {
const response = await this.rpc.proxy.request.bridge({
functionName: "file_roots",
payload: undefined,
@@ -430,7 +433,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FileRootsResponse;
};
- sendSearchFiles: EditRequests["sendSearchFiles"] = async (request) => {
+ public sendSearchFiles: EditRequests["sendSearchFiles"] = async (request) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "search_files",
payload: request,
@@ -438,7 +441,9 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FileSearchResponse;
};
- sendComponentValues: RunRequests["sendComponentValues"] = async (request) => {
+ public sendComponentValues: RunRequests["sendComponentValues"] = async (
+ request,
+ ) => {
await this.putControlRequest({
type: "update-ui-element",
...request,
@@ -447,11 +452,13 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendInstantiate: RunRequests["sendInstantiate"] = async (request) => {
+ public sendInstantiate: RunRequests["sendInstantiate"] = async (request) => {
return null;
};
- sendFunctionRequest: RunRequests["sendFunctionRequest"] = async (request) => {
+ public sendFunctionRequest: RunRequests["sendFunctionRequest"] = async (
+ request,
+ ) => {
await this.putControlRequest({
type: "invoke-function",
...request,
@@ -459,39 +466,37 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendCreateFileOrFolder: EditRequests["sendCreateFileOrFolder"] = async (
- request,
- ) => {
- // The WASM RPC boundary can only carry JSON, so we base64-encode the
- // file bytes here. The HTTP transport uses multipart/form-data instead.
- let contents: string | null = null;
- if (request.file) {
- const dataUrl = await serializeBlob(request.file);
- contents = dataUrl.split(",")[1] ?? "";
- }
- const response = await this.rpc.proxy.request.bridge({
- functionName: "create_file_or_directory",
- payload: {
- path: request.path,
- type: request.type,
- name: request.name,
- contents,
- },
- });
- return response as FileCreateResponse;
- };
+ public sendCreateFileOrFolder: EditRequests["sendCreateFileOrFolder"] =
+ async (request) => {
+ // The WASM RPC boundary can only carry JSON, so we base64-encode the
+ // file bytes here. The HTTP transport uses multipart/form-data instead.
+ let contents: string | null = null;
+ if (request.file) {
+ const dataUrl = await serializeBlob(request.file);
+ contents = dataUrl.split(",")[1] ?? "";
+ }
+ const response = await this.rpc.proxy.request.bridge({
+ functionName: "create_file_or_directory",
+ payload: {
+ path: request.path,
+ type: request.type,
+ name: request.name,
+ contents,
+ },
+ });
+ return response as FileCreateResponse;
+ };
- sendDeleteFileOrFolder: EditRequests["sendDeleteFileOrFolder"] = async (
- request,
- ) => {
- const response = await this.rpc.proxy.request.bridge({
- functionName: "delete_file_or_directory",
- payload: request,
- });
- return response as FileDeleteResponse;
- };
+ public sendDeleteFileOrFolder: EditRequests["sendDeleteFileOrFolder"] =
+ async (request) => {
+ const response = await this.rpc.proxy.request.bridge({
+ functionName: "delete_file_or_directory",
+ payload: request,
+ });
+ return response as FileDeleteResponse;
+ };
- sendCopyFileOrFolder: EditRequests["sendCopyFileOrFolder"] = async (
+ public sendCopyFileOrFolder: EditRequests["sendCopyFileOrFolder"] = async (
request,
) => {
const response = await this.rpc.proxy.request.bridge({
@@ -501,17 +506,16 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FileCopyResponse;
};
- sendRenameFileOrFolder: EditRequests["sendRenameFileOrFolder"] = async (
- request,
- ) => {
- const response = await this.rpc.proxy.request.bridge({
- functionName: "move_file_or_directory",
- payload: request,
- });
- return response as FileMoveResponse;
- };
+ public sendRenameFileOrFolder: EditRequests["sendRenameFileOrFolder"] =
+ async (request) => {
+ const response = await this.rpc.proxy.request.bridge({
+ functionName: "move_file_or_directory",
+ payload: request,
+ });
+ return response as FileMoveResponse;
+ };
- sendUpdateFile: EditRequests["sendUpdateFile"] = async (request) => {
+ public sendUpdateFile: EditRequests["sendUpdateFile"] = async (request) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "update_file",
payload: request,
@@ -519,7 +523,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FileUpdateResponse;
};
- sendFileDetails: EditRequests["sendFileDetails"] = async (request) => {
+ public sendFileDetails: EditRequests["sendFileDetails"] = async (request) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "file_details",
payload: request,
@@ -527,7 +531,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FileDetailsResponse;
};
- exportAsHTML: EditRequests["exportAsHTML"] = async (
+ public exportAsHTML: EditRequests["exportAsHTML"] = async (
request: ExportAsHTMLRequest,
) => {
await this.pendingSessionSave;
@@ -544,7 +548,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as ExportedFile<string>;
};
- exportAsMarkdown: EditRequests["exportAsMarkdown"] = async (
+ public exportAsMarkdown: EditRequests["exportAsMarkdown"] = async (
request: ExportAsMarkdownRequest,
) => {
await this.pendingSessionSave;
@@ -555,7 +559,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as ExportedFile<string>;
};
- exportAsScript: EditRequests["exportAsScript"] = async (
+ public exportAsScript: EditRequests["exportAsScript"] = async (
request: ExportAsScriptRequest,
) => {
await this.pendingSessionSave;
@@ -566,7 +570,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as ExportedFile<string>;
};
- previewDatasetColumn: EditRequests["previewDatasetColumn"] = async (
+ public previewDatasetColumn: EditRequests["previewDatasetColumn"] = async (
request,
) => {
await this.putControlRequest({
@@ -576,7 +580,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- previewSQLTable: EditRequests["previewSQLTable"] = async (request) => {
+ public previewSQLTable: EditRequests["previewSQLTable"] = async (request) => {
await this.putControlRequest({
type: "preview-sql-table",
...request,
@@ -584,7 +588,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- previewSQLTableList: EditRequests["previewSQLTableList"] = async (
+ public previewSQLTableList: EditRequests["previewSQLTableList"] = async (
request,
) => {
await this.putControlRequest({
@@ -594,7 +598,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- previewSQLSchemaList: EditRequests["previewSQLSchemaList"] = async (
+ public previewSQLSchemaList: EditRequests["previewSQLSchemaList"] = async (
request,
) => {
await this.putControlRequest({
@@ -604,7 +608,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- previewDataSourceConnection: EditRequests["previewDataSourceConnection"] =
+ public previewDataSourceConnection: EditRequests["previewDataSourceConnection"] =
async (request) => {
await this.putControlRequest({
type: "list-data-source-connection",
@@ -613,7 +617,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- validateSQL: EditRequests["validateSQL"] = async (request) => {
+ public validateSQL: EditRequests["validateSQL"] = async (request) => {
await this.putControlRequest({
type: "validate-sql",
...request,
@@ -621,7 +625,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendModelValue: RunRequests["sendModelValue"] = async (request) => {
+ public sendModelValue: RunRequests["sendModelValue"] = async (request) => {
await this.putControlRequest({
type: "model",
...request,
@@ -629,31 +633,31 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- sendDocumentTransaction = () => Promise.resolve(null);
+ public sendDocumentTransaction = () => Promise.resolve(null);
- addPackage: EditRequests["addPackage"] = async (request) => {
+ public addPackage: EditRequests["addPackage"] = async (request) => {
return this.rpc.proxy.request.addPackage(request);
};
- removePackage: EditRequests["removePackage"] = async (request) => {
+ public removePackage: EditRequests["removePackage"] = async (request) => {
return this.rpc.proxy.request.removePackage(request);
};
- getPackageList = async () => {
+ public getPackageList = async () => {
const response = await this.rpc.proxy.request.listPackages();
return response;
};
- getSandbox: EditRequests["getSandbox"] = async () => ({
+ public getSandbox: EditRequests["getSandbox"] = async () => ({
backend: null,
manifest: null,
filename: null,
});
- updateManifest: EditRequests["updateManifest"] = async () => {
+ public updateManifest: EditRequests["updateManifest"] = async () => {
throw new Error("Sandboxes are not supported in WebAssembly");
};
- syncSandbox: EditRequests["syncSandbox"] = async () => {
+ public syncSandbox: EditRequests["syncSandbox"] = async () => {
throw new Error("Sandboxes are not supported in WebAssembly");
};
- getDependencyTree: EditRequests["getDependencyTree"] = async () => {
+ public getDependencyTree: EditRequests["getDependencyTree"] = async () => {
// WASM doesn't support dependency trees yet
return {
tree: {
@@ -666,7 +670,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
};
- listSecretKeys: EditRequests["listSecretKeys"] = async (request) => {
+ public listSecretKeys: EditRequests["listSecretKeys"] = async (request) => {
await this.putControlRequest({
type: "list-secret-keys",
...request,
@@ -674,7 +678,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- discoverDataSources: EditRequests["discoverDataSources"] = async (
+ public discoverDataSources: EditRequests["discoverDataSources"] = async (
request,
) => {
await this.putControlRequest({
@@ -684,33 +688,33 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
- getUsageStats = throwNotImplemented;
- getEnvironmentInfo: EditRequests["getEnvironmentInfo"] = async () => {
+ public getUsageStats = throwNotImplemented;
+ public getEnvironmentInfo: EditRequests["getEnvironmentInfo"] = async () => {
const response = await this.rpc.proxy.request.bridge({
functionName: "get_environment_info",
payload: undefined,
});
return response as EnvironmentInfo;
};
- openTutorial = throwNotImplemented;
- getRecentFiles = throwNotImplemented;
- getWorkspaceFiles = throwNotImplemented;
- getRunningNotebooks = throwNotImplemented;
- shutdownSession = throwNotImplemented;
- getExportAvailability = throwNotImplemented;
- installExportRequirements = throwNotImplemented;
- exportAsIPYNB = throwNotImplemented;
- exportAsPDF = throwNotImplemented;
- autoExportAsHTML = throwNotImplemented;
- autoExportAsMarkdown = throwNotImplemented;
- autoExportAsIPYNB = throwNotImplemented;
- updateCellOutputs = throwNotImplemented;
- writeSecret = throwNotImplemented;
- invokeAiTool = throwNotImplemented;
- clearCache = throwNotImplemented;
- getCacheInfo = throwNotImplemented;
- listStorageEntries = throwNotImplemented;
- downloadStorage = throwNotImplemented;
+ public openTutorial = throwNotImplemented;
+ public getRecentFiles = throwNotImplemented;
+ public getWorkspaceFiles = throwNotImplemented;
+ public getRunningNotebooks = throwNotImplemented;
+ public shutdownSession = throwNotImplemented;
+ public getExportAvailability = throwNotImplemented;
+ public installExportRequirements = throwNotImplemented;
+ public exportAsIPYNB = throwNotImplemented;
+ public exportAsPDF = throwNotImplemented;
+ public autoExportAsHTML = throwNotImplemented;
+ public autoExportAsMarkdown = throwNotImplemented;
+ public autoExportAsIPYNB = throwNotImplemented;
+ public updateCellOutputs = throwNotImplemented;
+ public writeSecret = throwNotImplemented;
+ public invokeAiTool = throwNotImplemented;
+ public clearCache = throwNotImplemented;
+ public getCacheInfo = throwNotImplemented;
+ public listStorageEntries = throwNotImplemented;
+ public downloadStorage = throwNotImplemented;
private async putControlRequest(operation: CommandMessage) {
await this.rpc.proxy.request.bridge({
diff --git a/frontend/src/core/wasm/router.ts b/frontend/src/core/wasm/router.ts
index 8adad295ad..aa8c54656d 100644
--- a/frontend/src/core/wasm/router.ts
+++ b/frontend/src/core/wasm/router.ts
@@ -1,17 +1,17 @@
/* Copyright 2026 Marimo. All rights reserved. */
class URLPyodideRouter {
- getFilename(): string | null {
+ public getFilename(): string | null {
return this.getSearchParam("filename");
}
- setFilename(filename: string) {
+ public setFilename(filename: string) {
this.setSearchParam("filename", filename);
}
- getCodeFromSearchParam(): string | null {
+ public getCodeFromSearchParam(): string | null {
return this.getSearchParam("code");
}
- getCodeFromHash(): string | null {
+ public getCodeFromHash(): string | null {
const hash = window.location.hash;
const prefix = "#code/";
if (!hash.startsWith(prefix)) {
@@ -20,7 +20,7 @@ class URLPyodideRouter {
return hash.slice(prefix.length);
}
- setCodeForHash(code: string) {
+ public setCodeForHash(code: string) {
window.location.hash = `#code/${code}`;
}
diff --git a/frontend/src/core/wasm/store.ts b/frontend/src/core/wasm/store.ts
index 764219684b..c2ffa970bd 100644
--- a/frontend/src/core/wasm/store.ts
+++ b/frontend/src/core/wasm/store.ts
@@ -99,19 +99,19 @@ const emptyFileStore: FileStore = {
export class CompositeFileStore implements FileStore {
private stores: FileStore[];
- constructor(stores: FileStore[]) {
+ public constructor(stores: FileStore[]) {
this.stores = stores;
}
- insert(index: number, store: FileStore) {
+ public insert(index: number, store: FileStore) {
this.stores.splice(index, 0, store);
}
- saveFile(contents: string) {
+ public saveFile(contents: string) {
this.stores.forEach((store) => store.saveFile(contents));
}
- readFile() {
+ public readFile() {
for (const store of this.stores) {
const contents = store.readFile();
if (contents) {
diff --git a/frontend/src/core/wasm/worker/bootstrap.ts b/frontend/src/core/wasm/worker/bootstrap.ts
index d4e9cd4a63..3afeb809b5 100644
--- a/frontend/src/core/wasm/worker/bootstrap.ts
+++ b/frontend/src/core/wasm/worker/bootstrap.ts
@@ -36,12 +36,12 @@ export class DefaultWasmController implements WasmController {
private sessionGeneration = 0;
private activeSessionStops = new Set<PyCallable>();
- get requirePyodide() {
+ public get requirePyodide() {
invariant(this.pyodide, "Pyodide not loaded");
return this.pyodide;
}
- async bootstrap(
+ public async bootstrap(
opts: Parameters<WasmController["bootstrap"]>[0],
): Promise<PyodideInterface> {
const pyodide = await this.loadPyodideAndPackages(opts);
@@ -110,7 +110,10 @@ export class DefaultWasmController implements WasmController {
}
}
- async mountFilesystem(opts: { code: string; filename: string | null }) {
+ public async mountFilesystem(opts: {
+ code: string;
+ filename: string | null;
+ }) {
const span = t.startSpan("mountFilesystem");
// Set up the filesystem
WasmFileSystem.createHomeDir(this.requirePyodide);
@@ -124,7 +127,7 @@ export class DefaultWasmController implements WasmController {
});
}
- async startSession(opts: {
+ public async startSession(opts: {
queryParameters: Record<string, string | string[]>;
code: string;
filename: string | null;
@@ -250,7 +253,7 @@ export class DefaultWasmController implements WasmController {
return bridgeProxy as unknown as SerializedBridge;
}
- async stopSession(): Promise<void> {
+ public async stopSession(): Promise<void> {
this.sessionGeneration += 1;
const stops = [...this.activeSessionStops];
let hasFailure = false;
diff --git a/frontend/src/core/wasm/worker/message-buffer.ts b/frontend/src/core/wasm/worker/message-buffer.ts
index 133c9d4f36..985e316fce 100644
--- a/frontend/src/core/wasm/worker/message-buffer.ts
+++ b/frontend/src/core/wasm/worker/message-buffer.ts
@@ -8,12 +8,12 @@ export class MessageBuffer<T> {
private buffer: T[];
private started = false;
private onMessage: (data: T) => void;
- constructor(onMessage: (data: T) => void) {
+ public constructor(onMessage: (data: T) => void) {
this.onMessage = onMessage;
this.buffer = [];
}
- push = (data: T) => {
+ public push = (data: T) => {
if (this.started) {
this.onMessage(data);
} else {
@@ -24,7 +24,7 @@ export class MessageBuffer<T> {
/**
* Start processing messages
*/
- start = () => {
+ public start = () => {
this.started = true;
// Flush the buffer
this.buffer.forEach((data) => this.onMessage(data));
diff --git a/frontend/src/core/websocket/transports/__tests__/ws.test.ts b/frontend/src/core/websocket/transports/__tests__/ws.test.ts
index 77b8683552..131e8c5a45 100644
--- a/frontend/src/core/websocket/transports/__tests__/ws.test.ts
+++ b/frontend/src/core/websocket/transports/__tests__/ws.test.ts
@@ -7,20 +7,20 @@ let innerListeners: Record<string, ((e: unknown) => void)[]>;
vi.mock("partysocket/ws", () => {
class FakeReconnectingWebSocket {
- retryCount = 0;
- readyState = WebSocket.CONNECTING;
- constructor() {
+ public retryCount = 0;
+ public readyState = WebSocket.CONNECTING;
+ public constructor() {
innerListeners = { open: [], close: [], message: [], error: [] };
}
- addEventListener(event: string, cb: (e: unknown) => void) {
+ public addEventListener(event: string, cb: (e: unknown) => void) {
innerListeners[event].push(cb);
}
- removeEventListener(event: string, cb: (e: unknown) => void) {
+ public removeEventListener(event: string, cb: (e: unknown) => void) {
innerListeners[event] = innerListeners[event].filter((c) => c !== cb);
}
- reconnect() {}
- close() {}
- send() {}
+ public reconnect() {}
+ public close() {}
+ public send() {}
}
return { default: FakeReconnectingWebSocket };
});
diff --git a/frontend/src/core/websocket/transports/basic.ts b/frontend/src/core/websocket/transports/basic.ts
index b55c576402..77fe860a64 100644
--- a/frontend/src/core/websocket/transports/basic.ts
+++ b/frontend/src/core/websocket/transports/basic.ts
@@ -13,11 +13,13 @@ export class BasicTransport implements IConnectionTransport {
private subscriptions = new ConnectionSubscriptions();
private producer?: MessageProducer;
- static withProducerCallback(producer: MessageProducer): IConnectionTransport {
+ public static withProducerCallback(
+ producer: MessageProducer,
+ ): IConnectionTransport {
return new BasicTransport(producer);
}
- static empty(): IConnectionTransport {
+ public static empty(): IConnectionTransport {
return new BasicTransport();
}
@@ -39,21 +41,26 @@ export class BasicTransport implements IConnectionTransport {
});
}
- get readyState(): WebSocket["readyState"] {
+ public get readyState(): WebSocket["readyState"] {
return WebSocket.OPEN;
}
- reconnect(_code?: number | undefined, _reason?: string | undefined): void {
+ public reconnect(
+ _code?: number | undefined,
+ _reason?: string | undefined,
+ ): void {
this.close();
this.connect();
return;
}
- close(): void {
+ public close(): void {
this.subscriptions.notify("close", new Event("close"));
}
- send(data: string | ArrayBuffer | Blob | ArrayBufferView): Promise<void> {
+ public send(
+ data: string | ArrayBuffer | Blob | ArrayBufferView,
+ ): Promise<void> {
this.subscriptions.notify(
"message",
new MessageEvent("message", {
@@ -63,7 +70,7 @@ export class BasicTransport implements IConnectionTransport {
return Promise.resolve();
}
- addEventListener<T extends ConnectionEvent>(
+ public addEventListener<T extends ConnectionEvent>(
event: T,
callback: ConnectionTransportCallback<T>,
): void {
@@ -83,7 +90,7 @@ export class BasicTransport implements IConnectionTransport {
}
}
- removeEventListener<T extends ConnectionEvent>(
+ public removeEventListener<T extends ConnectionEvent>(
event: T,
callback: ConnectionTransportCallback<T>,
): void {
diff --git a/frontend/src/core/websocket/transports/sse.ts b/frontend/src/core/websocket/transports/sse.ts
index 6adb4e52f8..f1aaff3056 100644
--- a/frontend/src/core/websocket/transports/sse.ts
+++ b/frontend/src/core/websocket/transports/sse.ts
@@ -52,7 +52,7 @@ export class SseTransport implements IConnectionTransport {
private userClosed = false;
private state: WebSocket["readyState"] = WebSocket.CLOSED;
- constructor(
+ public constructor(
urlProvider: () => string,
headersProvider: () => Record<string, string> = () => ({}),
) {
@@ -60,11 +60,11 @@ export class SseTransport implements IConnectionTransport {
this.headersProvider = headersProvider;
}
- get readyState(): WebSocket["readyState"] {
+ public get readyState(): WebSocket["readyState"] {
return this.state;
}
- reconnect(_code?: number, _reason?: string): void {
+ public reconnect(_code?: number, _reason?: string): void {
this.userClosed = false;
this.retryCount = 0;
this.clearRetryTimer();
@@ -72,7 +72,7 @@ export class SseTransport implements IConnectionTransport {
this.connect();
}
- close(): void {
+ public close(): void {
this.userClosed = true;
this.clearRetryTimer();
this.state = WebSocket.CLOSED;
@@ -80,13 +80,13 @@ export class SseTransport implements IConnectionTransport {
this.abortController = null;
}
- send(_data: string | ArrayBuffer | Blob | ArrayBufferView): void {
+ public send(_data: string | ArrayBuffer | Blob | ArrayBufferView): void {
// The kernel connection is receive-only; all client requests go over
// HTTP POST endpoints.
Logger.warn("SseTransport does not support send(); dropping message");
}
- addEventListener<T extends ConnectionEvent>(
+ public addEventListener<T extends ConnectionEvent>(
event: T,
callback: ConnectionTransportCallback<T>,
): void {
@@ -96,7 +96,7 @@ export class SseTransport implements IConnectionTransport {
);
}
- removeEventListener<T extends ConnectionEvent>(
+ public removeEventListener<T extends ConnectionEvent>(
event: T,
callback: ConnectionTransportCallback<T>,
): void {
diff --git a/frontend/src/core/websocket/transports/transport.ts b/frontend/src/core/websocket/transports/transport.ts
index 3aff328f1a..2460845c2a 100644
--- a/frontend/src/core/websocket/transports/transport.ts
+++ b/frontend/src/core/websocket/transports/transport.ts
@@ -33,7 +33,7 @@ export class ConnectionSubscriptions {
Set<ConnectionTransportCallback<ConnectionEvent>>
>();
- addSubscription(
+ public addSubscription(
event: ConnectionEvent,
callback: ConnectionTransportCallback<ConnectionEvent>,
): void {
@@ -43,14 +43,14 @@ export class ConnectionSubscriptions {
this.subscriptions.get(event)?.add(callback);
}
- removeSubscription(
+ public removeSubscription(
event: ConnectionEvent,
callback: ConnectionTransportCallback<ConnectionEvent>,
): void {
this.subscriptions.get(event)?.delete(callback);
}
- notify(
+ public notify(
event: ConnectionEvent,
data: IConnectionTransportMap[ConnectionEvent],
): void {
diff --git a/frontend/src/core/websocket/transports/ws.ts b/frontend/src/core/websocket/transports/ws.ts
index dcb6ca0dd7..92d2ffbb25 100644
--- a/frontend/src/core/websocket/transports/ws.ts
+++ b/frontend/src/core/websocket/transports/ws.ts
@@ -20,7 +20,7 @@ export class WsTransport implements IConnectionTransport {
ConnectionTransportCallback<"close">
>();
- constructor(urlProvider: () => string) {
+ public constructor(urlProvider: () => string) {
this.inner = new ReconnectingWebSocket(urlProvider, undefined, {
maxRetries: MAX_RETRIES,
debug: false,
@@ -30,23 +30,25 @@ export class WsTransport implements IConnectionTransport {
});
}
- get readyState(): WebSocket["readyState"] {
+ public get readyState(): WebSocket["readyState"] {
return this.inner.readyState as WebSocket["readyState"];
}
- reconnect(code?: number, reason?: string): void {
+ public reconnect(code?: number, reason?: string): void {
this.inner.reconnect(code, reason);
}
- close(): void {
+ public close(): void {
this.inner.close();
}
- send(data: string | ArrayBuffer | Blob | ArrayBufferView<ArrayBuffer>): void {
+ public send(
+ data: string | ArrayBuffer | Blob | ArrayBufferView<ArrayBuffer>,
+ ): void {
this.inner.send(data);
}
- addEventListener<T extends ConnectionEvent>(
+ public addEventListener<T extends ConnectionEvent>(
event: T,
callback: ConnectionTransportCallback<T>,
): void {
@@ -78,7 +80,7 @@ export class WsTransport implements IConnectionTransport {
this.inner.addEventListener(event, callback as never);
}
- removeEventListener<T extends ConnectionEvent>(
+ public removeEventListener<T extends ConnectionEvent>(
event: T,
callback: ConnectionTransportCallback<T>,
): void {
diff --git a/frontend/src/hooks/__tests__/useOverflowDetection.test.tsx b/frontend/src/hooks/__tests__/useOverflowDetection.test.tsx
index 571849970e..249b352540 100644
--- a/frontend/src/hooks/__tests__/useOverflowDetection.test.tsx
+++ b/frontend/src/hooks/__tests__/useOverflowDetection.test.tsx
@@ -10,23 +10,23 @@ const mockObserve = vi.fn();
const mockDisconnect = vi.fn();
global.ResizeObserver = class MockResizeObserver {
- callback: ResizeObserverCallback;
+ public callback: ResizeObserverCallback;
- constructor(callback: ResizeObserverCallback) {
+ public constructor(callback: ResizeObserverCallback) {
this.callback = callback;
}
- observe(target: Element) {
+ public observe(target: Element) {
mockObserve(target);
// Simulate initial observation callback
this.callback([], this);
}
- unobserve() {
+ public unobserve() {
// noop
}
- disconnect() {
+ public disconnect() {
mockDisconnect();
}
};
diff --git a/frontend/src/hooks/__tests__/useResizeObserver.test.tsx b/frontend/src/hooks/__tests__/useResizeObserver.test.tsx
index dcfb076670..c3ecefc183 100644
--- a/frontend/src/hooks/__tests__/useResizeObserver.test.tsx
+++ b/frontend/src/hooks/__tests__/useResizeObserver.test.tsx
@@ -16,9 +16,9 @@ describe("useResizeObserver", () => {
it("should call observe when ref is provided", () => {
const observeSpy = vi.fn();
global.ResizeObserver = class MockedResizeObserver {
- observe = observeSpy;
- unobserve = vi.fn();
- disconnect = vi.fn();
+ public observe = observeSpy;
+ public unobserve = vi.fn();
+ public disconnect = vi.fn();
};
renderHook(() =>
@@ -33,9 +33,9 @@ describe("useResizeObserver", () => {
it("should not call observe when ref is not provided", () => {
const observeSpy = vi.fn();
global.ResizeObserver = class MockedResizeObserver {
- observe = observeSpy;
- unobserve = vi.fn();
- disconnect = vi.fn();
+ public observe = observeSpy;
+ public unobserve = vi.fn();
+ public disconnect = vi.fn();
};
renderHook(() =>
@@ -50,9 +50,9 @@ describe("useResizeObserver", () => {
it("should not call observe when skipped", () => {
const observeSpy = vi.fn();
global.ResizeObserver = class MockedResizeObserver {
- observe = observeSpy;
- unobserve = vi.fn();
- disconnect = vi.fn();
+ public observe = observeSpy;
+ public unobserve = vi.fn();
+ public disconnect = vi.fn();
};
renderHook(() =>
@@ -68,9 +68,9 @@ describe("useResizeObserver", () => {
it("disconnect should be called once unmounted", () => {
const disconnectSpy = vi.fn();
global.ResizeObserver = class MockedResizeObserver {
- observe = vi.fn();
- unobserve = vi.fn();
- disconnect = disconnectSpy;
+ public observe = vi.fn();
+ public unobserve = vi.fn();
+ public disconnect = disconnectSpy;
};
const { unmount } = renderHook(() =>
diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
index c65c8a9b08..3503b6f016 100644
--- a/frontend/src/plugins/core/registerReactComponent.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -336,7 +336,7 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {
private pluginRef = createRef<PluginSlotHandle>();
protected __type__ = customElementLocator;
- constructor() {
+ public constructor() {
super();
// Create a shadow root so we can store the React tree on the shadow root, while the original
// element's children are still on the DOM
@@ -349,7 +349,7 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {
});
}
- connectedCallback() {
+ public connectedCallback() {
// Skip mounting if this element is in the light DOM of another
// marimo custom element. The parent element's shadow DOM will
// re-create this element via getChildren() -> renderHTML(), so
@@ -383,7 +383,7 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {
});
}
- disconnectedCallback() {
+ public disconnectedCallback() {
this.observer.disconnect();
this.root?.unmount();
if (this.mounted) {
@@ -419,7 +419,7 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {
* Reset the plugin initial value and data.
* And then re-render the plugin.
*/
- reset() {
+ public reset() {
this.dispatchEvent(
createInputEvent(parseAttrValue(this.dataset.initialValue), this),
);
@@ -429,7 +429,7 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {
/**
* Re-render the plugin.
*/
- rerender() {
+ public rerender() {
this.pluginRef.current?.reset();
}
diff --git a/frontend/src/plugins/core/sidebar-element.tsx b/frontend/src/plugins/core/sidebar-element.tsx
index dcfe8013e8..54f58070bc 100644
--- a/frontend/src/plugins/core/sidebar-element.tsx
+++ b/frontend/src/plugins/core/sidebar-element.tsx
@@ -19,7 +19,7 @@ export function initializeSidebarElement(): void {
private observer?: MutationObserver;
private uniqueId = Symbol(createId());
- connectedCallback() {
+ public connectedCallback() {
// Render the component for the first time
this.mountReactComponent();
@@ -39,7 +39,7 @@ export function initializeSidebarElement(): void {
});
}
- disconnectedCallback() {
+ public disconnectedCallback() {
if (this.observer) {
this.observer.disconnect();
this.unmountReactComponent();
diff --git a/frontend/src/plugins/impl/ButtonPlugin.tsx b/frontend/src/plugins/impl/ButtonPlugin.tsx
index c7e261b928..a68757692a 100644
--- a/frontend/src/plugins/impl/ButtonPlugin.tsx
+++ b/frontend/src/plugins/impl/ButtonPlugin.tsx
@@ -20,9 +20,9 @@ interface Data {
}
export class ButtonPlugin implements IPlugin<number, Data> {
- tagName = "marimo-button";
+ public tagName = "marimo-button";
- validator = z.object({
+ public validator = z.object({
label: z.string(),
kind: zodIntent,
disabled: z.boolean().default(false),
@@ -31,7 +31,7 @@ export class ButtonPlugin implements IPlugin<number, Data> {
keyboardShortcut: z.string().optional(),
});
- render(props: IPluginProps<number, Data>): JSX.Element {
+ public render(props: IPluginProps<number, Data>): JSX.Element {
const {
data: { disabled, kind, label, fullWidth, tooltip, keyboardShortcut },
} = props;
diff --git a/frontend/src/plugins/impl/CheckboxPlugin.tsx b/frontend/src/plugins/impl/CheckboxPlugin.tsx
index 90af257f76..b491c1b566 100644
--- a/frontend/src/plugins/impl/CheckboxPlugin.tsx
+++ b/frontend/src/plugins/impl/CheckboxPlugin.tsx
@@ -18,15 +18,15 @@ interface Data {
}
export class CheckboxPlugin implements IPlugin<T, Data> {
- tagName = "marimo-checkbox";
+ public tagName = "marimo-checkbox";
- validator = z.object({
+ public validator = z.object({
initialValue: z.boolean(),
label: z.string().nullable(),
disabled: z.boolean().optional(),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return <CheckboxComponent {...props} />;
}
}
diff --git a/frontend/src/plugins/impl/CodeEditorPlugin.tsx b/frontend/src/plugins/impl/CodeEditorPlugin.tsx
index 7a1c354578..11331782ed 100644
--- a/frontend/src/plugins/impl/CodeEditorPlugin.tsx
+++ b/frontend/src/plugins/impl/CodeEditorPlugin.tsx
@@ -25,9 +25,9 @@ interface Data {
}
export class CodeEditorPlugin implements IPlugin<T, Data> {
- tagName = "marimo-code-editor";
+ public tagName = "marimo-code-editor";
- validator = z.object({
+ public validator = z.object({
initialValue: z.string(),
language: z.string().default("python"),
placeholder: z.string(),
@@ -40,7 +40,7 @@ export class CodeEditorPlugin implements IPlugin<T, Data> {
debounce: z.union([z.boolean(), z.number()]).default(false),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<CodeEditorComponent
{...props.data}
diff --git a/frontend/src/plugins/impl/DatePickerPlugin.tsx b/frontend/src/plugins/impl/DatePickerPlugin.tsx
index f80608d718..5ddb6bde61 100644
--- a/frontend/src/plugins/impl/DatePickerPlugin.tsx
+++ b/frontend/src/plugins/impl/DatePickerPlugin.tsx
@@ -19,9 +19,9 @@ interface Data {
}
export class DatePickerPlugin implements IPlugin<T, Data> {
- tagName = "marimo-date";
+ public tagName = "marimo-date";
- validator = z.object({
+ public validator = z.object({
initialValue: z.string(),
label: z.string().nullable(),
start: z.string(),
@@ -31,7 +31,7 @@ export class DatePickerPlugin implements IPlugin<T, Data> {
disabled: z.boolean().optional(),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<DatePickerComponent
{...props.data}
diff --git a/frontend/src/plugins/impl/DateRangePlugin.tsx b/frontend/src/plugins/impl/DateRangePlugin.tsx
index f47b90d12d..66101387b3 100644
--- a/frontend/src/plugins/impl/DateRangePlugin.tsx
+++ b/frontend/src/plugins/impl/DateRangePlugin.tsx
@@ -19,9 +19,9 @@ interface Data {
}
export class DateRangePickerPlugin implements IPlugin<T, Data> {
- tagName = "marimo-date-range";
+ public tagName = "marimo-date-range";
- validator = z.object({
+ public validator = z.object({
initialValue: z.tuple([z.string(), z.string()]),
label: z.string().nullable(),
start: z.string(),
@@ -31,7 +31,7 @@ export class DateRangePickerPlugin implements IPlugin<T, Data> {
disabled: z.boolean().optional(),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<DateRangePickerComponent
{...props.data}
diff --git a/frontend/src/plugins/impl/DateTimePickerPlugin.tsx b/frontend/src/plugins/impl/DateTimePickerPlugin.tsx
index 9482d878fc..076ed9501e 100644
--- a/frontend/src/plugins/impl/DateTimePickerPlugin.tsx
+++ b/frontend/src/plugins/impl/DateTimePickerPlugin.tsx
@@ -20,9 +20,9 @@ interface Data {
}
export class DateTimePickerPlugin implements IPlugin<T, Data> {
- tagName = "marimo-datetime";
+ public tagName = "marimo-datetime";
- validator = z.object({
+ public validator = z.object({
initialValue: z.string(),
label: z.string().nullable(),
start: z.string(),
@@ -33,7 +33,7 @@ export class DateTimePickerPlugin implements IPlugin<T, Data> {
disabled: z.boolean().optional(),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<DateTimePickerComponent
{...props.data}
diff --git a/frontend/src/plugins/impl/DictPlugin.tsx b/frontend/src/plugins/impl/DictPlugin.tsx
index 01b6518fac..0ebce2892b 100644
--- a/frontend/src/plugins/impl/DictPlugin.tsx
+++ b/frontend/src/plugins/impl/DictPlugin.tsx
@@ -18,14 +18,14 @@ interface Data {
}
export class DictPlugin implements IPlugin<T, Data> {
- tagName = "marimo-dict";
+ public tagName = "marimo-dict";
- validator = z.object({
+ public validator = z.object({
label: z.string().nullable(),
elementIds: z.record(z.string(), z.string()),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<Dict {...props.data} value={props.value} setValue={props.setValue}>
{props.children}
diff --git a/frontend/src/plugins/impl/DropdownPlugin.tsx b/frontend/src/plugins/impl/DropdownPlugin.tsx
index 0567e21ef7..a5d5cba0b8 100644
--- a/frontend/src/plugins/impl/DropdownPlugin.tsx
+++ b/frontend/src/plugins/impl/DropdownPlugin.tsx
@@ -17,9 +17,9 @@ interface Data {
}
export class DropdownPlugin implements IPlugin<string[], Data> {
- tagName = "marimo-dropdown";
+ public tagName = "marimo-dropdown";
- validator = z.object({
+ public validator = z.object({
initialValue: z.array(z.string()),
label: z.string().nullable(),
options: z.array(z.string()),
@@ -29,7 +29,7 @@ export class DropdownPlugin implements IPlugin<string[], Data> {
disabled: z.boolean().default(false),
});
- render(props: IPluginProps<string[], Data>): JSX.Element {
+ public render(props: IPluginProps<string[], Data>): JSX.Element {
if (props.data.searchable) {
const value = props.value.length > 0 ? props.value[0] : null;
const setValue = (newValue: string | null) =>
diff --git a/frontend/src/plugins/impl/FileUploadPlugin.tsx b/frontend/src/plugins/impl/FileUploadPlugin.tsx
index 7b05655645..225117425f 100644
--- a/frontend/src/plugins/impl/FileUploadPlugin.tsx
+++ b/frontend/src/plugins/impl/FileUploadPlugin.tsx
@@ -34,9 +34,9 @@ interface Data {
type T = [string, string][];
export class FileUploadPlugin implements IPlugin<T, Data> {
- tagName = "marimo-file";
+ public tagName = "marimo-file";
- validator = z.object({
+ public validator = z.object({
filetypes: z.array(z.string()),
multiple: z.boolean(),
kind: z.enum(["button", "area"]),
@@ -44,7 +44,7 @@ export class FileUploadPlugin implements IPlugin<T, Data> {
max_size: z.number(),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<FileUpload
label={props.data.label}
diff --git a/frontend/src/plugins/impl/MatrixPlugin.tsx b/frontend/src/plugins/impl/MatrixPlugin.tsx
index 6d8b8e0a38..6fcf3b85e3 100644
--- a/frontend/src/plugins/impl/MatrixPlugin.tsx
+++ b/frontend/src/plugins/impl/MatrixPlugin.tsx
@@ -23,11 +23,11 @@ interface Data {
}
export class MatrixPlugin implements IPlugin<T, Data> {
- tagName = "marimo-matrix";
+ public tagName = "marimo-matrix";
- cssStyles = [matrixCss];
+ public cssStyles = [matrixCss];
- validator = z.object({
+ public validator = z.object({
initialValue: z.array(z.array(z.number())),
label: z.string().nullable(),
minValue: z.array(z.array(z.number())).nullish(),
@@ -42,7 +42,7 @@ export class MatrixPlugin implements IPlugin<T, Data> {
disabled: z.array(z.array(z.boolean())),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<MatrixComponent
{...props.data}
diff --git a/frontend/src/plugins/impl/MicrophonePlugin.tsx b/frontend/src/plugins/impl/MicrophonePlugin.tsx
index 08ebab76fa..a8cd97de58 100644
--- a/frontend/src/plugins/impl/MicrophonePlugin.tsx
+++ b/frontend/src/plugins/impl/MicrophonePlugin.tsx
@@ -18,13 +18,13 @@ interface Data {
}
export class MicrophonePlugin implements IPlugin<Value, Data> {
- tagName = "marimo-microphone";
+ public tagName = "marimo-microphone";
- validator = z.object({
+ public validator = z.object({
label: z.string().nullish(),
});
- render(props: IPluginProps<Value, Data>): JSX.Element {
+ public render(props: IPluginProps<Value, Data>): JSX.Element {
return <Microphone {...props} />;
}
}
diff --git a/frontend/src/plugins/impl/MultiselectPlugin.tsx b/frontend/src/plugins/impl/MultiselectPlugin.tsx
index 6328fea884..760aa7dab1 100644
--- a/frontend/src/plugins/impl/MultiselectPlugin.tsx
+++ b/frontend/src/plugins/impl/MultiselectPlugin.tsx
@@ -17,9 +17,9 @@ interface Data {
type T = string[];
export class MultiselectPlugin implements IPlugin<T, Data> {
- tagName = "marimo-multiselect";
+ public tagName = "marimo-multiselect";
- validator = z.object({
+ public validator = z.object({
initialValue: z.array(z.string()),
label: z.string().nullable(),
options: z.array(z.string()),
@@ -28,7 +28,7 @@ export class MultiselectPlugin implements IPlugin<T, Data> {
disabled: z.boolean().default(false),
});
- render(props: IPluginProps<string[], Data>): JSX.Element {
+ public render(props: IPluginProps<string[], Data>): JSX.Element {
return (
<Multiselect
{...props.data}
diff --git a/frontend/src/plugins/impl/NumberPlugin.tsx b/frontend/src/plugins/impl/NumberPlugin.tsx
index a5199369b4..be97750cca 100644
--- a/frontend/src/plugins/impl/NumberPlugin.tsx
+++ b/frontend/src/plugins/impl/NumberPlugin.tsx
@@ -20,9 +20,9 @@ interface Data {
}
export class NumberPlugin implements IPlugin<T | null, Data> {
- tagName = "marimo-number";
+ public tagName = "marimo-number";
- validator = z.object({
+ public validator = z.object({
initialValue: z.number().nullish(),
label: z.string().nullable(),
start: z.number().nullish(),
@@ -33,7 +33,7 @@ export class NumberPlugin implements IPlugin<T | null, Data> {
disabled: z.boolean().optional(),
});
- render(props: IPluginProps<T | null, Data>): JSX.Element {
+ public render(props: IPluginProps<T | null, Data>): JSX.Element {
return (
<NumberComponent
{...props.data}
diff --git a/frontend/src/plugins/impl/RadioPlugin.tsx b/frontend/src/plugins/impl/RadioPlugin.tsx
index c1a6051845..87398f3512 100644
--- a/frontend/src/plugins/impl/RadioPlugin.tsx
+++ b/frontend/src/plugins/impl/RadioPlugin.tsx
@@ -25,9 +25,9 @@ interface Data {
type S = string | null;
export class RadioPlugin implements IPlugin<S, Data> {
- tagName = "marimo-radio";
+ public tagName = "marimo-radio";
- validator = z.object({
+ public validator = z.object({
initialValue: z.string().nullable(),
inline: z.boolean().default(false),
label: z.string().nullable(),
@@ -35,7 +35,7 @@ export class RadioPlugin implements IPlugin<S, Data> {
disabled: z.boolean().optional(),
});
- render(props: IPluginProps<S, Data>): JSX.Element {
+ public render(props: IPluginProps<S, Data>): JSX.Element {
return (
<Radio {...props.data} value={props.value} setValue={props.setValue} />
);
diff --git a/frontend/src/plugins/impl/RangeSliderPlugin.tsx b/frontend/src/plugins/impl/RangeSliderPlugin.tsx
index 6c596505c7..4d987daa89 100644
--- a/frontend/src/plugins/impl/RangeSliderPlugin.tsx
+++ b/frontend/src/plugins/impl/RangeSliderPlugin.tsx
@@ -26,9 +26,9 @@ interface Data {
}
export class RangeSliderPlugin implements IPlugin<T, Data> {
- tagName = "marimo-range-slider";
+ public tagName = "marimo-range-slider";
- validator = z.object({
+ public validator = z.object({
initialValue: z.array(z.number()),
label: z.string().nullable(),
start: z.number(),
@@ -42,7 +42,7 @@ export class RangeSliderPlugin implements IPlugin<T, Data> {
disabled: z.boolean().optional(),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
const valueMap = (sliderValue: number): number => {
if (props.data.steps && props.data.steps.length > 0) {
return props.data.steps[sliderValue];
diff --git a/frontend/src/plugins/impl/RefreshPlugin.tsx b/frontend/src/plugins/impl/RefreshPlugin.tsx
index 6d907f46f7..9f7051447e 100644
--- a/frontend/src/plugins/impl/RefreshPlugin.tsx
+++ b/frontend/src/plugins/impl/RefreshPlugin.tsx
@@ -51,9 +51,9 @@ const zodTimestring = z.string().superRefine((s, ctx) => {
});
export class RefreshPlugin implements IPlugin<Value, Data> {
- tagName = "marimo-refresh";
+ public tagName = "marimo-refresh";
- validator = z.object({
+ public validator = z.object({
options: z
.array(z.union([zodTimestring, z.number().min(MIN_INTERVAL)]))
.default([]),
@@ -63,7 +63,7 @@ export class RefreshPlugin implements IPlugin<Value, Data> {
label: z.string().nullable(),
});
- render(props: IPluginProps<Value, Data>): JSX.Element {
+ public render(props: IPluginProps<Value, Data>): JSX.Element {
return <RefreshComponent {...props} />;
}
}
diff --git a/frontend/src/plugins/impl/SliderPlugin.tsx b/frontend/src/plugins/impl/SliderPlugin.tsx
index c337ebb478..b2c834d8ca 100644
--- a/frontend/src/plugins/impl/SliderPlugin.tsx
+++ b/frontend/src/plugins/impl/SliderPlugin.tsx
@@ -31,9 +31,9 @@ interface Data {
}
export class SliderPlugin implements IPlugin<T, Data> {
- tagName = "marimo-slider";
+ public tagName = "marimo-slider";
- validator = z.object({
+ public validator = z.object({
initialValue: z.number(),
label: z.string().nullable(),
start: z.number(),
@@ -48,7 +48,7 @@ export class SliderPlugin implements IPlugin<T, Data> {
disabled: z.boolean().optional(),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
// Create the valueMap function
const valueMap = (sliderValue: number): number => {
const { steps } = props.data;
diff --git a/frontend/src/plugins/impl/SwitchPlugin.tsx b/frontend/src/plugins/impl/SwitchPlugin.tsx
index 179e3bb011..0cf31e8073 100644
--- a/frontend/src/plugins/impl/SwitchPlugin.tsx
+++ b/frontend/src/plugins/impl/SwitchPlugin.tsx
@@ -13,15 +13,15 @@ interface Data {
}
export class SwitchPlugin implements IPlugin<T, Data> {
- tagName = "marimo-switch";
+ public tagName = "marimo-switch";
- validator = z.object({
+ public validator = z.object({
initialValue: z.boolean(),
label: z.string().nullable(),
disabled: z.boolean().optional(),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return <SwitchComponent {...props} />;
}
}
diff --git a/frontend/src/plugins/impl/TabsPlugin.tsx b/frontend/src/plugins/impl/TabsPlugin.tsx
index 87aaeac4b6..4b0913cbeb 100644
--- a/frontend/src/plugins/impl/TabsPlugin.tsx
+++ b/frontend/src/plugins/impl/TabsPlugin.tsx
@@ -25,15 +25,15 @@ interface Data {
type T = string;
export class TabsPlugin implements IPlugin<T, Data> {
- tagName = "marimo-tabs";
+ public tagName = "marimo-tabs";
- validator = z.object({
+ public validator = z.object({
tabs: z.array(z.string()),
label: z.string().nullable(),
orientation: z.enum(["horizontal", "vertical"]).default("horizontal"),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<TabComponent
{...props.data}
diff --git a/frontend/src/plugins/impl/TextAreaPlugin.tsx b/frontend/src/plugins/impl/TextAreaPlugin.tsx
index 14829bc8bd..ea30759749 100644
--- a/frontend/src/plugins/impl/TextAreaPlugin.tsx
+++ b/frontend/src/plugins/impl/TextAreaPlugin.tsx
@@ -25,9 +25,9 @@ interface Data {
}
export class TextAreaPlugin implements IPlugin<T, Data> {
- tagName = "marimo-text-area";
+ public tagName = "marimo-text-area";
- validator = z.object({
+ public validator = z.object({
initialValue: z.string(),
placeholder: z.string(),
label: z.string().nullable(),
@@ -39,7 +39,7 @@ export class TextAreaPlugin implements IPlugin<T, Data> {
fullWidth: z.boolean().default(false),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<TextAreaComponent
{...props.data}
diff --git a/frontend/src/plugins/impl/TextInputPlugin.tsx b/frontend/src/plugins/impl/TextInputPlugin.tsx
index 599c9776f5..c011a8d20a 100644
--- a/frontend/src/plugins/impl/TextInputPlugin.tsx
+++ b/frontend/src/plugins/impl/TextInputPlugin.tsx
@@ -33,9 +33,9 @@ interface Data {
const MASK_PLACEHOLDER = "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
export class TextInputPlugin implements IPlugin<T, Data> {
- tagName = "marimo-text";
+ public tagName = "marimo-text";
- validator = z.object({
+ public validator = z.object({
initialValue: z.string(),
placeholder: z.string(),
label: z.string().nullable(),
@@ -48,7 +48,7 @@ export class TextInputPlugin implements IPlugin<T, Data> {
passwordHasValue: z.boolean().optional(),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
// Force remount on cell re-run so masked state resets cleanly
const remountKey =
props.data.kind === "password"
diff --git a/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx b/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx
index 718f75a523..bdf9eeb924 100644
--- a/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx
+++ b/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx
@@ -54,8 +54,8 @@ beforeEach(() => {
// like clientX. Polyfill it so fireEvent.pointerDown/Move/Up work.
// oxlint-disable-next-line typescript/no-explicit-any
(globalThis as any).PointerEvent = class PointerEvent extends MouseEvent {
- readonly pointerId: number;
- constructor(type: string, init: PointerEventInit = {}) {
+ public readonly pointerId: number;
+ public constructor(type: string, init: PointerEventInit = {}) {
super(type, init);
this.pointerId = init.pointerId ?? 0;
}
diff --git a/frontend/src/plugins/impl/anywidget/model.ts b/frontend/src/plugins/impl/anywidget/model.ts
index 9941ed4f88..b53a06cce5 100644
--- a/frontend/src/plugins/impl/anywidget/model.ts
+++ b/frontend/src/plugins/impl/anywidget/model.ts
@@ -64,11 +64,11 @@ export class Model<T extends ModelState> implements AnyModel<T> {
* (`widget_manager.get_model`). Assigned by the registry module at
* import time to avoid an import cycle.
*/
- static _modelManager: {
+ public static _modelManager: {
getModel(model_id: WidgetModelId): Promise<Model<any>>;
};
- constructor(data: T, comm: MarimoComm<T>, signal?: AbortSignal) {
+ public constructor(data: T, comm: MarimoComm<T>, signal?: AbortSignal) {
this.#data = data;
this.#comm = comm;
this.#dirtyFields = new Set();
@@ -84,7 +84,7 @@ export class Model<T extends ModelState> implements AnyModel<T> {
* Internal marimo API - not part of AnyWidget AFM.
* Access via getMarimoInternal().
*/
- [marimoSymbol]: MarimoInternalApi<T> = {
+ public [marimoSymbol]: MarimoInternalApi<T> = {
updateAndEmitDiffs: (value: T) => this.#updateAndEmitDiffs(value),
emitCustomMessage: (
message: CustomMessage,
@@ -92,7 +92,7 @@ export class Model<T extends ModelState> implements AnyModel<T> {
) => this.#emitCustomMessage(message, buffers),
};
- off(eventName?: string | null, callback?: EventHandler | null): void {
+ public off(eventName?: string | null, callback?: EventHandler | null): void {
if (!eventName) {
this.#listeners = {};
return;
@@ -106,7 +106,7 @@ export class Model<T extends ModelState> implements AnyModel<T> {
this.#listeners[eventName]?.delete(callback);
}
- send(
+ public send(
content: any,
callbacks?: any,
buffers?: ArrayBuffer[] | ArrayBufferView[],
@@ -121,7 +121,7 @@ export class Model<T extends ModelState> implements AnyModel<T> {
.then(() => callbacks?.());
}
- widget_manager = {
+ public widget_manager = {
async get_model<TT extends ModelState>(
model_id: WidgetModelId,
): Promise<AnyModel<TT>> {
@@ -135,18 +135,18 @@ export class Model<T extends ModelState> implements AnyModel<T> {
},
};
- get<K extends keyof T>(key: K): T[K] {
+ public get<K extends keyof T>(key: K): T[K] {
return this.#data[key];
}
- set<K extends keyof T>(key: K, value: T[K]): void {
+ public set<K extends keyof T>(key: K, value: T[K]): void {
this.#data = { ...this.#data, [key]: value };
this.#dirtyFields.add(key);
this.#emit(`change:${key as K & string}`, value);
this.#emitAnyChange();
}
- save_changes(): void {
+ public save_changes(): void {
if (this.#dirtyFields.size === 0) {
return;
}
@@ -169,7 +169,7 @@ export class Model<T extends ModelState> implements AnyModel<T> {
* `addEventListener({ signal })`) and is what `modelProxy` uses to
* scope listeners to view / binding lifetimes.
*/
- on(
+ public on(
eventName: string,
callback: EventHandler,
options?: { signal?: AbortSignal },
diff --git a/frontend/src/plugins/impl/anywidget/registry.ts b/frontend/src/plugins/impl/anywidget/registry.ts
index 041ae03ea2..9a7dfa1aae 100644
--- a/frontend/src/plugins/impl/anywidget/registry.ts
+++ b/frontend/src/plugins/impl/anywidget/registry.ts
@@ -41,7 +41,10 @@ export class WidgetRegistry implements WidgetResolver {
#timeout: number;
#isEditMode: () => boolean;
- constructor(timeout = 10_000, isEditMode: () => boolean = defaultIsEditMode) {
+ public constructor(
+ timeout = 10_000,
+ isEditMode: () => boolean = defaultIsEditMode,
+ ) {
this.#timeout = timeout;
this.#isEditMode = isEditMode;
}
@@ -71,7 +74,7 @@ export class WidgetRegistry implements WidgetResolver {
* hasn't arrived yet. Rejects after the registry timeout so a ref to
* a model that never opens fails loudly instead of hanging.
*/
- getModel(key: WidgetModelId): Promise<Model<ModelState>> {
+ public getModel(key: WidgetModelId): Promise<Model<ModelState>> {
return this.#getOrCreateRuntime(key).getModel();
}
@@ -79,7 +82,7 @@ export class WidgetRegistry implements WidgetResolver {
* Get a model synchronously if it exists and has been resolved.
* Returns undefined if the model doesn't exist or is still pending.
*/
- getModelSync(key: WidgetModelId): Model<ModelState> | undefined {
+ public getModelSync(key: WidgetModelId): Model<ModelState> | undefined {
return this.#runtimes.get(key)?.getModelSync();
}
@@ -87,14 +90,14 @@ export class WidgetRegistry implements WidgetResolver {
* Create a model with a managed lifecycle signal.
* The signal is aborted when the entry is deleted.
*/
- createModel(
+ public createModel(
key: WidgetModelId,
factory: (signal: AbortSignal) => Model<ModelState>,
): void {
this.#getOrCreateRuntime(key).createModel(factory);
}
- setModel(key: WidgetModelId, model: Model<ModelState>): void {
+ public setModel(key: WidgetModelId, model: Model<ModelState>): void {
this.#getOrCreateRuntime(key).setModel(model);
}
@@ -105,15 +108,15 @@ export class WidgetRegistry implements WidgetResolver {
* Specs only come from kernel-authored notifications; model state
* must never be treated as code (it is client-writable).
*/
- setSpec(key: WidgetModelId, spec: EsmSpec): void {
+ public setSpec(key: WidgetModelId, spec: EsmSpec): void {
this.#getOrCreateRuntime(key).setSpec(spec);
}
- getWidget<T = unknown>(key: WidgetModelId) {
+ public getWidget<T = unknown>(key: WidgetModelId) {
return this.#getOrCreateRuntime(key).getWidget<T>();
}
- createView(options: {
+ public createView(options: {
modelId: WidgetModelId;
el: HTMLElement;
signal: AbortSignal;
@@ -125,7 +128,7 @@ export class WidgetRegistry implements WidgetResolver {
* Tear down everything known about `key`: the model's lifecycle
* signal and the current generation.
*/
- delete(key: WidgetModelId): void {
+ public delete(key: WidgetModelId): void {
const runtime = this.#runtimes.get(key);
if (!runtime) {
return;
diff --git a/frontend/src/plugins/impl/anywidget/runtime.ts b/frontend/src/plugins/impl/anywidget/runtime.ts
index 9e5121dcb9..636201c550 100644
--- a/frontend/src/plugins/impl/anywidget/runtime.ts
+++ b/frontend/src/plugins/impl/anywidget/runtime.ts
@@ -60,7 +60,7 @@ export class WidgetRuntime {
#generationCleanup = Promise.resolve();
#css = "";
- constructor(key: WidgetModelId, options: WidgetRuntimeOptions) {
+ public constructor(key: WidgetModelId, options: WidgetRuntimeOptions) {
this.#key = key;
this.#timeout = options.timeout;
this.#isEditMode = options.isEditMode;
@@ -68,7 +68,7 @@ export class WidgetRuntime {
this.#onModelTimeout = options.onModelTimeout;
}
- getModel(): Promise<Model<ModelState>> {
+ public getModel(): Promise<Model<ModelState>> {
if (this.#model.status === "pending" && !this.#modelTimeout) {
this.#modelTimeout = setTimeout(() => {
if (this.#model.status === "pending") {
@@ -83,18 +83,20 @@ export class WidgetRuntime {
return this.#model.promise;
}
- getModelSync(): Model<ModelState> | undefined {
+ public getModelSync(): Model<ModelState> | undefined {
return this.#model.status === "resolved" ? this.#model.value : undefined;
}
- createModel(factory: (signal: AbortSignal) => Model<ModelState>): void {
+ public createModel(
+ factory: (signal: AbortSignal) => Model<ModelState>,
+ ): void {
if (this.#model.status !== "pending") {
return;
}
this.#resolveModel(factory(this.#controller.signal));
}
- setModel(model: Model<ModelState>): void {
+ public setModel(model: Model<ModelState>): void {
if (this.#model.status !== "pending") {
return;
}
@@ -121,7 +123,7 @@ export class WidgetRuntime {
);
}
- setSpec(spec: EsmSpec): void {
+ public setSpec(spec: EsmSpec): void {
if (!this.#esmSpec) {
this.#esmSpec = spec;
return;
@@ -138,7 +140,7 @@ export class WidgetRuntime {
}
}
- async getWidget<T = unknown>(): Promise<ResolvedWidget<T>> {
+ public async getWidget<T = unknown>(): Promise<ResolvedWidget<T>> {
const binding = await this.#getCurrentBinding();
return {
exports: binding.exports as T,
@@ -151,7 +153,7 @@ export class WidgetRuntime {
};
}
- async createView(options: {
+ public async createView(options: {
el: HTMLElement;
signal: AbortSignal;
}): Promise<void> {
@@ -341,7 +343,7 @@ export class WidgetRuntime {
view.signal.addEventListener("abort", release, { once: true });
}
- dispose(): void {
+ public dispose(): void {
if (this.#controller.signal.aborted) {
return;
}
diff --git a/frontend/src/plugins/impl/anywidget/widget-binding.ts b/frontend/src/plugins/impl/anywidget/widget-binding.ts
index 96c11f3356..da9e35b8a7 100644
--- a/frontend/src/plugins/impl/anywidget/widget-binding.ts
+++ b/frontend/src/plugins/impl/anywidget/widget-binding.ts
@@ -59,7 +59,7 @@ class WidgetDefRegistry {
* `kernelAuthored: true` only for URLs from an `EsmSpec`; it widens
* the import gate to remote and data URLs.
*/
- getModule(options: {
+ public getModule(options: {
jsUrl: string;
jsHash: string;
kernelAuthored?: boolean;
@@ -80,7 +80,7 @@ class WidgetDefRegistry {
return promise;
}
- invalidate(jsHash: string): void {
+ public invalidate(jsHash: string): void {
this.#cache.delete(jsHash);
}
@@ -180,7 +180,7 @@ export class WidgetBinding<T extends ModelState = ModelState> {
* `controller`'s signal. Aborting the controller mid-initialize
* still runs any legacy cleanup callback, and `create` rejects.
*/
- static async create<T extends ModelState>({
+ public static async create<T extends ModelState>({
widgetDef,
model,
createHost,
@@ -261,7 +261,7 @@ export class WidgetBinding<T extends ModelState = ModelState> {
* The object returned from `initialize`, or `undefined` if it
* returned a cleanup function or nothing.
*/
- get exports(): unknown {
+ public get exports(): unknown {
return this.#exports;
}
@@ -273,7 +273,7 @@ export class WidgetBinding<T extends ModelState = ModelState> {
* `render` reads current state via `model.get`; change listeners
* observe only subsequent changes, matching Jupyter semantics.
*/
- async createView(
+ public async createView(
target: { el: HTMLElement },
options: { signal: AbortSignal },
): Promise<void> {
@@ -346,7 +346,7 @@ export class WidgetBinding<T extends ModelState = ModelState> {
* Destroy this generation, running initialize/render cleanups and
* clearing listeners registered through its model proxies.
*/
- async destroy(): Promise<void> {
+ public async destroy(): Promise<void> {
Logger.debug("[WidgetBinding] Destroying binding generation");
this.#controller.abort();
await Promise.allSettled(this.#viewTasks);
diff --git a/frontend/src/plugins/impl/matplotlib/MatplotlibPlugin.tsx b/frontend/src/plugins/impl/matplotlib/MatplotlibPlugin.tsx
index 7ab26f52ee..decfff9a07 100644
--- a/frontend/src/plugins/impl/matplotlib/MatplotlibPlugin.tsx
+++ b/frontend/src/plugins/impl/matplotlib/MatplotlibPlugin.tsx
@@ -11,9 +11,9 @@ import {
} from "./matplotlib-renderer";
export class MatplotlibPlugin implements IPlugin<T, Data> {
- tagName = "marimo-matplotlib";
+ public tagName = "marimo-matplotlib";
- validator = z.object({
+ public validator = z.object({
chartBase64: z.string(),
xBounds: z.tuple([z.number(), z.number()]),
yBounds: z.tuple([z.number(), z.number()]),
@@ -28,7 +28,7 @@ export class MatplotlibPlugin implements IPlugin<T, Data> {
yScale: z.enum(["linear", "log"]).default("linear"),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<MatplotlibComponent
{...props.data}
diff --git a/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.ts b/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.ts
index abd0c5e2b8..cdb7aa12b8 100644
--- a/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.ts
+++ b/frontend/src/plugins/impl/matplotlib/__tests__/matplotlib-renderer.test.ts
@@ -228,8 +228,8 @@ function stubSyncImage() {
vi.stubGlobal(
"Image",
class {
- onload: (() => void) | null = null;
- set src(_value: string) {
+ public onload: (() => void) | null = null;
+ public set src(_value: string) {
this.onload?.();
}
},
diff --git a/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts b/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts
index 33548089ea..4aa9c85a43 100644
--- a/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts
+++ b/frontend/src/plugins/impl/matplotlib/matplotlib-renderer.ts
@@ -284,7 +284,7 @@ export class MatplotlibRenderer {
/** The devicePixelRatio the canvas buffer was last sized with. */
#backingDpr = 1;
- constructor(
+ public constructor(
container: HTMLDivElement,
options: { state: MatplotlibState; signal: AbortSignal },
) {
@@ -396,7 +396,7 @@ export class MatplotlibRenderer {
mq.addEventListener("change", onChange, { once: true, signal });
}
- update(state: MatplotlibState): void {
+ public update(state: MatplotlibState): void {
const prev = this.#state;
this.#state = state;
diff --git a/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.ts b/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.ts
index 4093ff631b..ff975221c4 100644
--- a/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.ts
+++ b/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.ts
@@ -10,14 +10,14 @@
* - onopen / onmessage / onclose callbacks
*/
export class MplCommWebSocket {
- readyState: number = WebSocket.OPEN;
+ public readyState: number = WebSocket.OPEN;
private sendFn: (msg: unknown) => void;
- onopen: (() => void) | null = null;
- onmessage: ((evt: MessageEvent) => void) | null = null;
- onclose: (() => void) | null = null;
+ public onopen: (() => void) | null = null;
+ public onmessage: ((evt: MessageEvent) => void) | null = null;
+ public onclose: (() => void) | null = null;
- constructor(sendFn: (msg: unknown) => void) {
+ public constructor(sendFn: (msg: unknown) => void) {
this.sendFn = sendFn;
}
@@ -27,7 +27,7 @@ export class MplCommWebSocket {
* socket instance stays bound to mpl.js (which wires `onopen`/`onmessage`
* onto it at construction); only the comm behind it changes.
*/
- setSendHandler(sendFn: (msg: unknown) => void): void {
+ public setSendHandler(sendFn: (msg: unknown) => void): void {
this.sendFn = sendFn;
}
@@ -35,14 +35,14 @@ export class MplCommWebSocket {
* Called by mpl.js to send a message to the backend.
* mpl.js always sends JSON strings.
*/
- send(data: string): void {
+ public send(data: string): void {
this.sendFn(JSON.parse(data));
}
/**
* Called when the backend pushes a JSON message via the model custom event.
*/
- receiveJson(data: unknown): void {
+ public receiveJson(data: unknown): void {
this.onmessage?.(
new MessageEvent("message", { data: JSON.stringify(data) }),
);
@@ -51,7 +51,7 @@ export class MplCommWebSocket {
/**
* Called when the backend pushes binary data (PNG render) via model custom event.
*/
- receiveBinary(buffer: DataView): void {
+ public receiveBinary(buffer: DataView): void {
const ab = buffer.buffer.slice(
buffer.byteOffset,
buffer.byteOffset + buffer.byteLength,
@@ -60,7 +60,7 @@ export class MplCommWebSocket {
this.onmessage?.(new MessageEvent("message", { data: blob }));
}
- close(): void {
+ public close(): void {
this.readyState = WebSocket.CLOSED;
this.onclose?.();
}
diff --git a/frontend/src/plugins/impl/panel/utils.ts b/frontend/src/plugins/impl/panel/utils.ts
index 9930df9915..0fc821cca6 100644
--- a/frontend/src/plugins/impl/panel/utils.ts
+++ b/frontend/src/plugins/impl/panel/utils.ts
@@ -60,12 +60,12 @@ export class EventBuffer<T> {
private processEvents: () => void;
private blockDuration: number;
- constructor(processEvents: () => void, blockDuration = 200) {
+ public constructor(processEvents: () => void, blockDuration = 200) {
this.processEvents = processEvents;
this.blockDuration = blockDuration;
}
- add(event: T) {
+ public add(event: T) {
this.buffer.push(event);
this.flush();
}
@@ -90,15 +90,15 @@ export class EventBuffer<T> {
}, this.blockDuration);
}
- size() {
+ public size() {
return this.buffer.length;
}
- clear() {
+ public clear() {
this.buffer = [];
}
- getAndClear() {
+ public getAndClear() {
const events = this.buffer;
this.buffer = [];
return events;
diff --git a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
index e65bc1f081..8f6c106bc2 100644
--- a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
+++ b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
@@ -55,9 +55,9 @@ type T =
| undefined;
export class PlotlyPlugin implements IPlugin<T, Data> {
- tagName = "marimo-plotly";
+ public tagName = "marimo-plotly";
- validator = z.object({
+ public validator = z.object({
figure: z
.object({})
.passthrough()
@@ -65,7 +65,7 @@ export class PlotlyPlugin implements IPlugin<T, Data> {
config: z.object({}).passthrough(),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ public render(props: IPluginProps<T, Data>): JSX.Element {
return (
<PlotlyComponent
{...props.data}
diff --git a/frontend/src/plugins/impl/vega/VegaPlugin.tsx b/frontend/src/plugins/impl/vega/VegaPlugin.tsx
index 7a53648152..2b19142c3d 100644
--- a/frontend/src/plugins/impl/vega/VegaPlugin.tsx
+++ b/frontend/src/plugins/impl/vega/VegaPlugin.tsx
@@ -12,9 +12,9 @@ import React, { type JSX } from "react";
const LazyVegaComponent = React.lazy(() => import("./vega-component"));
export class VegaPlugin implements IPlugin<VegaComponentState, Data> {
- tagName = "marimo-vega";
+ public tagName = "marimo-vega";
- validator = z.object({
+ public validator = z.object({
spec: z
.object({})
.passthrough()
@@ -26,7 +26,7 @@ export class VegaPlugin implements IPlugin<VegaComponentState, Data> {
embedOptions: z.object({}).passthrough().default({}),
});
- render(props: IPluginProps<VegaComponentState, Data>): JSX.Element {
+ public render(props: IPluginProps<VegaComponentState, Data>): JSX.Element {
return (
<LazyVegaComponent
value={props.value}
diff --git a/frontend/src/plugins/impl/vega/__tests__/use-vega-container-remeasure.test.ts b/frontend/src/plugins/impl/vega/__tests__/use-vega-container-remeasure.test.ts
index f7092d1813..c4a28e0ae6 100644
--- a/frontend/src/plugins/impl/vega/__tests__/use-vega-container-remeasure.test.ts
+++ b/frontend/src/plugins/impl/vega/__tests__/use-vega-container-remeasure.test.ts
@@ -10,27 +10,27 @@ describe("useVegaContainerRemeasure", () => {
let OriginalResizeObserver: typeof ResizeObserver;
class FakeResizeObserver {
- callback: ResizeObserverCallback;
- el: Element | null = null;
+ public callback: ResizeObserverCallback;
+ public el: Element | null = null;
- constructor(callback: ResizeObserverCallback) {
+ public constructor(callback: ResizeObserverCallback) {
this.callback = callback;
observers.push(this);
}
- observe(el: Element) {
+ public observe(el: Element) {
this.el = el;
}
- disconnect() {
+ public disconnect() {
this.el = null;
}
- unobserve() {
+ public unobserve() {
this.el = null;
}
- trigger(width: number) {
+ public trigger(width: number) {
this.callback(
[
{
diff --git a/frontend/src/plugins/layout/AccordionPlugin.tsx b/frontend/src/plugins/layout/AccordionPlugin.tsx
index 5374d56f7e..4c39a2791e 100644
--- a/frontend/src/plugins/layout/AccordionPlugin.tsx
+++ b/frontend/src/plugins/layout/AccordionPlugin.tsx
@@ -27,15 +27,15 @@ interface Data {
}
export class AccordionPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-accordion";
+ public tagName = "marimo-accordion";
- validator = z.object({
+ public validator = z.object({
labels: z.array(z.string()),
multiple: z.boolean(),
expanded: z.array(z.string()).default([]),
});
- render(props: IStatelessPluginProps<Data>): JSX.Element {
+ public render(props: IStatelessPluginProps<Data>): JSX.Element {
return (
<AccordionComponent {...props.data}>{props.children}</AccordionComponent>
);
diff --git a/frontend/src/plugins/layout/CalloutPlugin.tsx b/frontend/src/plugins/layout/CalloutPlugin.tsx
index 4e64706407..a5a1236040 100644
--- a/frontend/src/plugins/layout/CalloutPlugin.tsx
+++ b/frontend/src/plugins/layout/CalloutPlugin.tsx
@@ -25,15 +25,15 @@ interface Data {
}
export class CalloutPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-callout-output";
+ public tagName = "marimo-callout-output";
- validator = z.object({
+ public validator = z.object({
html: z.string(),
kind: zodIntent,
title: z.string().optional(),
});
- render({ data }: IStatelessPluginProps<Data>): JSX.Element {
+ public render({ data }: IStatelessPluginProps<Data>): JSX.Element {
return (
<CalloutOutput html={data.html} kind={data.kind} title={data.title} />
);
diff --git a/frontend/src/plugins/layout/ImageComparisonPlugin.tsx b/frontend/src/plugins/layout/ImageComparisonPlugin.tsx
index 83e7466d35..faf036b3a5 100644
--- a/frontend/src/plugins/layout/ImageComparisonPlugin.tsx
+++ b/frontend/src/plugins/layout/ImageComparisonPlugin.tsx
@@ -12,9 +12,9 @@ const LazyImageComparisonComponent = React.lazy(
);
export class ImageComparisonPlugin implements IStatelessPlugin<ImageComparisonData> {
- tagName = "marimo-image-comparison";
+ public tagName = "marimo-image-comparison";
- validator = z.object({
+ public validator = z.object({
beforeSrc: z.string(),
afterSrc: z.string(),
value: z.number().min(0).max(100).default(50),
@@ -23,7 +23,9 @@ export class ImageComparisonPlugin implements IStatelessPlugin<ImageComparisonDa
height: z.string().optional(),
});
- render(props: IStatelessPluginProps<ImageComparisonData>): JSX.Element {
+ public render(
+ props: IStatelessPluginProps<ImageComparisonData>,
+ ): JSX.Element {
return (
<React.Suspense fallback={<div>Loading image comparison...</div>}>
<LazyImageComparisonComponent {...props.data} />
diff --git a/frontend/src/plugins/layout/JsonOutputPlugin.tsx b/frontend/src/plugins/layout/JsonOutputPlugin.tsx
index dd18d3a57a..6cbb9101ba 100644
--- a/frontend/src/plugins/layout/JsonOutputPlugin.tsx
+++ b/frontend/src/plugins/layout/JsonOutputPlugin.tsx
@@ -21,15 +21,15 @@ interface Data {
}
export class JsonOutputPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-json-output";
+ public tagName = "marimo-json-output";
- validator = z.object({
+ public validator = z.object({
name: z.string().nullish(),
jsonData: z.unknown(),
valueTypes: z.enum(["json", "python"]).default("python"),
});
- render({ data }: IStatelessPluginProps<Data>): JSX.Element {
+ public render({ data }: IStatelessPluginProps<Data>): JSX.Element {
// `false` defaults to no text label
const name = data.name === undefined ? false : data.name || "";
return (
diff --git a/frontend/src/plugins/layout/MimeRenderPlugin.tsx b/frontend/src/plugins/layout/MimeRenderPlugin.tsx
index 2d0546e679..b7990a8f5a 100644
--- a/frontend/src/plugins/layout/MimeRenderPlugin.tsx
+++ b/frontend/src/plugins/layout/MimeRenderPlugin.tsx
@@ -15,9 +15,9 @@ interface Data {
}
export class MimeRendererPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-mime-renderer";
+ public tagName = "marimo-mime-renderer";
- validator = z.object({
+ public validator = z.object({
mime: z.string().transform((val) => val as OutputMessage["mimetype"]),
data: z
.union([
@@ -29,7 +29,7 @@ export class MimeRendererPlugin implements IStatelessPlugin<Data> {
.transform((val) => val as OutputMessage["data"]),
});
- render({ data }: IStatelessPluginProps<Data>): JSX.Element {
+ public render({ data }: IStatelessPluginProps<Data>): JSX.Element {
if (!data.data) {
return <div />;
}
diff --git a/frontend/src/plugins/layout/NavigationMenuPlugin.tsx b/frontend/src/plugins/layout/NavigationMenuPlugin.tsx
index 696dcec341..3738016da7 100644
--- a/frontend/src/plugins/layout/NavigationMenuPlugin.tsx
+++ b/frontend/src/plugins/layout/NavigationMenuPlugin.tsx
@@ -195,7 +195,7 @@ const NavigationMenuViewportPortal = ({
};
export class NavigationMenuPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-nav-menu";
+ public tagName = "marimo-nav-menu";
private menuItemValidator = z.object({
label: z.string(),
@@ -208,14 +208,14 @@ export class NavigationMenuPlugin implements IStatelessPlugin<Data> {
items: z.array(this.menuItemValidator),
});
- validator = z.object({
+ public validator = z.object({
items: z.array(
z.union([this.menuItemValidator, this.menuItemGroupValidator]),
),
orientation: z.enum(["horizontal", "vertical"]),
});
- render(props: IStatelessPluginProps<Data>): JSX.Element {
+ public render(props: IStatelessPluginProps<Data>): JSX.Element {
return <NavMenuComponent {...props.data} />;
}
}
diff --git a/frontend/src/plugins/layout/OutlinePlugin.tsx b/frontend/src/plugins/layout/OutlinePlugin.tsx
index 318e8c27a1..1337470553 100644
--- a/frontend/src/plugins/layout/OutlinePlugin.tsx
+++ b/frontend/src/plugins/layout/OutlinePlugin.tsx
@@ -51,13 +51,13 @@ const OutlineContent: React.FC<{ label?: string }> = ({ label }) => {
};
export class OutlinePlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-outline";
+ public tagName = "marimo-outline";
- validator = z.object({
+ public validator = z.object({
label: z.string().optional(),
});
- render(props: IStatelessPluginProps<Data>): JSX.Element {
+ public render(props: IStatelessPluginProps<Data>): JSX.Element {
const { label } = props.data;
return (
diff --git a/frontend/src/plugins/layout/ProgressPlugin.tsx b/frontend/src/plugins/layout/ProgressPlugin.tsx
index 9b9969420d..4e11e0012a 100644
--- a/frontend/src/plugins/layout/ProgressPlugin.tsx
+++ b/frontend/src/plugins/layout/ProgressPlugin.tsx
@@ -41,9 +41,9 @@ interface Data {
}
export class ProgressPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-progress";
+ public tagName = "marimo-progress";
- validator = z.object({
+ public validator = z.object({
title: z.string().optional(),
subtitle: z.string().optional(),
progress: z.union([z.number(), z.boolean()]),
@@ -52,7 +52,7 @@ export class ProgressPlugin implements IStatelessPlugin<Data> {
rate: z.number().optional(),
});
- render(props: IStatelessPluginProps<Data>): JSX.Element {
+ public render(props: IStatelessPluginProps<Data>): JSX.Element {
return <ProgressComponent {...props.data} />;
}
}
diff --git a/frontend/src/plugins/layout/RoutesPlugin.tsx b/frontend/src/plugins/layout/RoutesPlugin.tsx
index 54de400217..1796f385ba 100644
--- a/frontend/src/plugins/layout/RoutesPlugin.tsx
+++ b/frontend/src/plugins/layout/RoutesPlugin.tsx
@@ -21,13 +21,13 @@ interface Data {
}
export class RoutesPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-routes";
+ public tagName = "marimo-routes";
- validator = z.object({
+ public validator = z.object({
routes: z.array(z.string()),
});
- render(props: IStatelessPluginProps<Data>): React.ReactElement {
+ public render(props: IStatelessPluginProps<Data>): React.ReactElement {
return <RoutesComponent {...props.data}>{props.children}</RoutesComponent>;
}
}
diff --git a/frontend/src/plugins/layout/StatPlugin.tsx b/frontend/src/plugins/layout/StatPlugin.tsx
index 6c34f7b388..8bc7895078 100644
--- a/frontend/src/plugins/layout/StatPlugin.tsx
+++ b/frontend/src/plugins/layout/StatPlugin.tsx
@@ -25,9 +25,9 @@ interface Data {
}
export class StatPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-stat";
+ public tagName = "marimo-stat";
- validator = z.object({
+ public validator = z.object({
value: z.union([z.string(), z.number(), z.boolean()]).optional(),
label: z.string().optional(),
caption: z.string().optional(),
@@ -37,7 +37,7 @@ export class StatPlugin implements IStatelessPlugin<Data> {
slot: z.any().optional(),
});
- render({ data }: IStatelessPluginProps<Data>): JSX.Element {
+ public render({ data }: IStatelessPluginProps<Data>): JSX.Element {
return <StatComponent {...data} />;
}
}
diff --git a/frontend/src/plugins/layout/TexPlugin.tsx b/frontend/src/plugins/layout/TexPlugin.tsx
index cdd9483cb0..fdace99c85 100644
--- a/frontend/src/plugins/layout/TexPlugin.tsx
+++ b/frontend/src/plugins/layout/TexPlugin.tsx
@@ -15,11 +15,11 @@ import type {
* LaTeX.
*/
export class TexPlugin implements IStatelessPlugin<{}> {
- tagName = "marimo-tex";
+ public tagName = "marimo-tex";
- validator = z.object({});
+ public validator = z.object({});
- render(props: IStatelessPluginProps<{}>): JSX.Element {
+ public render(props: IStatelessPluginProps<{}>): JSX.Element {
return (
<TexComponent
host={props.host}
diff --git a/frontend/src/plugins/layout/carousel/CarouselPlugin.tsx b/frontend/src/plugins/layout/carousel/CarouselPlugin.tsx
index 646f011d46..dc6d035893 100644
--- a/frontend/src/plugins/layout/carousel/CarouselPlugin.tsx
+++ b/frontend/src/plugins/layout/carousel/CarouselPlugin.tsx
@@ -20,15 +20,15 @@ interface Data {
}
export class CarouselPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-carousel";
+ public tagName = "marimo-carousel";
- validator = z.object({
+ public validator = z.object({
index: z.string().nullish(),
height: z.union([z.string(), z.number()]).nullish(),
});
// TODO: Move async when we support async css
- cssStyles = [
+ public cssStyles = [
swiperCss,
swiperCssVirtual,
swiperCssNavigation,
@@ -38,7 +38,7 @@ export class CarouselPlugin implements IStatelessPlugin<Data> {
swiperSlidesCss,
];
- render(props: IStatelessPluginProps<Data>): JSX.Element {
+ public render(props: IStatelessPluginProps<Data>): JSX.Element {
return (
<LazySlidesComponent {...props.data} wrapAround={true}>
{props.children}
diff --git a/frontend/src/plugins/layout/mermaid/MermaidPlugin.tsx b/frontend/src/plugins/layout/mermaid/MermaidPlugin.tsx
index 24dfdefaac..13187b2608 100644
--- a/frontend/src/plugins/layout/mermaid/MermaidPlugin.tsx
+++ b/frontend/src/plugins/layout/mermaid/MermaidPlugin.tsx
@@ -14,15 +14,15 @@ interface Data {
}
export class MermaidPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-mermaid";
+ public tagName = "marimo-mermaid";
- validator = z.object({
+ public validator = z.object({
diagram: z.string(),
theme: z.string().optional(),
theme_variables: z.record(z.string(), z.string()).optional(),
});
- render(props: IStatelessPluginProps<Data>): JSX.Element {
+ public render(props: IStatelessPluginProps<Data>): JSX.Element {
return (
<LazyMermaid
diagram={props.data.diagram}
diff --git a/frontend/src/utils/Deferred.ts b/frontend/src/utils/Deferred.ts
index 0ba1f0adb1..ee285b8718 100644
--- a/frontend/src/utils/Deferred.ts
+++ b/frontend/src/utils/Deferred.ts
@@ -7,13 +7,13 @@
* cases where you need to check if a promise has settled without awaiting it.
*/
export class Deferred<T> {
- promise: Promise<T>;
- resolve!: (value: T | PromiseLike<T>) => void;
- reject!: (reason?: unknown) => void;
- status: "pending" | "resolved" | "rejected" = "pending";
- value: T | undefined = undefined;
+ public promise: Promise<T>;
+ public resolve!: (value: T | PromiseLike<T>) => void;
+ public reject!: (reason?: unknown) => void;
+ public status: "pending" | "resolved" | "rejected" = "pending";
+ public value: T | undefined = undefined;
- constructor() {
+ public constructor() {
this.promise = new Promise<T>((resolve, reject) => {
this.reject = (reason: unknown) => {
this.status = "rejected";
diff --git a/frontend/src/utils/async-capture-tracker.ts b/frontend/src/utils/async-capture-tracker.ts
index 5280cbaaa3..4ff6750dbe 100644
--- a/frontend/src/utils/async-capture-tracker.ts
+++ b/frontend/src/utils/async-capture-tracker.ts
@@ -66,7 +66,7 @@ export class AsyncCaptureTracker<K, R = unknown> {
* - Captured with a different value
* - In-flight with a different value (will be aborted on {@link startCapture})
*/
- needsCapture(key: K, inputValue: unknown): boolean {
+ public needsCapture(key: K, inputValue: unknown): boolean {
if (this.capturedInputs.get(key) === inputValue) {
return false;
}
@@ -82,7 +82,10 @@ export class AsyncCaptureTracker<K, R = unknown> {
* that resolves when the capture completes (with the result, or `undefined`
* on failure/abort). Returns `null` otherwise.
*/
- waitForInFlight(key: K, inputValue: unknown): Promise<R | undefined> | null {
+ public waitForInFlight(
+ key: K,
+ inputValue: unknown,
+ ): Promise<R | undefined> | null {
const flight = this.inFlight.get(key);
if (flight && flight.inputValue === inputValue) {
return flight.deferred.promise;
@@ -97,7 +100,7 @@ export class AsyncCaptureTracker<K, R = unknown> {
*
* @returns A {@link CaptureHandle} scoped to this attempt.
*/
- startCapture(key: K, inputValue: unknown): CaptureHandle<R> {
+ public startCapture(key: K, inputValue: unknown): CaptureHandle<R> {
const prev = this.inFlight.get(key);
if (prev) {
this.cancelEntry(prev);
@@ -133,7 +136,7 @@ export class AsyncCaptureTracker<K, R = unknown> {
* Remove tracking for keys not in the given set.
* Aborts in-flight captures and resolves their waiters with `undefined`.
*/
- prune(currentKeys: Set<K>): void {
+ public prune(currentKeys: Set<K>): void {
for (const key of this.capturedInputs.keys()) {
if (!currentKeys.has(key)) {
this.capturedInputs.delete(key);
@@ -148,12 +151,12 @@ export class AsyncCaptureTracker<K, R = unknown> {
}
/** Whether any captures are currently in-flight. */
- get isCapturing(): boolean {
+ public get isCapturing(): boolean {
return this.inFlight.size > 0;
}
/** Abort all in-flight captures. Resolves all waiters with `undefined`. */
- abort(): void {
+ public abort(): void {
for (const entry of this.inFlight.values()) {
this.cancelEntry(entry);
}
@@ -161,7 +164,7 @@ export class AsyncCaptureTracker<K, R = unknown> {
}
/** Reset all state. */
- reset(): void {
+ public reset(): void {
this.abort();
this.capturedInputs.clear();
}
diff --git a/frontend/src/utils/errors.ts b/frontend/src/utils/errors.ts
index 2ef6b67771..84fe7dd31b 100644
--- a/frontend/src/utils/errors.ts
+++ b/frontend/src/utils/errors.ts
@@ -68,9 +68,9 @@ function safeJSONParse(message: string): unknown {
* kept as `cause` so `prettyError` can surface its `detail`.
*/
export class HTTPError extends Error {
- readonly status: number;
+ public readonly status: number;
- constructor(status: number, statusText: string, body?: unknown) {
+ public constructor(status: number, statusText: string, body?: unknown) {
super(statusText, { cause: body });
this.name = "HTTPError";
this.status = status;
@@ -78,7 +78,7 @@ export class HTTPError extends Error {
}
export class CellNotInitializedError extends Error {
- constructor(
+ public constructor(
message = "The cell containing this UI element has not been run yet. Please run the cell first.",
) {
super(message);
@@ -87,7 +87,7 @@ export class CellNotInitializedError extends Error {
}
export class FunctionNotFoundError extends Error {
- constructor(
+ public constructor(
message = "This UI element could not reach its function on the kernel. Try re-running the cell.",
) {
super(message);
@@ -96,7 +96,7 @@ export class FunctionNotFoundError extends Error {
}
export class NoKernelConnectedError extends Error {
- constructor(message = "Not yet connected to a kernel.") {
+ public constructor(message = "Not yet connected to a kernel.") {
super(message);
this.name = "NoKernelConnectedError";
}
diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsx
index 2ef047213e..5e44d94803 100644
--- a/frontend/src/utils/id-tree.tsx
+++ b/frontend/src/utils/id-tree.tsx
@@ -28,7 +28,7 @@ export class TreeNode<T> {
public isCollapsed: boolean;
public children: TreeNode<T>[];
- constructor(value: T, isCollapsed: boolean, children: TreeNode<T>[]) {
+ public constructor(value: T, isCollapsed: boolean, children: TreeNode<T>[]) {
this.value = value;
this.isCollapsed = isCollapsed;
this.children = children;
@@ -38,7 +38,7 @@ export class TreeNode<T> {
* Recursively count the number of nodes in the tree
*/
@Memoize()
- geDescendantCount(): number {
+ public geDescendantCount(): number {
let count = 0;
const stack = [...this.children];
@@ -57,7 +57,7 @@ export class TreeNode<T> {
}
@Memoize()
- getDescendants(): T[] {
+ public getDescendants(): T[] {
const result: T[] = [];
const stack = [...this.children];
@@ -76,7 +76,7 @@ export class TreeNode<T> {
}
@Memoize()
- get inOrderIds(): T[] {
+ public get inOrderIds(): T[] {
const result: T[] = [];
// Use depth-first traversal to preserve logical document order
@@ -94,14 +94,14 @@ export class TreeNode<T> {
return result;
}
- toString(): string {
+ public toString(): string {
if (this.isCollapsed) {
return `${this.value} (collapsed)`;
}
return String(this.value);
}
- equals(other: TreeNode<T>): boolean {
+ public equals(other: TreeNode<T>): boolean {
return this.value === other.value;
}
}
@@ -117,7 +117,7 @@ export class CollapsibleTree<T> {
this.id = id;
}
- static from<T>(ids: T[]): CollapsibleTree<T> {
+ public static from<T>(ids: T[]): CollapsibleTree<T> {
const id = `tree_${uniqueId++}` as CellColumnId;
return new CollapsibleTree(
ids.map((id) => new TreeNode(id, false, [])),
@@ -128,7 +128,7 @@ export class CollapsibleTree<T> {
/**
* Create a new tree from ids, preserving structure from previous tree if possible
*/
- static fromWithPreviousShape<T>(
+ public static fromWithPreviousShape<T>(
ids: T[],
previousTree?: CollapsibleTree<T>,
): CollapsibleTree<T> {
@@ -163,31 +163,31 @@ export class CollapsibleTree<T> {
return newTree;
}
- withNodes(nodes: TreeNode<T>[]): CollapsibleTree<T> {
+ public withNodes(nodes: TreeNode<T>[]): CollapsibleTree<T> {
return new CollapsibleTree(nodes, this.id);
}
@Memoize()
- get topLevelIds(): T[] {
+ public get topLevelIds(): T[] {
return this.nodes.map((n) => n.value);
}
@Memoize()
- get inOrderIds(): T[] {
+ public get inOrderIds(): T[] {
return this.nodes.flatMap((n) => [n.value, ...n.inOrderIds]);
}
@Memoize()
- get idSet(): Set<T> {
+ public get idSet(): Set<T> {
return new Set(this.inOrderIds);
}
- get length(): number {
+ public get length(): number {
return this.nodes.length;
}
@Memoize()
- get _nodeMap(): Map<T, TreeNode<T>> {
+ public get _nodeMap(): Map<T, TreeNode<T>> {
const result = new Map<T, TreeNode<T>>();
for (const node of this.nodes) {
result.set(node.value, node);
@@ -200,7 +200,7 @@ export class CollapsibleTree<T> {
*
* Only works for the top-level nodes
*/
- getDescendants(id: T): T[] {
+ public getDescendants(id: T): T[] {
const node = this._nodeMap.get(id);
if (!node) {
Logger.warn(
@@ -216,7 +216,7 @@ export class CollapsibleTree<T> {
*
* Only works for the top-level nodes
*/
- isCollapsed(id: T): boolean {
+ public isCollapsed(id: T): boolean {
const node = this._nodeMap.get(id);
if (!node) {
Logger.warn(
@@ -230,7 +230,7 @@ export class CollapsibleTree<T> {
/**
* Get the index of the given node, or throw
*/
- indexOfOrThrow(id: T): CellIndex {
+ public indexOfOrThrow(id: T): CellIndex {
const index = this.nodes.findIndex((n) => n.value === id);
if (index === -1) {
throw new Error(
@@ -244,14 +244,14 @@ export class CollapsibleTree<T> {
* Get the top level nodes in the given range.
* This does not include descendants.
*/
- slice(start: number, end: number): T[] {
+ public slice(start: number, end: number): T[] {
return this.nodes.slice(start, end).map((n) => n.value);
}
/**
* Move the given node to the front
*/
- moveToFront(id: T): CollapsibleTree<T> {
+ public moveToFront(id: T): CollapsibleTree<T> {
const index = this.indexOfOrThrow(id);
return this.withNodes(arrayMove(this.nodes, index, 0));
}
@@ -259,7 +259,7 @@ export class CollapsibleTree<T> {
/**
* Move the given node to the back
*/
- moveToBack(id: T): CollapsibleTree<T> {
+ public moveToBack(id: T): CollapsibleTree<T> {
const index = this.indexOfOrThrow(id);
return this.withNodes(arrayMove(this.nodes, index, this.nodes.length - 1));
}
@@ -268,7 +268,7 @@ export class CollapsibleTree<T> {
* Collapse everything past the given node @param id
* until @param until or the end of the tree
*/
- collapse(id: T, until: T | undefined): CollapsibleTree<T> {
+ public collapse(id: T, until: T | undefined): CollapsibleTree<T> {
const nodeIndex = this.nodes.findIndex((n) => n.value === id);
if (nodeIndex === -1) {
throw new Error(
@@ -307,7 +307,7 @@ export class CollapsibleTree<T> {
* Only works for the top-level nodes
* Does not collapse the children of already collapsed nodes
*/
- collapseAll(
+ public collapseAll(
collapseRanges: ({ id: T; until: T | undefined } | null)[],
): CollapsibleTree<T> {
const nodes = [...this.nodes];
@@ -363,7 +363,7 @@ export class CollapsibleTree<T> {
* Expand a node and all of its children.
* If the node is already expanded, returns the same tree (no-op).
*/
- expand(id: T): CollapsibleTree<T> {
+ public expand(id: T): CollapsibleTree<T> {
const nodeIndex = this.nodes.findIndex((n) => n.value === id);
if (nodeIndex === -1) {
throw new Error(
@@ -387,7 +387,7 @@ export class CollapsibleTree<T> {
/**
* Expand all collapsed nodes in the tree, including nested ones
*/
- expandAll(): CollapsibleTree<T> {
+ public expandAll(): CollapsibleTree<T> {
let nodes = [...this.nodes];
let nodeIndex = 0;
@@ -411,21 +411,21 @@ export class CollapsibleTree<T> {
/**
* Move a node from one index to another
*/
- move(fromIdx: number, toIdx: number): CollapsibleTree<T> {
+ public move(fromIdx: number, toIdx: number): CollapsibleTree<T> {
return this.withNodes(arrayMove(this.nodes, fromIdx, toIdx));
}
/**
* Get the node at the given index
*/
- at(index: number): T | undefined {
+ public at(index: number): T | undefined {
return this.nodes.at(index)?.value;
}
/**
* Get the node at the given index
*/
- atOrThrow(index: number): T {
+ public atOrThrow(index: number): T {
const node = this.nodes.at(index);
if (node === undefined) {
throw new Error(`Node at index ${index} not found in tree`);
@@ -436,21 +436,21 @@ export class CollapsibleTree<T> {
/**
* Get the first node, or throw
*/
- first(): T {
+ public first(): T {
return this.atOrThrow(0);
}
/**
* Get the last node, or throw
*/
- last(): T {
+ public last(): T {
return this.atOrThrow(this.nodes.length - 1);
}
/**
* Get the next node after the given node, does not wrap.
*/
- after(id: T): T | undefined {
+ public after(id: T): T | undefined {
const index = this.indexOfOrThrow(id);
if (index === this.nodes.length - 1) {
return undefined;
@@ -461,7 +461,7 @@ export class CollapsibleTree<T> {
/**
* Get the previous node before the given node, does not wrap.
*/
- before(id: T): T | undefined {
+ public before(id: T): T | undefined {
const index = this.indexOfOrThrow(id);
if (index === 0) {
return undefined;
@@ -472,7 +472,7 @@ export class CollapsibleTree<T> {
/**
* Insert a node at the given index
*/
- insert(id: T, index: number): CollapsibleTree<T> {
+ public insert(id: T, index: number): CollapsibleTree<T> {
return this.withNodes(
arrayInsert(this.nodes, index, new TreeNode(id, false, [])),
);
@@ -481,28 +481,28 @@ export class CollapsibleTree<T> {
/**
* Insert a node at the end
*/
- insertAtEnd(id: T): CollapsibleTree<T> {
+ public insertAtEnd(id: T): CollapsibleTree<T> {
return this.insert(id, this.nodes.length);
}
/**
* Insert a node at the start
*/
- insertAtStart(id: T): CollapsibleTree<T> {
+ public insertAtStart(id: T): CollapsibleTree<T> {
return this.insert(id, 0);
}
/**
* Delete a node, expand if it was collapsed
*/
- deleteAtIndex(idx: number): CollapsibleTree<T> {
+ public deleteAtIndex(idx: number): CollapsibleTree<T> {
const id = this.atOrThrow(idx);
// Expand the node first (if collapsed) to bring children back to top level
const tree = this.expand(id);
return tree.withNodes(arrayDelete(tree.nodes, idx));
}
- delete(id: T): CollapsibleTree<T> {
+ public delete(id: T): CollapsibleTree<T> {
const index = this.indexOfOrThrow(id);
return this.deleteAtIndex(index);
}
@@ -510,14 +510,14 @@ export class CollapsibleTree<T> {
/**
* Get the number of nodes in the tree, not-including the given node
*/
- getCount(id: T): number {
+ public getCount(id: T): number {
return this._nodeMap.get(id)?.geDescendantCount() ?? 0;
}
/**
* Find and expand the node and all of its children
*/
- findAndExpandDeep(id: T): CollapsibleTree<T> {
+ public findAndExpandDeep(id: T): CollapsibleTree<T> {
const found = this.find(id);
if (found.length === 0) {
return this;
@@ -532,7 +532,7 @@ export class CollapsibleTree<T> {
* Find a node, returning the path to it
* With the last element being the node itself
*/
- find(id: T): T[] {
+ public find(id: T): T[] {
// We need to recursively find the node
function findNode(nodes: TreeNode<T>[], path: T[]): T[] {
for (const node of nodes) {
@@ -555,7 +555,7 @@ export class CollapsibleTree<T> {
* @param id the id of the node to split at
* @returns a tuple of the left and right trees
*/
- split(id: T): [CollapsibleTree<T>, CollapsibleTree<T> | undefined] {
+ public split(id: T): [CollapsibleTree<T>, CollapsibleTree<T> | undefined] {
const index = this.nodes.findIndex((n) => n.value === id);
if (index === -1) {
throw new Error(`Node ${id} not found in tree`);
@@ -570,14 +570,14 @@ export class CollapsibleTree<T> {
return [left, right];
}
- equals(other: CollapsibleTree<T>): boolean {
+ public equals(other: CollapsibleTree<T>): boolean {
return (
this.nodes.length === other.nodes.length &&
this.nodes.every((n, i) => n.value === other.nodes[i].value)
);
}
- toString(): string {
+ public toString(): string {
let depth = 0;
let result = "";
const asString = (nodes: TreeNode<T>[]) => {
@@ -596,7 +596,7 @@ export class CollapsibleTree<T> {
export class MultiColumn<T> {
private readonly columns: readonly CollapsibleTree<T>[];
- constructor(columns: readonly CollapsibleTree<T>[]) {
+ public constructor(columns: readonly CollapsibleTree<T>[]) {
this.columns = columns;
// Ensure there is always at least one column
@@ -605,7 +605,7 @@ export class MultiColumn<T> {
}
}
- static from<T>(idsList: T[][]): MultiColumn<T> {
+ public static from<T>(idsList: T[][]): MultiColumn<T> {
return new MultiColumn(idsList.map((ids) => CollapsibleTree.from(ids)));
}
@@ -613,7 +613,7 @@ export class MultiColumn<T> {
* Create a new MultiColumn from idsList,
* attempting to preserve structure from previous MultiColumn if possible.
*/
- static fromWithPreviousShape<T>(
+ public static fromWithPreviousShape<T>(
idsList: T[],
previousShape: MultiColumn<T>,
): MultiColumn<T> {
@@ -649,14 +649,14 @@ export class MultiColumn<T> {
}
@Memoize()
- isEmpty(): boolean {
+ public isEmpty(): boolean {
if (this.columns.length === 0) {
return true;
}
return this.columns.every((c) => c.nodes.length === 0);
}
- static fromIdsAndColumns<T>(
+ public static fromIdsAndColumns<T>(
idAndColumns: [T, number | undefined | null][],
): MultiColumn<T> {
// If column is undefined, use the previous column
@@ -682,11 +682,11 @@ export class MultiColumn<T> {
}
@Memoize()
- get topLevelIds(): T[][] {
+ public get topLevelIds(): T[][] {
return this.columns.map((c) => c.topLevelIds);
}
- get iterateTopLevelIds(): Iterable<T> {
+ public get iterateTopLevelIds(): Iterable<T> {
const columns = this.columns;
function* iter() {
@@ -701,33 +701,33 @@ export class MultiColumn<T> {
}
@Memoize()
- get inOrderIds(): T[] {
+ public get inOrderIds(): T[] {
return this.columns.flatMap((c) => c.inOrderIds);
}
- get colLength(): number {
+ public get colLength(): number {
return this.columns.length;
}
@Memoize()
- get idLength(): number {
+ public get idLength(): number {
return this.columns.reduce((acc, c) => acc + c.nodes.length, 0);
}
@Memoize()
- get _columnMap(): Map<CellColumnId, CollapsibleTree<T>> {
+ public get _columnMap(): Map<CellColumnId, CollapsibleTree<T>> {
return new Map(this.columns.map((c) => [c.id, c]));
}
- at(idx: number): CollapsibleTree<T> | undefined {
+ public at(idx: number): CollapsibleTree<T> | undefined {
return this.columns[idx];
}
- get(columnId: CellColumnId): CollapsibleTree<T> | undefined {
+ public get(columnId: CellColumnId): CollapsibleTree<T> | undefined {
return this._columnMap.get(columnId);
}
- atOrThrow(idx: number): CollapsibleTree<T> {
+ public atOrThrow(idx: number): CollapsibleTree<T> {
const column = this.columns[idx];
if (!column) {
throw new Error(`Column ${idx} not found`);
@@ -735,28 +735,31 @@ export class MultiColumn<T> {
return column;
}
- hasOnlyOneColumn(): boolean {
+ public hasOnlyOneColumn(): boolean {
return this.columns.length === 1;
}
- getColumns(): readonly CollapsibleTree<T>[] {
+ public getColumns(): readonly CollapsibleTree<T>[] {
return this.columns;
}
- hasOnlyOneId(): boolean {
+ public hasOnlyOneId(): boolean {
return this.idLength === 1;
}
@Memoize()
- getColumnIds(): CellColumnId[] {
+ public getColumnIds(): CellColumnId[] {
return this.columns.map((c) => c.id);
}
- indexOf(column: CollapsibleTree<T>): number {
+ public indexOf(column: CollapsibleTree<T>): number {
return this.columns.indexOf(column);
}
- addColumn(columnId: CellColumnId, initialIds: T[] = []): MultiColumn<T> {
+ public addColumn(
+ columnId: CellColumnId,
+ initialIds: T[] = [],
+ ): MultiColumn<T> {
return new MultiColumn(
this.columns.flatMap((c) => {
if (c.id === columnId) {
@@ -767,7 +770,7 @@ export class MultiColumn<T> {
);
}
- insertBreakpoint(cellId: T): MultiColumn<T> {
+ public insertBreakpoint(cellId: T): MultiColumn<T> {
const column = this.findWithId(cellId);
const [left, right] = column.split(cellId);
const newColumns = this.columns.flatMap((c) => {
@@ -779,7 +782,7 @@ export class MultiColumn<T> {
return new MultiColumn(newColumns);
}
- delete(columnId: CellColumnId): MultiColumn<T> {
+ public delete(columnId: CellColumnId): MultiColumn<T> {
// Move cells to preceding column
// If its the first column, move the cells to the next column
@@ -801,7 +804,7 @@ export class MultiColumn<T> {
return new MultiColumn(columns);
}
- mergeAllColumns(): MultiColumn<T> {
+ public mergeAllColumns(): MultiColumn<T> {
if (this.columns.length <= 1) {
return this;
}
@@ -811,7 +814,7 @@ export class MultiColumn<T> {
return new MultiColumn([firstColumn.withNodes(nodes)]);
}
- moveWithinColumn(
+ public moveWithinColumn(
col: CellColumnId,
fromIdx: CellIndex,
toIdx: CellIndex,
@@ -821,7 +824,7 @@ export class MultiColumn<T> {
});
}
- moveAcrossColumns(
+ public moveAcrossColumns(
fromCol: CellColumnId,
fromId: T,
toCol: CellColumnId,
@@ -868,7 +871,7 @@ export class MultiColumn<T> {
* @throws Error if any cellId is not found in any column.
* If targetId is among the moved cells, cells are inserted at the end of the target column.
*/
- moveCellsRelativeTo(
+ public moveCellsRelativeTo(
cellIds: T[],
targetId: T,
position: "before" | "after",
@@ -922,7 +925,7 @@ export class MultiColumn<T> {
return new MultiColumn(columnsWithRemovals);
}
- indexOfOrThrow(id: CellColumnId): number {
+ public indexOfOrThrow(id: CellColumnId): number {
const index = this.columns.findIndex((c) => c.id === id);
if (index === -1) {
throw new Error(
@@ -932,7 +935,7 @@ export class MultiColumn<T> {
return index;
}
- moveColumn(
+ public moveColumn(
fromCol: CellColumnId,
toCol: CellColumnId | "_left_" | "_right_",
): MultiColumn<T> {
@@ -951,7 +954,7 @@ export class MultiColumn<T> {
return new MultiColumn(arrayMove([...this.columns], fromIdx, toIdx));
}
- moveToNewColumn(cellId: T): MultiColumn<T> {
+ public moveToNewColumn(cellId: T): MultiColumn<T> {
const fromColumn = this.findWithId(cellId);
// Create new columns array with the cell removed from its original column
@@ -967,7 +970,7 @@ export class MultiColumn<T> {
return new MultiColumn([...columns, newColumn]);
}
- findWithId(id: T): CollapsibleTree<T> {
+ public findWithId(id: T): CollapsibleTree<T> {
const found = this.columns.find((c) => {
return c.inOrderIds.includes(id);
});
@@ -987,7 +990,7 @@ export class MultiColumn<T> {
* @returns new MultiColumn with the transformed column
* If the column was not updated, we return the object.
*/
- transformWithCellId(
+ public transformWithCellId(
id: T,
fn: (tree: CollapsibleTree<T>) => CollapsibleTree<T>,
): MultiColumn<T> {
@@ -1012,15 +1015,15 @@ export class MultiColumn<T> {
return new MultiColumn(columns);
}
- setupCellExists(): boolean {
+ public setupCellExists(): boolean {
return this.columns.some((c) => c.topLevelIds.includes(SETUP_CELL_ID as T));
}
- insertId(id: T, col: CellColumnId, index: CellIndex): MultiColumn<T> {
+ public insertId(id: T, col: CellColumnId, index: CellIndex): MultiColumn<T> {
return this.transform(col, (c) => c.insert(id, index));
}
- deleteById(cellId: T): MultiColumn<T> {
+ public deleteById(cellId: T): MultiColumn<T> {
return this.transformWithCellId(cellId, (c) => c.delete(cellId));
}
@@ -1030,7 +1033,7 @@ export class MultiColumn<T> {
* cells to their previous positions. Placements are sorted by
* (columnId, index) so insert order keeps indices valid.
*/
- placeCells(
+ public placeCells(
placements: Array<{ id: T; columnId: CellColumnId; index: CellIndex }>,
): MultiColumn<T> {
if (placements.length === 0) {
@@ -1052,7 +1055,7 @@ export class MultiColumn<T> {
return result;
}
- compact(): MultiColumn<T> {
+ public compact(): MultiColumn<T> {
// Don't compact if there's only one column
if (this.columns.length === 1) {
return this;
@@ -1070,7 +1073,7 @@ export class MultiColumn<T> {
/**
* Transform the column with the given column id
*/
- transform(
+ public transform(
columnId: CellColumnId,
fn: (tree: CollapsibleTree<T>) => CollapsibleTree<T>,
): MultiColumn<T> {
@@ -1101,7 +1104,7 @@ export class MultiColumn<T> {
* @param fn The function to transform each column
* @returns A new MultiColumn if any changes were made, otherwise this
*/
- transformAll(
+ public transformAll(
fn: (tree: CollapsibleTree<T>) => CollapsibleTree<T>,
): MultiColumn<T> {
let didChange = false;
diff --git a/frontend/src/utils/lru.ts b/frontend/src/utils/lru.ts
index 6796c3b166..b912ab5132 100644
--- a/frontend/src/utils/lru.ts
+++ b/frontend/src/utils/lru.ts
@@ -11,7 +11,7 @@ export class LRUCache<K, V> {
private cache = new Map<K, V>();
private options: LRUCacheOptions<K, V>;
- constructor(maxSize: number, options: LRUCacheOptions<K, V> = {}) {
+ public constructor(maxSize: number, options: LRUCacheOptions<K, V> = {}) {
this.maxSize = maxSize;
this.options = options;
}
diff --git a/frontend/src/utils/multi-map.ts b/frontend/src/utils/multi-map.ts
index 3b75707f11..ae43c351d3 100644
--- a/frontend/src/utils/multi-map.ts
+++ b/frontend/src/utils/multi-map.ts
@@ -6,15 +6,15 @@
export class MultiMap<K, V> {
private map = new Map<K, V[]>();
- get(key: K): V[] {
+ public get(key: K): V[] {
return this.map.get(key) ?? [];
}
- set(key: K, values: V[]): void {
+ public set(key: K, values: V[]): void {
this.map.set(key, values);
}
- add(key: K, value: V): void {
+ public add(key: K, value: V): void {
if (this.map.has(key)) {
// oxlint-disable-next-line typescript/no-non-null-assertion
this.map.get(key)!.push(value);
@@ -23,38 +23,40 @@ export class MultiMap<K, V> {
}
}
- has(key: K): boolean {
+ public has(key: K): boolean {
return this.map.has(key);
}
- delete(key: K): boolean {
+ public delete(key: K): boolean {
return this.map.delete(key);
}
- clear(): void {
+ public clear(): void {
this.map.clear();
}
- keys(): IterableIterator<K> {
+ public keys(): IterableIterator<K> {
return this.map.keys();
}
- values(): IterableIterator<V[]> {
+ public values(): IterableIterator<V[]> {
return this.map.values();
}
- entries(): IterableIterator<[K, V[]]> {
+ public entries(): IterableIterator<[K, V[]]> {
return this.map.entries();
}
- forEach(callback: (values: V[], key: K, map: Map<K, V[]>) => void): void {
+ public forEach(
+ callback: (values: V[], key: K, map: Map<K, V[]>) => void,
+ ): void {
this.map.forEach(callback);
}
/**
* Flatten all values into a single array.
*/
- flatValues(): V[] {
+ public flatValues(): V[] {
const result: V[] = [];
for (const arr of this.map.values()) {
result.push(...arr);
@@ -65,7 +67,7 @@ export class MultiMap<K, V> {
/**
* Number of keys in the MultiMap.
*/
- get size(): number {
+ public get size(): number {
return this.map.size;
}
}
diff --git a/frontend/src/utils/paths.ts b/frontend/src/utils/paths.ts
index 6e0d28bc27..7932eba723 100644
--- a/frontend/src/utils/paths.ts
+++ b/frontend/src/utils/paths.ts
@@ -41,24 +41,24 @@ export const Paths = {
export class PathBuilder {
public readonly deliminator: string;
- constructor(deliminator: "/" | "\\") {
+ public constructor(deliminator: "/" | "\\") {
this.deliminator = deliminator;
}
- static guessDeliminator(path: string): PathBuilder {
+ public static guessDeliminator(path: string): PathBuilder {
return path.includes("/") ? new PathBuilder("/") : new PathBuilder("\\");
}
- join(...paths: string[]): FilePath {
+ public join(...paths: string[]): FilePath {
return paths.filter(Boolean).join(this.deliminator) as FilePath;
}
- basename(path: FilePath): FilePath {
+ public basename(path: FilePath): FilePath {
const parts = path.split(this.deliminator);
return (parts.pop() ?? "") as FilePath;
}
- rest(path: FilePath, root: FilePath): FilePath {
+ public rest(path: FilePath, root: FilePath): FilePath {
const pathParts = path.split(this.deliminator);
const rootParts = root.split(this.deliminator);
let i = 0;
@@ -70,7 +70,7 @@ export class PathBuilder {
return pathParts.slice(i).join(this.deliminator) as FilePath;
}
- dirname(path: FilePath): FilePath {
+ public dirname(path: FilePath): FilePath {
const parts = path.split(this.deliminator);
parts.pop();
return parts.join(this.deliminator) as FilePath;
diff --git a/frontend/src/utils/pluralize.ts b/frontend/src/utils/pluralize.ts
index 915e0cfcf4..dafb39f944 100644
--- a/frontend/src/utils/pluralize.ts
+++ b/frontend/src/utils/pluralize.ts
@@ -4,7 +4,7 @@ export class PluralWord {
public singular: string;
public _plural?: string;
- constructor(singular: string, _plural?: string) {
+ public constructor(singular: string, _plural?: string) {
this.singular = singular;
this._plural = _plural;
}
@@ -21,11 +21,11 @@ export class PluralWord {
export class PluralWords {
private words: PluralWord[];
- constructor(words: PluralWord[]) {
+ public constructor(words: PluralWord[]) {
this.words = words;
}
- static of(...words: (PluralWord | string)[]) {
+ public static of(...words: (PluralWord | string)[]) {
return new PluralWords(
words.map((word) => {
if (typeof word === "string") {
diff --git a/frontend/src/utils/progress.ts b/frontend/src/utils/progress.ts
index 8f2cc2292c..edd7e82709 100644
--- a/frontend/src/utils/progress.ts
+++ b/frontend/src/utils/progress.ts
@@ -6,15 +6,15 @@ export class ProgressState {
private total: number | "indeterminate";
private listeners = new Set<ProgressListener>();
- constructor(total: number | "indeterminate") {
+ public constructor(total: number | "indeterminate") {
this.total = total;
}
- static indeterminate(): ProgressState {
+ public static indeterminate(): ProgressState {
return new ProgressState("indeterminate");
}
- addTotal(total: number) {
+ public addTotal(total: number) {
if (this.total === "indeterminate") {
this.total = total;
} else {
@@ -26,7 +26,7 @@ export class ProgressState {
/**
* Update the progress by the given increment.
*/
- increment(increment: number) {
+ public increment(increment: number) {
this.progress += increment;
this.notifyListeners();
}
@@ -34,7 +34,7 @@ export class ProgressState {
/**
* Get the progress as a percentage (0-100)
*/
- getProgress(): number | "indeterminate" {
+ public getProgress(): number | "indeterminate" {
if (this.total === "indeterminate") {
return "indeterminate";
}
@@ -45,7 +45,7 @@ export class ProgressState {
* Subscribe to progress updates.
* Returns an unsubscribe function.
*/
- subscribe(listener: ProgressListener): () => void {
+ public subscribe(listener: ProgressListener): () => void {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
diff --git a/frontend/src/utils/python-poet/poet.ts b/frontend/src/utils/python-poet/poet.ts
index 40a8e21a7d..a22a430060 100644
--- a/frontend/src/utils/python-poet/poet.ts
+++ b/frontend/src/utils/python-poet/poet.ts
@@ -25,12 +25,12 @@ function asString(value: string | PythonCode): string {
}
export class Variable implements PythonCode {
- name: string;
- constructor(name: string) {
+ public name: string;
+ public constructor(name: string) {
this.name = name;
}
- toCode(): string {
+ public toCode(): string {
return this.name;
}
}
@@ -43,16 +43,16 @@ interface LiteralOptions {
export class Literal implements PythonCode {
public readonly value: unknown;
public readonly opts: LiteralOptions;
- constructor(value: unknown, opts: LiteralOptions = {}) {
+ public constructor(value: unknown, opts: LiteralOptions = {}) {
this.value = value;
this.opts = opts;
}
- static from(value: unknown, opts: LiteralOptions = {}): Literal {
+ public static from(value: unknown, opts: LiteralOptions = {}): Literal {
return new Literal(value, opts);
}
- toCode(): string {
+ public toCode(): string {
const EMPTY_VALUE = "";
const { removeNull = false, removeUndefined = true } = this.opts;
@@ -122,12 +122,12 @@ export class VariableDeclaration implements PythonCode {
public name: string;
public value: string | PythonCode;
- constructor(name: string, value: string | PythonCode) {
+ public constructor(name: string, value: string | PythonCode) {
this.name = name;
this.value = value;
}
- toCode(): string {
+ public toCode(): string {
const right = asString(this.value);
if (right.includes("\n")) {
return `${this.name} = (\n${indent(right)}\n)`;
@@ -140,12 +140,12 @@ export class FunctionArg implements PythonCode {
public name: string;
public value: string | PythonCode;
- constructor(name: string, value: string | PythonCode) {
+ public constructor(name: string, value: string | PythonCode) {
this.name = name;
this.value = value;
}
- toCode(): string {
+ public toCode(): string {
return `${this.name}=${asString(this.value)}`;
}
}
@@ -155,7 +155,7 @@ export class FunctionCall implements PythonCode {
public name: string;
public multiLine: boolean;
- constructor(
+ public constructor(
name: string,
args: PythonCode[] | Record<string, PythonCode>,
multiLine = false,
@@ -165,7 +165,7 @@ export class FunctionCall implements PythonCode {
this.args = objectToArgs(args);
}
- toCode(): string {
+ public toCode(): string {
if (this.multiLine) {
if (this.args.length === 0) {
return `${this.name}()`;
@@ -178,11 +178,11 @@ export class FunctionCall implements PythonCode {
return `${this.name}(${this.args.map(asString).join(", ")})`;
}
- addArg(...args: PythonCode[]): FunctionCall {
+ public addArg(...args: PythonCode[]): FunctionCall {
return new FunctionCall(this.name, [...this.args, ...args], this.multiLine);
}
- chain(
+ public chain(
name: string,
args: PythonCode[] | Record<string, PythonCode>,
): FunctionCall {
diff --git a/frontend/src/utils/routes.ts b/frontend/src/utils/routes.ts
index 0fd2343ff1..70c4a7dbd4 100644
--- a/frontend/src/utils/routes.ts
+++ b/frontend/src/utils/routes.ts
@@ -13,7 +13,7 @@ export class TinyRouter {
pathFunction: MatchFunction<ParamData>;
}[];
- constructor(templates: string[]) {
+ public constructor(templates: string[]) {
this.routes = templates.map((template) => {
return {
template,
@@ -22,7 +22,9 @@ export class TinyRouter {
});
}
- match(location: Location): [Match<ParamData>, template: string] | false {
+ public match(
+ location: Location,
+ ): [Match<ParamData>, template: string] | false {
for (const { pathFunction, template } of this.routes) {
const match =
pathFunction(location.hash) || pathFunction(location.pathname);
diff --git a/frontend/src/utils/semaphore.ts b/frontend/src/utils/semaphore.ts
index 070c896fb9..3a2e2e9077 100644
--- a/frontend/src/utils/semaphore.ts
+++ b/frontend/src/utils/semaphore.ts
@@ -9,7 +9,7 @@ export class Semaphore {
private permits: number;
private waiters: Array<() => void> = [];
- constructor(permits: number) {
+ public constructor(permits: number) {
if (!Number.isInteger(permits) || permits < 1) {
throw new Error(
`Semaphore permits must be a positive integer, got ${permits}`,
@@ -20,16 +20,16 @@ export class Semaphore {
}
/** Permits currently available. */
- get available(): number {
+ public get available(): number {
return this.permits;
}
/** Number of waiters queued for a permit. */
- get pending(): number {
+ public get pending(): number {
return this.waiters.length;
}
- acquire(): Promise<void> {
+ public acquire(): Promise<void> {
if (this.permits > 0) {
this.permits--;
return Promise.resolve();
@@ -39,7 +39,7 @@ export class Semaphore {
});
}
- release(): void {
+ public release(): void {
const next = this.waiters.shift();
if (next) {
next();
@@ -54,7 +54,7 @@ export class Semaphore {
}
/** Acquire a permit, run `fn`, then release the permit. */
- async run<T>(fn: () => Promise<T>): Promise<T> {
+ public async run<T>(fn: () => Promise<T>): Promise<T> {
await this.acquire();
try {
return await fn();
diff --git a/frontend/src/utils/storage/storage.ts b/frontend/src/utils/storage/storage.ts
index 31c42b5d70..9b87949202 100644
--- a/frontend/src/utils/storage/storage.ts
+++ b/frontend/src/utils/storage/storage.ts
@@ -8,28 +8,28 @@ import { getIframeCapabilities } from "../capabilities";
class InMemoryStorage implements Storage {
private store = new Map<string, string>();
- get length(): number {
+ public get length(): number {
return this.store.size;
}
- clear(): void {
+ public clear(): void {
this.store.clear();
}
- getItem(key: string): string | null {
+ public getItem(key: string): string | null {
return this.store.get(key) || null;
}
- key(index: number): string | null {
+ public key(index: number): string | null {
const keys = [...this.store.keys()];
return keys[index] || null;
}
- removeItem(key: string): void {
+ public removeItem(key: string): void {
this.store.delete(key);
}
- setItem(key: string, value: string): void {
+ public setItem(key: string, value: string): void {
this.store.set(key, value);
}
}
diff --git a/frontend/src/utils/storage/typed.ts b/frontend/src/utils/storage/typed.ts
index 7e1457b24f..f89b7e20b3 100644
--- a/frontend/src/utils/storage/typed.ts
+++ b/frontend/src/utils/storage/typed.ts
@@ -16,12 +16,12 @@ export class TypedLocalStorage<T> implements ITypedStorage<T> {
private defaultValue: T;
private storage: Storage;
- constructor(defaultValue: T, storage = availableStorage) {
+ public constructor(defaultValue: T, storage = availableStorage) {
this.defaultValue = defaultValue;
this.storage = storage;
}
- get(key: string): T {
+ public get(key: string): T {
try {
const item = this.storage.getItem(key);
return item ? (JSON.parse(item) as T) : this.defaultValue;
@@ -30,11 +30,11 @@ export class TypedLocalStorage<T> implements ITypedStorage<T> {
}
}
- set(key: string, value: T) {
+ public set(key: string, value: T) {
this.storage.setItem(key, JSON.stringify(value));
}
- remove(key: string) {
+ public remove(key: string) {
this.storage.removeItem(key);
}
}
@@ -44,7 +44,7 @@ export class ZodLocalStorage<T> implements ITypedStorage<T> {
private getDefaultValue: () => T;
private storage: Storage;
- constructor(
+ public constructor(
schema: ZodType<T>,
getDefaultValue: () => T,
storage = availableStorage,
@@ -54,7 +54,7 @@ export class ZodLocalStorage<T> implements ITypedStorage<T> {
this.storage = storage;
}
- get(key: string): T {
+ public get(key: string): T {
try {
const item = this.storage.getItem(key);
if (item == null) {
@@ -72,11 +72,11 @@ export class ZodLocalStorage<T> implements ITypedStorage<T> {
}
}
- set(key: string, value: T) {
+ public set(key: string, value: T) {
this.storage.setItem(key, JSON.stringify(value));
}
- remove(key: string) {
+ public remove(key: string) {
this.storage.removeItem(key);
}
}
@@ -89,7 +89,11 @@ export class NotebookScopedLocalStorage<T> extends ZodLocalStorage<T> {
private filename: string | null;
private unsubscribeFromFilename: (() => void) | null;
- constructor(key: string, schema: ZodType<T>, getDefaultValue: () => T) {
+ public constructor(
+ key: string,
+ schema: ZodType<T>,
+ getDefaultValue: () => T,
+ ) {
const filename = store.get(filenameAtom);
super(schema, getDefaultValue);
this.filename = filename;
@@ -104,15 +108,15 @@ export class NotebookScopedLocalStorage<T> extends ZodLocalStorage<T> {
}
}
- override get(key: string) {
+ public override get(key: string) {
return super.get(this.createScopedKey(key, this.filename));
}
- override set(key: string, value: T) {
+ public override set(key: string, value: T) {
super.set(this.createScopedKey(key, this.filename), value);
}
- override remove(key: string) {
+ public override remove(key: string) {
super.remove(this.createScopedKey(key, this.filename));
}
diff --git a/frontend/src/utils/time.ts b/frontend/src/utils/time.ts
index 160de66e9e..3c69170f34 100644
--- a/frontend/src/utils/time.ts
+++ b/frontend/src/utils/time.ts
@@ -9,25 +9,25 @@ export type Seconds = TypedNumber<"seconds">;
export class Time {
private readonly ms: Milliseconds;
- static fromMilliseconds(ms: Milliseconds): Time;
- static fromMilliseconds(ms: Milliseconds | null): Time | null;
- static fromMilliseconds(ms: Milliseconds | null): Time | null {
+ public static fromMilliseconds(ms: Milliseconds): Time;
+ public static fromMilliseconds(ms: Milliseconds | null): Time | null;
+ public static fromMilliseconds(ms: Milliseconds | null): Time | null {
if (ms == null) {
return null;
}
return new Time(ms);
}
- static fromSeconds(s: Seconds): Time;
- static fromSeconds(s: Seconds | null): Time | null;
- static fromSeconds(s: Seconds | null): Time | null {
+ public static fromSeconds(s: Seconds): Time;
+ public static fromSeconds(s: Seconds | null): Time | null;
+ public static fromSeconds(s: Seconds | null): Time | null {
if (s == null) {
return null;
}
return new Time((s * 1000) as Milliseconds);
}
- static now(): Time {
+ public static now(): Time {
return new Time(Date.now() as Milliseconds);
}
@@ -35,11 +35,11 @@ export class Time {
this.ms = ms;
}
- toMilliseconds(): Milliseconds {
+ public toMilliseconds(): Milliseconds {
return this.ms;
}
- toSeconds(): Seconds {
+ public toSeconds(): Seconds {
return (this.ms / 1000) as Seconds;
}
}
diff --git a/frontend/src/utils/timed-cache.ts b/frontend/src/utils/timed-cache.ts
index 02d2d3f8aa..79dab5a4c8 100644
--- a/frontend/src/utils/timed-cache.ts
+++ b/frontend/src/utils/timed-cache.ts
@@ -9,7 +9,7 @@ export class TimedCache<T> {
private ttl: number;
private cache = new Map<string, { data: T; timestamp: number }>();
- constructor(options: TimedCacheOptions) {
+ public constructor(options: TimedCacheOptions) {
this.ttl = options.ttl;
}
@@ -22,7 +22,7 @@ export class TimedCache<T> {
}
}
- get(key: string): T | undefined {
+ public get(key: string): T | undefined {
this.cleanupExpiredEntries();
const cached = this.cache.get(key);
@@ -39,14 +39,14 @@ export class TimedCache<T> {
return cached.data;
}
- set(key: string, data: T): void {
+ public set(key: string, data: T): void {
this.cache.set(key, {
data,
timestamp: Date.now(),
});
}
- clear(): void {
+ public clear(): void {
this.cache.clear();
}
}
diff --git a/frontend/src/utils/tracer.ts b/frontend/src/utils/tracer.ts
index 37a69df792..35e6a09818 100644
--- a/frontend/src/utils/tracer.ts
+++ b/frontend/src/utils/tracer.ts
@@ -22,7 +22,10 @@ interface Span {
export class Tracer {
private spans: Span[] = [];
- startSpan(name: string, attributes: Record<string, unknown> = {}): Span {
+ public startSpan(
+ name: string,
+ attributes: Record<string, unknown> = {},
+ ): Span {
const span: Span = {
name,
startTime: Date.now(),
@@ -33,16 +36,16 @@ export class Tracer {
return span;
}
- endSpan(span: Span, status: SpanStatus = "ok"): void {
+ public endSpan(span: Span, status: SpanStatus = "ok"): void {
span.endTime = Date.now();
span.status = status;
}
- getSpans(): Span[] {
+ public getSpans(): Span[] {
return this.spans;
}
- wrap<T>(
+ public wrap<T>(
fn: () => T,
name?: string,
attributes: Record<string, unknown> = {},
@@ -58,7 +61,7 @@ export class Tracer {
}
}
- wrapAsync<T extends (...args: any[]) => Promise<any>>(
+ public wrapAsync<T extends (...args: any[]) => Promise<any>>(
fn: T,
name?: string,
attributes: Record<string, unknown> = {},
@@ -76,7 +79,7 @@ export class Tracer {
}) as T;
}
- logSpans(): void {
+ public logSpans(): void {
if (process.env.NODE_ENV !== "development") {
return;
}