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.

improvement: inline local images (virutal files) in the HTML export (#7087)

Myles Scolnick2f8f8ad31067
diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.py
index 5d13762132..5d62a1d134 100644
--- a/marimo/_runtime/virtual_file.py
+++ b/marimo/_runtime/virtual_file.py
@@ -221,6 +221,9 @@ class VirtualFileRegistry:
return
buffer = virtual_file.buffer
+ # Skip adding if buffer is empty
+ if len(buffer) == 0:
+ return
# Immediately writes the contents of the file to an in-memory
# buffer; not lazy.
#
diff --git a/marimo/_server/export/dom_traversal.py b/marimo/_server/export/dom_traversal.py
new file mode 100644
index 0000000000..8309cfe3e3
--- /dev/null
+++ b/marimo/_server/export/dom_traversal.py
@@ -0,0 +1,321 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import base64
+import mimetypes
+import re
+from html.parser import HTMLParser
+from typing import Callable, Optional, cast
+
+from marimo import _loggers
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._runtime.virtual_file import read_virtual_file
+from marimo._utils.data_uri import build_data_url
+
+LOGGER = _loggers.marimo_logger()
+
+
+class _HTMLAttributeReplacer(HTMLParser):
+ """HTML parser that finds and replaces attribute values in specific tags.
+
+ This parser traverses HTML strings and applies a custom replacement function
+ to specified attributes in allowed tags.
+
+ Example:
+ ```python
+ def upper_replacer(value: str) -> Optional[str]:
+ return value.upper()
+
+
+ replacer = HTMLAttributeReplacer(
+ allowed_tags={"img"},
+ allowed_attributes={"src"},
+ replacer_fn=upper_replacer,
+ )
+ replacer.feed('<img src="test.png">')
+ replacer.get_output()
+ ```
+ """
+
+ def __init__(
+ self,
+ allowed_tags: set[str],
+ allowed_attributes: set[str],
+ replacer_fn: Callable[[str], Optional[str]],
+ ) -> None:
+ """Initialize the HTML attribute replacer.
+
+ Args:
+ allowed_tags: Set of HTML tag names to process (e.g., {"img", "a"})
+ allowed_attributes: Set of attribute names to process (e.g., {"src", "href"})
+ replacer_fn: Function that takes an attribute value and returns
+ a replacement value, or None to keep the original
+ """
+ super().__init__()
+ self.allowed_tags = {tag.lower() for tag in allowed_tags}
+ self.allowed_attributes = {attr.lower() for attr in allowed_attributes}
+ self.replacer_fn = replacer_fn
+ self._output: list[str] = []
+
+ def handle_starttag(
+ self, tag: str, attrs: list[tuple[str, Optional[str]]]
+ ) -> None:
+ """Handle opening tags, replacing attributes if applicable."""
+ if tag.lower() in self.allowed_tags:
+ # Process attributes for allowed tags
+ new_attrs: list[tuple[str, Optional[str]]] = []
+ for attr_name, attr_value in attrs:
+ if attr_name.lower() in self.allowed_attributes and attr_value:
+ # Apply the replacer function
+ replacement = self.replacer_fn(attr_value)
+ new_attrs.append(
+ (
+ attr_name,
+ replacement
+ if replacement is not None
+ else attr_value,
+ )
+ )
+ else:
+ new_attrs.append((attr_name, attr_value))
+ attrs = new_attrs
+
+ # Reconstruct the tag
+ attrs_str = self._format_attrs(attrs)
+ self._output.append(f"<{tag}{attrs_str}>")
+
+ def handle_endtag(self, tag: str) -> None:
+ """Handle closing tags."""
+ self._output.append(f"</{tag}>")
+
+ def handle_data(self, data: str) -> None:
+ """Handle text content between tags."""
+ self._output.append(data)
+
+ def handle_startendtag(
+ self, tag: str, attrs: list[tuple[str, Optional[str]]]
+ ) -> None:
+ """Handle self-closing tags (e.g., <img />)."""
+ if tag.lower() in self.allowed_tags:
+ # Process attributes for allowed tags
+ new_attrs: list[tuple[str, Optional[str]]] = []
+ for attr_name, attr_value in attrs:
+ if attr_name.lower() in self.allowed_attributes and attr_value:
+ # Apply the replacer function
+ replacement = self.replacer_fn(attr_value)
+ new_attrs.append(
+ (
+ attr_name,
+ replacement
+ if replacement is not None
+ else attr_value,
+ )
+ )
+ else:
+ new_attrs.append((attr_name, attr_value))
+ attrs = new_attrs
+
+ # Reconstruct the self-closing tag
+ attrs_str = self._format_attrs(attrs)
+ self._output.append(f"<{tag}{attrs_str} />")
+
+ def handle_comment(self, data: str) -> None:
+ """Preserve HTML comments."""
+ self._output.append(f"<!--{data}-->")
+
+ def handle_decl(self, decl: str) -> None:
+ """Preserve declarations like DOCTYPE."""
+ self._output.append(f"<!{decl}>")
+
+ def handle_pi(self, data: str) -> None:
+ """Preserve processing instructions."""
+ self._output.append(f"<?{data}>")
+
+ def handle_charref(self, name: str) -> None:
+ """Preserve character references like &#123;."""
+ self._output.append(f"&#{name};")
+
+ def handle_entityref(self, name: str) -> None:
+ """Preserve entity references like &nbsp;."""
+ self._output.append(f"&{name};")
+
+ def _format_attrs(self, attrs: list[tuple[str, Optional[str]]]) -> str:
+ """Format attributes for output."""
+ if not attrs:
+ return ""
+ formatted = []
+ for name, value in attrs:
+ if value is None:
+ # Boolean attribute
+ formatted.append(name)
+ else:
+ # Escape quotes in the value
+ escaped_value = value.replace('"', "&quot;")
+ formatted.append(f'{name}="{escaped_value}"')
+ return " " + " ".join(formatted)
+
+ def get_output(self) -> str:
+ """Get the processed HTML output."""
+ return "".join(self._output)
+
+
+def replace_html_attributes(
+ html: str,
+ *,
+ allowed_tags: set[str],
+ allowed_attributes: set[str],
+ replacer_fn: Callable[[str], Optional[str]],
+) -> str:
+ """Replace attribute values in HTML using a custom function.
+
+ Args:
+ html: The HTML string to process
+ allowed_tags: Set of HTML tag names to process (e.g., {"img", "a"})
+ allowed_attributes: Set of attribute names to process (e.g., {"src", "href"})
+ replacer_fn: Function that takes an attribute value and returns
+ a replacement value, or None to keep the original
+
+ Returns:
+ The processed HTML string with replaced attributes
+
+ Example:
+ ```python
+ def virtual_file_replacer(value: str) -> Optional[str]:
+ if value.startswith("./@file/"):
+ return convert_to_data_uri(value)
+ return None
+
+
+ html = '<img src="./@file/123-test.png"><a href="https://example.com">Link</a>'
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img", "a"},
+ allowed_attributes={"src", "href"},
+ replacer_fn=virtual_file_replacer,
+ )
+ ```
+ """
+ parser = _HTMLAttributeReplacer(
+ allowed_tags=allowed_tags,
+ allowed_attributes=allowed_attributes,
+ replacer_fn=replacer_fn,
+ )
+ parser.feed(html)
+ return parser.get_output()
+
+
+# Virtual file pattern: ./@file/{byte_length}-{filename}
+VIRTUAL_FILE_PATTERN = re.compile(r"^\./@file/(\d+)-(.+)$")
+
+
+def _is_virtual_file_url(url: str) -> bool:
+ """Check if a URL is a virtual file reference.
+
+ Args:
+ url: The URL to check
+
+ Returns:
+ True if the URL matches the virtual file pattern (./@file/{byte_length}-{filename})
+ """
+ return VIRTUAL_FILE_PATTERN.match(url) is not None
+
+
+def _parse_virtual_file_url(url: str) -> Optional[tuple[int, str]]:
+ """Parse a virtual file URL into its components.
+
+ Args:
+ url: The virtual file URL (e.g., "./@file/29676-test.png")
+
+ Returns:
+ Tuple of (byte_length, filename) if the URL is valid, None otherwise
+ """
+ match = VIRTUAL_FILE_PATTERN.match(url)
+ if not match:
+ return None
+ byte_length_str, filename = match.groups()
+ return int(byte_length_str), filename
+
+
+def _virtual_file_to_data_uri(virtual_file_url: str) -> Optional[str]:
+ """Convert a virtual file URL to a data URI.
+
+ Args:
+ virtual_file_url: The virtual file URL (e.g., "./@file/29676-test.png")
+
+ Returns:
+ A data URI string, or None if the conversion fails
+ """
+ parsed = _parse_virtual_file_url(virtual_file_url)
+ if not parsed:
+ return None
+
+ byte_length, filename = parsed
+ try:
+ buffer_contents = read_virtual_file(filename, byte_length)
+ mime_type = mimetypes.guess_type(filename)[0] or "text/plain"
+ return build_data_url(
+ cast(KnownMimeType, mime_type),
+ base64.b64encode(buffer_contents),
+ )
+ except Exception as e:
+ LOGGER.warning(
+ "Failed to convert virtual file to data URI: %s. Error: %s",
+ virtual_file_url,
+ e,
+ )
+ return None
+
+
+def replace_virtual_files_with_data_uris(
+ html: str,
+ allowed_tags: set[str],
+ allowed_attributes: Optional[set[str]] = None,
+) -> tuple[str, set[str]]:
+ """Replace virtual file URLs with data URIs in HTML.
+
+ This is a convenience function that uses replace_html_attributes with a
+ virtual file to data URI replacer.
+
+ Args:
+ html: The HTML string to process
+ allowed_tags: Set of HTML tag names to process
+ allowed_attributes: Set of attribute names to process. Defaults to {"src", "href"}
+
+ Returns:
+ Tuple of (processed_html, replaced_files) where:
+ - processed_html: The HTML string with virtual files replaced by data URIs
+ - replaced_files: Set of virtual file URLs that were successfully replaced
+
+ Example:
+ ```python
+ html = '<img src="./@file/29676-25241121-ZSE6dgpj.png">'
+ result, replaced = replace_virtual_files_with_data_uris(
+ html, allowed_tags={"img"}
+ )
+ # replaced = {"./@file/29676-25241121-ZSE6dgpj.png"}
+ ```
+ """
+
+ if allowed_attributes is None:
+ allowed_attributes = {"src", "href", "data"}
+
+ replaced_files: set[str] = set()
+
+ def replacer(value: str) -> Optional[str]:
+ """Replace virtual file URLs with data URIs."""
+ if _is_virtual_file_url(value):
+ result = _virtual_file_to_data_uri(value)
+ if result is not None:
+ # Track successfully replaced files
+ replaced_files.add(value)
+ return result
+ return None
+
+ processed_html = replace_html_attributes(
+ html=html,
+ allowed_tags=allowed_tags,
+ allowed_attributes=allowed_attributes,
+ replacer_fn=replacer,
+ )
+
+ return processed_html, replaced_files
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 27d3e6ccd1..46988bd1b0 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -33,7 +33,12 @@ from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.mimetypes import KnownMimeType
from marimo._runtime import dataflow
from marimo._runtime.virtual_file import read_virtual_file
+from marimo._schemas.notebook import NotebookV1
from marimo._schemas.serialization import NotebookSerializationV1
+from marimo._schemas.session import NotebookSessionV1
+from marimo._server.export.dom_traversal import (
+ replace_virtual_files_with_data_uris,
+)
from marimo._server.export.utils import (
format_filename_title,
get_download_filename,
@@ -68,8 +73,17 @@ ROOT = (marimo_package_path() / "_static").resolve()
if TYPE_CHECKING:
from nbformat.notebooknode import NotebookNode # type: ignore
+VIRTUAL_FILE_ALLOWED_ATTRIBUTES = {"src"}
+# We don't include video/audio as it can potentially be too much data
+# and the current use-cases are for images.
+VIRTUAL_FILE_ALLOWED_TAGS = {"img"}
+
class Exporter:
+ # Virtual file URL format constants
+ _VIRTUAL_FILE_PATTERN = "./@file/"
+ _VIRTUAL_FILE_PREFIX_WITH_SLASH = "/@file/"
+
def export_as_html(
self,
*,
@@ -80,56 +94,34 @@ class Exporter:
request: ExportAsHTMLRequest,
) -> tuple[str, str]:
index_html = get_html_contents()
-
filename = get_filename(filename)
- virtual_files: dict[str, str] = {}
- for filename_and_length in request.files:
- if "@file/" in filename_and_length:
- virtual_file = filename_and_length[7:]
- try:
- byte_length, basename = virtual_file.split("-", 1)
- buffer_contents = read_virtual_file(
- basename, int(byte_length)
- )
- except Exception as e:
- LOGGER.warning(
- "File not found in export: %s. Error: %s",
- filename_and_length,
- e,
- )
- continue
- mime_type = mimetypes.guess_type(basename)[0] or "text/plain"
- virtual_files[filename_and_length] = build_data_url(
- cast(KnownMimeType, mime_type),
- base64.b64encode(buffer_contents),
- )
-
- # We only want pass the display config in the static notebook,
- # since we use:
- # - display.theme
- # - display.cell_output
- config = deep_copy(DEFAULT_CONFIG)
- config["display"] = display_config
+ # Configure notebook with display settings
+ config = self._prepare_display_config(display_config)
+ # Serialize notebook state
session_snapshot = serialize_session_view(
session_view, cell_ids=app.cell_manager.cell_ids()
)
notebook_snapshot = serialize_notebook(session_view, app.cell_manager)
- if not request.include_code:
- code = ""
- # Clear code and console outputs
- for cell in notebook_snapshot["cells"]:
- cell["code"] = ""
- cell["name"] = ""
- for output in session_snapshot["cells"]:
- output["console"] = []
- else:
- code = app.to_py()
- # We include the code hash regardless of whether we include the code
- code_hash = hash_code(app.to_py())
+ # Replace virtual files in HTML outputs with data URIs
+ session_snapshot, replaced_files = self._inline_virtual_files(
+ session_snapshot
+ )
+
+ # Prepare code for export
+ code = self._prepare_code(
+ request.include_code, app, notebook_snapshot, session_snapshot
+ )
+
+ # Build fallback virtual_files dict for files not in HTML outputs
+ virtual_files = self._build_virtual_files_dict(
+ request.files, replaced_files
+ )
+ # Generate final HTML
+ code_hash = hash_code(app.to_py())
html = static_notebook_template(
html=index_html,
user_config=config,
@@ -148,6 +140,141 @@ class Exporter:
download_filename = get_download_filename(filename, "html")
return html, download_filename
+ def _prepare_display_config(
+ self, display_config: DisplayConfig
+ ) -> MarimoConfig:
+ """Prepare config with display settings for static notebook."""
+ # We only want pass the display config in the static notebook,
+ # since we use:
+ # - display.theme
+ # - display.cell_output
+ config = deep_copy(DEFAULT_CONFIG)
+ config["display"] = display_config
+ return cast(MarimoConfig, config)
+
+ def _inline_virtual_files(
+ self, session_snapshot: NotebookSessionV1
+ ) -> tuple[NotebookSessionV1, set[str]]:
+ """Replace virtual file URLs with data URIs in session outputs.
+
+ Returns:
+ Tuple of (modified_snapshot, set_of_replaced_files)
+ """
+ replaced_files: set[str] = set()
+
+ for cell in session_snapshot["cells"]:
+ for output in cell["outputs"]:
+ if output["type"] != "data":
+ continue
+
+ for mime_type, data in output["data"].items():
+ if not isinstance(data, str):
+ continue
+ if self._VIRTUAL_FILE_PATTERN not in data:
+ continue
+
+ processed, files = replace_virtual_files_with_data_uris(
+ data,
+ allowed_tags=VIRTUAL_FILE_ALLOWED_TAGS,
+ allowed_attributes=VIRTUAL_FILE_ALLOWED_ATTRIBUTES,
+ )
+ replaced_files.update(files)
+ output["data"][mime_type] = processed
+
+ return session_snapshot, replaced_files
+
+ def _prepare_code(
+ self,
+ include_code: bool,
+ app: InternalApp,
+ notebook_snapshot: NotebookV1,
+ session_snapshot: NotebookSessionV1,
+ ) -> str:
+ """Prepare code for export, optionally clearing it."""
+ if not include_code:
+ # Clear code and console outputs
+ for nb_cell in notebook_snapshot["cells"]:
+ nb_cell["code"] = ""
+ nb_cell["name"] = DEFAULT_CELL_NAME
+ for snapshot_cell in session_snapshot["cells"]:
+ snapshot_cell["console"] = []
+ return ""
+
+ return app.to_py()
+
+ def _normalize_virtual_file_url(self, url: str) -> str:
+ """Normalize virtual file URL format from /@file/ to ./@file/."""
+ if url.startswith(self._VIRTUAL_FILE_PATTERN):
+ return url
+ return url.replace(
+ self._VIRTUAL_FILE_PREFIX_WITH_SLASH,
+ self._VIRTUAL_FILE_PATTERN,
+ 1,
+ )
+
+ def _build_virtual_files_dict(
+ self, file_urls: list[str], replaced_files: set[str]
+ ) -> dict[str, str]:
+ """Build dict of virtual files not already inlined in HTML.
+
+ Args:
+ file_urls: List of virtual file URLs from request
+ replaced_files: Set of URLs already replaced in HTML outputs
+
+ Returns:
+ Dict mapping file URLs to data URIs
+ """
+ virtual_files: dict[str, str] = {}
+
+ for file_url in file_urls:
+ # Skip files already replaced in HTML outputs
+ normalized_url = self._normalize_virtual_file_url(file_url)
+ if normalized_url in replaced_files:
+ LOGGER.debug(
+ "Skipping virtual file %s (already inlined in HTML)",
+ file_url,
+ )
+ continue
+
+ # Process virtual file URLs
+ if self._VIRTUAL_FILE_PREFIX_WITH_SLASH not in file_url:
+ continue
+
+ data_uri = self._read_virtual_file_as_data_uri(file_url)
+ if data_uri:
+ virtual_files[file_url] = data_uri
+
+ return virtual_files
+
+ def _read_virtual_file_as_data_uri(self, file_url: str) -> Optional[str]:
+ """Read a virtual file and convert it to a data URI.
+
+ Args:
+ file_url: Virtual file URL in format /@file/{byte_length}-{filename}
+
+ Returns:
+ Data URI string, or None if file cannot be read
+ """
+ # Extract byte_length and filename from URL
+ # Format: /@file/{byte_length}-{filename}
+ prefix_len = len(self._VIRTUAL_FILE_PREFIX_WITH_SLASH)
+ virtual_file = file_url[prefix_len:]
+
+ try:
+ byte_length_str, basename = virtual_file.split("-", 1)
+ buffer_contents = read_virtual_file(basename, int(byte_length_str))
+ except Exception as e:
+ LOGGER.warning(
+ "File not found in export: %s. Error: %s", file_url, e
+ )
+ return None
+
+ mime_type = mimetypes.guess_type(basename)[0] or "text/plain"
+ return build_data_url(
+ cast(KnownMimeType, mime_type),
+ base64.b64encode(buffer_contents),
+ )
+
def export_as_script(
self,
filename: Optional[str],
diff --git a/marimo/_smoke_tests/requests.py b/marimo/_smoke_tests/_requests.py
similarity index 100%
rename from marimo/_smoke_tests/requests.py
rename to marimo/_smoke_tests/_requests.py
diff --git a/marimo/_smoke_tests/media.py b/marimo/_smoke_tests/media.py
index a0451d3adb..e3199638f5 100644
--- a/marimo/_smoke_tests/media.py
+++ b/marimo/_smoke_tests/media.py
@@ -2,7 +2,7 @@
import marimo
-__generated_with = "0.15.5"
+__generated_with = "0.17.6"
app = marimo.App()
diff --git a/tests/_runtime/test_virtual_file.py b/tests/_runtime/test_virtual_file.py
index 9457f36163..2baf81820d 100644
--- a/tests/_runtime/test_virtual_file.py
+++ b/tests/_runtime/test_virtual_file.py
@@ -281,3 +281,23 @@ async def test_virtual_files_not_supported(
ctx = get_context()
assert len(ctx.virtual_file_registry.registry) == 0
ctx.virtual_files_supported = True
+
+
+async def test_virtual_file_empty_buffer(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = execution_kernel
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import io
+ import marimo as mo
+ bytestream = io.BytesIO(b"")
+ pdf_plugin = mo.pdf(bytestream)
+ """
+ ),
+ ]
+ )
+ # Empty buffers should not be added to the registry
+ assert len(get_context().virtual_file_registry.registry) == 0
diff --git a/tests/_server/export/test_dom_traversal.py b/tests/_server/export/test_dom_traversal.py
new file mode 100644
index 0000000000..66b80a11bd
--- /dev/null
+++ b/tests/_server/export/test_dom_traversal.py
@@ -0,0 +1,222 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._server.export.dom_traversal import (
+ _is_virtual_file_url,
+ _parse_virtual_file_url,
+ replace_html_attributes,
+)
+
+
+class TestHTMLAttributeReplacer:
+ def test_simple_replacement(self) -> None:
+ """Test basic attribute replacement."""
+ html = '<img src="test.png">'
+
+ def upper_replacer(value: str) -> str:
+ return value.upper()
+
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img"},
+ allowed_attributes={"src"},
+ replacer_fn=upper_replacer,
+ )
+ assert result == '<img src="TEST.PNG">'
+
+ def test_multiple_tags(self) -> None:
+ """Test replacement across multiple tags."""
+ html = '<img src="test.png"><a href="link.html">Link</a>'
+
+ def prefix_replacer(value: str) -> str:
+ return f"prefix_{value}"
+
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img", "a"},
+ allowed_attributes={"src", "href"},
+ replacer_fn=prefix_replacer,
+ )
+ assert (
+ result
+ == '<img src="prefix_test.png"><a href="prefix_link.html">Link</a>'
+ )
+
+ def test_selective_tag_replacement(self) -> None:
+ """Test that only allowed tags are processed."""
+ html = '<img src="test.png"><div data-src="other.png"></div>'
+
+ def prefix_replacer(value: str) -> str:
+ return f"prefix_{value}"
+
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img"}, # Only img, not div
+ allowed_attributes={"src", "data-src"},
+ replacer_fn=prefix_replacer,
+ )
+ # img src should be replaced, div data-src should not
+ assert (
+ result
+ == '<img src="prefix_test.png"><div data-src="other.png"></div>'
+ )
+
+ def test_selective_attribute_replacement(self) -> None:
+ """Test that only allowed attributes are processed."""
+ html = '<img src="test.png" alt="description">'
+
+ def prefix_replacer(value: str) -> str:
+ return f"prefix_{value}"
+
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img"},
+ allowed_attributes={"src"}, # Only src, not alt
+ replacer_fn=prefix_replacer,
+ )
+ # src should be replaced, alt should not
+ assert result == '<img src="prefix_test.png" alt="description">'
+
+ def test_none_return_keeps_original(self) -> None:
+ """Test that returning None from replacer keeps original value."""
+ html = '<img src="test.png">'
+
+ def conditional_replacer(value: str) -> str | None:
+ if value == "test.png":
+ return None # Keep original
+ return "replaced"
+
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img"},
+ allowed_attributes={"src"},
+ replacer_fn=conditional_replacer,
+ )
+ assert result == '<img src="test.png">'
+
+ def test_self_closing_tags(self) -> None:
+ """Test self-closing tags."""
+ html = '<img src="test.png" />'
+
+ def upper_replacer(value: str) -> str:
+ return value.upper()
+
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img"},
+ allowed_attributes={"src"},
+ replacer_fn=upper_replacer,
+ )
+ assert result == '<img src="TEST.PNG" />'
+
+ def test_preserves_other_content(self) -> None:
+ """Test that text and other elements are preserved."""
+ html = '<div>Text before<img src="test.png">Text after</div>'
+
+ def upper_replacer(value: str) -> str:
+ return value.upper()
+
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img"},
+ allowed_attributes={"src"},
+ replacer_fn=upper_replacer,
+ )
+ assert result == '<div>Text before<img src="TEST.PNG">Text after</div>'
+
+ def test_complex_html(self) -> None:
+ """Test with more complex HTML structure."""
+ html = """
+ <div class="container">
+ <img src="image1.png" alt="First" />
+ <a href="link.html">Click here</a>
+ <img src="image2.png" />
+ </div>
+ """
+
+ def prefix_replacer(value: str) -> str:
+ return f"https://cdn.example.com/{value}"
+
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img", "a"},
+ allowed_attributes={"src", "href"},
+ replacer_fn=prefix_replacer,
+ )
+
+ assert 'src="https://cdn.example.com/image1.png"' in result
+ assert 'src="https://cdn.example.com/image2.png"' in result
+ assert 'href="https://cdn.example.com/link.html"' in result
+
+ def test_quoted_attributes(self) -> None:
+ """Test that quotes in values are properly escaped."""
+ html = '<img src="test.png">'
+
+ def quote_replacer(value: str) -> str:
+ del value
+ return 'value with "quotes"'
+
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img"},
+ allowed_attributes={"src"},
+ replacer_fn=quote_replacer,
+ )
+ # Quotes should be escaped
+ assert 'src="value with &quot;quotes&quot;"' in result
+
+
+class TestVirtualFilePatterns:
+ def test_is_virtual_file_url(self) -> None:
+ """Test virtual file URL detection."""
+ assert _is_virtual_file_url("./@file/29676-test.png") is True
+ assert _is_virtual_file_url("./@file/123-file.jpg") is True
+ assert _is_virtual_file_url("https://example.com/image.png") is False
+ assert _is_virtual_file_url("./regular-file.png") is False
+ assert (
+ _is_virtual_file_url("@file/123-test.png") is False
+ ) # Missing ./
+
+ def test_parse_virtual_file_url(self) -> None:
+ """Test virtual file URL parsing."""
+ result = _parse_virtual_file_url("./@file/29676-test.png")
+ assert result == (29676, "test.png")
+
+ result = _parse_virtual_file_url("./@file/123-complex-file-name.jpg")
+ assert result == (123, "complex-file-name.jpg")
+
+ result = _parse_virtual_file_url("https://example.com/image.png")
+ assert result is None
+
+ def test_parse_virtual_file_with_hyphens(self) -> None:
+ """Test parsing virtual files with hyphens in filename."""
+ result = _parse_virtual_file_url("./@file/29676-25241121-ZSE6dgpj.png")
+ assert result == (29676, "25241121-ZSE6dgpj.png")
+
+
+class TestVirtualFileReplacement:
+ def test_conditional_replacement(self) -> None:
+ """Test that only virtual files are replaced."""
+ html = """
+ <img src="./@file/123-test.png">
+ <img src="https://example.com/image.png">
+ <img src="./regular.png">
+ """
+
+ def replacer(value: str) -> str | None:
+ if _is_virtual_file_url(value):
+ return "data:image/png;base64,MOCK_DATA"
+ return None
+
+ result = replace_html_attributes(
+ html,
+ allowed_tags={"img"},
+ allowed_attributes={"src"},
+ replacer_fn=replacer,
+ )
+
+ # Virtual file should be replaced
+ assert 'src="data:image/png;base64,MOCK_DATA"' in result
+ # Regular URLs should remain unchanged
+ assert 'src="https://example.com/image.png"' in result
+ assert 'src="./regular.png"' in result
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index 6150f84dbc..ef1b40daa6 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -918,3 +918,224 @@ def test_export_as_html_code_hash_consistency(session_view: SessionView):
assert '"code": "return' in html_with_code, (
"Cell code should be present when include_code=True"
)
+
+
+def test_export_html_replaces_virtual_files_in_outputs(
+ session_view: SessionView,
+):
+ """Test that virtual file URLs in HTML outputs are replaced with data URIs."""
+ app = App()
+
+ @app.cell()
+ def test_cell():
+ import marimo as mo
+
+ return mo.image(src="test.png")
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+
+ cell_ids = list(file_manager.app.cell_manager.cell_ids())
+
+ # Create HTML output with a virtual file reference
+ html_with_virtual_file = (
+ '<img src="./@file/100-test.png" alt="Test image">'
+ )
+
+ session_view.cell_operations[cell_ids[0]] = CellOp(
+ cell_id=cell_ids[0],
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/html",
+ data=html_with_virtual_file,
+ ),
+ console=[],
+ timestamp=0,
+ )
+ session_view.last_executed_code[cell_ids[0]] = (
+ "import marimo as mo\nreturn mo.image(src='test.png')"
+ )
+
+ exporter = Exporter()
+
+ # Include the virtual file in request.files
+ # Note: request.files uses /@file/ format (without the ./)
+ request = ExportAsHTMLRequest(
+ download=True,
+ files=["/@file/100-test.png"],
+ include_code=True,
+ )
+
+ # Mock read_virtual_file to return test image data
+ with patch(
+ "marimo._server.export.dom_traversal.read_virtual_file"
+ ) as mock_read:
+ mock_read.return_value = b"fake_image_data"
+
+ html, filename = exporter.export_as_html(
+ filename=file_manager.filename,
+ app=file_manager.app,
+ session_view=session_view,
+ display_config=DEFAULT_CONFIG["display"],
+ request=request,
+ )
+
+ assert filename == "notebook.html"
+
+ # Virtual file should be replaced with data URI in the output
+ assert "./@file/100-test.png" not in html
+ assert "data:image/png;base64," in html
+
+ # Verify the base64-encoded data is present (fake_image_data)
+ import base64
+
+ expected_b64 = base64.b64encode(b"fake_image_data").decode()
+ assert expected_b64 in html
+
+
+def test_export_html_replaces_multiple_virtual_files_complex(
+ session_view: SessionView,
+):
+ """Test virtual file replacement with multiple files and nested structures."""
+ app = App()
+
+ @app.cell()
+ def cell_1():
+ import marimo as mo
+
+ return mo.image(src="chart.png")
+
+ @app.cell()
+ def cell_2():
+ import marimo as mo
+
+ return mo.md("![Plot](./@file/200-plot.png)")
+
+ @app.cell()
+ def cell_3():
+ # Cell with both virtual file and external URL
+ return '<div><img src="./@file/300-diagram.svg"><img src="https://example.com/external.png"></div>'
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ cell_ids = list(file_manager.app.cell_manager.cell_ids())
+
+ # Cell 1: Image with virtual file
+ session_view.cell_operations[cell_ids[0]] = CellOp(
+ cell_id=cell_ids[0],
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/html",
+ data='<img src="./@file/100-chart.png" alt="Chart">',
+ ),
+ console=[],
+ timestamp=0,
+ )
+ session_view.last_executed_code[cell_ids[0]] = (
+ "import marimo as mo\nreturn mo.image(src='chart.png')"
+ )
+
+ # Cell 2: Markdown with virtual file
+ session_view.cell_operations[cell_ids[1]] = CellOp(
+ cell_id=cell_ids[1],
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/html",
+ data='<p><img src="./@file/200-plot.png" alt="Plot"></p>',
+ ),
+ console=[],
+ timestamp=1,
+ )
+ session_view.last_executed_code[cell_ids[1]] = (
+ "import marimo as mo\nreturn mo.md('![Plot](./@file/200-plot.png)')"
+ )
+
+ # Cell 3: Mixed - virtual file and external URL
+ session_view.cell_operations[cell_ids[2]] = CellOp(
+ cell_id=cell_ids[2],
+ status="idle",
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/html",
+ data='<div><img src="./@file/300-diagram.svg"><img src="https://example.com/external.png"></div>',
+ ),
+ console=[],
+ timestamp=2,
+ )
+ session_view.last_executed_code[cell_ids[2]] = (
+ 'return \'<div><img src="./@file/300-diagram.svg"><img src="https://example.com/external.png"></div>\''
+ )
+
+ exporter = Exporter()
+
+ # Include all virtual files plus an extra one not in outputs
+ # Note: request.files uses /@file/ format (without the ./)
+ request = ExportAsHTMLRequest(
+ download=True,
+ files=[
+ "/@file/100-chart.png",
+ "/@file/200-plot.png",
+ "/@file/300-diagram.svg",
+ "/@file/400-unused.txt", # Not in any output
+ ],
+ include_code=True,
+ )
+
+ # Mock read_virtual_file
+ def mock_read_side_effect(filename: str, byte_length: int) -> bytes:
+ """Return different mock data based on filename."""
+ del byte_length
+ if filename == "chart.png":
+ return b"chart_data"
+ elif filename == "plot.png":
+ return b"plot_data"
+ elif filename == "diagram.svg":
+ return b"<svg>diagram</svg>"
+ elif filename == "unused.txt":
+ return b"unused_content"
+ return b"default_data"
+
+ with (
+ patch(
+ "marimo._server.export.dom_traversal.read_virtual_file"
+ ) as mock_read_dom,
+ patch(
+ "marimo._server.export.exporter.read_virtual_file"
+ ) as mock_read_exporter,
+ ):
+ mock_read_dom.side_effect = mock_read_side_effect
+ mock_read_exporter.side_effect = mock_read_side_effect
+
+ html, filename = exporter.export_as_html(
+ filename=file_manager.filename,
+ app=file_manager.app,
+ session_view=session_view,
+ display_config=DEFAULT_CONFIG["display"],
+ request=request,
+ )
+
+ assert filename == "notebook.html"
+
+ # Verify base64-encoded data is present for replaced files
+ import base64
+
+ chart_b64 = base64.b64encode(b"chart_data").decode()
+ plot_b64 = base64.b64encode(b"plot_data").decode()
+ diagram_b64 = base64.b64encode(b"<svg>diagram</svg>").decode()
+
+ # At least some of the base64 data should be in the HTML
+ # (virtual files are replaced with data URIs)
+ assert chart_b64 in html, "Chart data should be embedded as base64"
+ assert plot_b64 in html, "Plot data should be embedded as base64"
+ assert diagram_b64 in html, "Diagram data should be embedded as base64"
+
+ # Data URIs should be present
+ assert "data:image/png;base64," in html # For chart and plot
+ assert "data:image/svg+xml;base64," in html # For diagram
+
+ # External URL should remain unchanged
+ assert "https://example.com/external.png" in html
+
+ # Virtual file URLs should be replaced (though they may be URL-encoded in JSON)
+ # So we just check that the base64 data is present, which proves replacement worked