|
24 | 24 | from copy import deepcopy |
25 | 25 | from datetime import datetime |
26 | 26 | from inspect import isawaitable |
27 | | -from typing import TYPE_CHECKING, Any, ClassVar, Final, Generic, Literal, NewType, cast, overload |
| 27 | +from typing import TYPE_CHECKING, Any, ClassVar, Final, Generic, Literal, NamedTuple, NewType, cast, overload |
28 | 28 |
|
29 | 29 | from typing_extensions import Required, TypedDict |
30 | 30 |
|
@@ -80,6 +80,44 @@ def _parse_content_list(contents_data: Sequence[Any]) -> list[Content]: |
80 | 80 | # region Internal Helper functions for unified Content |
81 | 81 |
|
82 | 82 |
|
| 83 | +class _ParsedDataUri(NamedTuple): |
| 84 | + """The parts of an RFC 2397 data URI.""" |
| 85 | + |
| 86 | + media_type: str |
| 87 | + is_base64: bool |
| 88 | + payload: str |
| 89 | + |
| 90 | + |
| 91 | +def _parse_data_uri(uri: str) -> _ParsedDataUri: |
| 92 | + """Parse a ``data:`` URI once, so every caller reads it the same way. |
| 93 | +
|
| 94 | + RFC 2397: ``data:[<media-type>][;parameter[=value]]...[;base64],<data>``. The media type is |
| 95 | + everything between ``data:`` and the first ``;`` and defaults to ``text/plain`` when empty. |
| 96 | + ``base64`` is the only encoding marker and is only valid once, as the last parameter; other |
| 97 | + parameters such as ``charset=utf-8`` are metadata. Only the metadata before the first comma |
| 98 | + is inspected, so a ``;base64,`` sequence inside the payload is never treated as a marker. |
| 99 | +
|
| 100 | + Raises: |
| 101 | + ContentError: If the URI has no comma or carries an unsupported encoding marker. |
| 102 | + """ |
| 103 | + if "," not in uri: |
| 104 | + raise ContentError("Data URI must contain a comma separating metadata and data") |
| 105 | + prefix, payload = uri.split(",", 1) |
| 106 | + parts = prefix.split(";") |
| 107 | + parameters = parts[1:] |
| 108 | + for index, parameter in enumerate(parameters): |
| 109 | + if parameter == "base64": |
| 110 | + if index != len(parameters) - 1: |
| 111 | + raise ContentError("Data URI 'base64' marker must be the last parameter") |
| 112 | + elif parameter and "=" not in parameter: |
| 113 | + raise ContentError(f"Unsupported data URI encoding: {parameter}") |
| 114 | + return _ParsedDataUri( |
| 115 | + media_type=parts[0][5:] or "text/plain", # Remove 'data:' |
| 116 | + is_base64=bool(parameters) and parameters[-1] == "base64", |
| 117 | + payload=payload, |
| 118 | + ) |
| 119 | + |
| 120 | + |
83 | 121 | def detect_media_type_from_base64( |
84 | 122 | *, |
85 | 123 | data_bytes: bytes | None = None, |
@@ -132,9 +170,13 @@ def detect_media_type_from_base64( |
132 | 170 | # Remove data URI prefix if present |
133 | 171 | if not data_uri.startswith("data:") or "," not in data_uri: |
134 | 172 | raise ValueError("Invalid data URI format.") |
135 | | - prefix, data_str = data_uri.split(",", 1) |
136 | | - if not prefix.endswith(";base64"): |
| 173 | + try: |
| 174 | + parsed = _parse_data_uri(data_uri) |
| 175 | + except ContentError as exc: |
| 176 | + raise ValueError(str(exc)) from exc |
| 177 | + if not parsed.is_base64: |
137 | 178 | raise ValueError("Data URI must use base64 encoding.") |
| 179 | + data_str = parsed.payload |
138 | 180 | if data_str is not None: |
139 | 181 | if data is not None: |
140 | 182 | raise ValueError("Provide exactly one of data_bytes, data_str, or data_uri.") |
@@ -212,11 +254,10 @@ def _get_data_bytes_as_str(content: Content) -> str | None: |
212 | 254 | if not uri.startswith("data:"): |
213 | 255 | return None |
214 | 256 |
|
215 | | - if ";base64," not in uri: |
| 257 | + parsed = _parse_data_uri(uri) |
| 258 | + if not parsed.is_base64: |
216 | 259 | raise ContentError("Data URI must use base64 encoding") |
217 | | - |
218 | | - _, data = uri.split(";base64,", 1) |
219 | | - return data |
| 260 | + return parsed.payload |
220 | 261 |
|
221 | 262 |
|
222 | 263 | def _get_data_bytes(content: Content) -> bytes | None: # pyright: ignore[reportUnusedFunction] |
@@ -259,24 +300,9 @@ def _validate_uri(uri: str, media_type: str | None) -> dict[str, Any]: |
259 | 300 |
|
260 | 301 | # Check for data URI |
261 | 302 | if uri.startswith("data:"): |
262 | | - if "," not in uri: |
263 | | - raise ContentError("Data URI must contain a comma separating metadata and data") |
264 | | - prefix, _ = uri.split(",", 1) |
265 | | - # RFC 2397: data:[<media-type>][;parameter[=value]]...[;base64],<data>. |
266 | | - # The media type is everything between "data:" and the first ";" and defaults |
267 | | - # to "text/plain" when empty. "base64" is the only encoding marker; other |
268 | | - # parameters such as charset=... are metadata, not encodings. |
269 | | - parts = prefix.split(";") |
| 303 | + parsed = _parse_data_uri(uri) |
270 | 304 | if media_type is None: |
271 | | - media_type = parts[0][5:] or "text/plain" # Remove 'data:' |
272 | | - parameters = parts[1:] |
273 | | - for index, parameter in enumerate(parameters): |
274 | | - if parameter == "base64": |
275 | | - # base64 is only valid as the last parameter, and only once. |
276 | | - if index != len(parameters) - 1: |
277 | | - raise ContentError("Data URI 'base64' marker must be the last parameter") |
278 | | - elif parameter and "=" not in parameter: |
279 | | - raise ContentError(f"Unsupported data URI encoding: {parameter}") |
| 305 | + media_type = parsed.media_type |
280 | 306 | return {"type": "data", "uri": uri, "media_type": media_type} |
281 | 307 |
|
282 | 308 | # Check for common URI schemes |
|
0 commit comments