We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. 

This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.

https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `litestar/_openapi/path_item.py`
Content:
```
1 from __future__ import annotations
2 
3 from inspect import cleandoc
4 from typing import TYPE_CHECKING
5 
6 from litestar._openapi.parameters import create_parameter_for_handler
7 from litestar._openapi.request_body import create_request_body
8 from litestar._openapi.responses import create_responses
9 from litestar._openapi.schema_generation import SchemaCreator
10 from litestar._openapi.utils import SEPARATORS_CLEANUP_PATTERN
11 from litestar.openapi.spec.path_item import PathItem
12 from litestar.utils.helpers import unwrap_partial
13 
14 __all__ = ("create_path_item", "extract_layered_values", "get_description_for_handler")
15 
16 
17 if TYPE_CHECKING:
18     from litestar.handlers.http_handlers import HTTPRouteHandler
19     from litestar.openapi.spec import Schema, SecurityRequirement
20     from litestar.plugins import OpenAPISchemaPluginProtocol
21     from litestar.routes import HTTPRoute
22     from litestar.types.callable_types import OperationIDCreator
23 
24 
25 def get_description_for_handler(route_handler: HTTPRouteHandler, use_handler_docstrings: bool) -> str | None:
26     """Produce the operation description for a route handler, either by using the description value if provided,
27 
28     or the docstring - if config is enabled.
29 
30     Args:
31         route_handler: A route handler instance.
32         use_handler_docstrings: If ``True`` and `route_handler.description`` is ``None` returns docstring of wrapped
33             handler function.
34 
35     Returns:
36         An optional description string
37     """
38     handler_description = route_handler.description
39     if handler_description is None and use_handler_docstrings:
40         fn = unwrap_partial(route_handler.fn.value)
41         return cleandoc(fn.__doc__) if fn.__doc__ else None
42     return handler_description
43 
44 
45 def extract_layered_values(
46     route_handler: HTTPRouteHandler,
47 ) -> tuple[list[str] | None, list[dict[str, list[str]]] | None]:
48     """Extract the tags and security values from the route handler layers.
49 
50     Args:
51         route_handler: A Route Handler instance.
52 
53     Returns:
54         A tuple of optional lists.
55     """
56     tags: list[str] = []
57     security: list[SecurityRequirement] = []
58     for layer in route_handler.ownership_layers:
59         if layer.tags:
60             tags.extend(layer.tags)
61         if layer.security:
62             security.extend(layer.security)
63     return sorted(set(tags)) if tags else None, security or None
64 
65 
66 def create_path_item(
67     create_examples: bool,
68     operation_id_creator: OperationIDCreator,
69     plugins: list[OpenAPISchemaPluginProtocol],
70     route: HTTPRoute,
71     schemas: dict[str, Schema],
72     use_handler_docstrings: bool,
73 ) -> tuple[PathItem, list[str]]:
74     """Create a PathItem for the given route parsing all http_methods into Operation Models.
75 
76     Args:
77         create_examples: Whether to auto-generate examples.
78         operation_id_creator: A function to generate operation ids.
79         plugins: A list of plugins.
80         route: An HTTPRoute instance.
81         schemas: A mapping of schemas.
82         use_handler_docstrings: Whether to use the handler docstring.
83 
84     Returns:
85         A tuple containing the path item and a list of operation ids.
86     """
87     path_item = PathItem()
88     operation_ids: list[str] = []
89 
90     request_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=True)
91     response_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=False)
92     for http_method, handler_tuple in route.route_handler_map.items():
93         route_handler, _ = handler_tuple
94 
95         if route_handler.include_in_schema:
96             handler_fields = route_handler.signature_model._fields if route_handler.signature_model else {}
97             parameters = (
98                 create_parameter_for_handler(
99                     route_handler=route_handler,
100                     handler_fields=handler_fields,
101                     path_parameters=route.path_parameters,
102                     schema_creator=request_schema_creator,
103                 )
104                 or None
105             )
106             raises_validation_error = bool("data" in handler_fields or path_item.parameters or parameters)
107 
108             request_body = None
109             if "data" in handler_fields:
110                 request_body = create_request_body(
111                     route_handler=route_handler, field=handler_fields["data"], schema_creator=request_schema_creator
112                 )
113             operation_id = route_handler.operation_id or operation_id_creator(
114                 route_handler, http_method, route.path_components
115             )
116             tags, security = extract_layered_values(route_handler)
117             operation = route_handler.operation_class(
118                 operation_id=operation_id,
119                 tags=tags,
120                 summary=route_handler.summary or SEPARATORS_CLEANUP_PATTERN.sub("", route_handler.handler_name.title()),
121                 description=get_description_for_handler(route_handler, use_handler_docstrings),
122                 deprecated=route_handler.deprecated,
123                 responses=create_responses(
124                     route_handler=route_handler,
125                     raises_validation_error=raises_validation_error,
126                     schema_creator=response_schema_creator,
127                 ),
128                 request_body=request_body,
129                 parameters=parameters,  # type: ignore[arg-type]
130                 security=security,
131             )
132             operation_ids.append(operation_id)
133             setattr(path_item, http_method.lower(), operation)
134 
135     return path_item, operation_ids
136
```

Path: `litestar/contrib/pydantic/pydantic_init_plugin.py`
Content:
```
1 from __future__ import annotations
2 
3 from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
4 from uuid import UUID
5 
6 from msgspec import ValidationError
7 
8 from litestar.exceptions import MissingDependencyException
9 from litestar.plugins import InitPluginProtocol
10 from litestar.serialization._msgspec_utils import ExtendedMsgSpecValidationError
11 from litestar.utils import is_class_and_subclass, is_pydantic_model_class
12 
13 if TYPE_CHECKING:
14     from litestar.config.app import AppConfig
15 
16 try:
17     import pydantic
18 except ImportError as e:
19     raise MissingDependencyException("pydantic") from e
20 
21 T = TypeVar("T")
22 
23 
24 def _dec_pydantic(model_type: type[pydantic.BaseModel], value: Any) -> pydantic.BaseModel:
25     try:
26         return (
27             model_type.model_validate(value, strict=False)
28             if hasattr(model_type, "model_validate")
29             else model_type.parse_obj(value)
30         )
31     except pydantic.ValidationError as e:
32         raise ExtendedMsgSpecValidationError(errors=cast("list[dict[str, Any]]", e.errors())) from e
33 
34 
35 def _dec_pydantic_uuid(
36     uuid_type: type[pydantic.UUID1] | type[pydantic.UUID3] | type[pydantic.UUID4] | type[pydantic.UUID5],
37     value: Any,
38 ) -> type[pydantic.UUID1] | type[pydantic.UUID3] | type[pydantic.UUID4] | type[pydantic.UUID5]:  # pragma: no cover
39     if isinstance(value, str):
40         value = uuid_type(value)
41 
42     elif isinstance(value, (bytes, bytearray)):
43         try:
44             value = uuid_type(value.decode())
45         except ValueError:
46             # 16 bytes in big-endian order as the bytes argument fail
47             # the above check
48             value = uuid_type(bytes=value)
49     elif isinstance(value, UUID):
50         value = uuid_type(str(value))
51 
52     if not isinstance(value, uuid_type):
53         raise ValidationError(f"Invalid UUID: {value!r}")
54 
55     if value._required_version != value.version:  # pyright: ignore
56         raise ValidationError(f"Invalid UUID version: {value!r}")
57 
58     return cast("type[pydantic.UUID1] | type[pydantic.UUID3] | type[pydantic.UUID4] | type[pydantic.UUID5]", value)
59 
60 
61 def _is_pydantic_uuid(value: Any) -> bool:  # pragma: no cover
62     return is_class_and_subclass(value, (pydantic.UUID1, pydantic.UUID3, pydantic.UUID4, pydantic.UUID5))
63 
64 
65 _base_encoders: dict[Any, Callable[[Any], Any]] = {
66     pydantic.EmailStr: str,
67     pydantic.NameEmail: str,
68     pydantic.ByteSize: lambda val: val.real,
69 }
70 
71 
72 class PydanticInitPlugin(InitPluginProtocol):
73     @classmethod
74     def encoders(cls) -> dict[Any, Callable[[Any], Any]]:
75         if pydantic.VERSION.startswith("1"):  # pragma: no cover
76             return {**_base_encoders, **cls._create_pydantic_v1_encoders()}
77         return {**_base_encoders, **cls._create_pydantic_v2_encoders()}
78 
79     @classmethod
80     def decoders(cls) -> list[tuple[Callable[[Any], bool], Callable[[Any, Any], Any]]]:
81         decoders: list[tuple[Callable[[Any], bool], Callable[[Any, Any], Any]]] = [
82             (is_pydantic_model_class, _dec_pydantic)
83         ]
84 
85         if pydantic.VERSION.startswith("1"):  # pragma: no cover
86             decoders.append((_is_pydantic_uuid, _dec_pydantic_uuid))
87 
88         return decoders
89 
90     @staticmethod
91     def _create_pydantic_v1_encoders() -> dict[Any, Callable[[Any], Any]]:  # pragma: no cover
92         return {
93             pydantic.BaseModel: lambda model: {
94                 k: v.decode() if isinstance(v, bytes) else v for k, v in model.dict().items()
95             },
96             pydantic.SecretField: str,
97             pydantic.StrictBool: int,
98             pydantic.color.Color: str,  # pyright: ignore
99             pydantic.ConstrainedBytes: lambda val: val.decode("utf-8"),
100             pydantic.ConstrainedDate: lambda val: val.isoformat(),
101         }
102 
103     @staticmethod
104     def _create_pydantic_v2_encoders() -> dict[Any, Callable[[Any], Any]]:
105         from pydantic_extra_types import color
106 
107         return {
108             pydantic.BaseModel: lambda model: model.model_dump(mode="json"),
109             color.Color: str,
110             pydantic.types.SecretStr: lambda val: "**********" if val else "",
111             pydantic.types.SecretBytes: lambda val: "**********" if val else "",
112         }
113 
114     def on_app_init(self, app_config: AppConfig) -> AppConfig:
115         app_config.type_encoders = {**(app_config.type_encoders or {}), **self.encoders()}
116         app_config.type_decoders = [*(app_config.type_decoders or []), *self.decoders()]
117         return app_config
118
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/litestar/_openapi/path_item.py b/litestar/_openapi/path_item.py
--- a/litestar/_openapi/path_item.py
+++ b/litestar/_openapi/path_item.py
@@ -88,7 +88,7 @@
     operation_ids: list[str] = []
 
     request_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=True)
-    response_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=False)
+    response_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=True)
     for http_method, handler_tuple in route.route_handler_map.items():
         route_handler, _ = handler_tuple
 
diff --git a/litestar/contrib/pydantic/pydantic_init_plugin.py b/litestar/contrib/pydantic/pydantic_init_plugin.py
--- a/litestar/contrib/pydantic/pydantic_init_plugin.py
+++ b/litestar/contrib/pydantic/pydantic_init_plugin.py
@@ -102,16 +102,20 @@
 
     @staticmethod
     def _create_pydantic_v2_encoders() -> dict[Any, Callable[[Any], Any]]:
-        from pydantic_extra_types import color
-
-        return {
+        try:
+            from pydantic_extra_types import color
+        except ImportError:
+            color = None  # type: ignore[assignment]
+        encoders: dict[Any, Callable[[Any], Any]] = {
             pydantic.BaseModel: lambda model: model.model_dump(mode="json"),
-            color.Color: str,
             pydantic.types.SecretStr: lambda val: "**********" if val else "",
             pydantic.types.SecretBytes: lambda val: "**********" if val else "",
         }
+        if color:
+            encoders[color.Color] = str
+        return encoders
 
     def on_app_init(self, app_config: AppConfig) -> AppConfig:
-        app_config.type_encoders = {**(app_config.type_encoders or {}), **self.encoders()}
-        app_config.type_decoders = [*(app_config.type_decoders or []), *self.decoders()]
+        app_config.type_encoders = {**self.encoders(), **(app_config.type_encoders or {})}
+        app_config.type_decoders = [*self.decoders(), *(app_config.type_decoders or [])]
         return app_config

{"golden_diff": "diff --git a/litestar/_openapi/path_item.py b/litestar/_openapi/path_item.py\n--- a/litestar/_openapi/path_item.py\n+++ b/litestar/_openapi/path_item.py\n@@ -88,7 +88,7 @@\n     operation_ids: list[str] = []\n \n     request_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=True)\n-    response_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=False)\n+    response_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=True)\n     for http_method, handler_tuple in route.route_handler_map.items():\n         route_handler, _ = handler_tuple\n \ndiff --git a/litestar/contrib/pydantic/pydantic_init_plugin.py b/litestar/contrib/pydantic/pydantic_init_plugin.py\n--- a/litestar/contrib/pydantic/pydantic_init_plugin.py\n+++ b/litestar/contrib/pydantic/pydantic_init_plugin.py\n@@ -102,16 +102,20 @@\n \n     @staticmethod\n     def _create_pydantic_v2_encoders() -> dict[Any, Callable[[Any], Any]]:\n-        from pydantic_extra_types import color\n-\n-        return {\n+        try:\n+            from pydantic_extra_types import color\n+        except ImportError:\n+            color = None  # type: ignore[assignment]\n+        encoders: dict[Any, Callable[[Any], Any]] = {\n             pydantic.BaseModel: lambda model: model.model_dump(mode=\"json\"),\n-            color.Color: str,\n             pydantic.types.SecretStr: lambda val: \"**********\" if val else \"\",\n             pydantic.types.SecretBytes: lambda val: \"**********\" if val else \"\",\n         }\n+        if color:\n+            encoders[color.Color] = str\n+        return encoders\n \n     def on_app_init(self, app_config: AppConfig) -> AppConfig:\n-        app_config.type_encoders = {**(app_config.type_encoders or {}), **self.encoders()}\n-        app_config.type_decoders = [*(app_config.type_decoders or []), *self.decoders()]\n+        app_config.type_encoders = {**self.encoders(), **(app_config.type_encoders or {})}\n+        app_config.type_decoders = [*self.decoders(), *(app_config.type_decoders or [])]\n         return app_config\n", "issue": "StaticFilesConfig and virtual directories\nI'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. \r\n\r\nThis is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.\r\n\r\nhttps://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32\n", "before_files": [{"content": "from __future__ import annotations\n\nfrom inspect import cleandoc\nfrom typing import TYPE_CHECKING\n\nfrom litestar._openapi.parameters import create_parameter_for_handler\nfrom litestar._openapi.request_body import create_request_body\nfrom litestar._openapi.responses import create_responses\nfrom litestar._openapi.schema_generation import SchemaCreator\nfrom litestar._openapi.utils import SEPARATORS_CLEANUP_PATTERN\nfrom litestar.openapi.spec.path_item import PathItem\nfrom litestar.utils.helpers import unwrap_partial\n\n__all__ = (\"create_path_item\", \"extract_layered_values\", \"get_description_for_handler\")\n\n\nif TYPE_CHECKING:\n    from litestar.handlers.http_handlers import HTTPRouteHandler\n    from litestar.openapi.spec import Schema, SecurityRequirement\n    from litestar.plugins import OpenAPISchemaPluginProtocol\n    from litestar.routes import HTTPRoute\n    from litestar.types.callable_types import OperationIDCreator\n\n\ndef get_description_for_handler(route_handler: HTTPRouteHandler, use_handler_docstrings: bool) -> str | None:\n    \"\"\"Produce the operation description for a route handler, either by using the description value if provided,\n\n    or the docstring - if config is enabled.\n\n    Args:\n        route_handler: A route handler instance.\n        use_handler_docstrings: If ``True`` and `route_handler.description`` is ``None` returns docstring of wrapped\n            handler function.\n\n    Returns:\n        An optional description string\n    \"\"\"\n    handler_description = route_handler.description\n    if handler_description is None and use_handler_docstrings:\n        fn = unwrap_partial(route_handler.fn.value)\n        return cleandoc(fn.__doc__) if fn.__doc__ else None\n    return handler_description\n\n\ndef extract_layered_values(\n    route_handler: HTTPRouteHandler,\n) -> tuple[list[str] | None, list[dict[str, list[str]]] | None]:\n    \"\"\"Extract the tags and security values from the route handler layers.\n\n    Args:\n        route_handler: A Route Handler instance.\n\n    Returns:\n        A tuple of optional lists.\n    \"\"\"\n    tags: list[str] = []\n    security: list[SecurityRequirement] = []\n    for layer in route_handler.ownership_layers:\n        if layer.tags:\n            tags.extend(layer.tags)\n        if layer.security:\n            security.extend(layer.security)\n    return sorted(set(tags)) if tags else None, security or None\n\n\ndef create_path_item(\n    create_examples: bool,\n    operation_id_creator: OperationIDCreator,\n    plugins: list[OpenAPISchemaPluginProtocol],\n    route: HTTPRoute,\n    schemas: dict[str, Schema],\n    use_handler_docstrings: bool,\n) -> tuple[PathItem, list[str]]:\n    \"\"\"Create a PathItem for the given route parsing all http_methods into Operation Models.\n\n    Args:\n        create_examples: Whether to auto-generate examples.\n        operation_id_creator: A function to generate operation ids.\n        plugins: A list of plugins.\n        route: An HTTPRoute instance.\n        schemas: A mapping of schemas.\n        use_handler_docstrings: Whether to use the handler docstring.\n\n    Returns:\n        A tuple containing the path item and a list of operation ids.\n    \"\"\"\n    path_item = PathItem()\n    operation_ids: list[str] = []\n\n    request_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=True)\n    response_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=False)\n    for http_method, handler_tuple in route.route_handler_map.items():\n        route_handler, _ = handler_tuple\n\n        if route_handler.include_in_schema:\n            handler_fields = route_handler.signature_model._fields if route_handler.signature_model else {}\n            parameters = (\n                create_parameter_for_handler(\n                    route_handler=route_handler,\n                    handler_fields=handler_fields,\n                    path_parameters=route.path_parameters,\n                    schema_creator=request_schema_creator,\n                )\n                or None\n            )\n            raises_validation_error = bool(\"data\" in handler_fields or path_item.parameters or parameters)\n\n            request_body = None\n            if \"data\" in handler_fields:\n                request_body = create_request_body(\n                    route_handler=route_handler, field=handler_fields[\"data\"], schema_creator=request_schema_creator\n                )\n            operation_id = route_handler.operation_id or operation_id_creator(\n                route_handler, http_method, route.path_components\n            )\n            tags, security = extract_layered_values(route_handler)\n            operation = route_handler.operation_class(\n                operation_id=operation_id,\n                tags=tags,\n                summary=route_handler.summary or SEPARATORS_CLEANUP_PATTERN.sub(\"\", route_handler.handler_name.title()),\n                description=get_description_for_handler(route_handler, use_handler_docstrings),\n                deprecated=route_handler.deprecated,\n                responses=create_responses(\n                    route_handler=route_handler,\n                    raises_validation_error=raises_validation_error,\n                    schema_creator=response_schema_creator,\n                ),\n                request_body=request_body,\n                parameters=parameters,  # type: ignore[arg-type]\n                security=security,\n            )\n            operation_ids.append(operation_id)\n            setattr(path_item, http_method.lower(), operation)\n\n    return path_item, operation_ids\n", "path": "litestar/_openapi/path_item.py"}, {"content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any, Callable, TypeVar, cast\nfrom uuid import UUID\n\nfrom msgspec import ValidationError\n\nfrom litestar.exceptions import MissingDependencyException\nfrom litestar.plugins import InitPluginProtocol\nfrom litestar.serialization._msgspec_utils import ExtendedMsgSpecValidationError\nfrom litestar.utils import is_class_and_subclass, is_pydantic_model_class\n\nif TYPE_CHECKING:\n    from litestar.config.app import AppConfig\n\ntry:\n    import pydantic\nexcept ImportError as e:\n    raise MissingDependencyException(\"pydantic\") from e\n\nT = TypeVar(\"T\")\n\n\ndef _dec_pydantic(model_type: type[pydantic.BaseModel], value: Any) -> pydantic.BaseModel:\n    try:\n        return (\n            model_type.model_validate(value, strict=False)\n            if hasattr(model_type, \"model_validate\")\n            else model_type.parse_obj(value)\n        )\n    except pydantic.ValidationError as e:\n        raise ExtendedMsgSpecValidationError(errors=cast(\"list[dict[str, Any]]\", e.errors())) from e\n\n\ndef _dec_pydantic_uuid(\n    uuid_type: type[pydantic.UUID1] | type[pydantic.UUID3] | type[pydantic.UUID4] | type[pydantic.UUID5],\n    value: Any,\n) -> type[pydantic.UUID1] | type[pydantic.UUID3] | type[pydantic.UUID4] | type[pydantic.UUID5]:  # pragma: no cover\n    if isinstance(value, str):\n        value = uuid_type(value)\n\n    elif isinstance(value, (bytes, bytearray)):\n        try:\n            value = uuid_type(value.decode())\n        except ValueError:\n            # 16 bytes in big-endian order as the bytes argument fail\n            # the above check\n            value = uuid_type(bytes=value)\n    elif isinstance(value, UUID):\n        value = uuid_type(str(value))\n\n    if not isinstance(value, uuid_type):\n        raise ValidationError(f\"Invalid UUID: {value!r}\")\n\n    if value._required_version != value.version:  # pyright: ignore\n        raise ValidationError(f\"Invalid UUID version: {value!r}\")\n\n    return cast(\"type[pydantic.UUID1] | type[pydantic.UUID3] | type[pydantic.UUID4] | type[pydantic.UUID5]\", value)\n\n\ndef _is_pydantic_uuid(value: Any) -> bool:  # pragma: no cover\n    return is_class_and_subclass(value, (pydantic.UUID1, pydantic.UUID3, pydantic.UUID4, pydantic.UUID5))\n\n\n_base_encoders: dict[Any, Callable[[Any], Any]] = {\n    pydantic.EmailStr: str,\n    pydantic.NameEmail: str,\n    pydantic.ByteSize: lambda val: val.real,\n}\n\n\nclass PydanticInitPlugin(InitPluginProtocol):\n    @classmethod\n    def encoders(cls) -> dict[Any, Callable[[Any], Any]]:\n        if pydantic.VERSION.startswith(\"1\"):  # pragma: no cover\n            return {**_base_encoders, **cls._create_pydantic_v1_encoders()}\n        return {**_base_encoders, **cls._create_pydantic_v2_encoders()}\n\n    @classmethod\n    def decoders(cls) -> list[tuple[Callable[[Any], bool], Callable[[Any, Any], Any]]]:\n        decoders: list[tuple[Callable[[Any], bool], Callable[[Any, Any], Any]]] = [\n            (is_pydantic_model_class, _dec_pydantic)\n        ]\n\n        if pydantic.VERSION.startswith(\"1\"):  # pragma: no cover\n            decoders.append((_is_pydantic_uuid, _dec_pydantic_uuid))\n\n        return decoders\n\n    @staticmethod\n    def _create_pydantic_v1_encoders() -> dict[Any, Callable[[Any], Any]]:  # pragma: no cover\n        return {\n            pydantic.BaseModel: lambda model: {\n                k: v.decode() if isinstance(v, bytes) else v for k, v in model.dict().items()\n            },\n            pydantic.SecretField: str,\n            pydantic.StrictBool: int,\n            pydantic.color.Color: str,  # pyright: ignore\n            pydantic.ConstrainedBytes: lambda val: val.decode(\"utf-8\"),\n            pydantic.ConstrainedDate: lambda val: val.isoformat(),\n        }\n\n    @staticmethod\n    def _create_pydantic_v2_encoders() -> dict[Any, Callable[[Any], Any]]:\n        from pydantic_extra_types import color\n\n        return {\n            pydantic.BaseModel: lambda model: model.model_dump(mode=\"json\"),\n            color.Color: str,\n            pydantic.types.SecretStr: lambda val: \"**********\" if val else \"\",\n            pydantic.types.SecretBytes: lambda val: \"**********\" if val else \"\",\n        }\n\n    def on_app_init(self, app_config: AppConfig) -> AppConfig:\n        app_config.type_encoders = {**(app_config.type_encoders or {}), **self.encoders()}\n        app_config.type_decoders = [*(app_config.type_decoders or []), *self.decoders()]\n        return app_config\n", "path": "litestar/contrib/pydantic/pydantic_init_plugin.py"}], "after_files": [{"content": "from __future__ import annotations\n\nfrom inspect import cleandoc\nfrom typing import TYPE_CHECKING\n\nfrom litestar._openapi.parameters import create_parameter_for_handler\nfrom litestar._openapi.request_body import create_request_body\nfrom litestar._openapi.responses import create_responses\nfrom litestar._openapi.schema_generation import SchemaCreator\nfrom litestar._openapi.utils import SEPARATORS_CLEANUP_PATTERN\nfrom litestar.openapi.spec.path_item import PathItem\nfrom litestar.utils.helpers import unwrap_partial\n\n__all__ = (\"create_path_item\", \"extract_layered_values\", \"get_description_for_handler\")\n\n\nif TYPE_CHECKING:\n    from litestar.handlers.http_handlers import HTTPRouteHandler\n    from litestar.openapi.spec import Schema, SecurityRequirement\n    from litestar.plugins import OpenAPISchemaPluginProtocol\n    from litestar.routes import HTTPRoute\n    from litestar.types.callable_types import OperationIDCreator\n\n\ndef get_description_for_handler(route_handler: HTTPRouteHandler, use_handler_docstrings: bool) -> str | None:\n    \"\"\"Produce the operation description for a route handler, either by using the description value if provided,\n\n    or the docstring - if config is enabled.\n\n    Args:\n        route_handler: A route handler instance.\n        use_handler_docstrings: If ``True`` and `route_handler.description`` is ``None` returns docstring of wrapped\n            handler function.\n\n    Returns:\n        An optional description string\n    \"\"\"\n    handler_description = route_handler.description\n    if handler_description is None and use_handler_docstrings:\n        fn = unwrap_partial(route_handler.fn.value)\n        return cleandoc(fn.__doc__) if fn.__doc__ else None\n    return handler_description\n\n\ndef extract_layered_values(\n    route_handler: HTTPRouteHandler,\n) -> tuple[list[str] | None, list[dict[str, list[str]]] | None]:\n    \"\"\"Extract the tags and security values from the route handler layers.\n\n    Args:\n        route_handler: A Route Handler instance.\n\n    Returns:\n        A tuple of optional lists.\n    \"\"\"\n    tags: list[str] = []\n    security: list[SecurityRequirement] = []\n    for layer in route_handler.ownership_layers:\n        if layer.tags:\n            tags.extend(layer.tags)\n        if layer.security:\n            security.extend(layer.security)\n    return sorted(set(tags)) if tags else None, security or None\n\n\ndef create_path_item(\n    create_examples: bool,\n    operation_id_creator: OperationIDCreator,\n    plugins: list[OpenAPISchemaPluginProtocol],\n    route: HTTPRoute,\n    schemas: dict[str, Schema],\n    use_handler_docstrings: bool,\n) -> tuple[PathItem, list[str]]:\n    \"\"\"Create a PathItem for the given route parsing all http_methods into Operation Models.\n\n    Args:\n        create_examples: Whether to auto-generate examples.\n        operation_id_creator: A function to generate operation ids.\n        plugins: A list of plugins.\n        route: An HTTPRoute instance.\n        schemas: A mapping of schemas.\n        use_handler_docstrings: Whether to use the handler docstring.\n\n    Returns:\n        A tuple containing the path item and a list of operation ids.\n    \"\"\"\n    path_item = PathItem()\n    operation_ids: list[str] = []\n\n    request_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=True)\n    response_schema_creator = SchemaCreator(create_examples, plugins, schemas, prefer_alias=True)\n    for http_method, handler_tuple in route.route_handler_map.items():\n        route_handler, _ = handler_tuple\n\n        if route_handler.include_in_schema:\n            handler_fields = route_handler.signature_model._fields if route_handler.signature_model else {}\n            parameters = (\n                create_parameter_for_handler(\n                    route_handler=route_handler,\n                    handler_fields=handler_fields,\n                    path_parameters=route.path_parameters,\n                    schema_creator=request_schema_creator,\n                )\n                or None\n            )\n            raises_validation_error = bool(\"data\" in handler_fields or path_item.parameters or parameters)\n\n            request_body = None\n            if \"data\" in handler_fields:\n                request_body = create_request_body(\n                    route_handler=route_handler, field=handler_fields[\"data\"], schema_creator=request_schema_creator\n                )\n            operation_id = route_handler.operation_id or operation_id_creator(\n                route_handler, http_method, route.path_components\n            )\n            tags, security = extract_layered_values(route_handler)\n            operation = route_handler.operation_class(\n                operation_id=operation_id,\n                tags=tags,\n                summary=route_handler.summary or SEPARATORS_CLEANUP_PATTERN.sub(\"\", route_handler.handler_name.title()),\n                description=get_description_for_handler(route_handler, use_handler_docstrings),\n                deprecated=route_handler.deprecated,\n                responses=create_responses(\n                    route_handler=route_handler,\n                    raises_validation_error=raises_validation_error,\n                    schema_creator=response_schema_creator,\n                ),\n                request_body=request_body,\n                parameters=parameters,  # type: ignore[arg-type]\n                security=security,\n            )\n            operation_ids.append(operation_id)\n            setattr(path_item, http_method.lower(), operation)\n\n    return path_item, operation_ids\n", "path": "litestar/_openapi/path_item.py"}, {"content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any, Callable, TypeVar, cast\nfrom uuid import UUID\n\nfrom msgspec import ValidationError\n\nfrom litestar.exceptions import MissingDependencyException\nfrom litestar.plugins import InitPluginProtocol\nfrom litestar.serialization._msgspec_utils import ExtendedMsgSpecValidationError\nfrom litestar.utils import is_class_and_subclass, is_pydantic_model_class\n\nif TYPE_CHECKING:\n    from litestar.config.app import AppConfig\n\ntry:\n    import pydantic\nexcept ImportError as e:\n    raise MissingDependencyException(\"pydantic\") from e\n\nT = TypeVar(\"T\")\n\n\ndef _dec_pydantic(model_type: type[pydantic.BaseModel], value: Any) -> pydantic.BaseModel:\n    try:\n        return (\n            model_type.model_validate(value, strict=False)\n            if hasattr(model_type, \"model_validate\")\n            else model_type.parse_obj(value)\n        )\n    except pydantic.ValidationError as e:\n        raise ExtendedMsgSpecValidationError(errors=cast(\"list[dict[str, Any]]\", e.errors())) from e\n\n\ndef _dec_pydantic_uuid(\n    uuid_type: type[pydantic.UUID1] | type[pydantic.UUID3] | type[pydantic.UUID4] | type[pydantic.UUID5],\n    value: Any,\n) -> type[pydantic.UUID1] | type[pydantic.UUID3] | type[pydantic.UUID4] | type[pydantic.UUID5]:  # pragma: no cover\n    if isinstance(value, str):\n        value = uuid_type(value)\n\n    elif isinstance(value, (bytes, bytearray)):\n        try:\n            value = uuid_type(value.decode())\n        except ValueError:\n            # 16 bytes in big-endian order as the bytes argument fail\n            # the above check\n            value = uuid_type(bytes=value)\n    elif isinstance(value, UUID):\n        value = uuid_type(str(value))\n\n    if not isinstance(value, uuid_type):\n        raise ValidationError(f\"Invalid UUID: {value!r}\")\n\n    if value._required_version != value.version:  # pyright: ignore\n        raise ValidationError(f\"Invalid UUID version: {value!r}\")\n\n    return cast(\"type[pydantic.UUID1] | type[pydantic.UUID3] | type[pydantic.UUID4] | type[pydantic.UUID5]\", value)\n\n\ndef _is_pydantic_uuid(value: Any) -> bool:  # pragma: no cover\n    return is_class_and_subclass(value, (pydantic.UUID1, pydantic.UUID3, pydantic.UUID4, pydantic.UUID5))\n\n\n_base_encoders: dict[Any, Callable[[Any], Any]] = {\n    pydantic.EmailStr: str,\n    pydantic.NameEmail: str,\n    pydantic.ByteSize: lambda val: val.real,\n}\n\n\nclass PydanticInitPlugin(InitPluginProtocol):\n    @classmethod\n    def encoders(cls) -> dict[Any, Callable[[Any], Any]]:\n        if pydantic.VERSION.startswith(\"1\"):  # pragma: no cover\n            return {**_base_encoders, **cls._create_pydantic_v1_encoders()}\n        return {**_base_encoders, **cls._create_pydantic_v2_encoders()}\n\n    @classmethod\n    def decoders(cls) -> list[tuple[Callable[[Any], bool], Callable[[Any, Any], Any]]]:\n        decoders: list[tuple[Callable[[Any], bool], Callable[[Any, Any], Any]]] = [\n            (is_pydantic_model_class, _dec_pydantic)\n        ]\n\n        if pydantic.VERSION.startswith(\"1\"):  # pragma: no cover\n            decoders.append((_is_pydantic_uuid, _dec_pydantic_uuid))\n\n        return decoders\n\n    @staticmethod\n    def _create_pydantic_v1_encoders() -> dict[Any, Callable[[Any], Any]]:  # pragma: no cover\n        return {\n            pydantic.BaseModel: lambda model: {\n                k: v.decode() if isinstance(v, bytes) else v for k, v in model.dict().items()\n            },\n            pydantic.SecretField: str,\n            pydantic.StrictBool: int,\n            pydantic.color.Color: str,  # pyright: ignore\n            pydantic.ConstrainedBytes: lambda val: val.decode(\"utf-8\"),\n            pydantic.ConstrainedDate: lambda val: val.isoformat(),\n        }\n\n    @staticmethod\n    def _create_pydantic_v2_encoders() -> dict[Any, Callable[[Any], Any]]:\n        try:\n            from pydantic_extra_types import color\n        except ImportError:\n            color = None  # type: ignore[assignment]\n        encoders: dict[Any, Callable[[Any], Any]] = {\n            pydantic.BaseModel: lambda model: model.model_dump(mode=\"json\"),\n            pydantic.types.SecretStr: lambda val: \"**********\" if val else \"\",\n            pydantic.types.SecretBytes: lambda val: \"**********\" if val else \"\",\n        }\n        if color:\n            encoders[color.Color] = str\n        return encoders\n\n    def on_app_init(self, app_config: AppConfig) -> AppConfig:\n        app_config.type_encoders = {**self.encoders(), **(app_config.type_encoders or {})}\n        app_config.type_decoders = [*self.decoders(), *(app_config.type_decoders or [])]\n        return app_config\n", "path": "litestar/contrib/pydantic/pydantic_init_plugin.py"}]}