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
feat: self-contained WASM export bundles for offline use (#10879)
Péter Gyarmatieed9fb166887
diff --git a/docs/guides/publishing/self_host_wasm.md b/docs/guides/publishing/self_host_wasm.mdindex e8621a4caa..1a03171292 100644--- a/docs/guides/publishing/self_host_wasm.md+++ b/docs/guides/publishing/self_host_wasm.md@@ -8,3 +8,45 @@ exported [WebAssembly notebooks](../wasm.md):- Serve the assets in the `assets` directory, next to the HTML file.- Possibly configure your web server to support serving `application/wasm/`files with the correct headers.++## Exporting for offline use++Use `--offline` to download the Python runtime and notebook packages alongside+the exported HTML.++Offline export requires [Playwright for Python and its Chromium browser](https://playwright.dev/python/docs/library#installation).+Use the Python environment where marimo is installed for all three commands:++```bash+python -m pip install playwright+python -m playwright install chromium+python -m marimo export html-wasm notebook.py -o dist --offline+```++The export requires internet access. Playwright runs Pyodide to resolve+browser-compatible dependencies without executing notebook cells. The result+can be served from a local HTTP server or copied to a static host:++```text+dist/+├── index.html+├── assets/+├── pyodide/+├── lockfile/+└── packages/+```++The HTML uses relative URLs for the bundled runtime, lockfile, and package+index, so the directory can be moved to another host or URL prefix. The+`packages` directory includes transitive dependencies, packages inferred from+imports that are available in Pyodide, and dependencies declared in+[inline script metadata](../package_management/inlining_dependencies.md).+Declare PyPI dependencies in that metadata, including packages installed+dynamically by the notebook.++`--offline` bundles Python dependencies. Data files, remote API calls, and+JavaScript assets fetched by notebook code or widgets still need local+alternatives. Serve the export over HTTP even when using it offline.++Without `--offline`, the browser uses the default hosted Python runtime and+package sources.diff --git a/frontend/src/core/wasm/__tests__/bootstrap.test.ts b/frontend/src/core/wasm/__tests__/bootstrap.test.tsnew file mode 100644index 0000000000..bfac451c6d--- /dev/null+++ b/frontend/src/core/wasm/__tests__/bootstrap.test.ts@@ -0,0 +1,63 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { loadPyodide } from "pyodide";+import type { PyodideInterface } from "pyodide";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { DefaultWasmController } from "../worker/bootstrap";++vi.mock("pyodide", () => ({ loadPyodide: vi.fn() }));+vi.mock("../worker/getMarimoWheel", () => ({+ getMarimoWheel: () => "marimo-base",+}));++const micropip = { set_index_urls: vi.fn(), destroy: vi.fn() };+const pyodide = { pyimport: vi.fn(() => micropip) };++beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(loadPyodide).mockResolvedValue(+ pyodide as unknown as PyodideInterface,+ );+});++describe("WASM runtime sources", () => {+ it("preserves the default runtime sources", async () => {+ await new DefaultWasmController().bootstrap({+ version: "0.24.2",+ pyodideVersion: "v314.0.0",+ });+ expect(loadPyodide).toHaveBeenCalledWith(+ expect.objectContaining({+ indexURL: "https://cdn.jsdelivr.net/pyodide/v314.0.0/full/",+ packageBaseUrl: "https://cdn.jsdelivr.net/pyodide/v314.0.0/full/",+ lockFileURL:+ "https://wasm.marimo.app/pyodide-lock.json?v=0.24.2&pyodide=v314.0.0",+ }),+ );+ expect(pyodide.pyimport).not.toHaveBeenCalled();+ });++ it("configures runtime and package sources before returning the interpreter", async () => {+ const controller = new DefaultWasmController();+ await controller.bootstrap({+ version: "0.24.2",+ pyodideVersion: "v314.0.0",+ pyodideIndexUrl: "https://example.com/runtime/",+ pyodideLockfileUrl: "https://example.com/lock.json",+ pypiIndexUrl: "https://example.com/pypi/{package_name}/json",+ });+ expect(loadPyodide).toHaveBeenCalledWith(+ expect.objectContaining({+ indexURL: "https://example.com/runtime/",+ packageBaseUrl: "https://example.com/runtime/",+ lockFileURL: "https://example.com/lock.json",+ }),+ );+ expect(pyodide.pyimport).toHaveBeenCalledWith("micropip");+ expect(micropip.set_index_urls).toHaveBeenCalledWith(+ "https://example.com/pypi/{package_name}/json",+ );+ expect(micropip.destroy).toHaveBeenCalledOnce();+ expect(controller.requirePyodide).toBe(pyodide);+ });+});diff --git a/frontend/src/core/wasm/__tests__/bridge.test.ts b/frontend/src/core/wasm/__tests__/bridge.test.tsindex a564a2594b..9a0c4769e1 100644--- a/frontend/src/core/wasm/__tests__/bridge.test.ts+++ b/frontend/src/core/wasm/__tests__/bridge.test.ts@@ -9,12 +9,14 @@ const {mockNotebookReadFile,mockReadNotebook,mockSaveNotebook,+ mockBootstrap,rpcListeners,} = vi.hoisted(() => ({mockBridge: vi.fn(),mockNotebookReadFile: vi.fn(),mockReadNotebook: vi.fn(),mockSaveNotebook: vi.fn(),+ mockBootstrap: vi.fn(),rpcListeners: {} as Record<string, () => void>,}));@@ -40,6 +42,7 @@ vi.stubGlobal("URL", MockURL);vi.mock("@/core/wasm/rpc", () => ({getWorkerRPC: () => ({+ send: { bootstrap: mockBootstrap },proxy: {request: {bridge: mockBridge,@@ -122,6 +125,11 @@ describe("PyodideBridge.readCode", () => {await PyodideBridge.INSTANCE.readCode();+ expect(mockBootstrap).toHaveBeenCalledWith({+ pyodideIndexUrl: undefined,+ pyodideLockfileUrl: undefined,+ pypiIndexUrl: undefined,+ });expect(mockNotebookReadFile).not.toHaveBeenCalled();});});diff --git a/frontend/src/core/wasm/__tests__/runtime-config.test.ts b/frontend/src/core/wasm/__tests__/runtime-config.test.tsnew file mode 100644index 0000000000..58aa3ab841--- /dev/null+++ b/frontend/src/core/wasm/__tests__/runtime-config.test.ts@@ -0,0 +1,58 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { afterEach, assert, describe, expect, it } from "vitest";+import { getWasmRuntimeConfig } from "../runtime-config";++afterEach(() => {+ document.head.innerHTML = "";+});++describe("getWasmRuntimeConfig", () => {+ it("uses runtime defaults when no URLs are configured", () => {+ expect(getWasmRuntimeConfig()).toEqual({+ pyodideIndexUrl: undefined,+ pyodideLockfileUrl: undefined,+ pypiIndexUrl: undefined,+ });+ });++ it("resolves URLs against the page base and preserves micropip placeholders", () => {+ document.head.innerHTML = `+ <base href="https://example.com/blog/post/">+ <marimo-wasm+ data-pyodide-index-url="../runtime/"+ data-pyodide-lockfile-url="/locks/pyodide.json?v=1&x=2"+ data-pypi-index-url="https://packages.example.com/{package_name}/json"+ ></marimo-wasm>`;+ expect(getWasmRuntimeConfig()).toEqual({+ pyodideIndexUrl: "https://example.com/blog/runtime/",+ pyodideLockfileUrl: "https://example.com/locks/pyodide.json?v=1&x=2",+ pypiIndexUrl: "https://packages.example.com/{package_name}/json",+ });+ });++ it.each(["pyodideIndexUrl", "pyodideLockfileUrl", "pypiIndexUrl"])(+ "ignores malformed %s while preserving valid overrides",+ (key) => {+ document.head.innerHTML = `+ <base href="https://example.com/notebook/">+ <marimo-wasm+ data-pyodide-index-url="./pyodide/"+ data-pyodide-lockfile-url="./lockfile/pyodide.json"+ data-pypi-index-url="./packages/{package_name}.json"+ ></marimo-wasm>`;+ const element = document.querySelector<HTMLElement>("marimo-wasm");+ assert(element);+ element.dataset[key] = "https://invalid host/";++ expect(getWasmRuntimeConfig()).toEqual({+ pyodideIndexUrl: "https://example.com/notebook/pyodide/",+ pyodideLockfileUrl:+ "https://example.com/notebook/lockfile/pyodide.json",+ pypiIndexUrl:+ "https://example.com/notebook/packages/{package_name}.json",+ [key]: undefined,+ });+ },+ );+});diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.tsindex 80fb961adc..edfc4c0003 100644--- a/frontend/src/core/wasm/bridge.ts+++ b/frontend/src/core/wasm/bridge.ts@@ -42,6 +42,7 @@ import { BasicTransport } from "../websocket/transports/basic";import type { IConnectionTransport } from "../websocket/transports/transport";import { PyodideRouter } from "./router";import { getWorkerRPC } from "./rpc";+import { getWasmRuntimeConfig } from "./runtime-config";import { createShareableLink } from "./share";import { wasmInitStateAtom } from "./state";import { fallbackFileStore, notebookFileStore } from "./store";@@ -84,6 +85,8 @@ export class PyodideBridge implements RunRequests, EditRequests {};}+ const runtimeConfig = getWasmRuntimeConfig();+// Create save workerconst saveWorker = createModuleWorker(new URL(saveWorkerUrl, import.meta.url),@@ -93,7 +96,9 @@ export class PyodideBridge implements RunRequests, EditRequests {},);- return getWorkerRPC<SaveWorkerSchema>(saveWorker).proxy.request;+ const rpc = getWorkerRPC<SaveWorkerSchema>(saveWorker);+ rpc.send.bootstrap(runtimeConfig);+ return rpc.proxy.request;}private constructor() {@@ -101,6 +106,8 @@ export class PyodideBridge implements RunRequests, EditRequests {return;}+ const runtimeConfig = getWasmRuntimeConfig();+// Create a workerconst worker = createModuleWorker(new URL(workerUrl, import.meta.url), {// Pass the version (and optional capability suffix) to the worker@@ -109,6 +116,7 @@ export class PyodideBridge implements RunRequests, EditRequests {// Create the RPCthis.rpc = getWorkerRPC<WorkerSchema>(worker);+ this.rpc.send.bootstrap(runtimeConfig);// Listenersthis.rpc.addMessageListener("ready", () => {diff --git a/frontend/src/core/wasm/rpc.ts b/frontend/src/core/wasm/rpc.tsindex 9a37e6325d..924cad17ff 100644--- a/frontend/src/core/wasm/rpc.ts+++ b/frontend/src/core/wasm/rpc.ts@@ -6,11 +6,13 @@ import {type RPCSchema,} from "rpc-anywhere";import { Logger } from "@/utils/Logger";+import type { WasmRuntimeConfig } from "./runtime-config";import { TRANSPORT_ID } from "./worker/constants";export type ParentSchema = RPCSchema<{messages: {consumerReady: {};+ bootstrap: WasmRuntimeConfig;};}>;diff --git a/frontend/src/core/wasm/runtime-config.ts b/frontend/src/core/wasm/runtime-config.tsnew file mode 100644index 0000000000..7461a19818--- /dev/null+++ b/frontend/src/core/wasm/runtime-config.ts@@ -0,0 +1,27 @@+/* Copyright 2026 Marimo. All rights reserved. */++export interface WasmRuntimeConfig {+ pyodideIndexUrl?: string;+ pyodideLockfileUrl?: string;+ pypiIndexUrl?: string;+}++export function getWasmRuntimeConfig(): WasmRuntimeConfig {+ const element = document.querySelector<HTMLElement>("marimo-wasm");+ const resolve = (url: string | undefined) => {+ try {+ return url ? new URL(url, document.baseURI).href : undefined;+ } catch {+ return undefined;+ }+ };+ return {+ pyodideIndexUrl: resolve(element?.dataset.pyodideIndexUrl),+ pyodideLockfileUrl: resolve(element?.dataset.pyodideLockfileUrl),+ // URL serialization escapes the placeholder understood by micropip.+ pypiIndexUrl: resolve(element?.dataset.pypiIndexUrl)?.replaceAll(+ "%7Bpackage_name%7D",+ "{package_name}",+ ),+ };+}diff --git a/frontend/src/core/wasm/worker/bootstrap.ts b/frontend/src/core/wasm/worker/bootstrap.tsindex 91ae31d88e..d4e9cd4a63 100644--- a/frontend/src/core/wasm/worker/bootstrap.ts+++ b/frontend/src/core/wasm/worker/bootstrap.ts@@ -41,10 +41,9 @@ export class DefaultWasmController implements WasmController {return this.pyodide;}- async bootstrap(opts: {- version: string;- pyodideVersion: string;- }): Promise<PyodideInterface> {+ async bootstrap(+ opts: Parameters<WasmController["bootstrap"]>[0],+ ): Promise<PyodideInterface> {const pyodide = await this.loadPyodideAndPackages(opts);if (MAKE_SNAPSHOT) {@@ -55,10 +54,9 @@ export class DefaultWasmController implements WasmController {return pyodide;}- private async loadPyodideAndPackages(opts: {- version: string;- pyodideVersion: string;- }): Promise<PyodideInterface> {+ private async loadPyodideAndPackages(+ opts: Parameters<WasmController["bootstrap"]>[0],+ ): Promise<PyodideInterface> {if (!loadPyodide) {throw new Error("loadPyodide is not defined");}@@ -68,7 +66,9 @@ export class DefaultWasmController implements WasmController {// Without this, this fails in Firefox with// `Could not extract indexURL path from pyodide module`// This fixes for Firefox and does not break Chrome/others- const indexURL = `https://cdn.jsdelivr.net/pyodide/${opts.pyodideVersion}/full/`;+ const indexURL =+ opts.pyodideIndexUrl ??+ `https://cdn.jsdelivr.net/pyodide/${opts.pyodideVersion}/full/`;const pyodide = await loadPyodide({// Perf: These get loaded while pyodide is being bootstrappedpackages: [@@ -81,16 +81,26 @@ export class DefaultWasmController implements WasmController {"packaging",],_makeSnapshot: MAKE_SNAPSHOT,- lockFileURL: `https://wasm.marimo.app/pyodide-lock.json?v=${opts.version}&pyodide=${opts.pyodideVersion}`,+ lockFileURL:+ opts.pyodideLockfileUrl ??+ `https://wasm.marimo.app/pyodide-lock.json?v=${opts.version}&pyodide=${opts.pyodideVersion}`,indexURL,// Since Pyodide 0.28.0, when lockFileURL is set, the package base URL// defaults to the lockfile's URL (wasm.marimo.app) instead of indexURL.// Unlike Node, browsers get no CDN fallback on a failed fetch, so we- // should pin packageBaseUrl back to the jsDelivr CDN to restore+ // should pin packageBaseUrl to indexURL to restore// the resolution akin to pre-0.28.packageBaseUrl: indexURL,convertNullToNone: true,});+ if (opts.pypiIndexUrl) {+ const micropip = pyodide.pyimport("micropip");+ try {+ micropip.set_index_urls(opts.pypiIndexUrl);+ } finally {+ micropip.destroy();+ }+ }this.pyodide = pyodide;span.end("ok");return pyodide;diff --git a/frontend/src/core/wasm/worker/save-worker.ts b/frontend/src/core/wasm/worker/save-worker.tsindex b211d7bd18..51325d6ce3 100644--- a/frontend/src/core/wasm/worker/save-worker.ts+++ b/frontend/src/core/wasm/worker/save-worker.ts@@ -9,9 +9,11 @@ import {} from "rpc-anywhere";import type { SaveNotebookRequest } from "@/core/network/types";import { decodeUtf8 } from "@/utils/strings";+import { Deferred } from "../../../utils/Deferred";import { prettyError } from "../../../utils/errors";import { Logger } from "../../../utils/Logger";import type { ParentSchema } from "../rpc";+import type { WasmRuntimeConfig } from "../runtime-config";import { TRANSPORT_ID } from "./constants";import { WasmFileSystem } from "./fs";import { getController } from "./getController";@@ -25,6 +27,8 @@ declare const self: Window & {pyodide: PyodideInterface;};+const runtimeConfig = new Deferred<WasmRuntimeConfig>();+// Initializeasync function loadPyodideAndPackages() {try {@@ -36,6 +40,7 @@ async function loadPyodideAndPackages() {const controller = await getController(marimoVersion);self.controller = controller;self.pyodide = await controller.bootstrap({+ ...(await runtimeConfig.promise),version: marimoVersion,pyodideVersion: pyodideVersion,});@@ -100,6 +105,8 @@ const rpc = createRPC<SaveWorkerSchema, ParentSchema>({requestHandler,});+rpc.addMessageListener("bootstrap", (config) => runtimeConfig.resolve(config));+rpc.send("ready", {});function getMarimoVersion() {diff --git a/frontend/src/core/wasm/worker/types.ts b/frontend/src/core/wasm/worker/types.tsindex c74d4e3f60..ded1150afc 100644--- a/frontend/src/core/wasm/worker/types.ts+++ b/frontend/src/core/wasm/worker/types.ts@@ -1,5 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */import type { PyodideInterface } from "pyodide";+import type { WasmRuntimeConfig } from "../runtime-config";import type { UserConfig } from "@/core/config/config-schema";import type {CommandMessage,@@ -43,10 +44,12 @@ export interface WasmController {* Prepare the wasm environment* @param opts.version - The marimo version*/- bootstrap(opts: {- version: string;- pyodideVersion: string;- }): Promise<PyodideInterface>;+ bootstrap(+ opts: WasmRuntimeConfig & {+ version: string;+ pyodideVersion: string;+ },+ ): Promise<PyodideInterface>;/*** Mount the filesystem* @param opts.code - The code to mountdiff --git a/frontend/src/core/wasm/worker/worker.ts b/frontend/src/core/wasm/worker/worker.tsindex c2fb6f24e0..d3c0c2b161 100644--- a/frontend/src/core/wasm/worker/worker.ts+++ b/frontend/src/core/wasm/worker/worker.ts@@ -22,6 +22,7 @@ import { prettyError } from "../../../utils/errors";import { invariant } from "../../../utils/invariant";import { Logger } from "../../../utils/Logger";import type { ParentSchema } from "../rpc";+import type { WasmRuntimeConfig } from "../runtime-config";import { TRANSPORT_ID } from "./constants";import { WasmFileSystem } from "./fs";import { getController } from "./getController";@@ -47,6 +48,8 @@ declare const self: Window & {const workerInitSpan = t.startSpan("worker:init");+const runtimeConfig = new Deferred<WasmRuntimeConfig>();+// Initialize pyodideasync function loadPyodideAndPackages() {try {@@ -58,6 +61,7 @@ async function loadPyodideAndPackages() {message: "Loading marimo...",});self.pyodide = await t.wrapAsync(controller.bootstrap.bind(controller))({+ ...(await runtimeConfig.promise),version: marimoVersion,pyodideVersion: pyodideVersion,});@@ -354,6 +358,8 @@ const rpc = createRPC<WorkerSchema, ParentSchema>({requestHandler,});+rpc.addMessageListener("bootstrap", (config) => runtimeConfig.resolve(config));+rpc.send("ready", {});/// Listenersdiff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex 8e96997082..befca4a502 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -55,6 +55,10 @@ from marimo._export.local_wheels import (wheel_dependency_names,with_wheel_dependencies,)+from marimo._export.offline import (+ OfflineExportError,+ check_offline_export_browser,+)from marimo._export.requests import (ExportResult,HTMLFileExportRequest,@@ -90,7 +94,10 @@ if TYPE_CHECKING:class _ExportWithCodeTransform(Protocol):def __call__(- self, *, code_transform: Callable[[str], str]+ self,+ *,+ code_transform: Callable[[str], str],+ local_wheel_paths: tuple[Path, ...],) -> ExportResult: ...@@ -898,9 +905,9 @@ Example:marimo export html-wasm notebook.py -o notebook.wasm.htmlThe exported HTML file runs the notebook using WebAssembly, without a local-Python or marimo installation. This lets you-share interactive notebooks on the web without setting up-infrastructure to run Python code.+Python or marimo installation. This lets you share interactive notebooks on+the web without setting up infrastructure to run Python code. By default, the+browser downloads the Python runtime and packages from hosted sources.The exported notebook runs using Pyodide, which supports mostbut not all Python packages. To learn more, see the Pyodide@@ -973,6 +980,11 @@ assets from a CDN and open the HTML file directly. Internet access is required."packages when possible."),)+ "--offline",+ is_flag=True,+ help="Download the Python runtime and notebook packages into the export directory.",+)@click.argument("name",required=True,@@ -990,9 +1002,14 @@ def html_wasm(sandbox: bool | None,force: bool,execute: bool,+ offline: bool,args: tuple[str, ...],) -> None:"""Export a notebook as a WASM-powered standalone HTML file."""+ if single_file and offline:+ raise click.UsageError(+ "--single-file and --offline cannot be used together."+ )if single_file and include_cloudflare:raise click.UsageError("--single-file and --include-cloudflare cannot be used together."@@ -1015,6 +1032,7 @@ def html_wasm(run_in_sandbox(sys.argv[1:],name=name,+ command_deps=["playwright"] if offline else None,pyodide_constraints=True,python_version_override=PYODIDE_PYTHON_VERSION,extra_env={_BOOTSTRAPPED_ENV: "1"},@@ -1036,7 +1054,30 @@ def html_wasm(sandbox = maybe_prompt_run_in_sandbox(name)if sandbox:- sys.exit(run_in_sandbox(sys.argv[1:], name=name))+ sys.exit(+ run_in_sandbox(+ sys.argv[1:],+ name=name,+ command_deps=["playwright"] if offline else None,+ )+ )++ if offline:+ if not DependencyManager.playwright.has():+ raise MarimoCLIMissingDependencyError(+ "Playwright is required to resolve packages for offline WASM export.",+ "playwright",+ followup_commands=get_playwright_chromium_setup_commands(),+ )+ try:+ asyncio_run(check_offline_export_browser())+ except Exception as error:+ setup_command = get_playwright_chromium_setup_commands()[0]+ raise click.ClickException(+ "Chromium could not start for offline WASM export.\n"+ f"Install the browser with: {setup_command}\n\n{error}"+ ) from error+ echo("Downloading the Python runtime and notebook packages...")out_dir = outputfilename = "index.html"@@ -1082,25 +1123,28 @@ def html_wasm(*metadata_wheels,*auto_wheel_dependencies(local_wheels),)+ wheel_paths = tuple(+ dependency.path for dependency in wheel_dependencies+ )result = export_callback(code_transform=partial(with_wheel_dependencies,wheel_dependencies=wheel_dependencies,- )+ ),+ local_wheel_paths=wheel_paths,)if not single_file:copy_local_wheels(out_dir,- tuple(- dependency.path- for dependency in wheel_dependencies- ),+ wheel_paths,source_wheel_dir=file_path.path.parent/ WASM_WHEEL_DIR,)return resultexcept LocalWheelError as error:raise click.UsageError(str(error)) from error+ except OfflineExportError as error:+ raise click.ClickException(str(error)) from errorwasm_options = WASMExportOptions(mode=mode,@@ -1125,12 +1169,15 @@ def html_wasm(file_path: MarimoPath,*,code_transform: Callable[[str], str],+ local_wheel_paths: tuple[Path, ...],) -> ExportResult:return asyncio_run(export_wasm(WASMFileExportRequest(path=file_path,options=wasm_options,+ offline_export_dir=out_dir if offline else None,+ local_wheel_paths=local_wheel_paths,execution=NotebookExecutionOptions(cli_args=cli_args,argv=list(args),@@ -1156,12 +1203,15 @@ def html_wasm(file_path: MarimoPath,*,code_transform: Callable[[str], str],+ local_wheel_paths: tuple[Path, ...],) -> ExportResult:return asyncio_run(export_wasm(WASMFileExportRequest(path=file_path,options=wasm_options,+ offline_export_dir=out_dir if offline else None,+ local_wheel_paths=local_wheel_paths,code_transform=code_transform,stdout=STDOUT,)diff --git a/marimo/_export/exporter.py b/marimo/_export/exporter.pyindex 6a9a9e55d5..773090e6b8 100644--- a/marimo/_export/exporter.py+++ b/marimo/_export/exporter.py@@ -538,6 +538,9 @@ class Exporter:code=request.code,asset_url=request.options.asset_url,show_code=request.options.show_code,+ pyodide_index_url=request.options.runtime.pyodide_index_url,+ pyodide_lockfile_url=request.options.runtime.pyodide_lockfile_url,+ pypi_index_url=request.options.runtime.pypi_index_url,layout=request.layout,session_snapshot=request.session_snapshot,notebook_snapshot=request.notebook_snapshot,diff --git a/marimo/_export/file.py b/marimo/_export/file.pyindex 18ce6ec5fc..4300da02df 100644--- a/marimo/_export/file.py+++ b/marimo/_export/file.py@@ -63,6 +63,7 @@ from marimo._runtime.layout.layout import (from marimo._runtime.patches import extract_docstring_from_headerfrom marimo._schemas.export_options import (IPYNBExportOptions,+ WASMExportOptions,)from marimo._schemas.serialization import NotebookSerializationfrom marimo._session.model import ConnectionState, SessionMode@@ -202,6 +203,33 @@ async def export_ipynb()+async def _prepare_wasm_export(+ code: str, request: WASMFileExportRequest+) -> tuple[str, WASMExportOptions]:+ if request.code_transform is not None:+ code = request.code_transform(code)+ options = request.options+ if request.offline_export_dir is not None:+ from marimo._export.offline import (+ OfflineExportError,+ bundle_wasm_runtime,+ )++ try:+ code, runtime = await bundle_wasm_runtime(+ code,+ request.offline_export_dir,+ sources=options.runtime,+ local_wheel_paths=request.local_wheel_paths,+ )+ except Exception as error:+ raise OfflineExportError(+ f"Offline export failed: {error}"+ ) from error+ options = replace(options, runtime=runtime)+ return code, options++async def export_wasm(request: WASMFileExportRequest,) -> ExportResult:@@ -223,8 +251,7 @@ async def export_wasm(resolved = config.get_config()code = app.to_py()- if request.code_transform is not None:- code = request.code_transform(code)+ code, options = await _prepare_wasm_export(code, request)result = Exporter().export_as_wasm(WASMExportRequest(@@ -232,7 +259,7 @@ async def export_wasm(app_config=app.config,display_config=resolved["display"],code=code,- options=request.options,+ options=options,layout=layout,sharing_config=resolved.get("sharing"),)@@ -521,8 +548,7 @@ async def _export_wasm_with_execution(code = pin_pep723_dependencies_for_wasm(file_manager.app.to_py(), request.path)- if request.code_transform is not None:- code = request.code_transform(code)+ code, options = await _prepare_wasm_export(code, request)html, filename = Exporter().export_as_wasm(WASMExportRequest(@@ -530,7 +556,7 @@ async def _export_wasm_with_execution(app_config=file_manager.app.config,display_config=display_config,code=code,- options=request.options,+ options=options,layout=layout,session_snapshot=snapshot.session,notebook_snapshot=snapshot.notebook,diff --git a/marimo/_export/offline.py b/marimo/_export/offline.pynew file mode 100644index 0000000000..ab9f40a617--- /dev/null+++ b/marimo/_export/offline.py@@ -0,0 +1,319 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+import hashlib+import html+import json+import shutil+import tempfile+from concurrent.futures import ThreadPoolExecutor+from contextlib import suppress+from pathlib import Path+from typing import TypedDict+from urllib.parse import quote, unquote, urljoin, urlparse++from marimo._environments import script_metadata+from marimo._export._html_asset_server import HtmlAssetServer+from marimo._pyodide.pyodide_constraints import PYODIDE_VERSION+from marimo._schemas.export_options import WASMRuntimeConfig+from marimo._utils import requests+from marimo._utils.inline_script_metadata import PyProjectReader+from marimo._version import __version__+++class OfflineExportError(RuntimeError):+ """The runtime or package bundle could not be prepared."""+++class _Package(TypedDict):+ name: str+ version: str+ file_name: str+ sha256: str | None+ depends: list[str]+++class _Lockfile(TypedDict):+ info: dict[str, str]+ packages: dict[str, _Package]+++_RESOLVE_PACKAGES = r"""async ({ indexURL, packageBaseUrl, lockfile, pypiIndexUrl, code, requirements }) => {+ const { loadPyodide } = await import(indexURL + "pyodide.mjs");+ const pyodide = await loadPyodide({ indexURL, packageBaseUrl, lockFileContents: lockfile });+ const errors = [];+ const callbacks = { errorCallback: message => errors.push(message) };+ await pyodide.loadPackage(+ ["micropip", "marimo-base", "docutils", "pygments", "jedi", "pyodide-http", "black"],+ callbacks,+ );+ if (errors.length) throw new Error(errors.join("\n"));+ pyodide.globals.set("requirements_json", JSON.stringify(requirements));+ pyodide.globals.set("index_url", pypiIndexUrl);+ pyodide.globals.set("base_url", location.href);+ await pyodide.runPythonAsync(`+import json+import micropip+from packaging.requirements import Requirement+from packaging.utils import canonicalize_name+from urllib.parse import urljoin++if index_url:+ micropip.set_index_urls(index_url)+requirements = []+requirement_names = []+for value in json.loads(requirements_json):+ requirement = Requirement(value)+ if requirement.marker and not requirement.marker.evaluate():+ continue+ if canonicalize_name(requirement.name) == "marimo":+ requirement.name = "marimo-base"+ if requirement.url:+ requirement.url = urljoin(base_url, requirement.url)+ requirements.append(str(requirement))+ requirement_names.append(canonicalize_name(requirement.name))+await micropip.install(requirements)+`);+ // Keep the same SQL dependency policy as shouldLoadDuckDBPackages.+ const usesDuckDB = /(^|\n)\s*(?:import\s+[^\n#]*\bduckdb\b|from\s+duckdb\b|[^\n#]*\bduckdb\s*\.)/.test(code);+ if (code.includes("mo.sql") || usesDuckDB || pyodide.runPython('"duckdb" in requirement_names')) {+ code += "\nimport duckdb, pandas, sqlglot";+ if (code.includes("polars")) code += "\nimport pyarrow";+ }+ await pyodide.loadPackagesFromImports(code, callbacks);+ if (errors.length) throw new Error(errors.join("\n"));+ const frozen = JSON.parse(pyodide.runPython("micropip.freeze()"));+ const loaded = new Set([...Object.keys(pyodide.loadedPackages), "marimo-base"].map(name => name.toLowerCase().replace(/[-_.]+/g, "-")));+ frozen.packages = Object.fromEntries(Object.entries(frozen.packages).filter(([name]) => loaded.has(name)));+ return frozen;+}"""+++def _download(url: str, target: Path, sha256: str | None = None) -> str:+ data = requests.get(url, timeout=60).raise_for_status().content+ digest = hashlib.sha256(data).hexdigest()+ if sha256 and digest != sha256:+ raise ValueError(f"Checksum mismatch for {url}")+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(data)+ return digest+++def _download_files(+ files: dict[Path, tuple[str, str | None]],+) -> dict[Path, str]:+ with ThreadPoolExecutor(max_workers=8) as pool:+ pending = {+ target: pool.submit(_download, url, target, checksum)+ for target, (url, checksum) in files.items()+ }+ return {target: future.result() for target, future in pending.items()}+++async def _download_all(+ files: dict[Path, tuple[str, str | None]],+) -> dict[Path, str]:+ task = asyncio.create_task(asyncio.to_thread(_download_files, files))+ try:+ return await asyncio.shield(task)+ except asyncio.CancelledError:+ # Threads cannot be cancelled. Join them before staging is cleaned up.+ with suppress(Exception):+ await asyncio.shield(task)+ raise+++def _rewrite_requirements(code: str, packages: dict[str, _Package]) -> str:+ from packaging.requirements import Requirement+ from packaging.specifiers import SpecifierSet+ from packaging.utils import canonicalize_name++ project = script_metadata.loads(code)+ if project is None:+ return code+ dependencies = []+ for value in project.get("dependencies", []):+ requirement = Requirement(str(value))+ name = canonicalize_name(requirement.name)+ requirement.name = name+ if requirement.url and name in packages:+ requirement.url = None+ requirement.specifier = SpecifierSet(+ f"=={packages[name]['version']}"+ )+ dependencies.append(str(requirement))+ project["dependencies"] = dependencies+ return script_metadata.replace_block(code, script_metadata.dumps(project))+++async def check_offline_export_browser() -> None:+ """Verify the resolver's browser can start before downloading assets."""+ from playwright.async_api import async_playwright # type: ignore[import-not-found]++ async with async_playwright() as playwright:+ browser = await playwright.chromium.launch()+ await browser.close()+++async def _resolve_packages(+ code: str,+ *,+ page_url: str,+ index_url: str,+ package_base_url: str,+ lockfile: _Lockfile,+ pypi_index_url: str | None,+) -> _Lockfile:+ from playwright.async_api import async_playwright # type: ignore[import-not-found]++ async with async_playwright() as playwright:+ browser = await playwright.chromium.launch()+ try:+ page = await browser.new_page()+ await page.goto(page_url)+ return await asyncio.wait_for(+ page.evaluate(+ _RESOLVE_PACKAGES,+ {+ "indexURL": index_url,+ "packageBaseUrl": package_base_url,+ "lockfile": lockfile,+ "pypiIndexUrl": pypi_index_url,+ "code": code,+ "requirements": PyProjectReader.from_script(+ code+ ).dependencies,+ },+ ),+ timeout=300,+ )+ finally:+ await browser.close()+++def _publish_bundle(+ staging: Path,+ output_dir: Path,+ resolved: _Lockfile,+ hashes: dict[Path, str],+) -> str:+ from packaging.requirements import Requirement+ from packaging.utils import canonicalize_name++ for name, package in resolved["packages"].items():+ name = canonicalize_name(Requirement(name).name)+ filename = package["file_name"]+ source = staging / "downloads" / filename+ digest = hashes[source]+ relative = f"{digest}/{filename}"+ target = staging / "packages" / relative+ target.parent.mkdir(parents=True, exist_ok=True)+ if source.exists():+ source.replace(target)+ package["sha256"] = digest+ package["file_name"] = f"../packages/{relative}"+ index = staging / "packages" / "index" / name / "index.html"+ index.parent.mkdir(parents=True, exist_ok=True)+ index.write_text(+ f'<!doctype html><a href="../../{quote(relative)}">{html.escape(filename)}</a>',+ encoding="utf-8",+ )+ # Existing exports keep the exact dependency set they were built with.+ lock_contents = json.dumps(resolved, sort_keys=True)+ lock_name = (+ hashlib.sha256(lock_contents.encode()).hexdigest()[:16] + ".json"+ )+ (staging / "lockfile").mkdir()+ (staging / "lockfile" / lock_name).write_text(+ lock_contents, encoding="utf-8"+ )+ # Publish the lockfile after its files, replacing individual files atomically.+ for directory in ("pyodide", "packages", "lockfile"):+ for source in (staging / directory).rglob("*"):+ if source.is_file():+ target = output_dir / source.relative_to(staging)+ target.parent.mkdir(parents=True, exist_ok=True)+ source.replace(target)+ return lock_name+++async def bundle_wasm_runtime(+ code: str,+ output_dir: Path,+ *,+ sources: WASMRuntimeConfig,+ local_wheel_paths: tuple[Path, ...] = (),+) -> tuple[str, WASMRuntimeConfig]:+ """Resolve packages in Pyodide and vendor them without executing cells."""+ index_url = sources.pyodide_index_url or (+ f"https://cdn.jsdelivr.net/pyodide/v{PYODIDE_VERSION}/full/"+ )+ index_url = index_url.rstrip("/") + "/"+ lockfile_url = sources.pyodide_lockfile_url or (+ f"https://wasm.marimo.app/pyodide-lock.json?v={__version__}"+ f"&pyodide=v{PYODIDE_VERSION}"+ )+ lockfile = await asyncio.to_thread(+ lambda: (+ requests.get(lockfile_url, timeout=60).raise_for_status().json()+ )+ )+ await asyncio.to_thread(output_dir.mkdir, parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(+ prefix=".marimo-offline-", dir=output_dir+ ) as tmp:+ staging = Path(tmp)+ for wheel in local_wheel_paths:+ target = staging / "public" / "wheels" / wheel.name+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(wheel, target)+ await _download_all(+ {+ staging / "pyodide" / name: (urljoin(index_url, name), None)+ for name in (+ "pyodide.mjs",+ "pyodide.asm.mjs",+ "pyodide.asm.wasm",+ "python_stdlib.zip",+ )+ }+ )+ # Match the browser workers' base so existing ../public/wheels URLs resolve.+ with HtmlAssetServer(+ directory=staging, route="/assets/offline.html"+ ) as server:+ server.set_html(+ "<!doctype html><title>Resolve notebook packages</title>"+ )+ resolved = await _resolve_packages(+ code,+ page_url=server.page_url,+ index_url=f"{server.base_url}/pyodide/",+ package_base_url=index_url,+ lockfile=lockfile,+ pypi_index_url=sources.pypi_index_url,+ )+ downloads: dict[Path, tuple[str, str | None]] = {}+ for package in resolved["packages"].values():+ url = urljoin(index_url, package["file_name"])+ filename = unquote(urlparse(url).path.rsplit("/", 1)[-1])+ if not filename or Path(filename).name != filename:+ raise ValueError(f"Invalid package filename: {url}")+ target = staging / "downloads" / filename+ source = (url, package["sha256"])+ if target in downloads and downloads[target] != source:+ raise ValueError(+ f"Conflicting package filename: {filename}"+ )+ downloads[target] = source+ package["file_name"] = filename+ hashes = await _download_all(downloads)+ lock_name = _publish_bundle(staging, output_dir, resolved, hashes)+ return _rewrite_requirements(+ code, resolved["packages"]+ ), WASMRuntimeConfig(+ pyodide_index_url="./pyodide/",+ pyodide_lockfile_url=f"./lockfile/{lock_name}",+ pypi_index_url="./packages/index/",+ )diff --git a/marimo/_export/requests.py b/marimo/_export/requests.pyindex f71a040e59..3ab2728754 100644--- a/marimo/_export/requests.py+++ b/marimo/_export/requests.py@@ -159,6 +159,8 @@ class WASMFileExportRequest:options: WASMExportOptionsexecution: NotebookExecutionOptions | None = Nonecache_export_dir: Path | None = None+ offline_export_dir: Path | None = None+ local_wheel_paths: tuple[Path, ...] = ()code_transform: Callable[[str], str] | None = Nonestdout: TextWriter | None = Nonediff --git a/marimo/_schemas/export_options.py b/marimo/_schemas/export_options.pyindex 9385c726d0..4c04646cf5 100644--- a/marimo/_schemas/export_options.py+++ b/marimo/_schemas/export_options.py@@ -1,7 +1,7 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import Literal, get_argsfrom marimo._convert.markdown.flavor.base import MarkdownFlavorName@@ -41,11 +41,19 @@ class MarkdownExportOptions:source_filename: str | None = None+@dataclass(frozen=True, kw_only=True)+class WASMRuntimeConfig:+ pyodide_index_url: str | None = None+ pyodide_lockfile_url: str | None = None+ pypi_index_url: str | None = None++@dataclass(frozen=True, kw_only=True)class WASMExportOptions:mode: WASMModeshow_code: boolasset_url: str | None = None+ runtime: WASMRuntimeConfig = field(default_factory=WASMRuntimeConfig)@dataclass(frozen=True, kw_only=True)diff --git a/marimo/_templates.py b/marimo/_templates.pyindex d85774b280..b2239f8c5c 100644--- a/marimo/_templates.py+++ b/marimo/_templates.py@@ -537,6 +537,9 @@ def wasm_notebook_template(mode: Literal["edit", "run"],code: str,show_code: bool,+ pyodide_index_url: str | None = None,+ pyodide_lockfile_url: str | None = None,+ pypi_index_url: str | None = None,layout: LayoutConfig | None = None,asset_url: str | None = None,session_snapshot: NotebookSessionV1 | None = None,@@ -575,8 +578,18 @@ def wasm_notebook_template(),)+ wasm_attributes = "".join(+ f' {name}="{_html_escape(value)}"'+ for name, value in (+ ("data-pyodide-index-url", pyodide_index_url),+ ("data-pyodide-lockfile-url", pyodide_lockfile_url),+ ("data-pypi-index-url", pypi_index_url),+ )+ if value is not None+ )body = body.replace(- "</head>", '<marimo-wasm hidden=""></marimo-wasm></head>'+ "</head>",+ f'<marimo-wasm hidden=""{wasm_attributes}></marimo-wasm></head>',)warning_script = """diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex 291d25dfe0..63f15c8526 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -286,6 +286,124 @@ class TestExportHTML:assert mount_config["mode"] == ("edit" if mode == "edit" else "read")assert mount_config["layout"] == {"type": "slides", "data": {}}+ @staticmethod+ def test_cli_export_html_wasm_offline(tmp_path: Path) -> None:+ from marimo._schemas.export_options import WASMRuntimeConfig++ notebook = tmp_path / "notebook.py"+ _write_minimal_wasm_notebook(notebook, ' "hello"\n return\n')+ out_dir = tmp_path / "out"+ runtime = WASMRuntimeConfig(+ pyodide_index_url="./pyodide/",+ pyodide_lockfile_url="./lockfile/test.json",+ pypi_index_url="./packages/index/",+ )++ async def bundle(+ code: str,+ output_dir: Path,+ *,+ sources: WASMRuntimeConfig,+ local_wheel_paths: tuple[Path, ...],+ ):+ assert output_dir == out_dir+ assert sources == WASMRuntimeConfig()+ assert local_wheel_paths == ()+ return code, runtime++ with (+ mock.patch(+ "marimo._export.offline.bundle_wasm_runtime",+ side_effect=bundle,+ ) as bundler,+ mock.patch(+ "marimo._cli.export.commands.check_offline_export_browser",+ new_callable=mock.AsyncMock,+ ) as browser_check,+ mock.patch.object(+ DependencyManager.playwright, "has", return_value=True+ ),+ ):+ result = _run_export(+ "html-wasm",+ str(notebook),+ "--output",+ str(out_dir),+ "--offline",+ )+ _assert_success(result)+ browser_check.assert_awaited_once_with()+ bundler.assert_called_once()+ html = (out_dir / "index.html").read_text()+ assert 'data-pyodide-index-url="./pyodide/"' in html+ assert 'data-pyodide-lockfile-url="./lockfile/test.json"' in html+ assert 'data-pypi-index-url="./packages/index/"' in html++ @staticmethod+ @pytest.mark.parametrize("playwright_installed", [False, True])+ def test_cli_offline_requires_browser_before_export(+ tmp_path: Path, playwright_installed: bool+ ) -> None:+ notebook = tmp_path / "notebook.py"+ _write_minimal_wasm_notebook(notebook, ' "hello"\n return\n')+ out_dir = tmp_path / "out"+ with (+ mock.patch.object(+ DependencyManager.playwright,+ "has",+ return_value=playwright_installed,+ ),+ mock.patch(+ "marimo._cli.export.commands.check_offline_export_browser",+ new_callable=mock.AsyncMock,+ side_effect=RuntimeError("Executable doesn't exist"),+ ) as browser_check,+ mock.patch(+ "marimo._cli.export.commands.get_playwright_chromium_setup_commands",+ return_value=["python -m playwright install chromium"],+ ),+ mock.patch("marimo._cli.export.commands.export_wasm") as export,+ ):+ result = _run_export(+ "html-wasm",+ str(notebook),+ "--output",+ str(out_dir),+ "--offline",+ "--no-sandbox",+ )+ assert result.exit_code == 1+ assert "python -m playwright install chromium" in result.output+ assert not out_dir.exists()+ export.assert_not_called()+ if playwright_installed:+ browser_check.assert_awaited_once_with()+ assert "Chromium could not start" in result.output+ assert "Executable doesn't exist" in result.output+ else:+ browser_check.assert_not_awaited()+ assert "Playwright is required" in result.output++ @staticmethod+ def test_failed_wasm_export_preserves_existing_wheels(+ tmp_path: Path,+ ) -> None:+ notebook = tmp_path / "notebook.py"+ _write_minimal_wasm_notebook(notebook, ' "hello"\n return\n')+ out_dir = tmp_path / "out"+ previous = out_dir / "public/wheels/previous-1.0-py3-none-any.whl"+ previous.parent.mkdir(parents=True)+ previous.write_bytes(b"previous wheel")+ with mock.patch(+ "marimo._cli.export.commands.export_wasm",+ side_effect=RuntimeError("export failed"),+ ):+ result = _run_export(+ "html-wasm", str(notebook), "--output", str(out_dir)+ )+ assert result.exit_code != 0+ assert previous.read_bytes() == b"previous wheel"+@staticmethoddef test_cli_export_html_wasm_single_file_dev_version(tmp_path: Path,@@ -311,7 +429,9 @@ class TestExportHTML:assert "[email protected]" not in html@staticmethod- @pytest.mark.parametrize("resource", ["module", "wheel", "cloudflare"])+ @pytest.mark.parametrize(+ "resource", ["module", "wheel", "cloudflare", "offline"]+ )def test_cli_export_html_wasm_single_file_requires_directory(tmp_path: Path, resource: str) -> None:@@ -337,6 +457,7 @@ class TestExportHTML:"-o",str(output),*(["--include-cloudflare"] if resource == "cloudflare" else []),+ *(["--offline"] if resource == "offline" else []),)assert result.exit_code == 2assert "--single-file" in result.outputdiff --git a/tests/_export/test_offline.py b/tests/_export/test_offline.pynew file mode 100644index 0000000000..c94ebc41c6--- /dev/null+++ b/tests/_export/test_offline.py@@ -0,0 +1,238 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+import hashlib+import json+import threading+from unittest import mock++import pytest++from marimo._export.offline import _resolve_packages, bundle_wasm_runtime+from marimo._schemas.export_options import WASMRuntimeConfig+from marimo._utils.requests import Response+++def sources() -> WASMRuntimeConfig:+ return WASMRuntimeConfig(+ pyodide_index_url="https://runtime.example/",+ pyodide_lockfile_url="https://runtime.example/lock.json",+ pypi_index_url="https://packages.example/simple/",+ )+++def resolver():+ wheel = b"downloaded wheel"+ package = {+ "name": "example",+ "version": "1.0",+ "file_name": "https://wheels.example/example-1.0-py3-none-any.whl",+ "sha256": hashlib.sha256(wheel).hexdigest(),+ "depends": [],+ "imports": ["example"],+ "install_dir": "site",+ }+ lock = {"info": {"python": "3.14.0"}, "packages": {"example": package}}++ def fetch(url: str, **kwargs: object):+ del kwargs+ data = (+ json.dumps(lock).encode() if url.endswith("lock.json") else wheel+ )+ return Response(200, data, {})++ with (+ mock.patch("marimo._export.offline.requests.get", side_effect=fetch),+ mock.patch(+ "marimo._export.offline._resolve_packages",+ new_callable=mock.AsyncMock,+ return_value=lock,+ ) as resolve,+ ):+ yield resolve+++async def test_bundle_is_relocatable_and_preserves_source_config(+ tmp_path, sources, resolver+):+ code = '# /// script\n# dependencies = ["Example @ https://wheels.example/example-1.0-py3-none-any.whl", "Marimo==0.24.2"]\n# ///\nraise RuntimeError("must not execute")\n'+ rewritten, runtime = await bundle_wasm_runtime(+ code, tmp_path, sources=sources+ )+ assert "example==1.0" in rewritten+ assert "marimo==0.24.2" in rewritten+ assert 'raise RuntimeError("must not execute")' in rewritten+ assert (+ resolver.call_args.kwargs["package_base_url"]+ == sources.pyodide_index_url+ )+ assert (+ resolver.call_args.kwargs["pypi_index_url"] == sources.pypi_index_url+ )+ assert runtime.pyodide_index_url == "./pyodide/"+ assert runtime.pypi_index_url == "./packages/index/"+ assert runtime.pyodide_lockfile_url is not None+ lock_path = tmp_path / runtime.pyodide_lockfile_url+ lock = json.loads(lock_path.read_text())+ package = lock["packages"]["example"]+ assert (+ package["file_name"]+ == f"../packages/{package['sha256']}/example-1.0-py3-none-any.whl"+ )+ assert "https://" not in lock_path.read_text()+ wheel = tmp_path / "pyodide" / package["file_name"]+ assert hashlib.sha256(wheel.read_bytes()).hexdigest() == package["sha256"]+ index = tmp_path / "packages/index/example/index.html"+ assert (+ f"../../{package['sha256']}/example-1.0-py3-none-any.whl"+ in index.read_text()+ )+ assert sorted(p.name for p in (tmp_path / "pyodide").iterdir()) == [+ "pyodide.asm.mjs",+ "pyodide.asm.wasm",+ "pyodide.mjs",+ "python_stdlib.zip",+ ]+ assert not list(tmp_path.glob(".marimo-offline-*"))+++async def test_bundle_rejects_package_names_outside_the_index(+ tmp_path, sources, resolver+):+ from packaging.requirements import InvalidRequirement++ packages = resolver.return_value["packages"]+ packages["../../escape"] = packages.pop("example")+ with pytest.raises(InvalidRequirement):+ await bundle_wasm_runtime("pass", tmp_path, sources=sources)+ assert list(tmp_path.iterdir()) == []+++async def test_bad_checksum_preserves_existing_bundle(+ tmp_path, sources, resolver+):+ existing = tmp_path / "pyodide/pyodide.asm.wasm"+ existing.parent.mkdir()+ existing.write_bytes(b"previous runtime")+ resolver.return_value["packages"]["example"]["sha256"] = "0" * 64+ with pytest.raises(ValueError, match="Checksum mismatch"):+ await bundle_wasm_runtime("pass", tmp_path, sources=sources)+ assert existing.read_bytes() == b"previous runtime"+ assert not list(tmp_path.glob(".marimo-offline-*"))+ assert not (tmp_path / "lockfile").exists()+++async def test_each_notebook_keeps_its_wheel_contents(+ tmp_path, sources, resolver+):+ _, first = await bundle_wasm_runtime("one = 1", tmp_path, sources=sources)+ # Each resolver result is a fresh lockfile, like micropip.freeze().+ resolver.return_value["packages"]["example"]["file_name"] = (+ "https://wheels.example/example-1.0-py3-none-any.whl"+ )+ changed = b"different wheel with the same filename and version"+ resolver.return_value["packages"]["example"]["sha256"] = hashlib.sha256(+ changed+ ).hexdigest()+ with mock.patch(+ "marimo._export.offline.requests.get",+ return_value=Response(200, changed, {}),+ ) as fetch:+ fetch.side_effect = lambda url, **_kwargs: Response(+ 200,+ json.dumps(resolver.return_value).encode()+ if url.endswith("lock.json")+ else changed,+ {},+ )+ _, second = await bundle_wasm_runtime(+ "one = 1", tmp_path, sources=sources+ )+ assert first.pyodide_lockfile_url != second.pyodide_lockfile_url+ for runtime, expected in [(first, b"downloaded wheel"), (second, changed)]:+ lock = json.loads(+ (tmp_path / runtime.pyodide_lockfile_url).read_text()+ )+ package = lock["packages"]["example"]+ assert (+ tmp_path / "pyodide" / package["file_name"]+ ).read_bytes() == expected+++async def test_cancelled_bundle_joins_downloads_before_cleanup(+ tmp_path, sources, resolver+):+ started = threading.Event()+ release = threading.Event()+ completed = []++ def download(url, target, checksum):+ del url, checksum+ started.set()+ assert release.wait(5)+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(b"download")+ completed.append(target)+ return hashlib.sha256(b"download").hexdigest()++ with mock.patch("marimo._export.offline._download", side_effect=download):+ task = asyncio.create_task(+ bundle_wasm_runtime("pass", tmp_path, sources=sources)+ )+ assert await asyncio.to_thread(started.wait, 5)+ task.cancel()+ await asyncio.sleep(0)+ assert not task.done()+ release.set()+ with pytest.raises(asyncio.CancelledError):+ await task+ resolver.assert_not_called()+ assert len(completed) == 4+ assert list(tmp_path.iterdir()) == []++[email protected]("phase", ["bootstrap", "imports"])+async def test_resolver_rejects_reported_package_failures(tmp_path, phase):+ pytest.importorskip("playwright.async_api")+ from marimo._export._html_asset_server import HtmlAssetServer+ from marimo._export.dependencies import _is_playwright_chromium_installed++ if not await _is_playwright_chromium_installed():+ pytest.skip("Chromium not installed")+ (tmp_path / "pyodide.mjs").write_text(+ "export async function loadPyodide() { return {"+ "globals: {set() {}}, runPythonAsync: async () => {}, runPython: () => false,"+ "loadPackage: async (_, callbacks) => {"+ + (+ 'callbacks.errorCallback("bootstrap download failed");'+ if phase == "bootstrap"+ else ""+ )+ + "}, loadPackagesFromImports: async (_, callbacks) => {"+ + (+ 'callbacks.errorCallback("imports download failed");'+ if phase == "imports"+ else ""+ )+ + "}};}"+ )+ with HtmlAssetServer(directory=tmp_path, route="/resolve.html") as server:+ server.set_html("<!doctype html>")+ with pytest.raises(Exception, match=f"{phase} download failed"):+ await _resolve_packages(+ "import numpy",+ page_url=server.page_url,+ index_url=server.base_url + "/",+ package_base_url=server.base_url + "/",+ lockfile={"info": {}, "packages": {}},+ pypi_index_url=None,+ )