Skip to content

Saleor Core: the high performance, composable, headless commerce API.

feat: use Pydantic for EditorJS (#18969)

Mikail484eb7c0edea
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b33c6a7e6f..4a4d40687d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -62,7 +62,9 @@ permissions.
See the [upgrading guide](https://docs.saleor.io/upgrade-guides/3-22-to-3-23##explicit-delivery-options-calculation) to learn more.
- `checkoutDeliveryMethodUpdate` mutation now accepts `CheckoutDelivery` ID as `deliveryMethodId` (ID returned by `deliveryOptionsCalculate` mutation). Usage of `ShippingMethod` ID is deprecated in favor of `CheckoutDelivery` ID.
+### EditorJS (Rich Text Editor)
+- Made the EditorJS parser stricter. We no longer accept unknown/extra fields. - #18969 by @NyanKiyoshi
### Other changes
diff --git a/saleor/attribute/migrations/0008_auto_20210407_0632.py b/saleor/attribute/migrations/0008_auto_20210407_0632.py
index 3f15a5d5e6..86d0b2bfbb 100644
--- a/saleor/attribute/migrations/0008_auto_20210407_0632.py
+++ b/saleor/attribute/migrations/0008_auto_20210407_0632.py
@@ -3,7 +3,7 @@
from django.db import migrations, models
import saleor.core.db.fields
-import saleor.core.utils.editorjs
+import saleor.core.editorjs
class Migration(migrations.Migration):
@@ -18,7 +18,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AddField(
@@ -27,7 +27,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.py
index 692694421d..766061155c 100644
--- a/saleor/attribute/models/base.py
+++ b/saleor/attribute/models/base.py
@@ -5,9 +5,9 @@ from django.db import models, transaction
from django.db.models import Case, Exists, F, OrderBy, OuterRef, Q, Value, When
from ...core.db.fields import SanitizedJSONField
+from ...core.editorjs import clean_editorjs
from ...core.models import ModelWithExternalReference, ModelWithMetadata, SortableModel
from ...core.units import MeasurementUnits
-from ...core.utils.editorjs import clean_editor_js
from ...core.utils.translations import Translation
from ...page.models import Page, PageType
from ...permission.enums import PageTypePermissions, ProductTypePermissions
@@ -372,7 +372,7 @@ class AttributeValue(ModelWithExternalReference):
attribute = models.ForeignKey(
Attribute, related_name="values", on_delete=models.CASCADE
)
- rich_text = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ rich_text = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
plain_text = models.TextField(
blank=True,
null=True,
@@ -505,7 +505,7 @@ class AttributeValueTranslation(Translation):
AttributeValue, related_name="translations", on_delete=models.CASCADE
)
name = models.CharField(max_length=250)
- rich_text = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ rich_text = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
plain_text = models.TextField(
blank=True,
null=True,
diff --git a/saleor/attribute/search.py b/saleor/attribute/search.py
index e8e6538159..d1b34fa69c 100644
--- a/saleor/attribute/search.py
+++ b/saleor/attribute/search.py
@@ -3,8 +3,8 @@ from typing import Union
from django.db.models import QuerySet, Value
from ..attribute import AttributeInputType
+from ..core.editorjs import editorjs_to_text
from ..core.postgres import NoValidationSearchVector
-from ..core.utils.editorjs import clean_editor_js
from .models import Attribute, AttributeValue
@@ -25,7 +25,7 @@ def get_search_vectors_for_attribute_values(
elif input_type == AttributeInputType.RICH_TEXT:
search_vectors += [
NoValidationSearchVector(
- Value(clean_editor_js(value.rich_text, to_string=True)),
+ Value(editorjs_to_text(value.rich_text)),
config="simple",
weight=weight,
)
diff --git a/saleor/attribute/tests/fixtures/attribute.py b/saleor/attribute/tests/fixtures/attribute.py
index 5ef78a7204..0733765f91 100644
--- a/saleor/attribute/tests/fixtures/attribute.py
+++ b/saleor/attribute/tests/fixtures/attribute.py
@@ -2,8 +2,8 @@ import datetime
import pytest
+from ....core.editorjs import editorjs_to_text
from ....core.units import MeasurementUnits
-from ....core.utils.editorjs import clean_editor_js
from ....core.utils.text import safe_truncate
from ....tests.utils import dummy_editorjs
from ... import AttributeEntityType, AttributeInputType, AttributeType
@@ -325,7 +325,7 @@ def rich_text_attribute(db):
text = "Rich text attribute content."
AttributeValue.objects.create(
attribute=attribute,
- name=safe_truncate(clean_editor_js(dummy_editorjs(text), to_string=True), 50),
+ name=safe_truncate(editorjs_to_text(dummy_editorjs(text)), 50),
slug=f"instance_{attribute.id}",
rich_text=dummy_editorjs(text),
)
@@ -346,7 +346,7 @@ def rich_text_attribute_page_type(db):
text = "Rich text attribute content."
AttributeValue.objects.create(
attribute=attribute,
- name=safe_truncate(clean_editor_js(dummy_editorjs(text), to_string=True), 50),
+ name=safe_truncate(editorjs_to_text(dummy_editorjs(text)), 50),
slug=f"instance_{attribute.id}",
rich_text=dummy_editorjs(text),
)
@@ -362,9 +362,7 @@ def rich_text_attribute_with_many_values(rich_text_attribute):
values.append(
AttributeValue(
attribute=attribute,
- name=safe_truncate(
- clean_editor_js(dummy_editorjs(text), to_string=True), 50
- ),
+ name=safe_truncate(editorjs_to_text(dummy_editorjs(text)), 50),
slug=f"instance_{attribute.id}_{i}",
rich_text=dummy_editorjs(text),
)
diff --git a/saleor/core/editorjs/__init__.py b/saleor/core/editorjs/__init__.py
new file mode 100644
index 0000000000..8e7f0af884
--- /dev/null
+++ b/saleor/core/editorjs/__init__.py
@@ -0,0 +1,3 @@
+from .converters import clean_editorjs, editorjs_to_text, parse_editorjs
+
+__all__ = ("clean_editorjs", "parse_editorjs", "editorjs_to_text")
diff --git a/saleor/core/editorjs/cleaners.py b/saleor/core/editorjs/cleaners.py
new file mode 100644
index 0000000000..98f1867053
--- /dev/null
+++ b/saleor/core/editorjs/cleaners.py
@@ -0,0 +1,121 @@
+import warnings
+from typing import Any, overload
+
+import nh3
+from django.conf import settings
+from django.core.exceptions import ValidationError
+from urllib3.util import parse_url
+
+from ..cleaners import URL_SCHEME_CLEANERS, URLCleanerError
+
+ALLOWED_URL_SCHEMES = {
+ # WARNING: do NOT add new schemes in directly to this list, only HTTP and HTTPS
+ # should be listed as they are cleaned by urllib3. Instead, add it to
+ # URL_SCHEME_CLEANERS and implement a cleaner that (at minimum) quotes
+ # special characters like "'<> and ASCII control characters
+ # (use urllib.util.parse.quote())
+ "http",
+ "https",
+ *URL_SCHEME_CLEANERS.keys(),
+}
+
+
+def _clean_url_value(dirty_url: str | None) -> str:
+ """Check if URL scheme is allowed."""
+ if not dirty_url:
+ return ""
+
+ try:
+ parsed_url = parse_url(dirty_url.strip())
+ except ValueError:
+ parsed_url = None
+
+ if (
+ parsed_url is None
+ or parsed_url.scheme
+ not in ALLOWED_URL_SCHEMES | settings.HTML_CLEANER_PREFS.allowed_schemes
+ ):
+ warnings.warn(
+ f"An invalid url or disallowed URL was sent: {dirty_url}",
+ stacklevel=3,
+ )
+ return "#invalid"
+
+ # If the scheme is HTTP(S), then urllib3 already took care of normalization
+ # and thus quoted everything that should be quoted (such as dangerous characters
+ # like `"`)
+ # See https://github.com/urllib3/urllib3/blob/bd37a23af4552548f55d3c723fcb604f9a4983ca/src/urllib3/util/url.py#L415-L446
+ if parsed_url.scheme in ("https", "http"):
+ return parsed_url.url
+
+ url_cleaner = URL_SCHEME_CLEANERS.get(parsed_url.scheme, None)
+
+ if url_cleaner is None:
+ if parsed_url.scheme in settings.HTML_CLEANER_PREFS.allowed_schemes:
+ # Deprecated: this is only for backward compatibility - it doesn't define
+ # a cleaner which is dangerous.
+ return dirty_url
+ # NOTE: this exception should never happen unless a maintainer didn't read the
+ # comment in ALLOWED_URL_SCHEMES
+ raise KeyError("No URL cleaner defined", parsed_url.scheme)
+
+ try:
+ return url_cleaner(dirty_url=dirty_url)
+ except URLCleanerError as exc:
+ # Note: InvalidUsage must NOT be handled (should return "Internal Error")
+ # it indicates a code bug if it's raised
+ raise ValidationError(str(exc)) from exc
+ except ValueError as exc:
+ # Note: we do not do str(exc) as may reveal sensitive information
+ raise ValidationError("Invalid URL") from exc
+
+
+def _clean_meta_dict(value: dict) -> dict:
+ if len(value) > 10:
+ raise ValueError("Invalid meta block for EditorJS: too many fields")
+ return value
+
+
+def _clean_nested_list_items(items: Any, current_depth: int = 0) -> Any:
+ """Validate the depth of nested EditorJS list isn't excessive.
+
+ Important: this is a "before" pydantic validator, meaning types aren't checked
+ yet as we want to run this validator early (instead of late).
+ """
+ if current_depth == settings.EDITOR_JS_LISTS_MAX_DEPTH:
+ raise ValidationError("Invalid EditorJS list: maximum nesting level exceeded")
+
+ # Type is invalid, skip it - we don't raise b/c pydantic will already take care
+ # of that and will show a helpful error
+ if not isinstance(items, list):
+ return items
+
+ for item in items:
+ # Type is invalid, skip it (pydantic will take care of raising)
+ if not isinstance(item, dict):
+ continue
+ if child_items := item.get("items"):
+ _clean_nested_list_items(child_items, current_depth + 1)
+ return items
+
+
+@overload
+def _clean_text(text: None) -> None: ...
+
+
+@overload
+def _clean_text(text: str) -> str: ...
+
+
+def _clean_text(text: str | None) -> str | None:
+ """Sanitize the text using nh3 to remove disallowed tags and attributes."""
+ if not text:
+ return text
+
+ return nh3.clean(
+ text,
+ url_schemes=ALLOWED_URL_SCHEMES | settings.HTML_CLEANER_PREFS.allowed_schemes,
+ attributes=settings.HTML_CLEANER_PREFS.allowed_attributes,
+ tag_attribute_values=settings.HTML_CLEANER_PREFS.allowed_attribute_values,
+ link_rel=settings.HTML_CLEANER_PREFS.link_rel,
+ )
diff --git a/saleor/core/editorjs/converters.py b/saleor/core/editorjs/converters.py
new file mode 100644
index 0000000000..24dc8b18af
--- /dev/null
+++ b/saleor/core/editorjs/converters.py
@@ -0,0 +1,91 @@
+import logging
+from typing import overload
+
+import pydantic_core
+from django.core.exceptions import ValidationError
+from django.utils.html import strip_tags
+
+from .models import EditorJSDocumentModel
+
+logger = logging.getLogger(__name__)
+
+
+def parse_editorjs(data: dict, *, for_django: bool = True) -> EditorJSDocumentModel:
+ """Parse EditorJS dictionary into a cleaned Pydantic model.
+
+ :param dict data: the EditorJS data to validate and to clean.
+ :param bool for_django: Whether to convert exceptions into something django
+ understands. Useful for models and GraphQL as ValidationError is automatically
+ handled. `False` should be passed if we want to handle the errors explicitly
+ or we need verbosity.
+ Can only be raised when ``for_django=False``.
+ :raises pydantic.ValidationError: when the input doesn't match the schema/models.
+ :raises django.core.exceptions.ValidationError: when Saleor checks don't pass.
+ """
+
+ try:
+ return EditorJSDocumentModel.model_validate(data)
+ except pydantic_core.ValidationError as exc:
+ if for_django is True:
+ # Needs to be logged because Saleor doesn't log handled errors in GraphQL
+ # and we cannot return the error the user as it can reveal internal information
+ logger.info("Received invalid EditorJS input: %s", str(exc))
+ raise ValidationError("Invalid input EditorJS format") from exc
+ raise
+
+
+@overload
+def clean_editorjs(data: dict, *, for_django: bool = True) -> dict: ...
+@overload
+def clean_editorjs(data: None, *, for_django: bool = True) -> None: ...
+
+
+def clean_editorjs(data: dict | None, *, for_django: bool = True) -> dict | None:
+ """Return a cleaned version of the EditorJS input.
+
+ :param dict data: the EditorJS data to validate and to clean.
+ :param bool for_django: Whether to convert exceptions into something django
+ understands. Useful for models and GraphQL as ValidationError is automatically
+ handled. `False` should be passed if we want to handle the errors explicitly
+ or we need verbosity.
+ :raises pydantic.ValidationError: when the input doesn't match the schema/models.
+ Can only be raised when ``for_django=False``.
+ :raises django.core.exceptions.ValidationError: when Saleor checks don't pass.
+ :return: A **copy** of the input dictionary that was cleaned.
+ """
+
+ if data is None:
+ return None
+ return parse_editorjs(data, for_django=for_django).model_dump(exclude_unset=True)
+
+
+def editorjs_to_text(data: dict | None, *, for_django: bool = True) -> str:
+ """Convert EditorJS blocks into plaintext.
+
+ :param bool for_django: Whether to convert exceptions into something django
+ understands. Useful for models and GraphQL as ValidationError is automatically
+ handled. `False` should be passed if we want to handle the errors explicitly
+ or we need verbosity.
+ :raises pydantic.ValidationError: when the input doesn't match the schema/models.
+ Can only be raised when ``for_django=False``.
+ :raises django.core.exceptions.ValidationError: when Saleor checks don't pass.
+ """
+
+ if data is None:
+ return ""
+
+ doc = parse_editorjs(data, for_django=for_django)
+
+ if not doc.blocks:
+ return ""
+
+ text = ""
+ sep = ""
+ for block in doc.blocks:
+ if text:
+ sep = " "
+
+ part = strip_tags(block.to_text())
+ if part:
+ text += f"{sep}{part}"
+ return text
diff --git a/saleor/core/editorjs/models.py b/saleor/core/editorjs/models.py
new file mode 100644
index 0000000000..42f54620fa
--- /dev/null
+++ b/saleor/core/editorjs/models.py
@@ -0,0 +1,453 @@
+from typing import Annotated, Literal, Union
+
+from django.conf import settings
+from django.core.exceptions import ValidationError
+from pydantic import (
+ AfterValidator,
+ BeforeValidator,
+ ConfigDict,
+ Field,
+)
+from pydantic import (
+ BaseModel as UnsafeBaseModel,
+)
+
+from .cleaners import (
+ _clean_meta_dict,
+ _clean_nested_list_items,
+ _clean_text,
+ _clean_url_value,
+)
+from .utils import maybe_to_int
+
+# Note: we use AfterValidator to ensure type stability otherwise we may end up
+# getting other types than ``str | None``
+Text = Annotated[str, AfterValidator(_clean_text)]
+URL = Annotated[str, AfterValidator(_clean_url_value)]
+
+MetaValue = int | float | bool | Text | None
+MetaDict = Annotated[dict[Text, MetaValue], AfterValidator(_clean_meta_dict)]
+ListItem = Union["EditorJSNestedListItemModel", Text, None]
+ListItems = Annotated[
+ list[ListItem] | None,
+ BeforeValidator(_clean_nested_list_items),
+]
+ListStyle = Annotated[
+ Literal["ordered", "unordered", "checklist"] | None,
+ AfterValidator(_clean_text),
+]
+LineantNumeric = Annotated[int | float, BeforeValidator(maybe_to_int)]
+
+
+class StrictBaseModel(UnsafeBaseModel):
+ """Strict version of the pydantic BaseModel.
+
+ Drops any extra field - extra fields could be a XSS vector due to not
+ being cleaned or assessed. For example, upgrading the EditorJS client-side
+ library could lead to new fields being added (thus opening new XSS holes),
+ as well some unofficial client-side libraries add custom (non-official) fields
+ which could be exploited.
+ """
+
+ model_config = ConfigDict(extra="ignore")
+
+
+class SizeDataModel(StrictBaseModel):
+ """An EditorJS ``data`` block that allows to set a size."""
+
+ width: LineantNumeric | None = None
+ height: LineantNumeric | None = None
+
+
+class EditorJSBlock(StrictBaseModel):
+ """Defines a base EditorJS block."""
+
+ def to_text(self) -> str:
+ """Convert the block into a plaintext form."""
+ raise NotImplementedError
+
+
+class EditorJSParagraphDataModel(StrictBaseModel):
+ """Match the data payload for an EditorJS paragraph block.
+
+ Example:
+ {
+ "text": "Hello"
+ }
+
+ """
+
+ text: Text | None = None
+ alignment: Text | None = None
+ align: Text | None = None
+
+
+class EditorJSHeaderDataModel(StrictBaseModel):
+ """Match the data payload for an EditorJS header block.
+
+ Example:
+ {
+ "text": "Title",
+ "level": 2
+ }
+
+ """
+
+ text: Text | None = None
+ level: LineantNumeric | None = None
+ alignment: Text | None = None
+ align: Text | None = None
+
+
+class EditorJSQuoteDataModel(SizeDataModel):
+ """Match the data payload for an EditorJS quote block.
+
+ Example:
+ {
+ "text": "Quote",
+ "caption": "Author"
+ }
+
+ """
+
+ text: Text | None = None
+ caption: Text | None = None
+ alignment: Text | None = None
+ align: Text | None = None
+
+
+class EditorJSEmbedDataModel(SizeDataModel):
+ """Match the data payload for an EditorJS embed block.
+
+ Example:
+ {
+ "embed": "https://www.youtube.com/embed/XXX",
+ "source": "https://youtu.be/XXX"
+ }
+
+ """
+
+ embed: URL | None = None
+ source: URL | None = None
+ caption: Text | None = None
+ service: Text | None = None
+
+
+class ImageFileModel(StrictBaseModel):
+ """Represent ``image.file`` object from EditorJS.
+
+ https://github.com/editor-js/image/blob/d7f0afb5f2e0110dc716941268e6689857a58830/README.md#output-data
+ """
+
+ url: URL | None = None
+
+
+class EditorJSImageDataModel(SizeDataModel):
+ """Match the data payload for an EditorJS image block.
+
+ Example:
+ {
+ "file": {
+ "url" : "https://example.com/image.png"
+ },
+ "caption" : "my caption",
+ "withBorder" : false,
+ "withBackground" : false,
+ "stretched" : true,
+ }
+
+ """
+
+ file: ImageFileModel | None = None
+ caption: Text | None = None
+ withBorder: bool | None = None
+ withBackground: bool | None = None
+ stretched: bool | None = None
+
+ # This is invalid but kept for backward compatibility
+ # (instead, user should put it in file.url)
+ url: URL | None = None
+
+
+class EditorJSNestedListItemModel(StrictBaseModel):
+ """Match an EditorJS nested list item object.
+
+ Example:
+ {
+ "content": "Apples",
+ "items": [
+ {
+ "content": "Apples",
+ "meta": {},
+ "items": [
+ {
+ "content": "Red",
+ "meta": {},
+ "items": []
+ },
+ ]
+ }
+ ],
+ "meta": {}
+ }
+
+ """
+
+ content: Text | None = None
+ items: list["EditorJSNestedListItemModel"] = Field(default_factory=list)
+ meta: MetaDict | None = Field(default_factory=dict)
+
+
+class EditorJSListDataModel(StrictBaseModel):
+ """Match the data payload for an EditorJS list block.
+
+ It encapsulates both legacy (flat lists) and nested (newer) format.
+
+ Example:
+ {
+ "style": "unordered",
+ "items": [
+ "One"
+ ]
+ }
+
+ """
+
+ style: ListStyle = None
+ items: ListItems = None
+ meta: MetaDict | None = Field(default_factory=dict)
+
+ def to_text(
+ self,
+ node: ListItem,
+ *,
+ current_depth: int,
+ max_depth: int,
+ ) -> str:
+ if current_depth > max_depth:
+ raise ValidationError(
+ "Invalid EditorJS list: maximum nesting level exceeded"
+ )
+
+ if isinstance(node, str):
+ return node
+
+ if not node:
+ return ""
+
+ parts = []
+
+ if node.content:
+ parts.append(node.content)
+
+ for item in node.items:
+ if isinstance(item, EditorJSNestedListItemModel):
+ if part := self.to_text(
+ item, current_depth=current_depth + 1, max_depth=max_depth
+ ):
+ parts.append(part)
+ elif isinstance(item, str):
+ if item:
+ parts.append(item)
+ else:
+ raise TypeError(f"Unexpected list member type: {item!r}")
+
+ return " ".join(parts)
+
+
+class EditorJSParagraphBlockModel(EditorJSBlock):
+ """Match an EditorJS paragraph block object.
+
+ Example:
+ {
+ "type": "paragraph",
+ "data": {
+ "text": "Hello"
+ }
+ }
+
+ """
+
+ type: Literal["paragraph"]
+ data: EditorJSParagraphDataModel
+ id: Text | None = None
+
+ def to_text(self) -> str:
+ return self.data.text or ""
+
+
+class EditorJSHeaderBlockModel(EditorJSBlock):
+ """Match an EditorJS header block object.
+
+ Example:
+ {
+ "type": "header",
+ "data": {
+ "text": "Title",
+ "level": 2
+ }
+ }
+
+ """
+
+ type: Literal["header"]
+ data: EditorJSHeaderDataModel
+ id: Text | None = None
+
+ def to_text(self) -> str:
+ return self.data.text or ""
+
+
+class EditorJSListBlockModel(EditorJSBlock):
+ """Match an EditorJS list block object.
+
+ Example:
+ {
+ "type": "list",
+ "data": {
+ "style": "unordered",
+ "items": [
+ "One"
+ ]
+ }
+ }
+
+ """
+
+ type: Literal["list"]
+ data: EditorJSListDataModel
+ id: Text | None = None
+
+ def to_text(self) -> str:
+ if not self.data.items:
+ return ""
+
+ text = ""
+ sep = ""
+ for item in self.data.items:
+ if text:
+ sep = " "
+ part = self.data.to_text(
+ node=item,
+ current_depth=0,
+ max_depth=settings.EDITOR_JS_LISTS_MAX_DEPTH,
+ )
+ if part:
+ text += f"{sep}{part}"
+ return text
+
+
+class EditorJSQuoteBlockModel(EditorJSBlock):
+ """Match an EditorJS quote block object.
+
+ Example:
+ {
+ "type": "quote",
+ "data": {
+ "text": "Quote",
+ "caption": "Author"
+ }
+ }
+
+ """
+
+ type: Literal["quote"]
+ data: EditorJSQuoteDataModel
+ id: Text | None = None
+
+ def to_text(self) -> str:
+ return self.data.text or ""
+
+
+class EditorJSEmbedBlockModel(EditorJSBlock):
+ """Match an EditorJS embed block object.
+
+ Example:
+ {
+ "type": "embed",
+ "data": {
+ "embed": "https://www.youtube.com/embed/dQw4w9WgXcQ",
+ "source": "https://youtu.be/dQw4w9WgXcQ"
+ }
+ }
+
+ """
+
+ type: Literal["embed"]
+ data: EditorJSEmbedDataModel
+ id: Text | None = None
+
+ def to_text(self) -> str:
+ text = ""
+ for field in ("source", "embed", "caption"):
+ if value := getattr(self.data, field, None):
+ sep = "" if not text else " "
+ text += f"{sep}{value}"
+ return text
+
+
+class EditorJSImageBlockModel(EditorJSBlock):
+ """Match an EditorJS image block object.
+
+ Example:
+ {
+ "type" : "image",
+ "data" : {
+ "file": {
+ "url" : "https://example.com/image.png"
+ },
+ "caption" : "my caption",
+ "withBorder" : false,
+ "withBackground" : false,
+ "stretched" : true,
+ }
+ }
+
+ """
+
+ type: Literal["image"]
+ data: EditorJSImageDataModel
+ id: Text | None = None
+
+ # This is invalid but kept for backward compatibility
+ # (instead, user should put it in data.file.url)
+ url: URL | None = None
+
+ def to_text(self) -> str:
+ text = ""
+ sep = ""
+ if self.data.file and (url := self.data.file.url):
+ text += f"{sep}{url}"
+ if text:
+ sep = " "
+ if caption := self.data.caption:
+ text += f"{sep}{caption}"
+ return text
+
+
+EditorJSBlockModel = Annotated[
+ EditorJSParagraphBlockModel
+ | EditorJSHeaderBlockModel
+ | EditorJSListBlockModel
+ | EditorJSQuoteBlockModel
+ | EditorJSEmbedBlockModel
+ | EditorJSImageBlockModel,
+ Field(discriminator="type"),
+]
+
+
+class EditorJSDocumentModel(StrictBaseModel):
+ """Match the root EditorJS document object.
+
+ Example:
+ {
+ "version": "2.29.0",
+ "time": 123456789,
+ "blocks": []
+ }
+
+ """
+
+ version: Text | None = None
+ time: int | float | None = None
+ blocks: list[EditorJSBlockModel] | None = None
diff --git a/saleor/core/editorjs/tests/__init__.py b/saleor/core/editorjs/tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/core/editorjs/tests/conftest.py b/saleor/core/editorjs/tests/conftest.py
new file mode 100644
index 0000000000..760b143abc
--- /dev/null
+++ b/saleor/core/editorjs/tests/conftest.py
@@ -0,0 +1,22 @@
+import pydantic_core
+import pytest
+
+
+def no_link_rel(cleaner_settings):
+ """Disable ``rel`` attribute for links.
+
+ This disables appending `rel="noopener noreferrer"` to link which simplifies
+ tests.
+ """
+ cleaner_settings.link_rel = None
+
+
+def assert_pydantic_errors(
+ exc: pydantic_core.ValidationError, expected_errors: list[dict]
+) -> None:
+ actual_errors = exc.errors()
+ assert len(actual_errors) == len(expected_errors)
+ for idx, err in enumerate(actual_errors):
+ for k, v in expected_errors[idx].items():
+ assert err[k] == v
diff --git a/saleor/core/utils/tests/test_editorjs.py b/saleor/core/editorjs/tests/test_editorjs.py
similarity index 75%
rename from saleor/core/utils/tests/test_editorjs.py
rename to saleor/core/editorjs/tests/test_editorjs.py
index 029f2d423a..8d2e9bc3b4 100644
--- a/saleor/core/utils/tests/test_editorjs.py
+++ b/saleor/core/editorjs/tests/test_editorjs.py
@@ -2,13 +2,16 @@ import json
import warnings
from copy import deepcopy
+import django.core.exceptions
+import pydantic_core
import pytest
-from django.core.exceptions import ValidationError
from django.utils.html import strip_tags
from ...cleaners.html import HtmlCleanerSettings
from ...deprecations import SaleorDeprecationWarning
-from ..editorjs import clean_editor_js, clean_text_data_block, clean_url
+from .. import clean_editorjs, editorjs_to_text
+from ..cleaners import _clean_url_value
+from .conftest import assert_pydantic_errors
DIRTY = "<img src=x onerror=alert(1)>"
CLEAN = '<img src="x">'
@@ -28,6 +31,16 @@ XSS_URLS = [
]
+def assert_paragraph_cleaned(text_input: str, expected_text_output: str) -> None:
+ input = {"blocks": [{"type": "paragraph", "data": {"text": text_input}}]}
+ expected = {
+ "blocks": [{"type": "paragraph", "data": {"text": expected_text_output}}]
+ }
+
+ actual = clean_editorjs(input, for_django=False)
+ assert actual == expected
+
+
@pytest.fixture
def cleaner_settings(settings):
old_prefs = settings.HTML_CLEANER_PREFS
@@ -68,7 +81,7 @@ def cleaner_settings(settings):
)
def test_clean_url(input_url, expected_cleaned_url, is_allowed):
with warnings.catch_warnings(record=True) as warns:
- actual = clean_url(input_url)
+ actual = _clean_url_value(input_url)
expected_warning_count = 0 if is_allowed else 1
assert len(warns) == expected_warning_count
@@ -88,8 +101,8 @@ def test_clean_url(input_url, expected_cleaned_url, is_allowed):
],
)
def test_clean_url_error_handling(input_url: str, expected_error: str):
- with pytest.raises(ValidationError, match=expected_error):
- clean_url(input_url)
+ with pytest.raises(django.core.exceptions.ValidationError, match=expected_error):
+ _clean_url_value(input_url)
def test_clean_url_allows_custom_allow_list(monkeypatch, cleaner_settings):
@@ -102,7 +115,7 @@ def test_clean_url_allows_custom_allow_list(monkeypatch, cleaner_settings):
# Should refuse the URL scheme if it's not allowed
with warnings.catch_warnings(record=True):
- assert clean_url(url) == "#invalid"
+ assert _clean_url_value(url) == "#invalid"
# Catches warnings due to deprecation notices from Saleor (v3.23.0)
with warnings.catch_warnings(record=True):
@@ -111,10 +124,10 @@ def test_clean_url_allows_custom_allow_list(monkeypatch, cleaner_settings):
# When allowed it should allow the use of that URL scheme even if a cleaner
# isn't defined.
- assert clean_url(url) == url
- assert clean_url("other:") == "other:"
+ assert _clean_url_value(url) == url
+ assert _clean_url_value("other:") == "other:"
with warnings.catch_warnings(record=True):
- assert clean_url("not-ok:") == "#invalid"
+ assert _clean_url_value("not-ok:") == "#invalid"
@pytest.mark.parametrize(
@@ -194,8 +207,7 @@ def test_clean_url_allows_custom_allow_list(monkeypatch, cleaner_settings):
],
)
def test_clean_text_data_block(_case: str, text: str, expected_cleaned_text: str):
- actual = clean_text_data_block(text)
- assert actual == expected_cleaned_text
+ assert_paragraph_cleaned(text, expected_cleaned_text)
@pytest.mark.parametrize(
@@ -235,8 +247,7 @@ def test_clean_text_data_block_allow_custom_attributes(
)
cleaner_settings.reload()
- actual = clean_text_data_block(html_input)
- assert actual == expected_output
+ assert_paragraph_cleaned(html_input, expected_output)
@pytest.mark.parametrize(
@@ -302,72 +313,68 @@ def test_clean_text_data_block_allow_custom_attribute_values(
)
cleaner_settings.reload()
- actual = clean_text_data_block(html_input)
- assert actual == expected_output
+ assert_paragraph_cleaned(html_input, expected_output)
@pytest.mark.parametrize(
- "text",
+ ("input_html", "expected_output_html"),
[
- "The Saleor Winter Sale is snowed under with seasonal offers. Unreal products "
- "at unreal prices. Literally, they are not real products, but the Saleor demo "
- "store is a genuine e-commerce leader.",
- 'The Saleor Winter Sale is snowed <a href="https://docs.saleor.io/">',
- 'The Saleor Sale is snowed <a href="https://docs.saleor.io/">. Test.',
- 'The Saleor Winter Sale is snowed <a href="https://docs.saleor.io/">. '
- 'Test <a href="https://docs.saleor.io/">.',
- "",
- "The Saleor Winter Sale is snowed <a >",
+ (
+ (
+ "The Saleor Winter Sale is snowed under with seasonal offers. Unreal products "
+ "at unreal prices. Literally, they are not real products, but the Saleor demo "
+ "store is a genuine e-commerce leader."
+ 'The Saleor Winter Sale is snowed <a href="https://docs.saleor.io/"></a>'
+ 'The Saleor Sale is snowed <a href="https://docs.saleor.io/">Test</a>.'
+ ""
+ "The Saleor Winter Sale is snowed <a >"
+ ),
+ (
+ "The Saleor Winter Sale is snowed under with seasonal offers. Unreal products "
+ "at unreal prices. Literally, they are not real products, but the Saleor demo "
+ "store is a genuine e-commerce leader."
+ 'The Saleor Winter Sale is snowed <a href="https://docs.saleor.io/"></a>'
+ 'The Saleor Sale is snowed <a href="https://docs.saleor.io/">Test</a>.'
+ ""
+ "The Saleor Winter Sale is snowed <a></a>"
+ ),
+ )
],
)
-def test_clean_editor_js(text):
+def test_clean_editor_js(input_html: str, expected_output_html: str, no_link_rel):
# given
- data = {"blocks": [{"data": {"text": text}, "type": "paragraph"}]}
-
- # when
- result = clean_editor_js(data)
-
- # then
- assert result == data
-
- # when
- result = clean_editor_js(data, to_string=True)
-
- # then
- assert result == strip_tags(text)
-
-
-def test_clean_editor_js_no_blocks():
- # given
- data = {}
+ input_data = {"blocks": [{"data": {"text": input_html}, "type": "paragraph"}]}
+ expected_output = {
+ "blocks": [{"data": {"text": expected_output_html}, "type": "paragraph"}]
+ }
# when
- result = clean_editor_js(data)
+ result = clean_editorjs(input_data, for_django=False)
# then
- assert result == data
+ assert result == expected_output
# when
- result = clean_editor_js(data, to_string=True)
+ result = editorjs_to_text(input_data)
# then
- assert result == ""
-
-
-def test_clean_editor_js_no_data():
- # given
- data = {"blocks": []}
-
- # when
- result = clean_editor_js(data)
+ assert result == strip_tags(expected_output_html)
- # then
- assert result == data
- # when
- result = clean_editor_js(data, to_string=True)
+ ("_case", "input_data", "expected_dict_out"),
+ [
+ ("No block provided", {}, {}),
+ ("Empty block list", {"blocks": []}, {"blocks": []}),
+ ],
+)
+def test_clean_editor_js_no_blocks(
+ _case: str, input_data: dict, expected_dict_out: dict
+):
+ result = clean_editorjs(input_data, for_django=False)
+ assert result == expected_dict_out
- # then
+ result = editorjs_to_text(input_data)
assert result == ""
@@ -389,7 +396,7 @@ def test_clean_editor_js_invalid_url():
}
# when
- result = clean_editor_js(data)
+ result = clean_editorjs(data, for_django=False)
# then
cleaned_text = result["blocks"][0]["data"]["text"]
@@ -398,14 +405,14 @@ def test_clean_editor_js_invalid_url():
assert "The Saleor Winter Sale" in cleaned_text
-def test_clean_editor_js_for_list():
+def test_clean_editor_js_for_list(no_link_rel):
# given
data = {
"blocks": [
{
"data": {
"text": "The Saleor Winter Sale is snowed "
- '<a href="https://docs.saleor.io/">. Test.'
+ '<a href="https://docs.saleor.io/">Test</a>.'
},
"type": "paragraph",
},
@@ -415,7 +422,7 @@ def test_clean_editor_js_for_list():
"style": "unordered",
"items": [
"It is a block-styled editor "
- '<a href="https://docs.saleor.io/">.',
+ '<a href="https://docs.saleor.io/"></a>.',
"It returns clean data output in JSON",
"Designed to be extendable and pluggable with a simple API",
"",
@@ -426,18 +433,18 @@ def test_clean_editor_js_for_list():
}
# when
- result = clean_editor_js(data)
+ result = clean_editorjs(data, for_django=False)
# then
assert result == data
# when
- result = clean_editor_js(data, to_string=True)
+ result = editorjs_to_text(data)
# then
assert result == strip_tags(
"The Saleor Winter Sale is snowed "
- '<a href="https://docs.saleor.io/">. Test.'
+ '<a href="https://docs.saleor.io/">Test</a>.'
" It is a block-styled editor "
'<a href="https://docs.saleor.io/">.'
" It returns clean data output in JSON"
@@ -470,7 +477,7 @@ def test_clean_editor_js_for_list_invalid_url():
}
# when
- result = clean_editor_js(data)
+ result = clean_editorjs(data, for_django=False)
# then
# Paragraph with invalid url should be cleaned
@@ -488,14 +495,14 @@ def test_clean_editor_js_for_list_invalid_url():
)
-def test_clean_editor_js_for_complex_description():
+def test_clean_editor_js_for_complex_description(no_link_rel):
# given
data = {
"blocks": [
{
"data": {
- "text": "The Saleor Winter Sale is snowed"
- '<a href="https://docs.saleor.io/">. Test.'
+ "text": "The Saleor Winter Sale is snowed "
+ '<a href="https://docs.saleor.io/">Test</a>.'
},
"type": "paragraph",
},
@@ -556,18 +563,18 @@ def test_clean_editor_js_for_complex_description():
}
# when
- result = clean_editor_js(data)
+ result = clean_editorjs(data, for_django=False)
# then
assert result == data
# when
- result = clean_editor_js(data, to_string=True)
+ result = editorjs_to_text(data)
# then
assert result == strip_tags(
- "The Saleor Winter Sale is snowed"
- '<a href="https://docs.saleor.io/">. Test.'
+ "The Saleor Winter Sale is snowed "
+ '<a href="https://docs.saleor.io/">Test</a>.'
" The one thing you be sure of is: Polish winters are quite"
" unpredictable. The coldest months are January and February"
" with temperatures around -3.0 °C (on average), but the"
@@ -599,7 +606,7 @@ def test_clean_editor_js_for_malicious_value():
}
# when
- result = clean_editor_js(data)
+ result = clean_editorjs(data, for_django=False)
# then
# Malicious elements should be stripped.
@@ -618,7 +625,7 @@ def test_clean_editor_js_image_invalid_url():
# when
with warnings.catch_warnings(record=True) as warns:
- result = clean_editor_js(data)
+ result = clean_editorjs(data, for_django=False)
assert len(warns) == 1
assert "disallowed URL was sent" in str(warns[0].message)
@@ -634,7 +641,7 @@ def test_clean_editor_js_image_disallowed_scheme():
# when
with warnings.catch_warnings(record=True) as warns:
- result = clean_editor_js(data)
+ result = clean_editorjs(data, for_django=False)
assert len(warns) == 1
assert "disallowed URL was sent" in str(warns[0].message)
@@ -643,8 +650,49 @@ def test_clean_editor_js_image_disallowed_scheme():
assert result["blocks"][0]["data"]["file"]["url"] == "#invalid"
+def test_clean_editorjs_image_can_put_extras():
+ """Ensure user can provide extra fields in 'data.image.file' without error.
+
+ This shouldn't be rejected, but any extra field provided should be automatically
+ deleted by Pydantic in order to prevent XSS attacks against unknown/unsupported
+ fields.
+
+ This is needed due to EditorJS specs stating that data.image.file can contain
+ anything.
+ """
+
+ input_data = {
+ "blocks": [
+ {
+ "type": "image",
+ "data": {
+ "file": {
+ # OK: known field
+ "url": "https://example.com/image.png",
+ # Unknown fields, thus should be dropped (but shouldn't return an
+ # error)
+ "foo": "bar",
+ DIRTY: DIRTY,
+ }
+ },
+ }
+ ]
+ }
+ expected_output = {
+ "blocks": [
+ {
+ "type": "image",
+ "data": {"file": {"url": "https://example.com/image.png"}},
+ }
+ ]
+ }
+
+ actual_output = clean_editorjs(input_data, for_django=False)
+ assert actual_output == expected_output
+
+
@pytest.mark.parametrize(
- ("_case", "data", "expected_results"),
+ ("_case", "data", "expected_results", "expected_errors"),
[
(
"Should clean list items",
@@ -663,6 +711,7 @@ def test_clean_editor_js_image_disallowed_scheme():
"items": ['<img src="invalid">'],
},
},
+ None,
),
(
"Should be able to clean when 1st item is empty",
@@ -681,6 +730,7 @@ def test_clean_editor_js_image_disallowed_scheme():
"items": ["", '<img src="invalid">'],
},
},
+ None,
),
(
"Should clean the style field",
@@ -692,17 +742,22 @@ def test_clean_editor_js_image_disallowed_scheme():
},
},
# Expects:
- {
- "type": "list",
- "data": {
- "style": 'unordered"/&gt;',
- "items": [],
- },
- },
+ None,
+ [
+ {
+ "loc": ("blocks", 0, "list", "data", "style"),
+ "msg": "Input should be 'ordered', 'unordered' or 'checklist'",
+ }
+ ],
),
],
)
-def test_clean_editorjs_legacy(_case: str, data: dict, expected_results: dict):
+def test_clean_editorjs_legacy(
+ _case: str,
+ data: dict,
+ expected_results: dict | None,
+ expected_errors: list[dict] | None,
+):
"""Ensure that legacy lists (non-nested) are supported.
Format: https://github.com/editor-js/list-legacy/blob/381254443234ebbec9cc508fa8a7b982b6a79418/README.md#output-data
@@ -710,11 +765,22 @@ def test_clean_editorjs_legacy(_case: str, data: dict, expected_results: dict):
data = {"blocks": [data]}
- actual_results = clean_editor_js(data)
- blocks = actual_results["blocks"]
- assert len(blocks) == 1
+ actual_results = None
+ err = None
- assert blocks[0] == expected_results
+ try:
+ actual_results = clean_editorjs(data, for_django=False)
+ except pydantic_core.ValidationError as exc:
+ err = exc
+
+ if expected_errors is not None:
+ assert err is not None
+ assert_pydantic_errors(err, expected_errors)
+ else:
+ assert err is None
+ blocks = actual_results["blocks"]
+ assert len(blocks) == 1
+ assert blocks == [expected_results]
@pytest.mark.parametrize(
@@ -764,7 +830,7 @@ def test_clean_editorjs_legacy(_case: str, data: dict, expected_results: dict):
},
),
(
- "Nulled meta is OK",
+ "Null meta is OK",
{
"type": "list",
"data": {
@@ -778,7 +844,7 @@ def test_clean_editorjs_legacy_works_for_valid_inputs(_case: str, data: dict):
data = {"blocks": [data]}
expected = deepcopy(data)
- actual = clean_editor_js(data)
+ actual = clean_editorjs(data, for_django=False)
# Valid data shouldn't have alterated
assert actual == expected
@@ -787,7 +853,7 @@ def test_clean_editorjs_legacy_works_for_valid_inputs(_case: str, data: dict):
@pytest.mark.parametrize(
("_case", "data", "expected_error"),
[
- ("Missing type", {}, "Missing required key: 'type'"),
+ ("Missing type", {}, "Unable to extract tag using discriminator 'type'"),
(
"Items invalid type",
{
@@ -796,7 +862,7 @@ def test_clean_editorjs_legacy_works_for_valid_inputs(_case: str, data: dict):
"items": 1,
},
},
- "Invalid EditorJS list: items property must be an array",
+ "Input should be a valid list",
),
(
"Items invalid type inside array",
@@ -806,7 +872,7 @@ def test_clean_editorjs_legacy_works_for_valid_inputs(_case: str, data: dict):
"items": [1],
},
},
- "Invalid EditorJS list: items must be either a string or an object",
+ "Input should be a valid dictionary or instance of EditorJSNestedListItemModel",
),
(
"Items invalid type inside array after valid value",
@@ -816,7 +882,7 @@ def test_clean_editorjs_legacy_works_for_valid_inputs(_case: str, data: dict):
"items": ["valid", 1],
},
},
- "Invalid EditorJS list: items must be strings",
+ "Input should be a valid dictionary or instance of EditorJSNestedListItemModel",
),
(
"Items invalid type inside style field",
@@ -827,7 +893,7 @@ def test_clean_editorjs_legacy_works_for_valid_inputs(_case: str, data: dict):
"items": ["valid"],
},
},
- "Invalid EditorJS list: style property must be a string",
+ "Input should be 'ordered', 'unordered' or 'checklist'",
),
],
)
@@ -838,8 +904,10 @@ def test_clean_editorjs_legacy_rejects_invalid(
data = {"blocks": [data]}
- with pytest.raises(ValidationError, match=expected_error):
- clean_editor_js(data)
+ with pytest.raises(pydantic_core.ValidationError) as exc:
+ clean_editorjs(data, for_django=False)
+
+ assert expected_error in str(exc.value)
@pytest.mark.parametrize(
@@ -1008,7 +1076,7 @@ def test_clean_editorjs_legacy_rejects_invalid(
def test_cleans_editorjs_nested_lists(_case: str, data: dict, expected_results: dict):
data = {"blocks": [data]}
- actual = clean_editor_js(data)
+ actual = clean_editorjs(data, for_django=False)
blocks = actual["blocks"]
assert len(blocks) == 1
@@ -1017,7 +1085,7 @@ def test_cleans_editorjs_nested_lists(_case: str, data: dict, expected_results:
@pytest.mark.parametrize(
- ("_case", "data", "expected_error"),
+ ("_case", "data", "expected_errors"),
[
(
"Item contains invalid type",
@@ -1041,7 +1109,34 @@ def test_cleans_editorjs_nested_lists(_case: str, data: dict, expected_results:
],
},
},
- "Invalid EditorJS list: items must be objects",
+ [
+ {
+ "loc": (
+ "blocks",
+ 0,
+ "list",
+ "data",
+ "items",
+ 0,
+ "EditorJSNestedListItemModel",
+ "items",
+ 1,
+ ),
+ "msg": "Input should be a valid dictionary or instance of EditorJSNestedListItemModel",
+ },
+ {
+ "loc": (
+ "blocks",
+ 0,
+ "list",
+ "data",
+ "items",
+ 0,
+ "function-after[_clean_text(), str]",
+ ),
+ "msg": "Input should be a valid string",
+ },
+ ],
),
(
"Invalid type in meta",
@@ -1049,10 +1144,32 @@ def test_cleans_editorjs_nested_lists(_case: str, data: dict, expected_results:
"type": "list",
"data": {"meta": {"key": object()}},
},
- (
- "Invalid meta block for EditorJS: value of a meta must either a string, "
- "an integer, or a float"
- ),
+ [
+ {
+ "loc": ("blocks", 0, "list", "data", "meta", "key", "int"),
+ "msg": "Input should be a valid integer",
+ },
+ {
+ "loc": ("blocks", 0, "list", "data", "meta", "key", "float"),
+ "msg": "Input should be a valid number",
+ },
+ {
+ "loc": ("blocks", 0, "list", "data", "meta", "key", "bool"),
+ "msg": "Input should be a valid boolean",
+ },
+ {
+ "loc": (
+ "blocks",
+ 0,
+ "list",
+ "data",
+ "meta",
+ "key",
+ "function-after[_clean_text(), str]",
+ ),
+ "msg": "Input should be a valid string",
+ },
+ ],
),
(
"Too many fields in meta",
@@ -1060,15 +1177,50 @@ def test_cleans_editorjs_nested_lists(_case: str, data: dict, expected_results:
"type": "list",
"data": {"meta": {str(i): i for i in range(11)}},
},
- "Invalid meta block for EditorJS: too many fields",
+ [
+ {
+ "loc": ("blocks", 0, "list", "data", "meta"),
+ "msg": "Value error, Invalid meta block for EditorJS: too many fields",
+ }
+ ],
),
(
"Keys must be a string",
{"type": "list", "data": {"meta": {1: "string"}}},
- "Invalid property for a meta member for EditorJS: must a string",
+ [
+ {
+ "loc": ("blocks", 0, "list", "data", "meta", 1, "[key]"),
+ "msg": "Input should be a valid string",
+ }
+ ],
),
- (
- "List too deep",
+ ],
+)
+def test_clean_editorjs_rejects_invalid_nested_lists(
+ _case: str,
+ data: dict,
+ expected_errors: list[dict],
+ settings,
+):
+ """Ensure when invalid data is provided a nested lists, it's rejected."""
+
+ settings.EDITOR_JS_LISTS_MAX_DEPTH = 3
+
+ data = {"blocks": [data]}
+
+ with pytest.raises(pydantic_core.ValidationError) as exc:
+ clean_editorjs(data, for_django=False)
+
+ assert_pydantic_errors(exc.value, expected_errors)
+
+
+def test_clean_editorjs_rejects_too_deep_nested_list(settings):
+ """A nested list that's too deep should be rejected as it's likely malicious."""
+
+ settings.EDITOR_JS_LISTS_MAX_DEPTH = 3
+
+ data = {
+ "blocks": [
{
"type": "list",
"data": {
@@ -1089,24 +1241,14 @@ def test_cleans_editorjs_nested_lists(_case: str, data: dict, expected_results:
]
},
},
- "Invalid EditorJS list: maximum nesting level exceeeded",
- ),
- ],
-)
-def test_clean_editorjs_rejects_invalid_nested_lists(
- _case: str,
- data: dict,
- expected_error: str,
- settings,
-):
- """Ensure when invalid data is provided a nested lists, it's rejected."""
-
- settings.EDITOR_JS_LISTS_MAX_DEPTH = 3
-
- data = {"blocks": [data]}
+ ]
+ }
- with pytest.raises(ValidationError, match=expected_error):
- clean_editor_js(data)
+ with pytest.raises(
+ django.core.exceptions.ValidationError,
+ match="Invalid EditorJS list: maximum nesting level exceeded",
+ ):
+ clean_editorjs(data, for_django=False)
def test_heading_level_cleaned():
@@ -1114,13 +1256,21 @@ def test_heading_level_cleaned():
data_input = {"type": "header", "data": {"level": DIRTY}}
- with pytest.raises(ValidationError, match="Heading level must be an integer"):
- clean_editor_js({"blocks": [data_input]})
+ with pytest.raises(pydantic_core.ValidationError) as exc:
+ clean_editorjs({"blocks": [data_input]}, for_django=False)
+
+ error_list = exc.value.errors()
+ assert len(error_list) == 1
+
+ [err] = error_list
+ assert err["input"] == DIRTY
+ assert err["loc"] == ("blocks", 0, "header", "data", "level")
+ assert err["msg"] == "Value error, Value must be an integer"
@pytest.mark.parametrize("block_type", ["image", "quote", "embed"])
@pytest.mark.parametrize(
- ("data_field", "expected_results", "excepted_error"),
+ ("data_field", "expected_results", "expected_errors"),
[
(
{"width": "1", "height": "1"},
@@ -1137,12 +1287,22 @@ def test_heading_level_cleaned():
(
{"width": DIRTY},
None,
- "width must be an integer",
+ [
+ {
+ "msg": "Value error, Value must be an integer",
+ "input": DIRTY,
+ }
+ ],
),
(
{"height": DIRTY},
None,
- "height must be an integer",
+ [
+ {
+ "msg": "Value error, Value must be an integer",
+ "input": DIRTY,
+ }
+ ],
),
],
)
@@ -1150,21 +1310,22 @@ def test_cleans_size_caption_blocks(
block_type: str,
data_field: dict,
expected_results: dict | None,
- excepted_error: str | None,
+ expected_errors: list[dict] | None,
):
"""Ensure all block types that have a caption field have their size fields cleaned."""
data = {"blocks": [{"type": block_type, "data": data_field}]}
error = None
+ actual = None
try:
- actual = clean_editor_js(data)
- except ValidationError as exc:
+ actual = clean_editorjs(data, for_django=False)
+ except pydantic_core.ValidationError as exc:
error = exc
- if excepted_error is not None:
+ if expected_errors is not None:
assert error is not None, "Expected an error but didn't find one"
- assert error.message == excepted_error
+ assert_pydantic_errors(error, expected_errors)
else:
assert error is None, "Didn't expect an error"
@@ -1279,9 +1440,26 @@ def test_cleans_all_editor_js_blocks(_case, data, expected_data):
"""Check all block types supported by Saleor and ensure they all gets cleaned."""
with warnings.catch_warnings(record=True):
- actual = clean_editor_js({"blocks": [data]})
+ actual = clean_editorjs({"blocks": [data]}, for_django=False)
assert len(actual["blocks"]) == 1
actual = actual["blocks"][0]
assert actual == expected_data
+
+
+ ("for_django", "expected_exception_cls"),
+ [
+ (True, django.core.exceptions.ValidationError),
+ (False, pydantic_core.ValidationError),
+ ],
+)
+def test_converts_exceptions_to_django(
+ for_django: bool, expected_exception_cls: type[BaseException]
+):
+ """Passing ``for_django=True`` it raise a Django exception instead of pydantic."""
+
+ input_data = {"blocks": 1}
+ with pytest.raises(expected_exception_cls):
+ clean_editorjs(input_data, for_django=for_django)
diff --git a/saleor/core/editorjs/tests/test_lists.py b/saleor/core/editorjs/tests/test_lists.py
new file mode 100644
index 0000000000..6831620f34
--- /dev/null
+++ b/saleor/core/editorjs/tests/test_lists.py
@@ -0,0 +1,97 @@
+import pytest
+
+from ...editorjs import editorjs_to_text
+
+
+ ("_case", "input_data", "expected_output"),
+ [
+ ("Missing items", {}, ""),
+ ("Missing null items", {"items": None}, ""),
+ ("Empty list", {"items": []}, ""),
+ ("List with 1 item", {"items": ["Item 1"]}, "Item 1"),
+ ("List with 2 items", {"items": ["Item 1", "Item 2"]}, "Item 1 Item 2"),
+ ],
+)
+def test_legacy_lists_to_text(_case: str, input_data: dict, expected_output: str):
+ """Legacy list format should successfully be transformed to text."""
+
+ data = {"blocks": [{"type": "list", "data": input_data}]}
+
+ actual_output = editorjs_to_text(data)
+ assert actual_output == expected_output
+
+
+ ("_case", "input_data", "expected_output"),
+ [
+ (
+ "1-deep list",
+ {
+ "items": [
+ {
+ "content": "Apples",
+ "meta": {},
+ "items": [],
+ }
+ ]
+ },
+ "Apples",
+ ),
+ (
+ "3-deep list",
+ {
+ "items": [
+ {
+ "content": "1 deep",
+ "meta": {},
+ "items": [
+ {
+ "content": "2 deep",
+ "meta": {},
+ "items": [
+ {
+ "content": "3 deep",
+ "meta": {},
+ "items": [],
+ }
+ ],
+ }
+ ],
+ }
+ ]
+ },
+ "1 deep 2 deep 3 deep",
+ ),
+ (
+ "List with surrounding items",
+ {
+ "items": [
+ {
+ "content": "level 1 - 1st member",
+ "meta": {},
+ "items": [],
+ },
+ {
+ "content": "level 1 - 2nd member",
+ "items": [{"items": [{"content": "level 2 member"}]}],
+ },
+ {"content": "level 1 - 3rd member"},
+ ]
+ },
+ (
+ "level 1 - 1st member "
+ "level 1 - 2nd member "
+ "level 2 member "
+ "level 1 - 3rd member"
+ ),
+ ),
+ ],
+)
+def test_nested_lists_to_text(_case: str, input_data: dict, expected_output: str):
+ """Nested list format should successfully be transformed to text."""
+
+ data = {"blocks": [{"type": "list", "data": input_data}]}
+
+ actual_output = editorjs_to_text(data)
+ assert actual_output == expected_output
diff --git a/saleor/core/editorjs/utils.py b/saleor/core/editorjs/utils.py
new file mode 100644
index 0000000000..9a9de479f2
--- /dev/null
+++ b/saleor/core/editorjs/utils.py
@@ -0,0 +1,18 @@
+from typing import Any
+
+
+def maybe_to_int(o: Any) -> int:
+ """Cast a given object to an integer if it's possible, otherwise it raises.
+
+ It's a lenient parsing for backward compatibility.
+ """
+
+ if isinstance(o, str):
+ if o.isnumeric() is False:
+ raise ValueError("Value must be an integer")
+ return int(o)
+
+ if isinstance(o, int) is False:
+ raise ValueError("Value must be an integer")
+
+ return o
diff --git a/saleor/core/management/commands/clean_editorjs_fields.py b/saleor/core/management/commands/clean_editorjs_fields.py
index 8769aefb28..208bc86556 100644
--- a/saleor/core/management/commands/clean_editorjs_fields.py
+++ b/saleor/core/management/commands/clean_editorjs_fields.py
@@ -23,7 +23,7 @@ from ....product.models import (
ProductTranslation,
)
from ....shipping.models import ShippingMethod, ShippingMethodTranslation
-from ...utils.editorjs import clean_editor_js
+from ...editorjs import clean_editorjs
# ((<model class>, <field to clean>), ...)
MODELS: tuple[tuple[type[models.Model], str], ...] = (
@@ -199,12 +199,12 @@ class Command(BaseCommand):
continue
# Dump to string before cleaning as the object will be mutated
- before = json.dumps(contents, indent=2)
+ before = json.dumps(contents, indent=2, sort_keys=True)
# Perform the cleaning
try:
- cleaned = clean_editor_js(contents)
+ cleaned = clean_editorjs(contents)
except (KeyError, ValidationError, ValueError) as exc:
msg = f"Found invalid data for row #{row.pk} ({table_name})"
if self.stop_on_error is True:
@@ -217,7 +217,7 @@ class Command(BaseCommand):
)
continue
- after = json.dumps(cleaned, indent=2)
+ after = json.dumps(cleaned, indent=2, sort_keys=True)
if after == before:
continue
diff --git a/saleor/core/utils/editorjs.py b/saleor/core/utils/editorjs.py
deleted file mode 100644
index 8716de5d06..0000000000
--- a/saleor/core/utils/editorjs.py
+++ /dev/null
@@ -1,521 +0,0 @@
-import warnings
-from typing import Any, Literal, TypedDict, cast, overload
-
-import nh3
-from django.conf import settings
-from django.core.exceptions import ValidationError
-from django.utils.html import strip_tags
-from urllib3.util import parse_url
-
-from ..cleaners import URL_SCHEME_CLEANERS, URLCleanerError
-
-# An allow list that lists the supported block types for ``clean_text_items()``
-# We return an error when the type is not part of the allow list
-# as a safety measure.
-#
-# Note: we only support the types that the Saleor Dashboard implements;
-# they are listed here: https://github.com/saleor/saleor-dashboard/blob/2b2311eb2a0a98567efbbe5eef5c3daf66eeeb92/pnpm-lock.yaml#L38-L49
-ALLOWED_TEXT_BLOCK_TYPES = ("paragraph", "header", "quote")
-
-ITEM_TYPE_TO_CLEAN_FUNC_MAP = {
- "image": lambda *params: clean_image_item(*params),
- "embed": lambda *params: clean_embed_item(*params),
- "quote": lambda *params: clean_quote_item(*params),
-}
-
-ALLOWED_URL_SCHEMES = {
- # WARNING: do NOT add new schemes in directly to this list, only HTTP and HTTPS
- # should be listed as they are cleaned by urllib3. Instead, add it to
- # URL_SCHEME_CLEANERS and implement a cleaner that (at minimum) quotes
- # special characters like "'<> and ASCII control characters
- # (use urllib.util.parse.quote())
- "http",
- "https",
- *URL_SCHEME_CLEANERS.keys(),
-}
-
-
-def maybe_to_int(o: Any, *, name: str) -> int:
- """Cast a given object to an integer if it's possible, otherwise it raises.
-
- It's a lenient parsing for backward compatibility.
- """
-
- if isinstance(o, str):
- if o.isnumeric() is False:
- raise ValidationError(f"{name} must be an integer")
- return int(o)
-
- if isinstance(o, int) is False:
- raise ValidationError(f"{name} must be an integer")
-
- return o
-
-
-class NestedListItemType(TypedDict):
- """The EditorJS inner items of a nested list.
-
- Example:
- {
- "type" : "list",
- "data" : {
- "style": "ordered",
- "meta": {
- "start": 2,
- "counterType": "upper-roman",
- },
- "items" : [
- { # <---
- "content": "Apples", # <---
- "meta": {}, # <---
- "items": [ # <---
- {
- "content": "Red",
- "meta": {},
- "items": []
- },
- ]
- },
- ]
- }
- }
-
- """
-
- content: str # The text
- meta: dict
- items: list["NestedListItemType"]
-
-
-class NestedListBlockType(TypedDict):
- """The EditorJS outer block of a nested list.
-
- Example:
- {
- "type" : "list",
- "data" : {
- "style": "ordered", # <---
- "meta": { # <---
- "start": 2, # <---
- "counterType": "upper-roman", # <---
- }, # <---
- "items" : [ # <---
- {
- "content": "Apples",
- "meta": {},
- "items": [
- {
- "content": "Red",
- "meta": {},
- "items": []
- },
- ]
- },
- ]
- }
- }
-
- """
-
- style: str
- meta: dict
- items: list["NestedListItemType"]
-
-
-@overload
-def clean_editor_js(
- definitions: dict | str | None, *, to_string: Literal[True]
-) -> str: ...
-
-
-@overload
-def clean_editor_js(definitions: dict) -> dict: ...
-
-
-@overload
-def clean_editor_js(definitions: None) -> None: ...
-
-
-def clean_editor_js(definitions, *, to_string=False) -> dict | str | None:
- """Sanitize a given EditorJS JSON definitions.
-
- Look for not allowed URLs, replaced them with `invalid` value, and clean valid ones.
-
- `to_string` flag is used for returning concatenated string from all blocks
- instead of returning json object.
- """
- if definitions is None:
- return "" if to_string else definitions
-
- blocks = definitions.get("blocks")
-
- if not blocks or not isinstance(blocks, list):
- return "" if to_string else definitions
-
- plain_text_list: list[str] = []
-
- for index, block in enumerate(blocks):
- block_type = block.get("type")
-
- if not block_type or isinstance(block_type, str) is False:
- raise ValidationError("Missing required key: 'type'")
-
- data = block.get("data")
- if not data or not isinstance(data, dict):
- continue
-
- params = [blocks, block, plain_text_list, to_string, index]
- if clean_func := ITEM_TYPE_TO_CLEAN_FUNC_MAP.get(block_type):
- for field in ("width", "height"):
- if (field_value := data.get(field)) is not None:
- data[field] = maybe_to_int(field_value, name=field)
- clean_func(*params)
- elif block_type == "list":
- clean_list_item(
- block=block,
- to_string=to_string,
- plain_text_list=plain_text_list,
- max_depth=settings.EDITOR_JS_LISTS_MAX_DEPTH,
- )
- else:
- clean_text_items(*params, block_type=block_type)
-
- return " ".join(plain_text_list) if to_string else definitions
-
-
-def clean_legacy_list(items: list[str], *, to_string: bool, plain_text_list: list[str]):
- for item_index, item in enumerate(items):
- if isinstance(item, str) is False:
- # Mixing types or version (legacy vs new lists) isn't allowed by Saleor,
- # nor by EditorJS.
- raise ValidationError("Invalid EditorJS list: items must be strings")
-
- if to_string:
- # Only appends the text if it's not empty as we do a `' '.join(...)`
- # i.e., otherwise it will create unneeded (and ugly) whitespaces.
- if item:
- plain_text_list.append(strip_tags(item))
- else:
- new_text = clean_text_data_block(item)
- items[item_index] = new_text
-
-
-def clean_meta_block(block: NestedListItemType | dict) -> None:
- """Clean the meta property of a given block.
-
- Args:
- block: the EditorJS block to clean which contains (or may contain) the 'meta' key
- at the root of the object.
-
- """
-
- key_count = 0
-
- meta = block.get("meta") or {}
- if isinstance(meta, (dict)) is False:
- raise ValidationError(
- "Invalid meta block for EditorJS: meta property must be an object"
- )
-
- for k, v in meta.items():
- # Validate the key
- if isinstance(k, str) is False:
- raise ValidationError(
- "Invalid property for a meta member for EditorJS: must a string"
- )
-
- # Validate the value
- if isinstance(v, str):
- meta[k] = clean_text_data_block(v)
- elif isinstance(v, int | float | bool) is False and v is not None:
- raise ValidationError(
- "Invalid meta block for EditorJS: value of a meta must either "
- "a string, an integer, or a float"
- )
-
- # Stop processing if an excessive key count is found
- key_count += 1
- if key_count > 10:
- raise ValidationError("Invalid meta block for EditorJS: too many fields")
-
-
-def clean_nested_list(
- items: list[NestedListItemType],
- *,
- current_depth: int,
- max_depth: int,
- to_string: bool,
- plain_text_list: list[str],
-):
- # Note: this already validated by ``clean_list_item()`` however, we still need
- # to perform this check as we are doing recursive checks which thus weren't
- # checked yet.
- if isinstance(items, list) is False:
- raise ValidationError("Invalid EditorJS list: items must be inside an array")
-
- if current_depth > max_depth:
- raise ValidationError("Invalid EditorJS list: maximum nesting level exceeeded")
-
- for item in items:
- if isinstance(item, dict) is False:
- # Mixing types or version (legacy vs new lists) isn't allowed by Saleor,
- # nor by EditorJS.
- raise ValidationError("Invalid EditorJS list: items must be objects")
-
- text = item.get("content", "")
- if isinstance(text, str) is False:
- raise ValidationError(
- "Invalid EditorJS list: the text contents must be a string"
- )
-
- if to_string:
- # Only append the text if it's not empty as we do a `' '.join(...)`
- # i.e., otherwise it will create unneeded (and ugly) whitespaces.
- if text:
- plain_text_list.append(strip_tags(text))
- else:
- item["content"] = clean_text_data_block(text)
- clean_meta_block(item)
-
- # Cleans the children (if any)
- clean_nested_list(
- items=item.get("items", []),
- current_depth=current_depth + 1,
- max_depth=max_depth,
- to_string=to_string,
- plain_text_list=plain_text_list,
- )
-
-
-def clean_list_item(
- block: dict,
- plain_text_list,
- to_string: bool,
- *,
- max_depth: int,
-):
- """Clean EditorJS lists, both legacy (non-nested) and the latest format (nested).
-
- Args:
- blocks: the list of blocks inside the EditorJS data that we are currently
- cleaning.
-
- block: the block to clean (`type: list`)
-
- to_string: whether the results should be exported to plaintext instead of
- EditorJS format.
-
- plain_text_list: array of plaintext values to append into when ``to_string``
- is set to ``True``.
-
- index: the block's position in the ``blocks`` array.
-
- max_depth: the maximum level of the list nesting. Limits the amount of recursions
- done. Must not be set too high (recommended value: 10)
-
- current_depth: should be set to 0 on the first call, then it gets automatically
- incremented during the recursive calls in order to keep track of
- the call depth.
-
- """
-
- data = block["data"]
- clean_meta_block(data)
-
- items = data.get("items", [])
- if isinstance(items, list) is False:
- raise ValidationError("Invalid EditorJS list: items property must be an array")
- items = cast(list, items)
-
- # Cleans the list style (unordered|ordered|checklist)
- # It's valid both for legacy and new (nested) list formats
- style: None | str
- if style := data.get("style"):
- if isinstance(style, str) is False:
- raise ValidationError(
- "Invalid EditorJS list: style property must be a string"
- )
- data["style"] = clean_text_data_block(style)
-
- # List empty
- if not items:
- return
-
- # Looks at the first item to determine whether it's legacy or nested (the new type).
- # We do not do this in a loop as we shouldn't allow users to mix legacy and
- # non-legacy within a block, this isn't valid EditorJS and thus should be rejected
- # by `clean_legacy_list()` and `clean_nested_list()` but this validation is deferred
- # to these functions in order to not iterate multiple times the lists.
- if isinstance(items[0], str):
- # Support for **legacy** lists (https://github.com/editor-js/list-legacy/blob/381254443234ebbec9cc508fa8a7b982b6a79418/README.md#output-data)
- clean_legacy_list(items, to_string=to_string, plain_text_list=plain_text_list)
- elif isinstance(items[0], dict):
- # Support for the new format (nested lists, https://github.com/editor-js/list/blob/f8cde313224499ed5bcf3e93864fc11c45fe7efb/README.md#output-data)
- clean_nested_list(
- items,
- max_depth=max_depth,
- current_depth=0,
- to_string=to_string,
- plain_text_list=plain_text_list,
- )
- else:
- raise ValidationError(
- "Invalid EditorJS list: items must be either a string or an object"
- )
-
-
-def clean_image_item(blocks, block, plain_text_list, to_string, index):
- data = block["data"]
-
- for obj in (
- # data.file.url -> support for newer versions of Edjs (2.x)
- data.get("file", {}),
- # data.url -> support for older version (1.x)
- data,
- ):
- if file_url := obj.get("url"):
- if to_string:
- plain_text_list.append(strip_tags(file_url))
- else:
- file_url = clean_url(file_url)
- obj["url"] = file_url
-
- if caption := data.get("caption"):
- if to_string:
- plain_text_list.append(strip_tags(caption))
- else:
- caption = clean_text_data_block(caption)
- data["caption"] = caption
-
-
-def clean_embed_item(blocks, block, plain_text_list, to_string, index):
- for field in ["source", "embed"]:
- data = block["data"].get(field)
- if not data:
- continue
- if to_string:
- plain_text_list.append(strip_tags(data))
- else:
- data = clean_url(data)
- blocks[index]["data"][field] = data
-
- caption = block["data"].get("caption")
- if caption:
- if to_string:
- plain_text_list.append(strip_tags(caption))
- else:
- blocks[index]["data"]["caption"] = clean_text_data_block(caption)
-
- if service := block["data"].get("service"):
- block["data"]["service"] = clean_text_data_block(service)
-
-
-def clean_quote_item(blocks, block, plain_text_list, to_string, index):
- """Clean a EditorJS `quote` block.
-
- Follows the specs from https://github.com/editor-js/quote/blob/78f70cf2391cc8aaf2d2e59615de3ad833d180c3/README.md#output-data
- """
-
- # Cleans all EditorJS fields from the data block
- for field in ["text", "caption", "alignment", "align"]:
- data = block["data"].get(field)
- if not data:
- continue
- blocks[index]["data"][field] = clean_text_data_block(data)
-
- if text := block["data"].get("text"):
- plain_text_list.append(strip_tags(text))
-
-
-def clean_text_items(
- blocks,
- block,
- plain_text_list,
- to_string,
- index,
- *,
- block_type: str,
-):
- if block_type not in ALLOWED_TEXT_BLOCK_TYPES:
- raise ValidationError(f"Unsupported block type: {block_type!r}")
-
- data = block["data"]
-
- text = data.get("text")
- if text:
- if to_string:
- plain_text_list.append(strip_tags(text))
- else:
- new_text = clean_text_data_block(text)
- data["text"] = new_text
-
- for field in ("alignment", "align"):
- if value := data.get(field):
- data[field] = clean_text_data_block(value)
-
- if heading_level := data.get("level"):
- data["level"] = maybe_to_int(heading_level, name="Heading level")
-
-
-def clean_text_data_block(text: str) -> str:
- """Sanitize the text using nh3 to remove malicious tags and attributes."""
- if not text:
- return text
-
- return nh3.clean(
- text,
- url_schemes=ALLOWED_URL_SCHEMES | settings.HTML_CLEANER_PREFS.allowed_schemes,
- attributes=settings.HTML_CLEANER_PREFS.allowed_attributes,
- tag_attribute_values=settings.HTML_CLEANER_PREFS.allowed_attribute_values,
- link_rel=settings.HTML_CLEANER_PREFS.link_rel,
- )
-
-
-def clean_url(dirty_url: str) -> str:
- """Check if URL scheme is allowed."""
- if not dirty_url:
- return ""
-
- try:
- parsed_url = parse_url(dirty_url.strip())
- except ValueError:
- parsed_url = None
-
- if (
- parsed_url is None
- or parsed_url.scheme
- not in ALLOWED_URL_SCHEMES | settings.HTML_CLEANER_PREFS.allowed_schemes
- ):
- warnings.warn(
- f"An invalid url or disallowed URL was sent: {dirty_url}",
- stacklevel=3,
- )
- return "#invalid"
-
- # If the scheme is HTTP(S), then urllib3 already took care of normalization
- # and thus quoted everything that should be quoted (such as dangerous characters
- # like `"`)
- # See https://github.com/urllib3/urllib3/blob/bd37a23af4552548f55d3c723fcb604f9a4983ca/src/urllib3/util/url.py#L415-L446
- if parsed_url.scheme in ("https", "http"):
- return parsed_url.url
-
- url_cleaner = URL_SCHEME_CLEANERS.get(parsed_url.scheme, None)
-
- if url_cleaner is None:
- if parsed_url.scheme in settings.HTML_CLEANER_PREFS.allowed_schemes:
- # Deprecated: this is only for backward compatibility - it doesn't define
- # a cleaner which is dangerous.
- return dirty_url
- # NOTE: this exception should never happen unless a maintainer didn't read the
- # comment in ALLOWED_URL_SCHEMES
- raise KeyError("No URL cleaner defined", parsed_url.scheme)
-
- try:
- return url_cleaner(dirty_url=dirty_url)
- except URLCleanerError as exc:
- # Note: InvalidUsage must NOT be handled (should return "Internal Error")
- # it indicates a code bug if it's raised
- raise ValidationError(str(exc)) from exc
- except ValueError as exc:
- # Note: we do not do str(exc) as may reveal sensitive information
- raise ValidationError("Invalid URL") from exc
diff --git a/saleor/csv/tests/export/products_data/utils.py b/saleor/csv/tests/export/products_data/utils.py
index 7336630e44..a2d899c10a 100644
--- a/saleor/csv/tests/export/products_data/utils.py
+++ b/saleor/csv/tests/export/products_data/utils.py
@@ -9,7 +9,7 @@ from .....attribute.models import (
Attribute,
AttributeProduct,
)
-from .....core.utils.editorjs import clean_editor_js
+from .....core.editorjs import editorjs_to_text
def add_product_attribute_data_to_expected_data(data, product, attribute_ids, pk=None):
@@ -73,7 +73,7 @@ def get_attribute_value(attribute, value_instance):
if attribute.unit:
value += f" {attribute.unit}"
elif attribute.input_type == AttributeInputType.RICH_TEXT:
- value = clean_editor_js(value_instance.rich_text, to_string=True)
+ value = editorjs_to_text(value_instance.rich_text)
elif attribute.input_type == AttributeInputType.SWATCH:
value = (
value_instance.file_url if value_instance.file_url else value_instance.value
diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.py
index d5aaa2c06e..e9e2d20565 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -11,8 +11,8 @@ from django.db.models.functions import Cast, Concat
from ...attribute import AttributeInputType
from ...attribute.models import AssignedVariantAttribute, Attribute, AttributeValue
+from ...core.editorjs import editorjs_to_text
from ...core.utils import build_absolute_uri
-from ...core.utils.editorjs import clean_editor_js
from ...product.models import (
ProductChannelListing,
ProductVariant,
@@ -481,9 +481,7 @@ def prepare_attribute_value(attribute_data: AttributeData):
else f"{data.value_name} {data.unit}"
)
),
- AttributeInputType.RICH_TEXT: (
- lambda data: clean_editor_js(data.rich_text, to_string=True)
- ),
+ AttributeInputType.RICH_TEXT: lambda data: editorjs_to_text(data.rich_text),
AttributeInputType.BOOLEAN: (
lambda data: str(data.boolean) if data.boolean is not None else None
),
diff --git a/saleor/discount/migrations/0045_promotions.py b/saleor/discount/migrations/0045_promotions.py
index 802f9d3aca..fbe77830fa 100644
--- a/saleor/discount/migrations/0045_promotions.py
+++ b/saleor/discount/migrations/0045_promotions.py
@@ -6,7 +6,7 @@ import django.utils.timezone
from django.db import migrations, models
import saleor.core.db.fields
-import saleor.core.utils.editorjs
+import saleor.core.editorjs
import saleor.core.utils.json_serializer
@@ -56,7 +56,7 @@ class Migration(migrations.Migration):
saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
(
@@ -102,7 +102,7 @@ class Migration(migrations.Migration):
saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
("catalogue_predicate", models.JSONField(blank=True, default=dict)),
@@ -315,7 +315,7 @@ class Migration(migrations.Migration):
saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
(
@@ -350,7 +350,7 @@ class Migration(migrations.Migration):
saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
(
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 3440406c24..1bae13b42e 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -15,8 +15,8 @@ from prices import Money, fixed_discount, percentage_discount
from ..app.models import App
from ..channel.models import Channel
from ..core.db.fields import MoneyField, SanitizedJSONField
+from ..core.editorjs import clean_editorjs
from ..core.models import ModelWithMetadata
-from ..core.utils.editorjs import clean_editor_js
from ..core.utils.json_serializer import CustomJsonEncoder
from ..core.utils.translations import Translation
from ..permission.enums import DiscountPermissions
@@ -326,7 +326,7 @@ class Promotion(ModelWithMetadata):
choices=PromotionType.CHOICES,
default=PromotionType.CATALOGUE,
)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
old_sale_id = models.IntegerField(blank=True, null=True, unique=True)
start_date = models.DateTimeField(default=timezone.now)
end_date = models.DateTimeField(null=True, blank=True)
@@ -363,7 +363,7 @@ class Promotion(ModelWithMetadata):
class PromotionTranslation(Translation):
name = models.CharField(max_length=255, null=True, blank=True)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
promotion = models.ForeignKey(
Promotion, related_name="translations", on_delete=models.CASCADE
)
@@ -381,7 +381,7 @@ class PromotionTranslation(Translation):
class PromotionRule(models.Model):
id = models.UUIDField(primary_key=True, editable=False, unique=True, default=uuid4)
name = models.CharField(max_length=255, blank=True, null=True)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
promotion = models.ForeignKey(
Promotion, on_delete=models.CASCADE, related_name="rules"
)
@@ -454,7 +454,7 @@ class PromotionRule_Variants(models.Model):
class PromotionRuleTranslation(Translation):
name = models.CharField(max_length=255, null=True, blank=True)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
promotion_rule = models.ForeignKey(
PromotionRule, related_name="translations", on_delete=models.CASCADE
)
diff --git a/saleor/graphql/attribute/utils/type_handlers.py b/saleor/graphql/attribute/utils/type_handlers.py
index 5080becb20..380899073f 100644
--- a/saleor/graphql/attribute/utils/type_handlers.py
+++ b/saleor/graphql/attribute/utils/type_handlers.py
@@ -13,11 +13,11 @@ from text_unidecode import unidecode
from ....attribute import AttributeEntityType, AttributeInputType
from ....attribute import models as attribute_models
from ....attribute.models import AttributeValue
+from ....core.editorjs import editorjs_to_text
from ....core.utils import (
generate_unique_slug,
prepare_unique_slug,
)
-from ....core.utils.editorjs import clean_editor_js
from ....core.utils.text import safe_truncate
from ....core.utils.url import get_default_storage_root_url
from ...core.utils import from_global_id_or_error, get_duplicated_values
@@ -664,7 +664,7 @@ class RichTextAttributeHandler(AttributeTypeHandler):
"""Handler for Rich Text attribute type."""
def clean_and_validate(self, attribute_errors: T_ERROR_DICT):
- text = clean_editor_js(self.values_input.rich_text or {}, to_string=True)
+ text = editorjs_to_text(self.values_input.rich_text or {})
if not text.strip() and self.attribute.value_required:
attribute_errors[AttributeInputErrors.VALUE_REQUIRED].append(
@@ -678,7 +678,7 @@ class RichTextAttributeHandler(AttributeTypeHandler):
defaults = {
"rich_text": rich_text,
- "name": safe_truncate(clean_editor_js(rich_text, to_string=True), 200),
+ "name": safe_truncate(editorjs_to_text(rich_text), 200),
}
return self._update_or_create_value(instance, defaults)
diff --git a/saleor/graphql/discount/tests/queries/test_promotion.py b/saleor/graphql/discount/tests/queries/test_promotion.py
index 89712156e1..608c5edbe6 100644
--- a/saleor/graphql/discount/tests/queries/test_promotion.py
+++ b/saleor/graphql/discount/tests/queries/test_promotion.py
@@ -342,7 +342,7 @@ def test_query_promotion_rule_translation(
):
assert rule["translation"]["name"] == promotion_rule_translation_fr.name
assert rule["translation"]["description"] == json.dumps(
- promotion_rule_translation_fr.description
+ promotion_rule_translation_fr.description, sort_keys=True
)
assert rule["translation"]["language"]["code"] == "FR"
else:
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
index df11795491..27e6d948e9 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -9,9 +9,9 @@ from django.utils.text import slugify
from graphene.utils.str_converters import to_camel_case
from text_unidecode import unidecode
+from ....core.editorjs import editorjs_to_text
from ....core.tracing import traced_atomic_transaction
from ....core.utils import prepare_unique_slug
-from ....core.utils.editorjs import clean_editor_js
from ....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirty
from ....permission.enums import ProductPermissions
from ....product import ProductMediaTypes, models
@@ -249,7 +249,7 @@ class ProductBulkCreate(BaseMutation):
description = cleaned_input.get("description")
cleaned_input["description_plaintext"] = (
- clean_editor_js(description, to_string=True) if description else ""
+ editorjs_to_text(description) if description else ""
)
slug = cleaned_input.get("slug")
diff --git a/saleor/graphql/product/mutations/category/category_create.py b/saleor/graphql/product/mutations/category/category_create.py
index 849197f3c0..70c50b00d0 100644
--- a/saleor/graphql/product/mutations/category/category_create.py
+++ b/saleor/graphql/product/mutations/category/category_create.py
@@ -1,7 +1,7 @@
import graphene
from django.core.exceptions import ValidationError
-from .....core.utils.editorjs import clean_editor_js
+from .....core.editorjs import editorjs_to_text
from .....permission.enums import ProductPermissions
from .....product import models
from .....product.error_codes import ProductErrorCode
@@ -76,7 +76,7 @@ class CategoryCreate(DeprecatedModelMutation):
cleaned_input = super().clean_input(info, instance, data, **kwargs)
description = cleaned_input.get("description")
cleaned_input["description_plaintext"] = (
- clean_editor_js(description, to_string=True) if description else ""
+ editorjs_to_text(description) if description else ""
)
try:
cleaned_input = validate_slug_and_generate_if_needed(
diff --git a/saleor/graphql/product/mutations/product/product_cleaner.py b/saleor/graphql/product/mutations/product/product_cleaner.py
index 048f205696..0c973c36ac 100644
--- a/saleor/graphql/product/mutations/product/product_cleaner.py
+++ b/saleor/graphql/product/mutations/product/product_cleaner.py
@@ -1,6 +1,6 @@
from django.core.exceptions import ValidationError
-from .....core.utils.editorjs import clean_editor_js
+from .....core.editorjs import editorjs_to_text
from .....product.error_codes import ProductErrorCode
from ....core.validators import validate_slug_and_generate_if_needed
@@ -30,5 +30,5 @@ def clean_description(cleaned_input: dict):
if "description" in cleaned_input:
description = cleaned_input["description"]
cleaned_input["description_plaintext"] = (
- clean_editor_js(description, to_string=True) if description else ""
+ editorjs_to_text(description) if description else ""
)
diff --git a/saleor/graphql/product/tests/deprecated/test_collection.py b/saleor/graphql/product/tests/deprecated/test_collection.py
index 699fc980d7..3ecd0bc417 100644
--- a/saleor/graphql/product/tests/deprecated/test_collection.py
+++ b/saleor/graphql/product/tests/deprecated/test_collection.py
@@ -39,7 +39,8 @@ def test_collections_query_with_default_channel_slug(
assert collection_data["name"] == published_collection.name
assert collection_data["slug"] == published_collection.slug
assert collection_data["description"] == json.dumps(
- published_collection.description
+ published_collection.description,
+ sort_keys=True,
)
assert (
collection_data["products"]["totalCount"]
diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.py
index 15fed93e93..4e4b4b50b9 100644
--- a/saleor/graphql/product/tests/mutations/test_product_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_create.py
@@ -643,7 +643,7 @@ def test_create_product_with_rich_text_attribute(
"Attribute", rich_text_attribute.id
)
rich_text_value = dummy_editorjs("test product" * 5)
- rich_text = json.dumps(rich_text_value)
+ rich_text = json.dumps(rich_text_value, sort_keys=True)
# test creating root product
variables = {
diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.py
index f3a075d9a4..605d7219d8 100644
--- a/saleor/graphql/product/tests/mutations/test_product_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_update.py
@@ -220,7 +220,7 @@ def test_update_product(
expected_other_description_json = other_description_json
text = expected_other_description_json["blocks"][0]["data"]["text"]
expected_other_description_json["blocks"][0]["data"]["text"] = strip_tags(text)
- other_description_json = json.dumps(other_description_json)
+ other_description_json = json.dumps(other_description_json, sort_keys=True)
product_id = graphene.Node.to_global_id("Product", product.pk)
category_id = graphene.Node.to_global_id("Category", non_default_category.pk)
@@ -276,7 +276,9 @@ def test_update_product(
assert data["errors"] == []
assert data["product"]["name"] == product_name
assert data["product"]["slug"] == product_slug
- assert data["product"]["description"] == json.dumps(expected_other_description_json)
+ assert data["product"]["description"] == json.dumps(
+ expected_other_description_json, sort_keys=True
+ )
assert data["product"]["chargeTaxes"] == product_charge_taxes
assert data["product"]["taxType"]["taxCode"] == product_tax_rate
assert not data["product"]["category"]["name"] == category.name
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
index 1879b7fb1e..67f4151bf3 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
@@ -840,7 +840,9 @@ def test_product_variant_bulk_create_with_rich_text_attribute(
"sku": sku,
"weight": 2.5,
"trackInventory": True,
- "attributes": [{"id": attribute_id, "richText": json.dumps(rich_text)}],
+ "attributes": [
+ {"id": attribute_id, "richText": json.dumps(rich_text, sort_keys=True)}
+ ],
}
]
@@ -858,7 +860,9 @@ def test_product_variant_bulk_create_with_rich_text_attribute(
assert not data["results"][0]["errors"]
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
- assert attributes[-1]["values"][0]["richText"] == json.dumps(rich_text)
+ assert attributes[-1]["values"][0]["richText"] == json.dumps(
+ rich_text, sort_keys=True
+ )
assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
expected_assigned_attribute = {
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
index 981c4aae5c..a4eb609329 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
@@ -2137,7 +2137,10 @@ def test_create_variant_invalid_variant_attributes(
"id": size_attr_id,
"values": [non_existent_attr_value, size_value_slug],
},
- {"id": rich_text_attr_id, "richText": json.dumps(dummy_editorjs(" "))},
+ {
+ "id": rich_text_attr_id,
+ "richText": json.dumps(dummy_editorjs(" "), sort_keys=True),
+ },
],
"trackInventory": True,
}
@@ -2311,7 +2314,9 @@ def test_create_variant_with_rich_text_attribute(
assert not content["errors"]
assert data["name"] == sku
assert data["sku"] == sku
- assert data["attributes"][-1]["values"][0]["richText"] == json.dumps(rich_text)
+ assert data["attributes"][-1]["values"][0]["richText"] == json.dumps(
+ rich_text, sort_keys=True
+ )
assigned_attributes = data["assignedAttributes"]
expected_assigned_attribute = {
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
index d2ccee8df4..65cb398101 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
@@ -1374,7 +1374,7 @@ def test_update_variant_with_rich_text_attribute(
"id": variant_id,
"sku": sku,
"attributes": [
- {"id": attr_id, "richText": json.dumps(rich_text)},
+ {"id": attr_id, "richText": json.dumps(rich_text, sort_keys=True)},
],
}
rich_text_attribute_value.slug = f"{variant.id}_{rich_text_attribute.id}"
@@ -1394,7 +1394,9 @@ def test_update_variant_with_rich_text_attribute(
assert not content["errors"]
assert data["sku"] == sku
assert data["attributes"][-1]["attribute"]["slug"] == rich_text_attribute.slug
- assert data["attributes"][-1]["values"][0]["richText"] == json.dumps(rich_text)
+ assert data["attributes"][-1]["values"][0]["richText"] == json.dumps(
+ rich_text, sort_keys=True
+ )
assigned_attributes = data["assignedAttributes"]
expected_assigned_attribute = {
diff --git a/saleor/graphql/translations/mutations/attribute_value_bulk_translate.py b/saleor/graphql/translations/mutations/attribute_value_bulk_translate.py
index 99d1ecc6c1..ad4aa3532f 100644
--- a/saleor/graphql/translations/mutations/attribute_value_bulk_translate.py
+++ b/saleor/graphql/translations/mutations/attribute_value_bulk_translate.py
@@ -3,7 +3,7 @@ from django.core.exceptions import ValidationError
from graphql.error import GraphQLError
from ....attribute import AttributeInputType, models
-from ....core.utils.editorjs import clean_editor_js
+from ....core.editorjs import editorjs_to_text
from ....core.utils.text import safe_truncate
from ....permission.enums import SitePermissions
from ...attribute.types import AttributeValueTranslation
@@ -138,7 +138,7 @@ class AttributeValueBulkTranslate(BaseBulkTranslateMutation):
attribute = instance.attribute_value.attribute
if attribute.input_type == AttributeInputType.RICH_TEXT:
input_data["name"] = safe_truncate(
- clean_editor_js(input_data["rich_text"], to_string=True), 250
+ editorjs_to_text(input_data["rich_text"]), 250
)
elif attribute.input_type == AttributeInputType.PLAIN_TEXT:
input_data["name"] = safe_truncate(input_data["plain_text"], 250)
diff --git a/saleor/graphql/translations/mutations/attribute_value_translate.py b/saleor/graphql/translations/mutations/attribute_value_translate.py
index 1b32a46380..e32b322523 100644
--- a/saleor/graphql/translations/mutations/attribute_value_translate.py
+++ b/saleor/graphql/translations/mutations/attribute_value_translate.py
@@ -2,7 +2,7 @@ import graphene
from ....attribute import AttributeInputType
from ....attribute import models as attribute_models
-from ....core.utils.editorjs import clean_editor_js
+from ....core.editorjs import editorjs_to_text
from ....core.utils.text import safe_truncate
from ....permission.enums import SitePermissions
from ...attribute.types import AttributeValue
@@ -46,7 +46,7 @@ class AttributeValueTranslate(BaseTranslateMutation):
if "name" not in input_data.keys() or input_data["name"] is None:
if instance.attribute.input_type == AttributeInputType.RICH_TEXT:
input_data["name"] = safe_truncate(
- clean_editor_js(input_data["rich_text"], to_string=True), 250
+ editorjs_to_text(input_data["rich_text"]), 250
)
elif instance.attribute.input_type == AttributeInputType.PLAIN_TEXT:
input_data["name"] = safe_truncate(input_data["plain_text"], 250)
diff --git a/saleor/graphql/translations/tests/mutations/test_promotion_rule_translate.py b/saleor/graphql/translations/tests/mutations/test_promotion_rule_translate.py
index 16d78017e1..0dd7ccfc43 100644
--- a/saleor/graphql/translations/tests/mutations/test_promotion_rule_translate.py
+++ b/saleor/graphql/translations/tests/mutations/test_promotion_rule_translate.py
@@ -79,7 +79,7 @@ def test_promotion_rule_create_translation(
translation_data = data["promotionRule"]["translation"]
assert translation_data["name"] == "Polish rule name"
- assert translation_data["description"] == json.dumps(description_json)
+ assert json.loads(translation_data["description"]) == description_json
assert translation_data["language"]["code"] == "PL"
translation = promotion_rule.translations.first()
diff --git a/saleor/graphql/translations/tests/mutations/test_promotion_translate.py b/saleor/graphql/translations/tests/mutations/test_promotion_translate.py
index 6b401eb18f..14608ddc5f 100644
--- a/saleor/graphql/translations/tests/mutations/test_promotion_translate.py
+++ b/saleor/graphql/translations/tests/mutations/test_promotion_translate.py
@@ -81,7 +81,7 @@ def test_promotion_create_translation(
translation_data = data["promotion"]["translation"]
assert translation_data["name"] == "Polish promotion name"
- assert translation_data["description"] == json.dumps(description_json)
+ assert json.loads(translation_data["description"]) == description_json
assert translation_data["language"]["code"] == "PL"
assert translation_data["__typename"] == "PromotionTranslation"
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index d0421337b8..c59ec9b2ee 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -467,7 +467,8 @@ def test_attribute_value_translation(user_api_client, attribute_value_generator)
]
assert attribute_value["translation"]["name"] == "Różowy"
assert attribute_value["translation"]["richText"] == json.dumps(
- dummy_editorjs("Pink")
+ dummy_editorjs("Pink"),
+ sort_keys=True,
)
assert attribute_value["translation"]["language"]["code"] == "PL"
@@ -2136,7 +2137,7 @@ def test_rich_text_attribute_value_create_translation(
"AttributeValue", attribute_value.id
)
expected_base_text = "Nowy Opis"
- expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text), sort_keys=True)
# when
response = staff_api_client.post_graphql(
@@ -2270,7 +2271,7 @@ def test_rich_text_attribute_value_update_translation_only_rich_text(
"AttributeValue", attribute_value.id
)
expected_base_text = "Nowy Opis"
- expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text), sort_keys=True)
# when
response = staff_api_client.post_graphql(
@@ -2307,7 +2308,7 @@ def test_rich_text_attribute_value_update_translation_only_rich_text_long_text(
"AttributeValue", attribute_value.id
)
expected_base_text = "Nowy Opis. " * 250
- expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text), sort_keys=True)
# when
response = staff_api_client.post_graphql(
@@ -2347,7 +2348,7 @@ def test_rich_text_attribute_value_update_translation_only_rich_text_name_set_ma
)
expected_name = "Moja nazwa attrybutu"
expected_base_text = "Nowy Opis"
- expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text), sort_keys=True)
# when
response = staff_api_client.post_graphql(
@@ -2384,7 +2385,7 @@ def test_rich_text_attribute_value_update_translation_only_rich_text_empty_name(
"AttributeValue", attribute_value.id
)
expected_base_text = "Nowy Opis"
- expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text), sort_keys=True)
# when
response = staff_api_client.post_graphql(
@@ -2421,7 +2422,7 @@ def test_rich_text_attribute_value_update_translation_only_rich_text_name_null(
"AttributeValue", attribute_value.id
)
expected_base_text = "Nowy Opis"
- expected_rich_text = json.dumps(dummy_editorjs(expected_base_text))
+ expected_rich_text = json.dumps(dummy_editorjs(expected_base_text), sort_keys=True)
# when
response = staff_api_client.post_graphql(
@@ -3854,8 +3855,12 @@ def test_product_attribute_value_rich_text_translation(
attribute_value_response = data["translation"]["attributeValues"][0]
assert attribute_value_response["name"] == attribute_value.name
- assert attribute_value_response["richText"] == json.dumps(attribute_value.rich_text)
- assert attribute_value_response["translation"]["richText"] == json.dumps(rich_text)
+ assert attribute_value_response["richText"] == json.dumps(
+ attribute_value.rich_text, sort_keys=True
+ )
+ assert attribute_value_response["translation"]["richText"] == json.dumps(
+ rich_text, sort_keys=True
+ )
def test_product_attribute_value_plain_text_translation(
@@ -4086,8 +4091,12 @@ def test_product_variant_attribute_value_rich_text_translation(
translations_response = data["translation"]["attributeValues"][0]
assert translations_response["name"] == attribute_value.name
- assert translations_response["richText"] == json.dumps(attribute_value.rich_text)
- assert translations_response["translation"]["richText"] == json.dumps(rich_text)
+ assert translations_response["richText"] == json.dumps(
+ attribute_value.rich_text, sort_keys=True
+ )
+ assert translations_response["translation"]["richText"] == json.dumps(
+ rich_text, sort_keys=True
+ )
def test_product_variant_attribute_value_plain_text_translation(
@@ -4229,8 +4238,12 @@ def test_page_attribute_value_rich_text_translation(
attribute_value_response = data["translation"]["attributeValues"][0]
assert attribute_value_response["name"] == attribute_value.name
- assert attribute_value_response["richText"] == json.dumps(attribute_value.rich_text)
- assert attribute_value_response["translation"]["richText"] == json.dumps(rich_text)
+ assert attribute_value_response["richText"] == json.dumps(
+ attribute_value.rich_text, sort_keys=True
+ )
+ assert attribute_value_response["translation"]["richText"] == json.dumps(
+ rich_text, sort_keys=True
+ )
def test_page_attribute_value_plain_text_translation(
@@ -4446,7 +4459,8 @@ def test_translation_query_promotion(
assert data["name"] == promotion.name
assert data["translation"]["name"] == promotion_translation_fr.name
assert data["translation"]["description"] == json.dumps(
- promotion_translation_fr.description
+ promotion_translation_fr.description,
+ sort_keys=True,
)
@@ -4496,5 +4510,6 @@ def test_translation_query_promotion_rule(
assert data["name"] == promotion_rule.name
assert data["translation"]["name"] == promotion_rule_translation_fr.name
assert data["translation"]["description"] == json.dumps(
- promotion_rule_translation_fr.description
+ promotion_rule_translation_fr.description,
+ sort_keys=True,
)
diff --git a/saleor/page/migrations/0016_auto_20201112_0904.py b/saleor/page/migrations/0016_auto_20201112_0904.py
index 15ba9ea658..d4188e4b1b 100644
--- a/saleor/page/migrations/0016_auto_20201112_0904.py
+++ b/saleor/page/migrations/0016_auto_20201112_0904.py
@@ -3,7 +3,7 @@
from django.db import migrations
import saleor.core.db.fields
-import saleor.core.utils.editorjs
+import saleor.core.editorjs
class Migration(migrations.Migration):
@@ -18,7 +18,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -27,7 +27,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
]
diff --git a/saleor/page/migrations/0018_migrate_content_json_into_content.py b/saleor/page/migrations/0018_migrate_content_json_into_content.py
index 3c52419291..6dbe7f5103 100644
--- a/saleor/page/migrations/0018_migrate_content_json_into_content.py
+++ b/saleor/page/migrations/0018_migrate_content_json_into_content.py
@@ -4,7 +4,7 @@ from django.db import migrations
from django.db.models import F
import saleor.core.db.fields
-import saleor.core.utils.editorjs
+import saleor.core.editorjs
def clean_content_field(apps, schema_editor):
@@ -39,7 +39,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -48,7 +48,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.RunPython(
diff --git a/saleor/page/migrations/0020_update_content_fields.py b/saleor/page/migrations/0020_update_content_fields.py
index 4c3943526b..17b99e17a6 100644
--- a/saleor/page/migrations/0020_update_content_fields.py
+++ b/saleor/page/migrations/0020_update_content_fields.py
@@ -3,7 +3,7 @@
from django.db import migrations
import saleor.core.db.fields
-import saleor.core.utils.editorjs
+import saleor.core.editorjs
def update_empty_content_field(apps, schema_editor):
@@ -26,7 +26,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -35,7 +35,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.RunPython(
diff --git a/saleor/page/models.py b/saleor/page/models.py
index adf56a23ee..f5f4c20bbc 100644
--- a/saleor/page/models.py
+++ b/saleor/page/models.py
@@ -5,8 +5,8 @@ from django.contrib.postgres.search import SearchVectorField
from django.db import models
from ..core.db.fields import SanitizedJSONField
+from ..core.editorjs import clean_editorjs
from ..core.models import ModelWithMetadata, PublishableModel, PublishedQuerySet
-from ..core.utils.editorjs import clean_editor_js
from ..permission.enums import PagePermissions, PageTypePermissions
from ..seo.models import SeoModel, SeoModelTranslationWithSlug
@@ -31,7 +31,7 @@ class Page(ModelWithMetadata, SeoModel, PublishableModel):
page_type = models.ForeignKey(
"PageType", related_name="pages", on_delete=models.CASCADE
)
- content = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ content = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
search_vector = SearchVectorField(blank=True, null=True)
search_index_dirty = models.BooleanField(default=True, db_default=True)
@@ -59,7 +59,7 @@ class PageTranslation(SeoModelTranslationWithSlug):
Page, related_name="translations", on_delete=models.CASCADE
)
title = models.CharField(max_length=255, blank=True, null=True)
- content = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ content = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
class Meta:
constraints = [
diff --git a/saleor/page/search.py b/saleor/page/search.py
index 27144ddf12..311e5cef5d 100644
--- a/saleor/page/search.py
+++ b/saleor/page/search.py
@@ -9,8 +9,8 @@ from ..attribute.models import Attribute, AttributeValue
from ..attribute.search import get_search_vectors_for_attribute_values
from ..core.context import with_promise_context
from ..core.db.connection import allow_writer
+from ..core.editorjs import editorjs_to_text
from ..core.postgres import FlatConcatSearchVector, NoValidationSearchVector
-from ..core.utils.editorjs import clean_editor_js
from ..graphql.attribute.dataloaders.assigned_attributes import (
AttributesByPageIdAndLimitLoader,
AttributeValuesByPageIdAndAttributeIdAndLimitLoader,
@@ -164,7 +164,7 @@ def prepare_page_search_vector_value(
if content := page.content:
search_vectors += [
NoValidationSearchVector(
- Value(clean_editor_js(content, to_string=True)),
+ Value(editorjs_to_text(content)),
config="simple",
weight="A",
)
diff --git a/saleor/product/migrations/0131_auto_20201112_0904.py b/saleor/product/migrations/0131_auto_20201112_0904.py
index 6e538dfd6f..2d89194f81 100644
--- a/saleor/product/migrations/0131_auto_20201112_0904.py
+++ b/saleor/product/migrations/0131_auto_20201112_0904.py
@@ -3,7 +3,7 @@
from django.db import migrations
import saleor.core.db.fields
-import saleor.core.utils.editorjs
+import saleor.core.editorjs
class Migration(migrations.Migration):
@@ -18,7 +18,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -27,7 +27,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -36,7 +36,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -45,7 +45,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -54,7 +54,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -63,7 +63,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
]
diff --git a/saleor/product/migrations/0138_migrate_description_json_into_description.py b/saleor/product/migrations/0138_migrate_description_json_into_description.py
index d3c14af7b6..f3905e6c26 100644
--- a/saleor/product/migrations/0138_migrate_description_json_into_description.py
+++ b/saleor/product/migrations/0138_migrate_description_json_into_description.py
@@ -4,7 +4,7 @@ from django.db import migrations
from django.db.models import F
import saleor.core.db.fields
-import saleor.core.utils.editorjs
+import saleor.core.editorjs
def clean_description_field(apps, schema_editor):
@@ -65,7 +65,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -74,7 +74,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -83,7 +83,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -92,7 +92,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -101,7 +101,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -110,7 +110,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
default=dict,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.RunPython(
diff --git a/saleor/product/migrations/0141_update_descritpion_fields.py b/saleor/product/migrations/0141_update_descritpion_fields.py
index 3cd98a93ee..5922538746 100644
--- a/saleor/product/migrations/0141_update_descritpion_fields.py
+++ b/saleor/product/migrations/0141_update_descritpion_fields.py
@@ -3,7 +3,7 @@
from django.db import migrations
import saleor.core.db.fields
-import saleor.core.utils.editorjs
+import saleor.core.editorjs
def update_empty_description_field(apps, schema_editor):
@@ -39,7 +39,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -48,7 +48,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -57,7 +57,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -66,7 +66,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -75,7 +75,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AlterField(
@@ -84,7 +84,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.RunPython(
diff --git a/saleor/product/migrations/0178_fix_description_plaintext_field.py b/saleor/product/migrations/0178_fix_description_plaintext_field.py
index 068a8d0bb0..2a0ccb74cb 100644
--- a/saleor/product/migrations/0178_fix_description_plaintext_field.py
+++ b/saleor/product/migrations/0178_fix_description_plaintext_field.py
@@ -3,7 +3,7 @@
from django.db import migrations
from django.db.models import Q
-from ...core.utils.editorjs import clean_editor_js
+from ...core.editorjs import editorjs_to_text
BATCH_SIZE = 2000
@@ -32,9 +32,7 @@ def set_description_plaintext_if_description_exists(apps, schema_editor):
for batch_pks in queryset_in_batches(queryset):
products = Product.objects.filter(pk__in=batch_pks)
for product in products:
- product.description_plaintext = clean_editor_js(
- product.description, to_string=True
- )
+ product.description_plaintext = editorjs_to_text(product.description)
product.search_index_dirty = True
Product.objects.bulk_update(
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 74eb4faca7..fe08f8586b 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -19,6 +19,7 @@ from prices import Money
from ..channel.models import Channel
from ..core.db.fields import MoneyField, SanitizedJSONField
+from ..core.editorjs import clean_editorjs
from ..core.models import (
ModelWithExternalReference,
ModelWithMetadata,
@@ -26,7 +27,6 @@ from ..core.models import (
SortableModel,
)
from ..core.units import WeightUnits
-from ..core.utils.editorjs import clean_editor_js
from ..core.utils.translations import Translation, get_translation
from ..core.weight import zero_weight
from ..discount.models import PromotionRule
@@ -52,7 +52,7 @@ ALL_PRODUCTS_PERMISSIONS = [
class Category(ModelWithMetadata, MPTTModel, SeoModel):
name = models.CharField(max_length=250)
slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
description_plaintext = TextField(blank=True)
updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
parent = models.ForeignKey(
@@ -87,7 +87,7 @@ class CategoryTranslation(SeoModelTranslationWithSlug):
Category, related_name="translations", on_delete=models.CASCADE
)
name = models.CharField(max_length=128, blank=True, null=True)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
class Meta:
constraints = [
@@ -99,7 +99,7 @@ class CategoryTranslation(SeoModelTranslationWithSlug):
unique_together = (("language_code", "category"),)
def __str__(self) -> str:
- return self.name if self.name else str(self.pk)
+ return self.name or str(self.pk)
def __repr__(self) -> str:
class_ = type(self)
@@ -177,7 +177,7 @@ class Product(SeoModel, ModelWithMetadata, ModelWithExternalReference):
)
name = models.CharField(max_length=250)
slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
description_plaintext = TextField(blank=True)
search_document = models.TextField(blank=True, default="")
search_vector = SearchVectorField(blank=True, null=True)
@@ -269,7 +269,7 @@ class ProductTranslation(SeoModelTranslationWithSlug):
Product, related_name="translations", on_delete=models.CASCADE
)
name = models.CharField(max_length=250, blank=True, null=True)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
class Meta:
constraints = [
@@ -281,7 +281,7 @@ class ProductTranslation(SeoModelTranslationWithSlug):
unique_together = (("language_code", "product"),)
def __str__(self) -> str:
- return self.name if self.name else str(self.pk)
+ return self.name or str(self.pk)
def __repr__(self) -> str:
class_ = type(self)
@@ -658,7 +658,7 @@ class Collection(SeoModel, ModelWithMetadata):
)
background_image_alt = models.CharField(max_length=128, blank=True)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
objects = managers.CollectionManager()
@@ -704,7 +704,7 @@ class CollectionTranslation(SeoModelTranslationWithSlug):
Collection, related_name="translations", on_delete=models.CASCADE
)
name = models.CharField(max_length=128, blank=True, null=True)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
class Meta:
constraints = [
@@ -720,7 +720,7 @@ class CollectionTranslation(SeoModelTranslationWithSlug):
return f"{class_.__name__}(pk={self.pk!r}, name={self.name!r}, collection_pk={self.collection_id!r})"
def __str__(self) -> str:
- return self.name if self.name else str(self.pk)
+ return self.name or str(self.pk)
def get_translated_object_id(self):
return "Collection", self.collection_id
diff --git a/saleor/shipping/migrations/0030_auto_20210415_1001.py b/saleor/shipping/migrations/0030_auto_20210415_1001.py
index b8f00af561..afb839ee29 100644
--- a/saleor/shipping/migrations/0030_auto_20210415_1001.py
+++ b/saleor/shipping/migrations/0030_auto_20210415_1001.py
@@ -3,7 +3,7 @@
from django.db import migrations
import saleor.core.db.fields
-import saleor.core.utils.editorjs
+import saleor.core.editorjs
class Migration(migrations.Migration):
@@ -18,7 +18,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
migrations.AddField(
@@ -27,7 +27,7 @@ class Migration(migrations.Migration):
field=saleor.core.db.fields.SanitizedJSONField(
blank=True,
null=True,
- sanitizer=saleor.core.utils.editorjs.clean_editor_js,
+ sanitizer=saleor.core.editorjs.clean_editorjs,
),
),
]
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 4b86d15a15..2d5845174e 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -12,9 +12,9 @@ from prices import Money
from ..channel.models import Channel
from ..core.db.fields import MoneyField, SanitizedJSONField
+from ..core.editorjs import clean_editorjs
from ..core.models import ModelWithMetadata
from ..core.units import WeightUnits
-from ..core.utils.editorjs import clean_editor_js
from ..core.utils.translations import Translation
from ..core.weight import convert_weight, get_default_weight_unit, zero_weight
from ..permission.enums import ShippingPermissions
@@ -254,7 +254,7 @@ class ShippingMethod(ModelWithMetadata):
excluded_products = models.ManyToManyField("product.Product", blank=True)
maximum_delivery_days = models.PositiveIntegerField(null=True, blank=True)
minimum_delivery_days = models.PositiveIntegerField(null=True, blank=True)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
tax_class = models.ForeignKey(
TaxClass,
related_name="shipping_methods",
@@ -353,7 +353,7 @@ class ShippingMethodTranslation(Translation):
shipping_method = models.ForeignKey(
ShippingMethod, related_name="translations", on_delete=models.CASCADE
)
- description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
+ description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editorjs)
class Meta:
unique_together = (("language_code", "shipping_method"),)
diff --git a/saleor/tests/e2e/promotions/test_staff_can_translate_promotions.py b/saleor/tests/e2e/promotions/test_staff_can_translate_promotions.py
index 628020b114..6ee8ba7044 100644
--- a/saleor/tests/e2e/promotions/test_staff_can_translate_promotions.py
+++ b/saleor/tests/e2e/promotions/test_staff_can_translate_promotions.py
@@ -116,7 +116,8 @@ def test_staff_translate_promotions_core_2119(
assert promotion_translation_data["language"]["code"] == "PL"
assert promotion_translation_data["name"] == "Promocja Testowa"
assert promotion_translation_data["description"] == json.dumps(
- promotion_translated_description
+ promotion_translated_description,
+ sort_keys=True,
)
# Step 3 - Get list of promotions rules translations
@@ -143,5 +144,6 @@ def test_staff_translate_promotions_core_2119(
assert promotion_rule_translation_data["language"]["code"] == "PL"
assert promotion_rule_translation_data["name"] == "Testowa Reguła"
assert promotion_rule_translation_data["description"] == json.dumps(
- rule_translated_description
+ rule_translated_description,
+ sort_keys=True,
)
diff --git a/saleor/tests/e2e/promotions/test_unable_to_query_nor_mutate_sale_updated_by_promotion_translations.py b/saleor/tests/e2e/promotions/test_unable_to_query_nor_mutate_sale_updated_by_promotion_translations.py
index 8b8047211c..6d38c3e694 100644
--- a/saleor/tests/e2e/promotions/test_unable_to_query_nor_mutate_sale_updated_by_promotion_translations.py
+++ b/saleor/tests/e2e/promotions/test_unable_to_query_nor_mutate_sale_updated_by_promotion_translations.py
@@ -121,7 +121,7 @@ def test_unable_to_query_nor_mutate_sale_updated_by_promotion_translations_CORE_
assert promotion_translation_data["language"]["code"] == "PL"
assert promotion_translation_data["name"] == "Promocja Testowa"
assert promotion_translation_data["description"] == json.dumps(
- promotion_translated_description
+ promotion_translated_description, sort_keys=True
)
# Step 3 - Run mutation saleChannelListingUpdate
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 905d401b3a..eff2bb8c7f 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -606,19 +606,13 @@ def description_json():
return {
"blocks": [
{
- "key": "",
"data": {
"text": "E-commerce for the PWA era",
"level": 2,
},
- "text": "E-commerce for the PWA era",
"type": "header",
- "depth": 0,
- "entityRanges": [],
- "inlineStyleRanges": [],
},
{
- "key": "",
"data": {
"text": (
"A modular, high performance e-commerce storefront "
@@ -626,21 +620,14 @@ def description_json():
)
},
"type": "paragraph",
- "depth": 0,
- "entityRanges": [],
- "inlineStyleRanges": [],
},
{
- "key": "",
- "data": {},
- "text": "",
+ "data": {
+ "text": "",
+ },
"type": "paragraph",
- "depth": 0,
- "entityRanges": [],
- "inlineStyleRanges": [],
},
{
- "key": "",
"data": {
"text": (
"Saleor is a rapidly-growing open source e-commerce platform "
@@ -653,36 +640,18 @@ def description_json():
),
},
"type": "paragraph",
- "depth": 0,
- "entityRanges": [],
- "inlineStyleRanges": [],
},
{
- "key": "",
"data": {"text": ""},
"type": "paragraph",
- "depth": 0,
- "entityRanges": [],
- "inlineStyleRanges": [],
},
{
- "key": "",
"data": {
"text": "Get Saleor today!",
},
"type": "paragraph",
- "depth": 0,
- "entityRanges": [{"key": 0, "length": 17, "offset": 0}],
- "inlineStyleRanges": [],
},
],
- "entityMap": {
- "0": {
- "data": {"href": "https://github.com/mirumee/saleor"},
- "type": "LINK",
- "mutability": "MUTABLE",
- }
- },
}
@@ -691,21 +660,15 @@ def other_description_json():
return {
"blocks": [
{
- "key": "",
"data": {
"text": (
"A GRAPHQL-FIRST <b>ECOMMERCE</b> PLATFORM FOR PERFECTIONISTS"
),
"level": 2,
},
- "text": "A GRAPHQL-FIRST ECOMMERCE PLATFORM FOR PERFECTIONISTS",
"type": "header",
- "depth": 0,
- "entityRanges": [],
- "inlineStyleRanges": [],
},
{
- "key": "",
"data": {
"text": (
"Saleor is powered by a GraphQL server running on "
@@ -713,12 +676,8 @@ def other_description_json():
),
},
"type": "paragraph",
- "depth": 0,
- "entityRanges": [],
- "inlineStyleRanges": [],
},
],
- "entityMap": {},
}
diff --git a/saleor/tests/utils.py b/saleor/tests/utils.py
index 643d600af4..1da1aecaf1 100644
--- a/saleor/tests/utils.py
+++ b/saleor/tests/utils.py
@@ -1,6 +1,7 @@
import json
import math
from decimal import Decimal
+from typing import Any, Literal, overload
import pytest
from django.conf import settings
@@ -9,6 +10,7 @@ from opentelemetry.sdk.metrics.export import DataPointT, Metric, MetricsData
from opentelemetry.sdk.trace import ReadableSpan
from ..core.db.connection import allow_writer
+from ..core.editorjs.models import EditorJSDocumentModel
from ..core.telemetry import Scope
@@ -59,9 +61,23 @@ def prepare_test_db_connections():
connections[replica] = FakeDbReplicaConnection(connections[replica]) # type: ignore[assignment]
-def dummy_editorjs(text, json_format=False):
- data = {"blocks": [{"data": {"text": text}, "type": "paragraph"}]}
- return json.dumps(data) if json_format else data
+@overload
+def dummy_editorjs(text: str, json_format: Literal[True]) -> str: ...
+@overload
+def dummy_editorjs(
+ text: str, json_format: Literal[False] = False
+) -> dict[str, Any]: ...
+
+
+def dummy_editorjs(text: str, json_format: bool = False) -> dict[str, Any] | str:
+ data = EditorJSDocumentModel.model_validate(
+ {"blocks": [{"data": {"text": text}, "type": "paragraph"}]}
+ ).model_dump(exclude_unset=True)
+
+ if json_format:
+ return json.dumps(data, sort_keys=True)
+
+ return data
def round_down(price: Decimal) -> Decimal:
diff --git a/uv.lock b/uv.lock
index 3f807b908d..ea317d571e 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2032,7 +2032,7 @@ wheels = [
[[package]]
name = "pydantic"
-version = "2.11.9"
+version = "2.12.5"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "annotated-types", marker = "platform_python_implementation != 'PyPy'" },
@@ -2040,34 +2040,38 @@ dependencies = [
{ name = "typing-extensions", marker = "platform_python_implementation != 'PyPy'" },
{ name = "typing-inspection", marker = "platform_python_implementation != 'PyPy'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/ff/5d/09a551ba512d7ca404d785072700d3f6727a02f6f3c24ecfd081c7cf0aa8/pydantic-2.11.9.tar.gz", hash = "sha256:6b8ffda597a14812a7975c90b82a8a2e777d9257aba3453f973acd3c032a18e2", size = 788495, upload-time = "2025-09-13T11:26:39.325Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/69/44/36f1a6e523abc58ae5f928898e4aca2e0ea509b5aa6f6f392a5d882be928/pydantic-2.12.5.tar.gz", hash = "sha256:4d351024c75c0f085a9febbb665ce8c0c6ec5d30e903bdb6394b7ede26aebb49", size = 821591, upload-time = "2025-11-26T15:11:46.471Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/3e/d3/108f2006987c58e76691d5ae5d200dd3e0f532cb4e5fa3560751c3a1feba/pydantic-2.11.9-py3-none-any.whl", hash = "sha256:c42dd626f5cfc1c6950ce6205ea58c93efa406da65f479dcb4029d5934857da2", size = 444855, upload-time = "2025-09-13T11:26:36.909Z" },
+ { url = "https://files.pythonhosted.org/packages/5a/87/b70ad306ebb6f9b585f114d0ac2137d792b48be34d732d60e597c2f8465a/pydantic-2.12.5-py3-none-any.whl", hash = "sha256:e561593fccf61e8a20fc46dfc2dfe075b8be7d0188df33f221ad1f0139180f9d", size = 463580, upload-time = "2025-11-26T15:11:44.605Z" },
]
[[package]]
name = "pydantic-core"
-version = "2.33.2"
+version = "2.41.5"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions", marker = "platform_python_implementation != 'PyPy'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/ad/88/5f2260bdfae97aabf98f1778d43f69574390ad787afb646292a638c923d4/pydantic_core-2.33.2.tar.gz", hash = "sha256:7cb8bc3605c29176e1b105350d2e6474142d7c1bd1d9327c4a9bdb46bf827acc", size = 435195, upload-time = "2025-04-23T18:33:52.104Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/18/8a/2b41c97f554ec8c71f2a8a5f85cb56a8b0956addfe8b0efb5b3d77e8bdc3/pydantic_core-2.33.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a7ec89dc587667f22b6a0b6579c249fca9026ce7c333fc142ba42411fa243cdc", size = 2009000, upload-time = "2025-04-23T18:31:25.863Z" },
- { url = "https://files.pythonhosted.org/packages/a1/02/6224312aacb3c8ecbaa959897af57181fb6cf3a3d7917fd44d0f2917e6f2/pydantic_core-2.33.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3c6db6e52c6d70aa0d00d45cdb9b40f0433b96380071ea80b09277dba021ddf7", size = 1847996, upload-time = "2025-04-23T18:31:27.341Z" },
- { url = "https://files.pythonhosted.org/packages/d6/46/6dcdf084a523dbe0a0be59d054734b86a981726f221f4562aed313dbcb49/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e61206137cbc65e6d5256e1166f88331d3b6238e082d9f74613b9b765fb9025", size = 1880957, upload-time = "2025-04-23T18:31:28.956Z" },
- { url = "https://files.pythonhosted.org/packages/ec/6b/1ec2c03837ac00886ba8160ce041ce4e325b41d06a034adbef11339ae422/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eb8c529b2819c37140eb51b914153063d27ed88e3bdc31b71198a198e921e011", size = 1964199, upload-time = "2025-04-23T18:31:31.025Z" },
- { url = "https://files.pythonhosted.org/packages/2d/1d/6bf34d6adb9debd9136bd197ca72642203ce9aaaa85cfcbfcf20f9696e83/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c52b02ad8b4e2cf14ca7b3d918f3eb0ee91e63b3167c32591e57c4317e134f8f", size = 2120296, upload-time = "2025-04-23T18:31:32.514Z" },
- { url = "https://files.pythonhosted.org/packages/e0/94/2bd0aaf5a591e974b32a9f7123f16637776c304471a0ab33cf263cf5591a/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:96081f1605125ba0855dfda83f6f3df5ec90c61195421ba72223de35ccfb2f88", size = 2676109, upload-time = "2025-04-23T18:31:33.958Z" },
- { url = "https://files.pythonhosted.org/packages/f9/41/4b043778cf9c4285d59742281a769eac371b9e47e35f98ad321349cc5d61/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8f57a69461af2a5fa6e6bbd7a5f60d3b7e6cebb687f55106933188e79ad155c1", size = 2002028, upload-time = "2025-04-23T18:31:39.095Z" },
- { url = "https://files.pythonhosted.org/packages/cb/d5/7bb781bf2748ce3d03af04d5c969fa1308880e1dca35a9bd94e1a96a922e/pydantic_core-2.33.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:572c7e6c8bb4774d2ac88929e3d1f12bc45714ae5ee6d9a788a9fb35e60bb04b", size = 2100044, upload-time = "2025-04-23T18:31:41.034Z" },
- { url = "https://files.pythonhosted.org/packages/fe/36/def5e53e1eb0ad896785702a5bbfd25eed546cdcf4087ad285021a90ed53/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:db4b41f9bd95fbe5acd76d89920336ba96f03e149097365afe1cb092fceb89a1", size = 2058881, upload-time = "2025-04-23T18:31:42.757Z" },
- { url = "https://files.pythonhosted.org/packages/01/6c/57f8d70b2ee57fc3dc8b9610315949837fa8c11d86927b9bb044f8705419/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:fa854f5cf7e33842a892e5c73f45327760bc7bc516339fda888c75ae60edaeb6", size = 2227034, upload-time = "2025-04-23T18:31:44.304Z" },
- { url = "https://files.pythonhosted.org/packages/27/b9/9c17f0396a82b3d5cbea4c24d742083422639e7bb1d5bf600e12cb176a13/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:5f483cfb75ff703095c59e365360cb73e00185e01aaea067cd19acffd2ab20ea", size = 2234187, upload-time = "2025-04-23T18:31:45.891Z" },
- { url = "https://files.pythonhosted.org/packages/b0/6a/adf5734ffd52bf86d865093ad70b2ce543415e0e356f6cacabbc0d9ad910/pydantic_core-2.33.2-cp312-cp312-win32.whl", hash = "sha256:9cb1da0f5a471435a7bc7e439b8a728e8b61e59784b2af70d7c169f8dd8ae290", size = 1892628, upload-time = "2025-04-23T18:31:47.819Z" },
- { url = "https://files.pythonhosted.org/packages/43/e4/5479fecb3606c1368d496a825d8411e126133c41224c1e7238be58b87d7e/pydantic_core-2.33.2-cp312-cp312-win_amd64.whl", hash = "sha256:f941635f2a3d96b2973e867144fde513665c87f13fe0e193c158ac51bfaaa7b2", size = 1955866, upload-time = "2025-04-23T18:31:49.635Z" },
- { url = "https://files.pythonhosted.org/packages/0d/24/8b11e8b3e2be9dd82df4b11408a67c61bb4dc4f8e11b5b0fc888b38118b5/pydantic_core-2.33.2-cp312-cp312-win_arm64.whl", hash = "sha256:cca3868ddfaccfbc4bfb1d608e2ccaaebe0ae628e1416aeb9c4d88c001bb45ab", size = 1888894, upload-time = "2025-04-23T18:31:51.609Z" },
+sdist = { url = "https://files.pythonhosted.org/packages/71/70/23b021c950c2addd24ec408e9ab05d59b035b39d97cdc1130e1bce647bb6/pydantic_core-2.41.5.tar.gz", hash = "sha256:08daa51ea16ad373ffd5e7606252cc32f07bc72b28284b6bc9c6df804816476e", size = 460952, upload-time = "2025-11-04T13:43:49.098Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5f/5d/5f6c63eebb5afee93bcaae4ce9a898f3373ca23df3ccaef086d0233a35a7/pydantic_core-2.41.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:f41a7489d32336dbf2199c8c0a215390a751c5b014c2c1c5366e817202e9cdf7", size = 2110990, upload-time = "2025-11-04T13:39:58.079Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/32/9c2e8ccb57c01111e0fd091f236c7b371c1bccea0fa85247ac55b1e2b6b6/pydantic_core-2.41.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:070259a8818988b9a84a449a2a7337c7f430a22acc0859c6b110aa7212a6d9c0", size = 1896003, upload-time = "2025-11-04T13:39:59.956Z" },
+ { url = "https://files.pythonhosted.org/packages/68/b8/a01b53cb0e59139fbc9e4fda3e9724ede8de279097179be4ff31f1abb65a/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e96cea19e34778f8d59fe40775a7a574d95816eb150850a85a7a4c8f4b94ac69", size = 1919200, upload-time = "2025-11-04T13:40:02.241Z" },
+ { url = "https://files.pythonhosted.org/packages/38/de/8c36b5198a29bdaade07b5985e80a233a5ac27137846f3bc2d3b40a47360/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ed2e99c456e3fadd05c991f8f437ef902e00eedf34320ba2b0842bd1c3ca3a75", size = 2052578, upload-time = "2025-11-04T13:40:04.401Z" },
+ { url = "https://files.pythonhosted.org/packages/00/b5/0e8e4b5b081eac6cb3dbb7e60a65907549a1ce035a724368c330112adfdd/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:65840751b72fbfd82c3c640cff9284545342a4f1eb1586ad0636955b261b0b05", size = 2208504, upload-time = "2025-11-04T13:40:06.072Z" },
+ { url = "https://files.pythonhosted.org/packages/77/56/87a61aad59c7c5b9dc8caad5a41a5545cba3810c3e828708b3d7404f6cef/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e536c98a7626a98feb2d3eaf75944ef6f3dbee447e1f841eae16f2f0a72d8ddc", size = 2335816, upload-time = "2025-11-04T13:40:07.835Z" },
+ { url = "https://files.pythonhosted.org/packages/0d/76/941cc9f73529988688a665a5c0ecff1112b3d95ab48f81db5f7606f522d3/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eceb81a8d74f9267ef4081e246ffd6d129da5d87e37a77c9bde550cb04870c1c", size = 2075366, upload-time = "2025-11-04T13:40:09.804Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/43/ebef01f69baa07a482844faaa0a591bad1ef129253ffd0cdaa9d8a7f72d3/pydantic_core-2.41.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d38548150c39b74aeeb0ce8ee1d8e82696f4a4e16ddc6de7b1d8823f7de4b9b5", size = 2171698, upload-time = "2025-11-04T13:40:12.004Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/87/41f3202e4193e3bacfc2c065fab7706ebe81af46a83d3e27605029c1f5a6/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:c23e27686783f60290e36827f9c626e63154b82b116d7fe9adba1fda36da706c", size = 2132603, upload-time = "2025-11-04T13:40:13.868Z" },
+ { url = "https://files.pythonhosted.org/packages/49/7d/4c00df99cb12070b6bccdef4a195255e6020a550d572768d92cc54dba91a/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:482c982f814460eabe1d3bb0adfdc583387bd4691ef00b90575ca0d2b6fe2294", size = 2329591, upload-time = "2025-11-04T13:40:15.672Z" },
+ { url = "https://files.pythonhosted.org/packages/cc/6a/ebf4b1d65d458f3cda6a7335d141305dfa19bdc61140a884d165a8a1bbc7/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:bfea2a5f0b4d8d43adf9d7b8bf019fb46fdd10a2e5cde477fbcb9d1fa08c68e1", size = 2319068, upload-time = "2025-11-04T13:40:17.532Z" },
+ { url = "https://files.pythonhosted.org/packages/49/3b/774f2b5cd4192d5ab75870ce4381fd89cf218af999515baf07e7206753f0/pydantic_core-2.41.5-cp312-cp312-win32.whl", hash = "sha256:b74557b16e390ec12dca509bce9264c3bbd128f8a2c376eaa68003d7f327276d", size = 1985908, upload-time = "2025-11-04T13:40:19.309Z" },
+ { url = "https://files.pythonhosted.org/packages/86/45/00173a033c801cacf67c190fef088789394feaf88a98a7035b0e40d53dc9/pydantic_core-2.41.5-cp312-cp312-win_amd64.whl", hash = "sha256:1962293292865bca8e54702b08a4f26da73adc83dd1fcf26fbc875b35d81c815", size = 2020145, upload-time = "2025-11-04T13:40:21.548Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/22/91fbc821fa6d261b376a3f73809f907cec5ca6025642c463d3488aad22fb/pydantic_core-2.41.5-cp312-cp312-win_arm64.whl", hash = "sha256:1746d4a3d9a794cacae06a5eaaccb4b8643a131d45fbc9af23e353dc0a5ba5c3", size = 1976179, upload-time = "2025-11-04T13:40:23.393Z" },
+ { url = "https://files.pythonhosted.org/packages/09/32/59b0c7e63e277fa7911c2fc70ccfb45ce4b98991e7ef37110663437005af/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:7da7087d756b19037bc2c06edc6c170eeef3c3bafcb8f532ff17d64dc427adfd", size = 2110495, upload-time = "2025-11-04T13:42:49.689Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/81/05e400037eaf55ad400bcd318c05bb345b57e708887f07ddb2d20e3f0e98/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:aabf5777b5c8ca26f7824cb4a120a740c9588ed58df9b2d196ce92fba42ff8dc", size = 1915388, upload-time = "2025-11-04T13:42:52.215Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/0d/e3549b2399f71d56476b77dbf3cf8937cec5cd70536bdc0e374a421d0599/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c007fe8a43d43b3969e8469004e9845944f1a80e6acd47c150856bb87f230c56", size = 1942879, upload-time = "2025-11-04T13:42:56.483Z" },
+ { url = "https://files.pythonhosted.org/packages/f7/07/34573da085946b6a313d7c42f82f16e8920bfd730665de2d11c0c37a74b5/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76d0819de158cd855d1cbb8fcafdf6f5cf1eb8e470abe056d5d161106e38062b", size = 2139017, upload-time = "2025-11-04T13:42:59.471Z" },
]
[[package]]
@@ -3019,14 +3023,14 @@ wheels = [
[[package]]
name = "typing-inspection"
-version = "0.4.1"
+version = "0.4.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions", marker = "platform_python_implementation != 'PyPy'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/f8/b1/0c11f5058406b3af7609f121aaa6b609744687f1d158b3c3a5bf4cc94238/typing_inspection-0.4.1.tar.gz", hash = "sha256:6ae134cc0203c33377d43188d4064e9b357dba58cff3185f22924610e70a9d28", size = 75726, upload-time = "2025-05-21T18:55:23.885Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/55/e3/70399cb7dd41c10ac53367ae42139cf4b1ca5f36bb3dc6c9d33acdb43655/typing_inspection-0.4.2.tar.gz", hash = "sha256:ba561c48a67c5958007083d386c3295464928b01faa735ab8547c5692e87f464", size = 75949, upload-time = "2025-10-01T02:14:41.687Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/17/69/cd203477f944c353c31bade965f880aa1061fd6bf05ded0726ca845b6ff7/typing_inspection-0.4.1-py3-none-any.whl", hash = "sha256:389055682238f53b04f7badcb49b989835495a96700ced5dab2d8feae4b26f51", size = 14552, upload-time = "2025-05-21T18:55:22.152Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" },
]
[[package]]