litestar-vite 0.2.2__py3-none-any.whl → 0.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of litestar-vite might be problematic. Click here for more details.

@@ -21,5 +21,7 @@ class InertiaConfig:
21
21
  """An identifier to use on routes to exclude a route from the generated routes typescript file."""
22
22
  redirect_unauthorized_to: str | None = None
23
23
  """Optionally supply a path where unauthorized requests should redirect."""
24
- extra_page_props: dict[str, Any] = field(default_factory=dict)
25
- """A dictionary of values to automatically add in to page props on every request."""
24
+ extra_static_page_props: dict[str, Any] = field(default_factory=dict)
25
+ """A dictionary of values to automatically add in to page props on every response."""
26
+ extra_session_page_props: set[str] = field(default_factory=set)
27
+ """A set of session keys for which the value automatically be added (if it exists) to the response."""
@@ -1,4 +1,3 @@
1
- import contextlib
2
1
  import re
3
2
  from typing import TYPE_CHECKING, Any, cast
4
3
 
@@ -44,7 +43,7 @@ class _HTTPConflictException(HTTPException):
44
43
  status_code = HTTP_409_CONFLICT
45
44
 
46
45
 
47
- def exception_to_http_response(request: Request[UserT, AuthT, StateT], exc: Exception) -> Response[Any]: # noqa: PLR0911
46
+ def exception_to_http_response(request: Request[UserT, AuthT, StateT], exc: Exception) -> Response[Any]:
48
47
  """Handler for all exceptions subclassed from HTTPException."""
49
48
  inertia_enabled = getattr(request, "inertia_enabled", False) or getattr(request, "is_inertia", False)
50
49
  if isinstance(exc, NotFoundError):
@@ -57,17 +56,25 @@ def exception_to_http_response(request: Request[UserT, AuthT, StateT], exc: Exce
57
56
  if request.app.debug and http_exc not in (PermissionDeniedException, NotFoundError):
58
57
  return cast("Response[Any]", create_debug_response(request, exc))
59
58
  return cast("Response[Any]", create_exception_response(request, http_exc(detail=str(exc.__cause__))))
59
+ return create_inertia_exception_response(request, exc)
60
+
61
+
62
+ def create_inertia_exception_response(request: Request[UserT, AuthT, StateT], exc: Exception) -> Response[Any]:
63
+ """Create the inertia exception response"""
60
64
  is_inertia = getattr(request, "is_inertia", False)
61
65
  status_code = getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR)
62
- preferred_type = MediaType.HTML if inertia_enabled and not is_inertia else MediaType.JSON
66
+ preferred_type = MediaType.HTML if not is_inertia else MediaType.JSON
63
67
  detail = getattr(exc, "detail", "") # litestar exceptions
64
68
  extras = getattr(exc, "extra", "") # msgspec exceptions
65
69
  content = {"status_code": status_code, "message": getattr(exc, "detail", "")}
66
70
  inertia_plugin = cast("InertiaPlugin", request.app.plugins.get("InertiaPlugin"))
67
71
  if extras:
68
72
  content.update({"extra": extras})
69
- with contextlib.suppress(Exception):
73
+ try:
70
74
  flash(request, detail, category="error")
75
+ except Exception as flash_exc:
76
+ msg = f"Failed to set the `flash` session state. Reason: {flash_exc.__cause__!s}"
77
+ request.logger.exception(msg)
71
78
  if extras and len(extras) >= 1:
72
79
  message = extras[0]
73
80
  default_field = f"root.{message.get('key')}" if message.get("key", None) is not None else "root" # type: ignore
@@ -75,8 +82,7 @@ def exception_to_http_response(request: Request[UserT, AuthT, StateT], exc: Exce
75
82
  match = FIELD_ERR_RE.search(error_detail)
76
83
  field = match.group(1) if match else default_field
77
84
  if isinstance(message, dict):
78
- with contextlib.suppress(Exception):
79
- error(request, field, error_detail)
85
+ error(request, field, error_detail)
80
86
  if status_code in {HTTP_422_UNPROCESSABLE_ENTITY, HTTP_400_BAD_REQUEST} or isinstance(
81
87
  exc,
82
88
  PermissionDeniedException,
@@ -85,15 +91,15 @@ def exception_to_http_response(request: Request[UserT, AuthT, StateT], exc: Exce
85
91
  if isinstance(exc, PermissionDeniedException):
86
92
  return InertiaBack(request)
87
93
  if status_code == HTTP_401_UNAUTHORIZED or isinstance(exc, NotAuthorizedException):
88
- redirect_to = (
94
+ if (
89
95
  inertia_plugin.config.redirect_unauthorized_to is not None
90
96
  and str(request.url) != inertia_plugin.config.redirect_unauthorized_to
91
- )
92
- if redirect_to:
93
- return InertiaRedirect(request, redirect_to=cast("str", inertia_plugin.config.redirect_unauthorized_to))
94
- return InertiaBack(request)
95
- return InertiaResponse[Any](
96
- media_type=preferred_type,
97
- content=content,
98
- status_code=status_code,
99
- )
97
+ ):
98
+ return InertiaRedirect(request, redirect_to=inertia_plugin.config.redirect_unauthorized_to)
99
+ if str(request.url) != inertia_plugin.config.redirect_unauthorized_to:
100
+ return InertiaResponse[Any](
101
+ media_type=preferred_type,
102
+ content=content,
103
+ status_code=status_code,
104
+ )
105
+ return InertiaBack(request)
@@ -16,7 +16,6 @@ from litestar.response import Redirect
16
16
  from litestar.response.base import ASGIResponse
17
17
  from litestar.serialization import get_serializer
18
18
  from litestar.status_codes import HTTP_200_OK, HTTP_303_SEE_OTHER, HTTP_307_TEMPORARY_REDIRECT, HTTP_409_CONFLICT
19
- from litestar.types import Empty
20
19
  from litestar.utils.deprecation import warn_deprecation
21
20
  from litestar.utils.empty import value_or_default
22
21
  from litestar.utils.helpers import get_enum_string_value
@@ -47,7 +46,11 @@ def share(
47
46
  key: str,
48
47
  value: Any,
49
48
  ) -> None:
50
- connection.session.setdefault("_shared", {}).update({key: value})
49
+ try:
50
+ connection.session.setdefault("_shared", {}).update({key: value})
51
+ except Exception as exc:
52
+ msg = f"Failed to set the `share` session state. Reason: {exc.__cause__!s}"
53
+ connection.logger.exception(msg)
51
54
 
52
55
 
53
56
  def error(
@@ -55,7 +58,11 @@ def error(
55
58
  key: str,
56
59
  message: str,
57
60
  ) -> None:
58
- connection.session.setdefault("_errors", {}).update({key: message})
61
+ try:
62
+ connection.session.setdefault("_errors", {}).update({key: message})
63
+ except Exception as exc:
64
+ msg = f"Failed to set the `error` session state. Reason: {exc.__cause__!s}"
65
+ connection.logger.exception(msg)
59
66
 
60
67
 
61
68
  def get_shared_props(request: ASGIConnection[Any, Any, Any, Any]) -> Dict[str, Any]: # noqa: UP006
@@ -64,19 +71,26 @@ def get_shared_props(request: ASGIConnection[Any, Any, Any, Any]) -> Dict[str, A
64
71
 
65
72
  Be sure to call this before `self.create_template_context` if you would like to include the `flash` message details.
66
73
  """
67
- error_bag = request.headers.get("X-Inertia-Error-Bag", None)
68
- has_active_session = not (not request.session or request.scope["session"] is Empty)
69
- errors: dict[str, Any] = request.session.pop("_errors", {}) if has_active_session else {}
70
- props: dict[str, Any] = request.session.pop("_shared", {}) if has_active_session else {}
71
- flash: dict[str, list[str]] = defaultdict(list)
72
- for message in cast("List[Dict[str,Any]]", request.session.pop("_messages", []) if has_active_session else []):
73
- flash[message["category"]].append(message["message"])
74
-
75
- inertia_plugin = cast("InertiaPlugin", request.app.plugins.get("InertiaPlugin"))
76
- props.update(inertia_plugin.config.extra_page_props)
74
+ props: dict[str, Any] = {}
75
+ try:
76
+ error_bag = request.headers.get("X-Inertia-Error-Bag", None)
77
+ errors: dict[str, Any] = request.session.pop("_errors", {})
78
+ props.update(cast("Dict[str,Any]", request.session.pop("_shared", {})))
79
+ flash: dict[str, list[str]] = defaultdict(list)
80
+ for message in cast("List[Dict[str,Any]]", request.session.pop("_messages", [])):
81
+ flash[message["category"]].append(message["message"])
82
+
83
+ inertia_plugin = cast("InertiaPlugin", request.app.plugins.get("InertiaPlugin"))
84
+ props.update(inertia_plugin.config.extra_static_page_props)
85
+ for session_prop in inertia_plugin.config.extra_session_page_props:
86
+ if session_prop not in props and session_prop in request.session:
87
+ props[session_prop] = request.session.get(session_prop)
88
+ props["flash"] = flash
89
+ props["errors"] = {error_bag: errors} if error_bag is not None else errors
90
+ except Exception as exc:
91
+ msg = f"Failed to set the `error` session state. Reason: {exc.__cause__}"
92
+ request.logger.exception(msg)
77
93
  props["csrf_token"] = value_or_default(ScopeState.from_scope(request.scope).csrf_token, "")
78
- props["flash"] = flash
79
- props["errors"] = {error_bag: errors} if error_bag is not None else errors
80
94
  return props
81
95
 
82
96
 
litestar_vite/plugin.py CHANGED
@@ -28,7 +28,7 @@ def set_environment(config: ViteConfig) -> None:
28
28
  os.environ.setdefault("VITE_PORT", str(config.port))
29
29
  os.environ.setdefault("VITE_HOST", config.host)
30
30
  os.environ.setdefault("VITE_PROTOCOL", config.protocol)
31
- os.environ.setdefault("APP_URL", "http://localhost:8000")
31
+ os.environ.setdefault("APP_URL", f"http://localhost:{os.environ.get('LITESTAR_PORT',8000)}")
32
32
  if config.dev_mode:
33
33
  os.environ.setdefault("VITE_DEV_MODE", str(config.dev_mode))
34
34
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: litestar-vite
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Vite plugin for Litestar
5
5
  Project-URL: Changelog, https://cofin.github.io/litestar-vite/latest/changelog
6
6
  Project-URL: Discord, https://discord.gg/X3FJqy8d2j
@@ -4,17 +4,17 @@ litestar_vite/cli.py,sha256=foXJ-xW1bvUEsT7nPo1hbN0FLaDzHWPG4zpmqN__rY0,10976
4
4
  litestar_vite/commands.py,sha256=sfTdFfMcDxnW3_tbmIIBjpHmNdQYKHjSguGxXNP8SVw,4440
5
5
  litestar_vite/config.py,sha256=J5U0hBa_cD7lm15lg24QqMy3hsZ_1QIIETxwaNZIm84,7523
6
6
  litestar_vite/loader.py,sha256=USrzNDppXgXLvW5WCuIgKPuM6MlECNIssnkwb_p-E8s,8117
7
- litestar_vite/plugin.py,sha256=2rwlumH3CFozb_7NGOFwn20BMZ_4JTNHiWh0oyaN-gc,5131
7
+ litestar_vite/plugin.py,sha256=p4VPKYdWw5qIYZ1OwfdMRcwM_Q-vfoDEmIbu3IyF7oI,5166
8
8
  litestar_vite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
9
  litestar_vite/template_engine.py,sha256=ffC4KPtUUNkuC0tJ0bD1Bu7c8lE33vKP0US1fWUYnO8,3853
10
10
  litestar_vite/inertia/__init__.py,sha256=PMOon8tag-20riAkHH3U4VLk7NBwt9lHsOHHSKMQHJQ,695
11
11
  litestar_vite/inertia/_utils.py,sha256=ijO9Lgka7ZPIAHkby9szbTGoSg0nDShC2bqWT9cDxi0,1956
12
- litestar_vite/inertia/config.py,sha256=6cYR4m5oGsJnL_rH6Dt8bQJ804Oq6knj6qDsCVUqNsI,942
13
- litestar_vite/inertia/exception_handler.py,sha256=yTgyd5BkOyTvg8HKWgQEzJuOIBnd4uv7LkCBee_pEPw,4433
12
+ litestar_vite/inertia/config.py,sha256=ziEO-xQ5SoE7niri39PMXYgieM94Yf0y4BCFyaMs6P0,1125
13
+ litestar_vite/inertia/exception_handler.py,sha256=DZQGVt7nNZRB1QcGFe2CXZwTXgMvR-8ldYS-P5AqpCw,4746
14
14
  litestar_vite/inertia/middleware.py,sha256=NEDcAoT7GMWA9hEGvANZ3MG5_p3MmZX57RF95T71les,1716
15
15
  litestar_vite/inertia/plugin.py,sha256=ebAG9XnDBahttuc7WIUgBd3o_Ys8MdPS273LPNs5H8A,2344
16
16
  litestar_vite/inertia/request.py,sha256=hk8m1pmDiMbWhVurRDHfDPD24nMHp56JzUKV6SBDeqA,3665
17
- litestar_vite/inertia/response.py,sha256=vvpvz-yNTyboIa2dzVMhaMrCxzDTgyM2U_nGEwbN3Po,15051
17
+ litestar_vite/inertia/response.py,sha256=yQd10cMgsYj0QO0zpjvvZu42x8u1hdf9FYffHQK1tL8,15652
18
18
  litestar_vite/inertia/routes.py,sha256=QksJm2RUfL-WbuhOieYnPXXWO5GYnPtmsYEm6Ef8Yeo,1782
19
19
  litestar_vite/inertia/types.py,sha256=tLp0pm1N__hcWC875khf6wH1nuFlKS9-VjDqgsRkXnw,702
20
20
  litestar_vite/templates/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -24,7 +24,7 @@ litestar_vite/templates/package.json.j2,sha256=0JWgdTuaSZ25EmCltF_zbqDdpxfvCLeYu
24
24
  litestar_vite/templates/styles.css.j2,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
25
  litestar_vite/templates/tsconfig.json.j2,sha256=q1REIuVyXUHCy4Zi2kgTkmrhdT98vyY89k-WTrImOj8,843
26
26
  litestar_vite/templates/vite.config.ts.j2,sha256=FZ4OJaB8Kjby_nlx4_LCP8eCe1LRi8kW2GspCiVMfDY,1115
27
- litestar_vite-0.2.2.dist-info/METADATA,sha256=ue7XPxpNkXIidXS7TKrqzeYEMwDjKexrjLHFnxodwO4,6180
28
- litestar_vite-0.2.2.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
29
- litestar_vite-0.2.2.dist-info/licenses/LICENSE,sha256=HeTiEfEgvroUXZe_xAmYHxtTBgw--mbXyZLsWDYabHc,1069
30
- litestar_vite-0.2.2.dist-info/RECORD,,
27
+ litestar_vite-0.2.3.dist-info/METADATA,sha256=NtL87u2sEObXDgcqZdHr2q8jTNkISPw30mEnGwIwjxE,6180
28
+ litestar_vite-0.2.3.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
29
+ litestar_vite-0.2.3.dist-info/licenses/LICENSE,sha256=HeTiEfEgvroUXZe_xAmYHxtTBgw--mbXyZLsWDYabHc,1069
30
+ litestar_vite-0.2.3.dist-info/RECORD,,