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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
experimental: support virtual files in static export (#396)
Myles Scolnickf23028812910
diff --git a/frontend/package.json b/frontend/package.jsonindex 9b44b41b00..c1361e2cfd 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -62,6 +62,7 @@"@types/jsdom": "^21.1.5","@types/react-grid-layout": "^1.3.4","@uiw/react-codemirror": "^4.21.20",+ "blob-polyfill": "^7.0.20220408","class-variance-authority": "^0.7.0","clsx": "^1.2.1","cmdk": "^0.2.0",@@ -144,7 +145,6 @@"@testing-library/user-event": "^14.5.1","@types/katex": "^0.16.5","@types/lodash-es": "^4.17.10",- "@types/node": "^20.8.10","@types/react": "^18.2.36","@types/react-dom": "^18.2.14","@types/react-plotly.js": "^2.6.2",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex e0c7a71c24..94a19ad1f4 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -155,6 +155,9 @@ dependencies:'@uiw/react-codemirror':specifier: ^4.21.20version: 4.21.20(@babel/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])([email protected])([email protected])([email protected])+ blob-polyfill:+ specifier: ^7.0.20220408+ version: 7.0.20220408class-variance-authority:specifier: ^0.7.0version: 0.7.0@@ -313,9 +316,6 @@ devDependencies:'@types/lodash-es':specifier: ^4.17.10version: 4.17.10- '@types/node':- specifier: ^20.8.10- version: 20.8.10'@types/react':specifier: ^18.2.36version: 18.2.36@@ -7703,6 +7703,10 @@ packages:readable-stream: 3.6.0dev: true+ resolution: {integrity: sha512-oD8Ydw+5lNoqq+en24iuPt1QixdPpe/nUF8azTHnviCZYu9zUC+TwdzIp5orpblJosNlgNbVmmAb//c6d6ImUQ==}+ dev: false+resolution: {integrity: sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==}engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}diff --git a/frontend/src/__tests__/setup.ts b/frontend/src/__tests__/setup.tsnew file mode 100644index 0000000000..b86bf3449e--- /dev/null+++ b/frontend/src/__tests__/setup.ts@@ -0,0 +1,4 @@+/* Copyright 2023 Marimo. All rights reserved. */++// Required for testing ser/deser of blobs+import "blob-polyfill";diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex c92ca042df..a1f994181c 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -51,8 +51,9 @@ export function useNotebookActions(opts: { filename?: string | null }) {icon: <FolderDownIcon size={14} strokeWidth={1.5} />,label: "Export as HTML",hidden: !getFeatureFlag("static_export"),- handle: () => {- return downloadAsHTML({ filename: filename || "notebook.html" });+ handle: async () => {+ await downloadAsHTML({ filename: filename || "notebook.html" });+ return;},},{diff --git a/frontend/src/core/App.tsx b/frontend/src/core/App.tsxindex ad704740ed..f43ddd8bae 100644--- a/frontend/src/core/App.tsx+++ b/frontend/src/core/App.tsx@@ -55,6 +55,7 @@ import { useAtom } from "jotai";import { useRunStaleCells } from "../components/editor/cell/useRunCells";import { formatAll } from "./codemirror/format";import { cn } from "@/utils/cn";+import { isStaticNotebook } from "./static/static-state";interface AppProps {userConfig: UserConfig;@@ -196,6 +197,10 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {});useWindowEventListener("beforeunload", (e: BeforeUnloadEvent) => {+ if (isStaticNotebook()) {+ return;+ }+if (needsSave) {e.preventDefault();return (e.returnValue =diff --git a/frontend/src/core/cells/ids.ts b/frontend/src/core/cells/ids.tsindex 1da17c5b03..bcd04e2bc2 100644--- a/frontend/src/core/cells/ids.ts+++ b/frontend/src/core/cells/ids.ts@@ -49,3 +49,18 @@ export const HTMLCellId = {return element.closest('div[id^="cell-"]');},};++/**+ * A typed UIElementId+ */+export type UIElementId = `${CellId}-${string}`;+export const UIElementId = {+ parse(element: Element): UIElementId | null {+ return element.getAttribute("object-id") as UIElementId | null;+ },+ parseOrThrow(element: Element): UIElementId {+ const id = UIElementId.parse(element);+ invariant(id, "<marimo-ui-element/> missing object-id attribute");+ return id;+ },+};diff --git a/frontend/src/core/dom/UIElement.ts b/frontend/src/core/dom/UIElement.tsindex 70885e6d22..866c83143d 100644--- a/frontend/src/core/dom/UIElement.ts+++ b/frontend/src/core/dom/UIElement.ts@@ -1,6 +1,7 @@/* Copyright 2023 Marimo. All rights reserved. */import { Logger } from "../../utils/Logger";import { Functions } from "../../utils/functions";+import { UIElementId } from "../cells/ids";import { defineCustomElement } from "./defineCustomElement";import { MarimoValueInputEventType, marimoValueInputEvent } from "./events";import { UI_ELEMENT_REGISTRY } from "./uiregistry";@@ -83,7 +84,7 @@ export function initializeUIElement() {return;}- const objectId = this.getAttribute("object-id");+ const objectId = UIElementId.parseOrThrow(this);this.inputListener = (e: MarimoValueInputEventType) => {// TODO: just fill in the objectId and let the document handle// broadcast? that would still let other elements cancel the event@@ -122,7 +123,7 @@ export function initializeUIElement() {// It is critical that the element is registered in this method,// and not in the constructor, since it may be disconnected and// reconnected without being re-constructed- const objectId = this.getAttribute("object-id") as string;+ const objectId = UIElementId.parseOrThrow(this);const child = this.firstElementChild as HTMLElement;UI_ELEMENT_REGISTRY.registerInstance(objectId, child);@@ -136,7 +137,7 @@ export function initializeUIElement() {if (this.initialized) {// Unregister everythingdocument.removeEventListener(marimoValueInputEvent, this.inputListener);- const objectId = this.getAttribute("object-id") as string;+ const objectId = UIElementId.parseOrThrow(this);UI_ELEMENT_REGISTRY.removeInstance(objectId,this.firstElementChild as HTMLElement@@ -187,18 +188,18 @@ export function initializeUIElement() {* Given a node, check if its parent or itself is a UIElement,* and return its objectId if so.*/-export function getUIElementObjectId(target: HTMLElement): string | null {+export function getUIElementObjectId(target: HTMLElement): UIElementId | null {if (!target) {return null;}if (target.nodeName === UI_ELEMENT_TAG_NAME) {- return target.getAttribute("object-id");+ return UIElementId.parseOrThrow(target);}const node = target.parentElement;if (node?.nodeName === UI_ELEMENT_TAG_NAME) {- return node.getAttribute("object-id");+ return UIElementId.parseOrThrow(node);}return null;diff --git a/frontend/src/core/dom/events.ts b/frontend/src/core/dom/events.tsindex 46707a8299..b1b00a7d3d 100644--- a/frontend/src/core/dom/events.ts+++ b/frontend/src/core/dom/events.ts@@ -1,4 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */+import { UIElementId } from "../cells/ids";+export type ValueType = unknown;export type MarimoValueInputEventType = CustomEvent<{@@ -13,7 +15,7 @@ export type MarimoValueUpdateEventType = CustomEvent<{}>;export const marimoValueUpdateEvent = "marimo-value-update";-export type MarimoValueReadyEventType = CustomEvent<{ objectId: string }>;+export type MarimoValueReadyEventType = CustomEvent<{ objectId: UIElementId }>;export const marimoValueReadyEvent = "marimo-value-ready";/**diff --git a/frontend/src/core/dom/htmlUtils.ts b/frontend/src/core/dom/htmlUtils.tsindex 3f75898fc0..587c7cb478 100644--- a/frontend/src/core/dom/htmlUtils.ts+++ b/frontend/src/core/dom/htmlUtils.ts@@ -3,6 +3,7 @@ import { assertExists } from "@/utils/assertExists";import { UI_ELEMENT_REGISTRY } from "./uiregistry";import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";import { Objects } from "@/utils/objects";+import { UIElementId } from "../cells/ids";/*** Parse an attribute value as JSON.@@ -25,7 +26,9 @@ export function parseDataset(element: HTMLElement): Record<string, unknown> {*/export function parseInitialValue<T>(element: HTMLElement): T {// If parent is a <marimo-ui-element/> and has object-id, use that as the initialize the value- const objectId = element.parentElement?.getAttribute("object-id");+ const objectId = element.parentElement+ ? UIElementId.parse(element.parentElement)+ : undefined;if (objectId && UI_ELEMENT_REGISTRY.has(objectId)) {return UI_ELEMENT_REGISTRY.lookupValue(objectId) as T;}diff --git a/frontend/src/core/dom/uiregistry.ts b/frontend/src/core/dom/uiregistry.tsindex 670249e3cc..9f598681b0 100644--- a/frontend/src/core/dom/uiregistry.ts+++ b/frontend/src/core/dom/uiregistry.ts@@ -1,5 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */import { repl } from "../../utils/repl";+import { CellId, UIElementId } from "../cells/ids";import {ValueType,marimoValueUpdateEvent,@@ -27,11 +28,17 @@ export class UIElementRegistry {// maps UIElement objectIds to entries.entries: Map<string, UIElementEntry>;- constructor() {+ /**+ * Shared instance of UIElementRegistry since this must be a singleton.+ */+ static readonly INSTANCE = new UIElementRegistry();++ private constructor() {+ repl(UIElementRegistry.INSTANCE, "UIElementRegistry");this.entries = new Map();}- has(objectId: string): boolean {+ has(objectId: UIElementId): boolean {return this.entries.has(objectId);}@@ -41,7 +48,7 @@ export class UIElementRegistry {* @param objectId - id of the UIElement* @param instance - the HTMLElement that the UIElement wraps*/- registerInstance(objectId: string, instance: HTMLElement) {+ registerInstance(objectId: UIElementId, instance: HTMLElement) {const entry = this.entries.get(objectId);if (entry === undefined) {this.entries.set(objectId, {@@ -64,7 +71,7 @@ export class UIElementRegistry {* @param instance - the HTMLElement to remove**/- removeInstance(objectId: string, instance: HTMLElement) {+ 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@@ -84,7 +91,7 @@ export class UIElementRegistry {** @param cellId - stringified cellId*/- removeElementsByCell(cellId: string) {+ removeElementsByCell(cellId: CellId) {const objectIds = [...this.entries.keys()].filter((objectId) =>objectId.startsWith(`${cellId}-`));@@ -117,7 +124,7 @@ export class UIElementRegistry {*/broadcastValueUpdate(initiator: HTMLElement,- objectId: string,+ objectId: UIElementId,value: ValueType): void {const entry = this.entries.get(objectId);@@ -148,5 +155,4 @@ export class UIElementRegistry {}}-export const UI_ELEMENT_REGISTRY = new UIElementRegistry();-repl(UI_ELEMENT_REGISTRY, "UI_ELEMENT_REGISTRY");+export const UI_ELEMENT_REGISTRY = UIElementRegistry.INSTANCE;diff --git a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snapindex 1e4543c9be..69d2f73611 100644--- a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap+++ b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap@@ -81,6 +81,9 @@ exports[`download-html > should construct html correctly 1`] = `};window.__MARIMO_STATIC__.assetUrl =\\"https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist\\";+ window.__MARIMO_STATIC__.files = {+ \\"/@file/note.txt\\": { base64: \\"data:text/plain;base64,bm90ZQo=\\" },+ };</script><scriptdiff --git a/frontend/src/core/static/__tests__/download-html.test.ts b/frontend/src/core/static/__tests__/download-html.test.tsindex dbc3700431..25554524d4 100644--- a/frontend/src/core/static/__tests__/download-html.test.ts+++ b/frontend/src/core/static/__tests__/download-html.test.ts@@ -69,6 +69,11 @@ describe("download-html", () => {},cellRuntime: { [cellId]: createCellRuntimeState() },},+ files: {+ "/@file/note.txt": {+ base64: "data:text/plain;base64,bm90ZQo=",+ },+ },assetUrl: `https://cdn.jsdelivr.net/npm/@marimo-team/frontend@${version}/dist`,filename: "app",existingDocument: new JSDOM(DOC).window.document,diff --git a/frontend/src/core/static/__tests__/files.test.ts b/frontend/src/core/static/__tests__/files.test.tsnew file mode 100644index 0000000000..eb2fa6abc7--- /dev/null+++ b/frontend/src/core/static/__tests__/files.test.ts@@ -0,0 +1,76 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { describe, afterEach, expect, it, vi } from "vitest";+import { patchFetch, patchVegaLoader } from "../files";++describe("patchFetch", () => {+ const originalFetch = window.fetch;++ afterEach(() => {+ window.fetch = originalFetch; // Restore original fetch after each test+ });++ it("should return a blob response when a virtual file is fetched", async () => {+ const virtualFiles = {+ "/@file/virtual-file.txt": {+ base64: "data:text/plain;base64,VGVzdCBjb250ZW50", // Base64 for "Test content"+ },+ };++ patchFetch(virtualFiles);++ const response = await fetch("/@file/virtual-file.txt");+ const blob = await response.blob();+ const text = await blob.text();++ expect(response instanceof Response).toBeTruthy();+ expect(text).toBe("Test content");+ });++ it("should fallback to original fetch for non-virtual files", async () => {+ const mockResponse = new Response("Not a virtual file");+ window.fetch = vi.fn().mockResolvedValue(mockResponse);++ const unpatch = patchFetch({}); // No virtual files++ const response = await fetch("/@file/non-virtual-file.txt");+ const text = await response.text();++ unpatch();+ expect(window.fetch).toHaveBeenCalledWith(+ "/@file/non-virtual-file.txt",+ undefined+ );+ expect(text).toBe("Not a virtual file");+ });+});++describe("patchVegaLoader", () => {+ it("should return file content for virtual files", async () => {+ const virtualFiles = {+ "virtual-file.json": {+ base64: "data:application/json;base64,eyJrZXkiOiAidmFsdWUifQ==", // Base64 for '{"key": "value"}'+ },+ };++ const loader = {+ http: vi.fn((url) => Promise.resolve(`Original content for ${url}`)),+ };+ patchVegaLoader(loader, virtualFiles);++ const content = await loader.http("virtual-file.json");+ expect(content).toBe('{"key": "value"}');+ });++ it("should fallback to original http method for non-virtual files", async () => {+ const loader = {+ http: vi.fn((url) => Promise.resolve(`Original content for ${url}`)),+ };++ const unpatch = patchVegaLoader(loader, {});+ const content = await loader.http("non-virtual-file.json");+ unpatch(); // Restore the original http function++ expect(content).toBe("Original content for non-virtual-file.json");+ expect(loader.http).toHaveBeenCalledWith("non-virtual-file.json");+ });+});diff --git a/frontend/src/core/static/__tests__/virtual-file-tracker.test.ts b/frontend/src/core/static/__tests__/virtual-file-tracker.test.tsnew file mode 100644index 0000000000..4c3e83d98c--- /dev/null+++ b/frontend/src/core/static/__tests__/virtual-file-tracker.test.ts@@ -0,0 +1,92 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { expect, describe, it } from "vitest";+import { VirtualFileTracker, findVirtualFiles } from "../virtual-file-tracker";+import { CellId } from "@/core/cells/ids";+import { OutputMessage } from "@/core/kernel/messages";++describe("findVirtualFiles", () => {+ it("should return a set containing all virtual file paths in a string", () => {+ const input =+ "Some text /@file/test-file.js more text /@file/another-file.txt end";+ const expected = new Set([+ "/@file/test-file.js",+ "/@file/another-file.txt",+ ]);+ const result = findVirtualFiles(input);+ expect(result).toEqual(expected);+ });++ it("should return an empty set if no virtual file paths are present", () => {+ const input = "Some text without virtual file paths";+ const expected = new Set();+ const result = findVirtualFiles(input);+ expect(result).toEqual(expected);+ });++ it("should handle non-string inputs by converting them to JSON strings", () => {+ const input = { key: "value", path: "/@file/json-file.json" };+ const expected = new Set(["/@file/json-file.json"]);+ const result = findVirtualFiles(input);+ expect(result).toEqual(expected);+ });++ it("should return an empty set if the input is an empty string", () => {+ const input = "";+ const expected = new Set();+ const result = findVirtualFiles(input);+ expect(result).toEqual(expected);+ });++ it("should return an empty set if the input is null or undefined", () => {+ expect(findVirtualFiles(null)).toEqual(new Set());+ expect(findVirtualFiles(undefined)).toEqual(new Set());+ });++ it("should correctly identify virtual files with complex extensions", () => {+ const input = "File with complex extension /@file/complex-file.min.js";+ const expected = new Set(["/@file/complex-file.min.js"]);+ const result = findVirtualFiles(input);+ expect(result).toEqual(expected);+ });++ it("should not include non-virtual file paths", () => {+ const input =+ "Regular file path /some/regular/file.txt and virtual file /@file/virtual-file.md";+ const expected = new Set(["/@file/virtual-file.md"]);+ const result = findVirtualFiles(input);+ expect(result).toEqual(expected);+ });+});++describe("VirtualFileTracker", () => {+ it("should track virtual files, append, clear", () => {+ const tracker = VirtualFileTracker.INSTANCE;+ const cellId = "test-cell-id" as CellId;+ tracker.track({+ cell_id: cellId,+ output: {+ mimetype: "text/html",+ data: "Some text /@file/test-file.js more text",+ } as OutputMessage,+ });+ expect(tracker.virtualFiles.get(cellId)).toEqual(+ new Set(["/@file/test-file.js"])+ );++ // can append+ tracker.track({+ cell_id: cellId,+ output: {+ mimetype: "text/html",+ data: "Some text /@file/another-file.txt more text",+ } as OutputMessage,+ });+ expect(tracker.virtualFiles.get(cellId)).toEqual(+ new Set(["/@file/test-file.js", "/@file/another-file.txt"])+ );++ // can clear+ tracker.removeForCellId(cellId);+ expect(tracker.virtualFiles.get(cellId)).toEqual(undefined);+ });+});diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.tsindex 3010de366c..c87240c8b0 100644--- a/frontend/src/core/static/download-html.ts+++ b/frontend/src/core/static/download-html.ts@@ -1,6 +1,8 @@/* Copyright 2023 Marimo. All rights reserved. */import { NotebookState, getNotebook } from "../cells/cells";import { getMarimoVersion } from "../dom/marimo-tag";+import { downloadVirtualFiles } from "./files";+import { StaticVirtualFiles } from "./types";// For Testing:// Flip this to true to use local assets instead of CDN@@ -10,7 +12,7 @@ const ENABLE_LOCAL_ASSETS = false;/*** Downloads the current notebook as an HTML file.*/-export function downloadAsHTML(opts: { filename?: string }) {+export async function downloadAsHTML(opts: { filename?: string }) {const { filename } = opts;const notebook = getNotebook();const version = getMarimoVersion();@@ -26,6 +28,7 @@ export function downloadAsHTML(opts: { filename?: string }) {assetUrl: assetUrl,filename: filename || "notebook",existingDocument: document,+ files: await downloadVirtualFiles(),});const url = URL.createObjectURL(new Blob([html], { type: "text/html" }));@@ -43,9 +46,10 @@ export function constructHTML(opts: {notebookState: Pick<NotebookState, "cellIds" | "cellData" | "cellRuntime">;assetUrl: string;filename: string;+ files: StaticVirtualFiles;existingDocument: Document;}) {- const { version, notebookState, assetUrl, existingDocument } = opts;+ const { version, notebookState, assetUrl, existingDocument, files } = opts;const staticHead = existingDocument.head.cloneNode(true) as HTMLHeadElement;@@ -85,6 +89,7 @@ export function constructHTML(opts: {cellRuntime: notebookState.cellRuntime,})};window.__MARIMO_STATIC__.assetUrl = "${assetUrl}";+ window.__MARIMO_STATIC__.files = ${JSON.stringify(files)};</script></body></html>diff --git a/frontend/src/core/static/files.ts b/frontend/src/core/static/files.tsnew file mode 100644index 0000000000..96307ba4a9--- /dev/null+++ b/frontend/src/core/static/files.ts@@ -0,0 +1,92 @@+/* Copyright 2023 Marimo. All rights reserved. */++import { Logger } from "@/utils/Logger";+import { VirtualFileTracker } from "./virtual-file-tracker";+import { StaticVirtualFiles } from "./types";+import { deserializeBlob, serializeBlob } from "@/utils/blob";+import { getStaticVirtualFiles } from "./static-state";+import { Sets } from "@/utils/sets";++/**+ * Download virtual files used in the notebook+ */+export async function downloadVirtualFiles(): Promise<StaticVirtualFiles> {+ const files: StaticVirtualFiles = {};++ const virtualFiles = Sets.merge(+ ...VirtualFileTracker.INSTANCE.virtualFiles.values()+ );++ for (const url of virtualFiles) {+ try {+ const response = await fetch(url);+ const contentType = response.headers.get("Content-Type") ?? "";+ if (!contentType) {+ Logger.warn(`Content-Type header missing for virtual file ${url}`);+ }+ const data = await response.blob();+ const base64 = await serializeBlob(data);+ files[url] = { base64 };+ } catch (error) {+ Logger.warn(`Error downloading virtual file ${url}`, error);+ }+ }++ return files;+}++/**+ * Patch fetch to resolve virtual files+ */+export function patchFetch(+ files: StaticVirtualFiles = getStaticVirtualFiles()+) {+ // Store the original fetch function+ const originalFetch = window.fetch;++ // Override the global fetch so when /@file/ is used, it returns the blob data+ window.fetch = async (input, init) => {+ const urlString = input instanceof Request ? input.url : input.toString();++ const url = urlString.startsWith("/")+ ? new URL(urlString, window.location.origin)+ : new URL(urlString);++ if (files[url.pathname]) {+ const { base64 } = files[url.pathname];+ const blob = await deserializeBlob(base64);+ return new Response(blob);+ }++ // Fallback to the original fetch+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ return (originalFetch as any)(input, init);+ };++ return () => {+ window.fetch = originalFetch;+ };+}++export function patchVegaLoader(+ loader: {+ http: (url: string) => Promise<string>;+ },+ files: StaticVirtualFiles = getStaticVirtualFiles()+) {+ const originalHttp = loader.http;++ loader.http = async (url: string) => {+ if (files[url]) {+ const { base64 } = files[url];+ const blob = await deserializeBlob(base64);+ return blob.text();+ }++ return originalHttp(url);+ };++ return () => {+ loader.http = originalHttp;+ };+}diff --git a/frontend/src/core/static/static-state.ts b/frontend/src/core/static/static-state.tsindex 5174d0f006..dc4d325ba3 100644--- a/frontend/src/core/static/static-state.ts+++ b/frontend/src/core/static/static-state.ts@@ -1,20 +1,14 @@/* Copyright 2023 Marimo. All rights reserved. */import { invariant } from "@/utils/invariant";-import { NotebookState } from "../cells/cells";--export interface StaticNotebookState- extends Pick<NotebookState, "cellIds" | "cellData" | "cellRuntime"> {- version: string;- assetUrl: string;-}+import {+ MarimoStaticState,+ StaticNotebookState,+ StaticVirtualFiles,+} from "./types";declare global {interface Window {- __MARIMO_STATIC__?: {- version: string;- notebookState: StaticNotebookState;- assetUrl: string;- };+ __MARIMO_STATIC__?: MarimoStaticState;}}@@ -35,3 +29,9 @@ export function getStaticNotebookAssetUrl(): string {return window.__MARIMO_STATIC__.assetUrl;}++export function getStaticVirtualFiles(): StaticVirtualFiles {+ invariant(window.__MARIMO_STATIC__ !== undefined, "Not a static notebook");++ return window.__MARIMO_STATIC__.files;+}diff --git a/frontend/src/core/static/types.ts b/frontend/src/core/static/types.tsnew file mode 100644index 0000000000..563c35ac80--- /dev/null+++ b/frontend/src/core/static/types.ts@@ -0,0 +1,17 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { NotebookState } from "../cells/cells";++export interface StaticNotebookState+ extends Pick<NotebookState, "cellIds" | "cellData" | "cellRuntime"> {+ version: string;+ assetUrl: string;+}++export type StaticVirtualFiles = Record<string, { base64: string }>;++export interface MarimoStaticState {+ version: string;+ notebookState: StaticNotebookState;+ assetUrl: string;+ files: StaticVirtualFiles;+}diff --git a/frontend/src/core/static/virtual-file-tracker.ts b/frontend/src/core/static/virtual-file-tracker.tsnew file mode 100644index 0000000000..e208ed3615--- /dev/null+++ b/frontend/src/core/static/virtual-file-tracker.ts@@ -0,0 +1,67 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { CellMessage } from "../kernel/messages";+import { CellId } from "../cells/ids";+import { repl } from "@/utils/repl";++// Virtual files are of the form /@file/<file-name>.<extension>+const VIRTUAL_FILE_REGEX = /\/@file\/([^\s/]+)\.([\dA-Za-z]+)/g;++/**+ * Tracks virtual files that are present on the page.+ */+export class VirtualFileTracker {+ /**+ * Shared instance of VirtualFileTracker since this must be a singleton.+ */+ static readonly INSTANCE = new VirtualFileTracker();++ virtualFiles = new Map<CellId, Set<string>>();++ private constructor() {+ repl(VirtualFileTracker.INSTANCE, "VirtualFileTracker");+ }++ track(message: Pick<CellMessage, "cell_id" | "output">): void {+ const { cell_id, output } = message;+ if (!output) {+ return;+ }++ switch (output.mimetype) {+ case "application/json":+ case "text/html": {+ const prev = this.virtualFiles.get(cell_id);+ const matches = findVirtualFiles(output.data);+ prev?.forEach((file) => matches.add(file));+ this.virtualFiles.set(cell_id, matches);+ return;+ }+ default:+ return;+ }+ }++ removeForCellId(cellId: CellId): void {+ this.virtualFiles.delete(cellId);+ }+}++// @visibleForTesting+export function findVirtualFiles(str: unknown): Set<string> {+ if (!str) {+ return new Set();+ }++ const files = new Set<string>();+ const asString = typeof str === "string" ? str : JSON.stringify(str);+ const matches = asString.match(VIRTUAL_FILE_REGEX);++ // For each match, add the file to the set of virtual files+ if (matches) {+ for (const match of matches) {+ files.add(match);+ }+ }++ return files;+}diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 94c3c0131d..2ee0f5b844 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -25,6 +25,7 @@ import { prettyError } from "@/utils/errors";import { isStaticNotebook } from "../static/static-state";import { useRef } from "react";import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";+import { VirtualFileTracker } from "../static/virtual-file-tracker";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -128,6 +129,7 @@ export function useMarimoWebSocket(opts: {// if the same cell-id is later reused for another element.const { cell_id } = msg.data;UI_ELEMENT_REGISTRY.removeElementsByCell(cell_id);+ VirtualFileTracker.INSTANCE.removeForCellId(cell_id);return;}case "completion-result":@@ -146,6 +148,7 @@ export function useMarimoWebSocket(opts: {*/const body = msg.data;handleCellMessage({ cellId: body.cell_id, message: body });+ VirtualFileTracker.INSTANCE.track(body);return;}case "variables":diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex 0935744492..800d2d8210 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -10,6 +10,9 @@ import { reportVitals } from "./utils/vitals";import { Provider } from "jotai";import { store } from "./core/state/jotai";import { maybeRegisterVSCodeBindings } from "./core/vscode/vscode-bindings";+import { patchFetch, patchVegaLoader } from "./core/static/files";+import { isStaticNotebook } from "./core/static/static-state";+import { vegaLoader } from "./plugins/impl/vega/loader";maybeRegisterVSCodeBindings();@@ -32,6 +35,12 @@ if (import.meta.env.DEV && import.meta.env.VITE_MSW) {});}+// If we're in static mode, we need to patch fetch to use the virtual file+if (isStaticNotebook()) {+ patchFetch();+ patchVegaLoader(vegaLoader);+}+// eslint-disable-next-line @typescript-eslint/no-non-null-assertion, ssr-friendly/no-dom-globals-in-module-scopeconst root = ReactDOM.createRoot(document.getElementById("root")!);diff --git a/frontend/src/utils/__tests__/blob.test.ts b/frontend/src/utils/__tests__/blob.test.tsnew file mode 100644index 0000000000..bb32b347b1--- /dev/null+++ b/frontend/src/utils/__tests__/blob.test.ts@@ -0,0 +1,52 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { beforeEach, expect, describe, test } from "vitest";+import { serializeBlob, deserializeBlob } from "../blob";++describe("Blob serialization and deserialization", () => {+ const testString = "Hello, world!";+ const mimeType = "text/plain";+ let testBlob: Blob;++ beforeEach(() => {+ testBlob = new Blob([testString], { type: mimeType });+ });++ test("serializeBlob should serialize a Blob to a base64 string", async () => {+ const serialized = await serializeBlob(testBlob);+ expect(serialized).toBeDefined();+ expect(serialized).toContain(`data:${mimeType};base64,`);+ });++ test("deserializeBlob should deserialize a base64 string to a Blob", async () => {+ const serialized = await serializeBlob(testBlob);+ const deserialized = await deserializeBlob(serialized);+ expect(deserialized).toBeDefined();+ expect(deserialized.size).toBe(testBlob.size);+ expect(deserialized.type).toBe(testBlob.type);+ });++ test("deserialized Blob should contain the original content", async () => {+ const serialized = await serializeBlob(testBlob);+ const deserialized = await deserializeBlob(serialized);+ const reader = new FileReader();+ // eslint-disable-next-line unicorn/prefer-blob-reading-methods+ reader.readAsText(deserialized);+ await new Promise((resolve) => {+ reader.onload = () => {+ expect(reader.result).toBe(testString);+ resolve(null);+ };+ });+ });++ test("image Blobs should be deserialized correctly", async () => {+ const imageBlob = new Blob([new Uint8Array([1, 2, 3])], {+ type: "image/png",+ });+ const serialized = await serializeBlob(imageBlob);+ const deserialized = await deserializeBlob(serialized);+ expect(deserialized).toBeDefined();+ expect(deserialized.size).toBe(imageBlob.size);+ expect(deserialized.type).toBe(imageBlob.type);+ });+});diff --git a/frontend/src/utils/blob.ts b/frontend/src/utils/blob.tsnew file mode 100644index 0000000000..eab6ee8064--- /dev/null+++ b/frontend/src/utils/blob.ts@@ -0,0 +1,36 @@+/* Copyright 2023 Marimo. All rights reserved. */+export function serializeBlob(blob: Blob): Promise<string> {+ return new Promise<string>((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = (event) => {+ resolve(event.target?.result as string);+ };+ reader.onerror = (error) => {+ reject(error);+ };+ reader.readAsDataURL(blob);+ });+}++export function deserializeBlob(serializedBlob: string): Promise<Blob> {+ return new Promise((resolve, reject) => {+ try {+ // Extract the base64 data from the data URL+ const [prefix, base64Data] = serializedBlob.split(",", 2);+ const mimeType = /^data:(.+);base64$/.exec(prefix)?.[1];+ // Decode the base64 string+ const binaryString = atob(base64Data);+ // Convert the binary string to an array buffer+ const len = binaryString.length;+ const bytes = new Uint8Array(len);+ for (let i = 0; i < len; i++) {+ bytes[i] = binaryString.charCodeAt(i);+ }+ // Create a new Blob from the array buffer+ const blob = new Blob([bytes], { type: mimeType });+ resolve(blob);+ } catch (error) {+ reject(error);+ }+ });+}diff --git a/frontend/src/utils/sets.ts b/frontend/src/utils/sets.tsnew file mode 100644index 0000000000..27fb4be2f2--- /dev/null+++ b/frontend/src/utils/sets.ts@@ -0,0 +1,12 @@+/* Copyright 2023 Marimo. All rights reserved. */+export const Sets = {+ merge<T>(...sets: Array<Set<T>>): Set<T> {+ const result = new Set<T>();+ for (const set of sets) {+ for (const item of set) {+ result.add(item);+ }+ }+ return result;+ },+};diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.tsindex a353a0911e..a983420173 100644--- a/frontend/vitest.config.ts+++ b/frontend/vitest.config.ts@@ -6,6 +6,7 @@ export default defineConfig({test: {environment: "jsdom",include: ["src/**/*.test.ts"],+ setupFiles: ["src/__tests__/setup.ts"],},plugins: [tsconfigPaths()],});