litestar-vite 0.12.1__py3-none-any.whl → 0.13.0__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.

@@ -0,0 +1,116 @@
1
+ from __future__ import annotations
2
+
3
+ from functools import cached_property
4
+ from typing import TYPE_CHECKING
5
+ from urllib.parse import unquote
6
+
7
+ from litestar import Request
8
+ from litestar.connection.base import (
9
+ AuthT,
10
+ StateT,
11
+ UserT,
12
+ empty_receive,
13
+ empty_send,
14
+ )
15
+
16
+ from litestar_vite.inertia._utils import InertiaHeaders
17
+
18
+ __all__ = ("InertiaDetails", "InertiaRequest")
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ from litestar.types import Receive, Scope, Send
23
+
24
+
25
+ class InertiaDetails:
26
+ """InertiaDetails holds all the values sent by Inertia client in headers and provide convenient properties."""
27
+
28
+ def __init__(self, request: Request[UserT, AuthT, StateT]) -> None:
29
+ """Initialize :class:`InertiaDetails`"""
30
+ self.request = request
31
+
32
+ def _get_header_value(self, name: InertiaHeaders) -> str | None:
33
+ """Parse request header
34
+
35
+ Check for uri encoded header and unquotes it in readable format.
36
+ """
37
+
38
+ if value := self.request.headers.get(name.value.lower()):
39
+ is_uri_encoded = self.request.headers.get(f"{name.value.lower()}-uri-autoencoded") == "true"
40
+ return unquote(value) if is_uri_encoded else value
41
+ return None
42
+
43
+ def _get_route_component(self) -> str | None:
44
+ """Get the route component.
45
+
46
+ Checks for the `component` key within the route configuration.
47
+ """
48
+ rh = self.request.scope.get("route_handler") # pyright: ignore[reportUnknownMemberType]
49
+ if rh:
50
+ return rh.opt.get("component")
51
+ return None
52
+
53
+ def __bool__(self) -> bool:
54
+ """Check if request is sent by an Inertia client."""
55
+ return self._get_header_value(InertiaHeaders.ENABLED) == "true"
56
+
57
+ @cached_property
58
+ def route_component(self) -> str | None:
59
+ """Partial Data Reload."""
60
+ return self._get_route_component()
61
+
62
+ @cached_property
63
+ def partial_component(self) -> str | None:
64
+ """Partial Data Reload."""
65
+ return self._get_header_value(InertiaHeaders.PARTIAL_COMPONENT)
66
+
67
+ @cached_property
68
+ def partial_data(self) -> str | None:
69
+ """Partial Data Reload."""
70
+ return self._get_header_value(InertiaHeaders.PARTIAL_DATA)
71
+
72
+ @cached_property
73
+ def referer(self) -> str | None:
74
+ """Partial Data Reload."""
75
+ return self._get_header_value(InertiaHeaders.REFERER)
76
+
77
+ @cached_property
78
+ def is_partial_render(self) -> bool:
79
+ """Is Partial Data Reload."""
80
+ return bool(self.partial_component == self.route_component and self.partial_data)
81
+
82
+ @cached_property
83
+ def partial_keys(self) -> list[str]:
84
+ """Is Partial Data Reload."""
85
+ return self.partial_data.split(",") if self.partial_data is not None else []
86
+
87
+
88
+ class InertiaRequest(Request[UserT, AuthT, StateT]):
89
+ """Inertia Request class to work with Inertia client."""
90
+
91
+ __slots__ = ("inertia",)
92
+
93
+ def __init__(self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send) -> None:
94
+ """Initialize :class:`InertiaRequest`"""
95
+ super().__init__(scope=scope, receive=receive, send=send)
96
+ self.inertia = InertiaDetails(self)
97
+
98
+ @property
99
+ def is_inertia(self) -> bool:
100
+ """True if the request contained inertia headers."""
101
+ return bool(self.inertia)
102
+
103
+ @property
104
+ def inertia_enabled(self) -> bool:
105
+ """True if the route handler contains an inertia enabled configuration."""
106
+ return bool(self.inertia.route_component is not None)
107
+
108
+ @property
109
+ def is_partial_render(self) -> bool:
110
+ """True if the route handler contains an inertia enabled configuration."""
111
+ return self.inertia.is_partial_render
112
+
113
+ @property
114
+ def partial_keys(self) -> set[str]:
115
+ """True if the route handler contains an inertia enabled configuration."""
116
+ return set(self.inertia.partial_keys)
@@ -0,0 +1,319 @@
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ from collections.abc import Mapping
5
+ from mimetypes import guess_type
6
+ from pathlib import PurePath
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Any,
10
+ Iterable,
11
+ TypeVar,
12
+ cast,
13
+ )
14
+ from urllib.parse import quote, urlparse, urlunparse
15
+
16
+ from litestar import Litestar, MediaType, Request, Response
17
+ from litestar.datastructures.cookie import Cookie
18
+ from litestar.exceptions import ImproperlyConfiguredException
19
+ from litestar.response import Redirect
20
+ from litestar.response.base import ASGIResponse
21
+ from litestar.serialization import get_serializer
22
+ from litestar.status_codes import HTTP_200_OK, HTTP_303_SEE_OTHER, HTTP_307_TEMPORARY_REDIRECT, HTTP_409_CONFLICT
23
+ from litestar.utils.deprecation import warn_deprecation
24
+ from litestar.utils.empty import value_or_default
25
+ from litestar.utils.helpers import get_enum_string_value
26
+ from litestar.utils.scope.state import ScopeState
27
+
28
+ from litestar_vite.inertia._utils import get_headers
29
+ from litestar_vite.inertia.helpers import (
30
+ get_shared_props,
31
+ is_or_contains_lazy_prop,
32
+ js_routes_script,
33
+ lazy_render,
34
+ should_render,
35
+ )
36
+ from litestar_vite.inertia.plugin import InertiaPlugin
37
+ from litestar_vite.inertia.types import InertiaHeaderType, PageProps
38
+ from litestar_vite.plugin import VitePlugin
39
+
40
+ if TYPE_CHECKING:
41
+ from litestar.app import Litestar
42
+ from litestar.background_tasks import BackgroundTask, BackgroundTasks
43
+ from litestar.connection.base import AuthT, StateT, UserT
44
+ from litestar.types import ResponseCookies, ResponseHeaders, TypeEncodersMap
45
+
46
+
47
+ T = TypeVar("T")
48
+
49
+
50
+ class InertiaResponse(Response[T]):
51
+ """Inertia Response"""
52
+
53
+ def __init__(
54
+ self,
55
+ content: T,
56
+ *,
57
+ template_name: str | None = None,
58
+ template_str: str | None = None,
59
+ background: BackgroundTask | BackgroundTasks | None = None,
60
+ context: dict[str, Any] | None = None,
61
+ cookies: ResponseCookies | None = None,
62
+ encoding: str = "utf-8",
63
+ headers: ResponseHeaders | None = None,
64
+ media_type: MediaType | str | None = None,
65
+ status_code: int = HTTP_200_OK,
66
+ type_encoders: TypeEncodersMap | None = None,
67
+ ) -> None:
68
+ """Handle the rendering of a given template into a bytes string.
69
+
70
+ Args:
71
+ content: A value for the response body that will be rendered into bytes string.
72
+ template_name: Path-like name for the template to be rendered, e.g. ``index.html``.
73
+ template_str: A string representing the template, e.g. ``tmpl = "Hello <strong>World</strong>"``.
74
+ background: A :class:`BackgroundTask <.background_tasks.BackgroundTask>` instance or
75
+ :class:`BackgroundTasks <.background_tasks.BackgroundTasks>` to execute after the response is finished.
76
+ Defaults to ``None``.
77
+ context: A dictionary of key/value pairs to be passed to the temple engine's render method.
78
+ cookies: A list of :class:`Cookie <.datastructures.Cookie>` instances to be set under the response
79
+ ``Set-Cookie`` header.
80
+ encoding: Content encoding
81
+ headers: A string keyed dictionary of response headers. Header keys are insensitive.
82
+ media_type: A string or member of the :class:`MediaType <.enums.MediaType>` enum. If not set, try to infer
83
+ the media type based on the template name. If this fails, fall back to ``text/plain``.
84
+ status_code: A value for the response HTTP status code.
85
+ type_encoders: A mapping of types to callables that transform them into types supported for serialization.
86
+ """
87
+ if template_name and template_str:
88
+ msg = "Either template_name or template_str must be provided, not both."
89
+ raise ValueError(msg)
90
+ self.content = content
91
+ self.background = background
92
+ self.cookies: list[Cookie] = (
93
+ [Cookie(key=key, value=value) for key, value in cookies.items()]
94
+ if isinstance(cookies, Mapping)
95
+ else list(cookies or [])
96
+ )
97
+ self.encoding = encoding
98
+ self.headers: dict[str, Any] = (
99
+ dict(headers) if isinstance(headers, Mapping) else {h.name: h.value for h in headers or {}}
100
+ )
101
+ self.media_type = media_type
102
+ self.status_code = status_code
103
+ self.response_type_encoders = {**(self.type_encoders or {}), **(type_encoders or {})}
104
+ self.context = context or {}
105
+ self.template_name = template_name
106
+ self.template_str = template_str
107
+
108
+ def create_template_context(
109
+ self,
110
+ request: Request[UserT, AuthT, StateT],
111
+ page_props: PageProps[T],
112
+ type_encoders: TypeEncodersMap | None = None,
113
+ ) -> dict[str, Any]:
114
+ """Create a context object for the template.
115
+
116
+ Args:
117
+ request: A :class:`Request <.connection.Request>` instance.
118
+ page_props: A formatted object to return the inertia configuration.
119
+ type_encoders: A mapping of types to callables that transform them into types supported for serialization.
120
+
121
+ Returns:
122
+ A dictionary holding the template context
123
+ """
124
+ csrf_token = value_or_default(ScopeState.from_scope(request.scope).csrf_token, "")
125
+ inertia_props = self.render(page_props, MediaType.JSON, get_serializer(type_encoders)).decode()
126
+ return {
127
+ **self.context,
128
+ "inertia": inertia_props,
129
+ "js_routes": js_routes_script(request.app.state.js_routes),
130
+ "request": request,
131
+ "csrf_input": f'<input type="hidden" name="_csrf_token" value="{csrf_token}" />',
132
+ }
133
+
134
+ def to_asgi_response( # noqa: C901, PLR0912
135
+ self,
136
+ app: Litestar | None,
137
+ request: Request[UserT, AuthT, StateT],
138
+ *,
139
+ background: BackgroundTask | BackgroundTasks | None = None,
140
+ cookies: Iterable[Cookie] | None = None,
141
+ encoded_headers: Iterable[tuple[bytes, bytes]] | None = None,
142
+ headers: dict[str, str] | None = None,
143
+ is_head_response: bool = False,
144
+ media_type: MediaType | str | None = None,
145
+ status_code: int | None = None,
146
+ type_encoders: TypeEncodersMap | None = None,
147
+ ) -> ASGIResponse:
148
+ if app is not None:
149
+ warn_deprecation(
150
+ version="2.1",
151
+ deprecated_name="app",
152
+ kind="parameter",
153
+ removal_in="3.0.0",
154
+ alternative="request.app",
155
+ )
156
+ inertia_enabled = cast(
157
+ "bool",
158
+ getattr(request, "inertia_enabled", False) or getattr(request, "is_inertia", False),
159
+ )
160
+ is_inertia = cast("bool", getattr(request, "is_inertia", False))
161
+ headers = {**headers, **self.headers} if headers is not None else self.headers
162
+ cookies = self.cookies if cookies is None else itertools.chain(self.cookies, cookies)
163
+ type_encoders = (
164
+ {**type_encoders, **(self.response_type_encoders or {})} if type_encoders else self.response_type_encoders
165
+ )
166
+ if not inertia_enabled:
167
+ media_type = get_enum_string_value(self.media_type or media_type or MediaType.JSON)
168
+ return ASGIResponse(
169
+ background=self.background or background,
170
+ body=self.render(self.content, media_type, get_serializer(type_encoders)),
171
+ cookies=cookies,
172
+ encoded_headers=encoded_headers,
173
+ encoding=self.encoding,
174
+ headers=headers,
175
+ is_head_response=is_head_response,
176
+ media_type=media_type,
177
+ status_code=self.status_code or status_code,
178
+ )
179
+ is_partial_render = cast("bool", getattr(request, "is_partial_render", False))
180
+ partial_keys = cast("set[str]", getattr(request, "partial_keys", {}))
181
+ vite_plugin = request.app.plugins.get(VitePlugin)
182
+ inertia_plugin = request.app.plugins.get(InertiaPlugin)
183
+ template_engine = request.app.template_engine # pyright: ignore[reportUnknownVariableType,reportUnknownMemberType]
184
+ headers.update(
185
+ {"Vary": "Accept", **get_headers(InertiaHeaderType(enabled=True))},
186
+ )
187
+ shared_props = get_shared_props(
188
+ request,
189
+ partial_data=partial_keys if is_partial_render else None,
190
+ )
191
+ if is_or_contains_lazy_prop(self.content):
192
+ filtered_content = lazy_render(
193
+ self.content,
194
+ partial_keys if is_partial_render else None,
195
+ inertia_plugin.portal,
196
+ )
197
+ if filtered_content is not None:
198
+ shared_props["content"] = filtered_content
199
+ elif should_render(self.content, partial_keys):
200
+ shared_props["content"] = self.content
201
+
202
+ page_props = PageProps[T](
203
+ component=request.inertia.route_component, # type: ignore[attr-defined] # pyright: ignore[reportUnknownArgumentType,reportUnknownMemberType,reportAttributeAccessIssue]
204
+ props=shared_props, # pyright: ignore[reportArgumentType]
205
+ version=vite_plugin.asset_loader.version_id,
206
+ url=request.url.path,
207
+ )
208
+ if is_inertia:
209
+ media_type = get_enum_string_value(self.media_type or media_type or MediaType.JSON)
210
+ body = self.render(page_props, media_type, get_serializer(type_encoders))
211
+ return ASGIResponse( # pyright: ignore[reportUnknownMemberType]
212
+ background=self.background or background,
213
+ body=body,
214
+ cookies=cookies,
215
+ encoded_headers=encoded_headers,
216
+ encoding=self.encoding,
217
+ headers=headers,
218
+ is_head_response=is_head_response,
219
+ media_type=media_type,
220
+ status_code=self.status_code or status_code,
221
+ )
222
+
223
+ if not template_engine:
224
+ msg = "Template engine is not configured"
225
+ raise ImproperlyConfiguredException(msg)
226
+ # it should default to HTML at this point unless the user specified something
227
+ media_type = media_type or MediaType.HTML
228
+ if not media_type:
229
+ if self.template_name:
230
+ suffixes = PurePath(self.template_name).suffixes
231
+ for suffix in suffixes:
232
+ if _type := guess_type(f"name{suffix}")[0]:
233
+ media_type = _type
234
+ break
235
+ else:
236
+ media_type = MediaType.TEXT
237
+ else:
238
+ media_type = MediaType.HTML
239
+ context = self.create_template_context(request, page_props, type_encoders) # pyright: ignore[reportUnknownMemberType]
240
+ if self.template_str is not None:
241
+ body = template_engine.render_string(self.template_str, context).encode(self.encoding) # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
242
+ else:
243
+ template_name = self.template_name or inertia_plugin.config.root_template
244
+ template = template_engine.get_template(template_name) # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
245
+ body = template.render(**context).encode(self.encoding) # pyright: ignore[reportUnknownVariableType,reportUnknownMemberType]
246
+
247
+ return ASGIResponse( # pyright: ignore[reportUnknownMemberType]
248
+ background=self.background or background,
249
+ body=body, # pyright: ignore[reportUnknownArgumentType]
250
+ cookies=cookies,
251
+ encoded_headers=encoded_headers,
252
+ encoding=self.encoding,
253
+ headers=headers,
254
+ is_head_response=is_head_response,
255
+ media_type=media_type,
256
+ status_code=self.status_code or status_code,
257
+ )
258
+
259
+
260
+ class InertiaExternalRedirect(Response[Any]):
261
+ """Client side redirect."""
262
+
263
+ def __init__(
264
+ self,
265
+ request: Request[Any, Any, Any],
266
+ redirect_to: str,
267
+ **kwargs: Any,
268
+ ) -> None:
269
+ """Initialize external redirect, Set status code to 409 (required by Inertia),
270
+ and pass redirect url.
271
+ """
272
+ super().__init__(
273
+ content=b"",
274
+ status_code=HTTP_409_CONFLICT,
275
+ headers={"X-Inertia-Location": quote(redirect_to, safe="/#%[]=:;$&()+,!?*@'~")},
276
+ cookies=request.cookies,
277
+ **kwargs,
278
+ )
279
+
280
+
281
+ class InertiaRedirect(Redirect):
282
+ """Client side redirect."""
283
+
284
+ def __init__(
285
+ self,
286
+ request: Request[Any, Any, Any],
287
+ redirect_to: str,
288
+ **kwargs: Any,
289
+ ) -> None:
290
+ """Initialize external redirect, Set status code to 409 (required by Inertia),
291
+ and pass redirect url.
292
+ """
293
+ referer = urlparse(request.headers.get("Referer", str(request.base_url)))
294
+ redirect_to = urlunparse(urlparse(redirect_to)._replace(scheme=referer.scheme))
295
+ super().__init__(
296
+ path=redirect_to,
297
+ status_code=HTTP_307_TEMPORARY_REDIRECT if request.method == "GET" else HTTP_303_SEE_OTHER,
298
+ cookies=request.cookies,
299
+ **kwargs,
300
+ )
301
+
302
+
303
+ class InertiaBack(Redirect):
304
+ """Client side redirect."""
305
+
306
+ def __init__(
307
+ self,
308
+ request: Request[Any, Any, Any],
309
+ **kwargs: Any,
310
+ ) -> None:
311
+ """Initialize external redirect, Set status code to 409 (required by Inertia),
312
+ and pass redirect url.
313
+ """
314
+ super().__init__(
315
+ path=request.headers.get("Referer", str(request.base_url)),
316
+ status_code=HTTP_307_TEMPORARY_REDIRECT if request.method == "GET" else HTTP_303_SEE_OTHER,
317
+ cookies=request.cookies,
318
+ **kwargs,
319
+ )
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from functools import cached_property
5
+ from typing import TYPE_CHECKING
6
+
7
+ from litestar.app import DEFAULT_OPENAPI_CONFIG
8
+ from litestar.cli._utils import (
9
+ remove_default_schema_routes,
10
+ remove_routes_with_patterns,
11
+ )
12
+ from litestar.routes import ASGIRoute, WebSocketRoute
13
+ from litestar.serialization import encode_json
14
+
15
+ if TYPE_CHECKING:
16
+ from litestar import Litestar
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Routes:
21
+ routes: dict[str, str]
22
+
23
+ @cached_property
24
+ def formatted_routes(self) -> str:
25
+ return encode_json(self.routes).decode(encoding="utf-8")
26
+
27
+
28
+ EXCLUDED_METHODS = {"HEAD", "OPTIONS", "TRACE"}
29
+
30
+
31
+ def generate_js_routes(
32
+ app: Litestar,
33
+ exclude: tuple[str, ...] | None = None,
34
+ schema: bool = False,
35
+ ) -> Routes:
36
+ sorted_routes = sorted(app.routes, key=lambda r: r.path)
37
+ if not schema:
38
+ openapi_config = app.openapi_config or DEFAULT_OPENAPI_CONFIG
39
+ sorted_routes = remove_default_schema_routes(sorted_routes, openapi_config)
40
+ if exclude is not None:
41
+ sorted_routes = remove_routes_with_patterns(sorted_routes, exclude)
42
+ route_list: dict[str, str] = {}
43
+ for route in sorted_routes:
44
+ if isinstance(route, (ASGIRoute, WebSocketRoute)):
45
+ route_name = route.route_handler.name or route.route_handler.handler_name
46
+ if len(route.methods.difference(EXCLUDED_METHODS)) > 0:
47
+ route_list[route_name] = route.path
48
+ else:
49
+ for handler in route.route_handlers:
50
+ route_name = handler.name or handler.handler_name
51
+ if handler.http_methods.isdisjoint(EXCLUDED_METHODS):
52
+ route_list[route_name] = route.path
53
+
54
+ return Routes(routes=route_list)
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Generic, TypedDict, TypeVar
5
+
6
+ __all__ = (
7
+ "InertiaHeaderType",
8
+ "PageProps",
9
+ )
10
+
11
+
12
+ T = TypeVar("T")
13
+
14
+
15
+ @dataclass
16
+ class PageProps(Generic[T]):
17
+ """Inertia Page Props Type."""
18
+
19
+ component: str
20
+ url: str
21
+ version: str
22
+ props: dict[str, Any]
23
+
24
+
25
+ @dataclass
26
+ class InertiaProps(Generic[T]):
27
+ """Inertia Props Type."""
28
+
29
+ page: PageProps[T]
30
+
31
+
32
+ class InertiaHeaderType(TypedDict, total=False):
33
+ """Type for inertia_headers parameter in get_headers()."""
34
+
35
+ enabled: bool | None
36
+ version: str | None
37
+ location: str | None
38
+ partial_data: str | None
39
+ partial_component: str | None