litestar-vite 0.8.0__py3-none-any.whl → 0.8.1__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.
- litestar_vite/__init__.py +9 -0
- litestar_vite/__metadata__.py +18 -0
- litestar_vite/cli.py +324 -0
- litestar_vite/commands.py +131 -0
- litestar_vite/config.py +173 -0
- litestar_vite/inertia/__init__.py +34 -0
- litestar_vite/inertia/_utils.py +63 -0
- litestar_vite/inertia/config.py +29 -0
- litestar_vite/inertia/exception_handler.py +116 -0
- litestar_vite/inertia/middleware.py +52 -0
- litestar_vite/inertia/plugin.py +64 -0
- litestar_vite/inertia/request.py +116 -0
- litestar_vite/inertia/response.py +373 -0
- litestar_vite/inertia/routes.py +54 -0
- litestar_vite/inertia/types.py +39 -0
- litestar_vite/loader.py +221 -0
- litestar_vite/plugin.py +136 -0
- litestar_vite/py.typed +0 -0
- litestar_vite/template_engine.py +103 -0
- litestar_vite/templates/__init__.py +0 -0
- litestar_vite/templates/index.html.j2 +16 -0
- litestar_vite/templates/main.ts.j2 +1 -0
- litestar_vite/templates/package.json.j2 +11 -0
- litestar_vite/templates/styles.css.j2 +0 -0
- litestar_vite/templates/tsconfig.json.j2 +30 -0
- litestar_vite/templates/vite.config.ts.j2 +38 -0
- {litestar_vite-0.8.0.dist-info → litestar_vite-0.8.1.dist-info}/METADATA +1 -1
- litestar_vite-0.8.1.dist-info/RECORD +30 -0
- litestar_vite-0.8.0.dist-info/RECORD +0 -4
- {litestar_vite-0.8.0.dist-info → litestar_vite-0.8.1.dist-info}/WHEEL +0 -0
- {litestar_vite-0.8.0.dist-info → litestar_vite-0.8.1.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
from mimetypes import guess_type
|
|
7
|
+
from pathlib import PurePath
|
|
8
|
+
from textwrap import dedent
|
|
9
|
+
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, TypeVar, cast
|
|
10
|
+
from urllib.parse import quote, urlparse, urlunparse
|
|
11
|
+
|
|
12
|
+
from litestar import Litestar, MediaType, Request, Response
|
|
13
|
+
from litestar.datastructures.cookie import Cookie
|
|
14
|
+
from litestar.exceptions import ImproperlyConfiguredException
|
|
15
|
+
from litestar.response import Redirect
|
|
16
|
+
from litestar.response.base import ASGIResponse
|
|
17
|
+
from litestar.serialization import get_serializer
|
|
18
|
+
from litestar.status_codes import HTTP_200_OK, HTTP_303_SEE_OTHER, HTTP_307_TEMPORARY_REDIRECT, HTTP_409_CONFLICT
|
|
19
|
+
from litestar.utils.deprecation import warn_deprecation
|
|
20
|
+
from litestar.utils.empty import value_or_default
|
|
21
|
+
from litestar.utils.helpers import get_enum_string_value
|
|
22
|
+
from litestar.utils.scope.state import ScopeState
|
|
23
|
+
from markupsafe import Markup
|
|
24
|
+
|
|
25
|
+
from litestar_vite.inertia._utils import get_headers
|
|
26
|
+
from litestar_vite.inertia.types import InertiaHeaderType, PageProps
|
|
27
|
+
from litestar_vite.plugin import VitePlugin
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from litestar.app import Litestar
|
|
31
|
+
from litestar.background_tasks import BackgroundTask, BackgroundTasks
|
|
32
|
+
from litestar.connection import ASGIConnection
|
|
33
|
+
from litestar.connection.base import AuthT, StateT, UserT
|
|
34
|
+
from litestar.types import ResponseCookies, ResponseHeaders, TypeEncodersMap
|
|
35
|
+
|
|
36
|
+
from litestar_vite.inertia.routes import Routes
|
|
37
|
+
|
|
38
|
+
from .plugin import InertiaPlugin
|
|
39
|
+
|
|
40
|
+
T = TypeVar("T")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def share(
|
|
44
|
+
connection: ASGIConnection[Any, Any, Any, Any],
|
|
45
|
+
key: str,
|
|
46
|
+
value: Any,
|
|
47
|
+
) -> None:
|
|
48
|
+
try:
|
|
49
|
+
connection.session.setdefault("_shared", {}).update({key: value})
|
|
50
|
+
except (AttributeError, ImproperlyConfiguredException):
|
|
51
|
+
msg = "Unable to set `share` session state. A valid session was not found for this request."
|
|
52
|
+
connection.logger.warning(msg)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def error(
|
|
56
|
+
connection: ASGIConnection[Any, Any, Any, Any],
|
|
57
|
+
key: str,
|
|
58
|
+
message: str,
|
|
59
|
+
) -> None:
|
|
60
|
+
try:
|
|
61
|
+
connection.session.setdefault("_errors", {}).update({key: message})
|
|
62
|
+
except (AttributeError, ImproperlyConfiguredException):
|
|
63
|
+
msg = "Unable to set `error` session state. A valid session was not found for this request."
|
|
64
|
+
connection.logger.warning(msg)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def get_shared_props(
|
|
68
|
+
request: ASGIConnection[Any, Any, Any, Any],
|
|
69
|
+
partial_data: set[str] | None = None,
|
|
70
|
+
) -> Dict[str, Any]: # noqa: UP006
|
|
71
|
+
"""Return shared session props for a request
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
Be sure to call this before `self.create_template_context` if you would like to include the `flash` message details.
|
|
75
|
+
"""
|
|
76
|
+
props: dict[str, Any] = {}
|
|
77
|
+
flash: dict[str, list[str]] = defaultdict(list)
|
|
78
|
+
errors: dict[str, Any] = {}
|
|
79
|
+
error_bag = request.headers.get("X-Inertia-Error-Bag", None)
|
|
80
|
+
try:
|
|
81
|
+
errors = request.session.pop("_errors", {})
|
|
82
|
+
props.update(cast("Dict[str,Any]", request.session.pop("_shared", {})))
|
|
83
|
+
for message in cast("List[Dict[str,Any]]", request.session.pop("_messages", [])):
|
|
84
|
+
flash[message["category"]].append(message["message"])
|
|
85
|
+
|
|
86
|
+
inertia_plugin = cast("InertiaPlugin", request.app.plugins.get("InertiaPlugin"))
|
|
87
|
+
props.update(inertia_plugin.config.extra_static_page_props)
|
|
88
|
+
for session_prop in inertia_plugin.config.extra_session_page_props:
|
|
89
|
+
if session_prop not in props and session_prop in request.session:
|
|
90
|
+
props[session_prop] = request.session.get(session_prop)
|
|
91
|
+
|
|
92
|
+
except (AttributeError, ImproperlyConfiguredException):
|
|
93
|
+
msg = "Unable to generate all shared props. A valid session was not found for this request."
|
|
94
|
+
request.logger.warning(msg)
|
|
95
|
+
props["flash"] = flash
|
|
96
|
+
props["errors"] = {error_bag: errors} if error_bag is not None else errors
|
|
97
|
+
props["csrf_token"] = value_or_default(ScopeState.from_scope(request.scope).csrf_token, "")
|
|
98
|
+
return props
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def js_routes_script(js_routes: Routes) -> Markup:
|
|
102
|
+
@lru_cache
|
|
103
|
+
def _markup_safe_json_dumps(js_routes: str) -> Markup:
|
|
104
|
+
js = js_routes.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026").replace("'", "\\u0027")
|
|
105
|
+
return Markup(js)
|
|
106
|
+
|
|
107
|
+
return Markup(
|
|
108
|
+
dedent(f"""
|
|
109
|
+
<script type="module">
|
|
110
|
+
globalThis.routes = JSON.parse('{_markup_safe_json_dumps(js_routes.formatted_routes)}')
|
|
111
|
+
</script>
|
|
112
|
+
"""),
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class InertiaResponse(Response[T]):
|
|
117
|
+
"""Inertia Response"""
|
|
118
|
+
|
|
119
|
+
def __init__(
|
|
120
|
+
self,
|
|
121
|
+
content: T,
|
|
122
|
+
*,
|
|
123
|
+
template_name: str | None = None,
|
|
124
|
+
template_str: str | None = None,
|
|
125
|
+
background: BackgroundTask | BackgroundTasks | None = None,
|
|
126
|
+
context: dict[str, Any] | None = None,
|
|
127
|
+
cookies: ResponseCookies | None = None,
|
|
128
|
+
encoding: str = "utf-8",
|
|
129
|
+
headers: ResponseHeaders | None = None,
|
|
130
|
+
media_type: MediaType | str | None = None,
|
|
131
|
+
status_code: int = HTTP_200_OK,
|
|
132
|
+
type_encoders: TypeEncodersMap | None = None,
|
|
133
|
+
) -> None:
|
|
134
|
+
"""Handle the rendering of a given template into a bytes string.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
content: A value for the response body that will be rendered into bytes string.
|
|
138
|
+
template_name: Path-like name for the template to be rendered, e.g. ``index.html``.
|
|
139
|
+
template_str: A string representing the template, e.g. ``tmpl = "Hello <strong>World</strong>"``.
|
|
140
|
+
background: A :class:`BackgroundTask <.background_tasks.BackgroundTask>` instance or
|
|
141
|
+
:class:`BackgroundTasks <.background_tasks.BackgroundTasks>` to execute after the response is finished.
|
|
142
|
+
Defaults to ``None``.
|
|
143
|
+
context: A dictionary of key/value pairs to be passed to the temple engine's render method.
|
|
144
|
+
cookies: A list of :class:`Cookie <.datastructures.Cookie>` instances to be set under the response
|
|
145
|
+
``Set-Cookie`` header.
|
|
146
|
+
encoding: Content encoding
|
|
147
|
+
headers: A string keyed dictionary of response headers. Header keys are insensitive.
|
|
148
|
+
media_type: A string or member of the :class:`MediaType <.enums.MediaType>` enum. If not set, try to infer
|
|
149
|
+
the media type based on the template name. If this fails, fall back to ``text/plain``.
|
|
150
|
+
status_code: A value for the response HTTP status code.
|
|
151
|
+
type_encoders: A mapping of types to callables that transform them into types supported for serialization.
|
|
152
|
+
"""
|
|
153
|
+
if template_name and template_str:
|
|
154
|
+
msg = "Either template_name or template_str must be provided, not both."
|
|
155
|
+
raise ValueError(msg)
|
|
156
|
+
self.content = content
|
|
157
|
+
self.background = background
|
|
158
|
+
self.cookies: list[Cookie] = (
|
|
159
|
+
[Cookie(key=key, value=value) for key, value in cookies.items()]
|
|
160
|
+
if isinstance(cookies, Mapping)
|
|
161
|
+
else list(cookies or [])
|
|
162
|
+
)
|
|
163
|
+
self.encoding = encoding
|
|
164
|
+
self.headers: dict[str, Any] = (
|
|
165
|
+
dict(headers) if isinstance(headers, Mapping) else {h.name: h.value for h in headers or {}}
|
|
166
|
+
)
|
|
167
|
+
self.media_type = media_type
|
|
168
|
+
self.status_code = status_code
|
|
169
|
+
self.response_type_encoders = {**(self.type_encoders or {}), **(type_encoders or {})}
|
|
170
|
+
self.context = context or {}
|
|
171
|
+
self.template_name = template_name
|
|
172
|
+
self.template_str = template_str
|
|
173
|
+
|
|
174
|
+
def create_template_context(
|
|
175
|
+
self,
|
|
176
|
+
request: Request[UserT, AuthT, StateT],
|
|
177
|
+
page_props: PageProps[T],
|
|
178
|
+
type_encoders: TypeEncodersMap | None = None,
|
|
179
|
+
) -> dict[str, Any]:
|
|
180
|
+
"""Create a context object for the template.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
request: A :class:`Request <.connection.Request>` instance.
|
|
184
|
+
page_props: A formatted object to return the inertia configuration.
|
|
185
|
+
type_encoders: A mapping of types to callables that transform them into types supported for serialization.
|
|
186
|
+
|
|
187
|
+
Returns:
|
|
188
|
+
A dictionary holding the template context
|
|
189
|
+
"""
|
|
190
|
+
csrf_token = value_or_default(ScopeState.from_scope(request.scope).csrf_token, "")
|
|
191
|
+
inertia_props = self.render(page_props, MediaType.JSON, get_serializer(type_encoders)).decode()
|
|
192
|
+
return {
|
|
193
|
+
**self.context,
|
|
194
|
+
"inertia": inertia_props,
|
|
195
|
+
"js_routes": js_routes_script(request.app.state.js_routes),
|
|
196
|
+
"request": request,
|
|
197
|
+
"csrf_input": f'<input type="hidden" name="_csrf_token" value="{csrf_token}" />',
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
def to_asgi_response(
|
|
201
|
+
self,
|
|
202
|
+
app: Litestar | None,
|
|
203
|
+
request: Request[UserT, AuthT, StateT],
|
|
204
|
+
*,
|
|
205
|
+
background: BackgroundTask | BackgroundTasks | None = None,
|
|
206
|
+
cookies: Iterable[Cookie] | None = None,
|
|
207
|
+
encoded_headers: Iterable[tuple[bytes, bytes]] | None = None,
|
|
208
|
+
headers: dict[str, str] | None = None,
|
|
209
|
+
is_head_response: bool = False,
|
|
210
|
+
media_type: MediaType | str | None = None,
|
|
211
|
+
status_code: int | None = None,
|
|
212
|
+
type_encoders: TypeEncodersMap | None = None,
|
|
213
|
+
) -> ASGIResponse:
|
|
214
|
+
if app is not None:
|
|
215
|
+
warn_deprecation(
|
|
216
|
+
version="2.1",
|
|
217
|
+
deprecated_name="app",
|
|
218
|
+
kind="parameter",
|
|
219
|
+
removal_in="3.0.0",
|
|
220
|
+
alternative="request.app",
|
|
221
|
+
)
|
|
222
|
+
inertia_enabled = cast(
|
|
223
|
+
"bool",
|
|
224
|
+
getattr(request, "inertia_enabled", False) or getattr(request, "is_inertia", False),
|
|
225
|
+
)
|
|
226
|
+
is_inertia = cast("bool", getattr(request, "is_inertia", False))
|
|
227
|
+
headers = {**headers, **self.headers} if headers is not None else self.headers
|
|
228
|
+
cookies = self.cookies if cookies is None else itertools.chain(self.cookies, cookies)
|
|
229
|
+
type_encoders = (
|
|
230
|
+
{**type_encoders, **(self.response_type_encoders or {})} if type_encoders else self.response_type_encoders
|
|
231
|
+
)
|
|
232
|
+
if not inertia_enabled:
|
|
233
|
+
media_type = get_enum_string_value(self.media_type or media_type or MediaType.JSON)
|
|
234
|
+
return ASGIResponse(
|
|
235
|
+
background=self.background or background,
|
|
236
|
+
body=self.render(self.content, media_type, get_serializer(type_encoders)),
|
|
237
|
+
cookies=cookies,
|
|
238
|
+
encoded_headers=encoded_headers,
|
|
239
|
+
encoding=self.encoding,
|
|
240
|
+
headers=headers,
|
|
241
|
+
is_head_response=is_head_response,
|
|
242
|
+
media_type=media_type,
|
|
243
|
+
status_code=self.status_code or status_code,
|
|
244
|
+
)
|
|
245
|
+
is_partial_render = cast("bool", getattr(request, "is_partial_render", False))
|
|
246
|
+
partial_keys = cast("set[str]", getattr(request, "partial_keys", {}))
|
|
247
|
+
vite_plugin = request.app.plugins.get(VitePlugin)
|
|
248
|
+
template_engine = vite_plugin.template_config.to_engine()
|
|
249
|
+
headers.update(
|
|
250
|
+
{"Vary": "Accept", **get_headers(InertiaHeaderType(enabled=True))},
|
|
251
|
+
)
|
|
252
|
+
shared_props = get_shared_props(request, partial_data=partial_keys if is_partial_render else None)
|
|
253
|
+
shared_props["content"] = self.content
|
|
254
|
+
page_props = PageProps[T](
|
|
255
|
+
component=request.inertia.route_component, # type: ignore[attr-defined] # pyright: ignore[reportUnknownArgumentType,reportUnknownMemberType,reportAttributeAccessIssue]
|
|
256
|
+
props=shared_props, # pyright: ignore[reportArgumentType]
|
|
257
|
+
version=template_engine.asset_loader.version_id,
|
|
258
|
+
url=request.url.path,
|
|
259
|
+
)
|
|
260
|
+
if is_inertia:
|
|
261
|
+
media_type = get_enum_string_value(self.media_type or media_type or MediaType.JSON)
|
|
262
|
+
body = self.render(page_props, media_type, get_serializer(type_encoders))
|
|
263
|
+
return ASGIResponse(
|
|
264
|
+
background=self.background or background,
|
|
265
|
+
body=body,
|
|
266
|
+
cookies=cookies,
|
|
267
|
+
encoded_headers=encoded_headers,
|
|
268
|
+
encoding=self.encoding,
|
|
269
|
+
headers=headers,
|
|
270
|
+
is_head_response=is_head_response,
|
|
271
|
+
media_type=media_type,
|
|
272
|
+
status_code=self.status_code or status_code,
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
if not template_engine:
|
|
276
|
+
msg = "Template engine is not configured"
|
|
277
|
+
raise ImproperlyConfiguredException(msg)
|
|
278
|
+
# it should default to HTML at this point unless the user specified something
|
|
279
|
+
media_type = media_type or MediaType.HTML
|
|
280
|
+
if not media_type:
|
|
281
|
+
if self.template_name:
|
|
282
|
+
suffixes = PurePath(self.template_name).suffixes
|
|
283
|
+
for suffix in suffixes:
|
|
284
|
+
if _type := guess_type(f"name{suffix}")[0]:
|
|
285
|
+
media_type = _type
|
|
286
|
+
break
|
|
287
|
+
else:
|
|
288
|
+
media_type = MediaType.TEXT
|
|
289
|
+
else:
|
|
290
|
+
media_type = MediaType.HTML
|
|
291
|
+
context = self.create_template_context(request, page_props, type_encoders) # pyright: ignore[reportUnknownMemberType]
|
|
292
|
+
if self.template_str is not None:
|
|
293
|
+
body = template_engine.render_string(self.template_str, context).encode(self.encoding)
|
|
294
|
+
else:
|
|
295
|
+
inertia_plugin = cast("InertiaPlugin", request.app.plugins.get("InertiaPlugin"))
|
|
296
|
+
template_name = self.template_name or inertia_plugin.config.root_template
|
|
297
|
+
# cast to str b/c we know that either template_name cannot be None if template_str is None
|
|
298
|
+
template = template_engine.get_template(template_name)
|
|
299
|
+
body = template.render(**context).encode(self.encoding)
|
|
300
|
+
|
|
301
|
+
return ASGIResponse(
|
|
302
|
+
background=self.background or background,
|
|
303
|
+
body=body,
|
|
304
|
+
cookies=cookies,
|
|
305
|
+
encoded_headers=encoded_headers,
|
|
306
|
+
encoding=self.encoding,
|
|
307
|
+
headers=headers,
|
|
308
|
+
is_head_response=is_head_response,
|
|
309
|
+
media_type=media_type,
|
|
310
|
+
status_code=self.status_code or status_code,
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
class InertiaExternalRedirect(Response[Any]):
|
|
315
|
+
"""Client side redirect."""
|
|
316
|
+
|
|
317
|
+
def __init__(
|
|
318
|
+
self,
|
|
319
|
+
request: Request[Any, Any, Any],
|
|
320
|
+
redirect_to: str,
|
|
321
|
+
**kwargs: Any,
|
|
322
|
+
) -> None:
|
|
323
|
+
"""Initialize external redirect, Set status code to 409 (required by Inertia),
|
|
324
|
+
and pass redirect url.
|
|
325
|
+
"""
|
|
326
|
+
super().__init__(
|
|
327
|
+
content=b"",
|
|
328
|
+
status_code=HTTP_409_CONFLICT,
|
|
329
|
+
headers={"X-Inertia-Location": quote(redirect_to, safe="/#%[]=:;$&()+,!?*@'~")},
|
|
330
|
+
cookies=request.cookies,
|
|
331
|
+
**kwargs,
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
class InertiaRedirect(Redirect):
|
|
336
|
+
"""Client side redirect."""
|
|
337
|
+
|
|
338
|
+
def __init__(
|
|
339
|
+
self,
|
|
340
|
+
request: Request[Any, Any, Any],
|
|
341
|
+
redirect_to: str,
|
|
342
|
+
**kwargs: Any,
|
|
343
|
+
) -> None:
|
|
344
|
+
"""Initialize external redirect, Set status code to 409 (required by Inertia),
|
|
345
|
+
and pass redirect url.
|
|
346
|
+
"""
|
|
347
|
+
referer = urlparse(request.headers.get("Referer", str(request.base_url)))
|
|
348
|
+
redirect_to = urlunparse(urlparse(redirect_to)._replace(scheme=referer.scheme))
|
|
349
|
+
super().__init__(
|
|
350
|
+
path=redirect_to,
|
|
351
|
+
status_code=HTTP_307_TEMPORARY_REDIRECT if request.method == "GET" else HTTP_303_SEE_OTHER,
|
|
352
|
+
cookies=request.cookies,
|
|
353
|
+
**kwargs,
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
class InertiaBack(Redirect):
|
|
358
|
+
"""Client side redirect."""
|
|
359
|
+
|
|
360
|
+
def __init__(
|
|
361
|
+
self,
|
|
362
|
+
request: Request[Any, Any, Any],
|
|
363
|
+
**kwargs: Any,
|
|
364
|
+
) -> None:
|
|
365
|
+
"""Initialize external redirect, Set status code to 409 (required by Inertia),
|
|
366
|
+
and pass redirect url.
|
|
367
|
+
"""
|
|
368
|
+
super().__init__(
|
|
369
|
+
path=request.headers.get("Referer", str(request.base_url)),
|
|
370
|
+
status_code=HTTP_307_TEMPORARY_REDIRECT if request.method == "GET" else HTTP_303_SEE_OTHER,
|
|
371
|
+
cookies=request.cookies,
|
|
372
|
+
**kwargs,
|
|
373
|
+
)
|
|
@@ -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
|
litestar_vite/loader.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from functools import cached_property
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from textwrap import dedent
|
|
7
|
+
from typing import TYPE_CHECKING, Any, ClassVar
|
|
8
|
+
from urllib.parse import urljoin
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from litestar_vite.config import ViteConfig
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ViteAssetLoader:
|
|
15
|
+
"""Vite manifest loader.
|
|
16
|
+
|
|
17
|
+
Please see: https://vitejs.dev/guide/backend-integration.html
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
_instance: ClassVar[ViteAssetLoader | None] = None
|
|
21
|
+
|
|
22
|
+
def __init__(self, config: ViteConfig) -> None:
|
|
23
|
+
self._config = config
|
|
24
|
+
self._manifest: dict[str, Any] = {}
|
|
25
|
+
self._manifest_content: str = ""
|
|
26
|
+
self._vite_base_path: str | None = None
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def initialize_loader(cls, config: ViteConfig) -> ViteAssetLoader:
|
|
30
|
+
"""Singleton manifest loader."""
|
|
31
|
+
if cls._instance is None:
|
|
32
|
+
cls._instance = cls(config=config)
|
|
33
|
+
cls._instance.parse_manifest()
|
|
34
|
+
return cls._instance
|
|
35
|
+
|
|
36
|
+
@cached_property
|
|
37
|
+
def version_id(self) -> str:
|
|
38
|
+
if self._manifest_content != "":
|
|
39
|
+
return str(hash(self.manifest_content))
|
|
40
|
+
return "1.0"
|
|
41
|
+
|
|
42
|
+
def parse_manifest(self) -> None:
|
|
43
|
+
"""Parse the Vite manifest file.
|
|
44
|
+
|
|
45
|
+
The manifest file is a JSON file that maps source files to their corresponding output files.
|
|
46
|
+
Example manifest file structure:
|
|
47
|
+
|
|
48
|
+
.. code-block:: json
|
|
49
|
+
|
|
50
|
+
{
|
|
51
|
+
"main.js": {
|
|
52
|
+
"file": "assets/main.4889e940.js",
|
|
53
|
+
"src": "main.js",
|
|
54
|
+
"isEntry": true,
|
|
55
|
+
"dynamicImports": ["views/foo.js"],
|
|
56
|
+
"css": ["assets/main.b82dbe22.css"],
|
|
57
|
+
"assets": ["assets/asset.0ab0f9cd.png"]
|
|
58
|
+
},
|
|
59
|
+
"views/foo.js": {
|
|
60
|
+
"file": "assets/foo.869aea0d.js",
|
|
61
|
+
"src": "views/foo.js",
|
|
62
|
+
"isDynamicEntry": true,
|
|
63
|
+
"imports": ["_shared.83069a53.js"]
|
|
64
|
+
},
|
|
65
|
+
"_shared.83069a53.js": {
|
|
66
|
+
"file": "assets/shared.83069a53.js"
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
The manifest is parsed and stored in memory for asset resolution during template rendering.
|
|
71
|
+
"""
|
|
72
|
+
if self._config.hot_reload and self._config.dev_mode:
|
|
73
|
+
hot_file_path = Path(
|
|
74
|
+
f"{self._config.bundle_dir}/{self._config.hot_file}",
|
|
75
|
+
)
|
|
76
|
+
if hot_file_path.exists():
|
|
77
|
+
with hot_file_path.open() as hot_file:
|
|
78
|
+
self._vite_base_path = hot_file.read()
|
|
79
|
+
|
|
80
|
+
else:
|
|
81
|
+
manifest_path = Path(f"{self._config.bundle_dir}/{self._config.manifest_name}")
|
|
82
|
+
try:
|
|
83
|
+
if manifest_path.exists():
|
|
84
|
+
with manifest_path.open() as manifest_file:
|
|
85
|
+
self.manifest_content = manifest_file.read()
|
|
86
|
+
self._manifest = json.loads(self.manifest_content)
|
|
87
|
+
else:
|
|
88
|
+
self._manifest = {}
|
|
89
|
+
except Exception as exc:
|
|
90
|
+
msg = "There was an issue reading the Vite manifest file at %s. Did you forget to build your assets?"
|
|
91
|
+
raise RuntimeError(
|
|
92
|
+
msg,
|
|
93
|
+
manifest_path,
|
|
94
|
+
) from exc
|
|
95
|
+
|
|
96
|
+
def generate_ws_client_tags(self) -> str:
|
|
97
|
+
"""Generate the script tag for the Vite WS client for HMR.
|
|
98
|
+
|
|
99
|
+
Only used when hot module reloading is enabled, in production this method returns an empty string.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
str: The script tag or an empty string.
|
|
103
|
+
"""
|
|
104
|
+
if self._config.hot_reload and self._config.dev_mode:
|
|
105
|
+
return self._script_tag(
|
|
106
|
+
self._vite_server_url("@vite/client"),
|
|
107
|
+
{"type": "module"},
|
|
108
|
+
)
|
|
109
|
+
return ""
|
|
110
|
+
|
|
111
|
+
def generate_react_hmr_tags(self) -> str:
|
|
112
|
+
"""Generate the script tag for the Vite WS client for HMR.
|
|
113
|
+
|
|
114
|
+
Only used when hot module reloading is enabled, in production this method returns an empty string.
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
str: The script tag or an empty string.
|
|
118
|
+
"""
|
|
119
|
+
if self._config.is_react and self._config.hot_reload and self._config.dev_mode:
|
|
120
|
+
return dedent(f"""
|
|
121
|
+
<script type="module">
|
|
122
|
+
import RefreshRuntime from '{self._vite_server_url()}@react-refresh'
|
|
123
|
+
RefreshRuntime.injectIntoGlobalHook(window)
|
|
124
|
+
window.$RefreshReg$ = () => {{}}
|
|
125
|
+
window.$RefreshSig$ = () => (type) => type
|
|
126
|
+
window.__vite_plugin_react_preamble_installed__=true
|
|
127
|
+
</script>
|
|
128
|
+
""")
|
|
129
|
+
return ""
|
|
130
|
+
|
|
131
|
+
def generate_asset_tags(self, path: str | list[str], scripts_attrs: dict[str, str] | None = None) -> str:
|
|
132
|
+
"""Generate all assets include tags for the file in argument.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
str: All tags to import this asset in your HTML page.
|
|
136
|
+
"""
|
|
137
|
+
if isinstance(path, str):
|
|
138
|
+
path = [path]
|
|
139
|
+
if self._config.hot_reload and self._config.dev_mode:
|
|
140
|
+
return "".join(
|
|
141
|
+
[
|
|
142
|
+
self._style_tag(self._vite_server_url(p))
|
|
143
|
+
if p.endswith(".css")
|
|
144
|
+
else self._script_tag(
|
|
145
|
+
self._vite_server_url(p),
|
|
146
|
+
{"type": "module", "async": "", "defer": ""},
|
|
147
|
+
)
|
|
148
|
+
for p in path
|
|
149
|
+
],
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
if any(p for p in path if p not in self._manifest):
|
|
153
|
+
msg = "Cannot find %s in Vite manifest at %s. Did you forget to build your assets after an update?"
|
|
154
|
+
raise RuntimeError(
|
|
155
|
+
msg,
|
|
156
|
+
path,
|
|
157
|
+
Path(f"{self._config.bundle_dir}/{self._config.manifest_name}"),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
tags: list[str] = []
|
|
161
|
+
manifest_entry: dict[str, Any] = {}
|
|
162
|
+
manifest_entry.update({p: self._manifest[p] for p in path})
|
|
163
|
+
if not scripts_attrs:
|
|
164
|
+
scripts_attrs = {"type": "module", "async": "", "defer": ""}
|
|
165
|
+
for manifest in manifest_entry.values():
|
|
166
|
+
if "css" in manifest:
|
|
167
|
+
tags.extend(
|
|
168
|
+
self._style_tag(urljoin(self._config.asset_url, css_path)) for css_path in manifest.get("css", {})
|
|
169
|
+
)
|
|
170
|
+
# Add dependent "vendor"
|
|
171
|
+
if "imports" in manifest:
|
|
172
|
+
tags.extend(
|
|
173
|
+
self.generate_asset_tags(vendor_path, scripts_attrs=scripts_attrs)
|
|
174
|
+
for vendor_path in manifest.get("imports", {})
|
|
175
|
+
)
|
|
176
|
+
# Add the script by itself
|
|
177
|
+
if manifest.get("file").endswith(".css"):
|
|
178
|
+
tags.append(
|
|
179
|
+
self._style_tag(urljoin(self._config.asset_url, manifest["file"])),
|
|
180
|
+
)
|
|
181
|
+
else:
|
|
182
|
+
tags.append(
|
|
183
|
+
self._script_tag(
|
|
184
|
+
urljoin(self._config.asset_url, manifest["file"]),
|
|
185
|
+
attrs=scripts_attrs,
|
|
186
|
+
),
|
|
187
|
+
)
|
|
188
|
+
return "".join(tags)
|
|
189
|
+
|
|
190
|
+
def _vite_server_url(self, path: str | None = None) -> str:
|
|
191
|
+
"""Generate an URL to and asset served by the Vite development server.
|
|
192
|
+
|
|
193
|
+
Keyword Arguments:
|
|
194
|
+
path: Path to the asset. (default: {None})
|
|
195
|
+
|
|
196
|
+
Returns:
|
|
197
|
+
str: Full URL to the asset.
|
|
198
|
+
"""
|
|
199
|
+
base_path = self._vite_base_path or f"{self._config.protocol}://{self._config.host}:{self._config.port}"
|
|
200
|
+
return urljoin(
|
|
201
|
+
base_path,
|
|
202
|
+
urljoin(self._config.asset_url, path if path is not None else ""),
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
def _script_tag(self, src: str, attrs: dict[str, str] | None = None) -> str:
|
|
206
|
+
"""Generate an HTML script tag."""
|
|
207
|
+
if attrs is None:
|
|
208
|
+
attrs = {}
|
|
209
|
+
attrs_str = " ".join([f'{key}="{value}"' for key, value in attrs.items()])
|
|
210
|
+
return f'<script {attrs_str} src="{src}"></script>'
|
|
211
|
+
|
|
212
|
+
def _style_tag(self, href: str) -> str:
|
|
213
|
+
"""Generate and HTML <link> stylesheet tag for CSS.
|
|
214
|
+
|
|
215
|
+
Args:
|
|
216
|
+
href: CSS file URL.
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
str: CSS link tag.
|
|
220
|
+
"""
|
|
221
|
+
return f'<link rel="stylesheet" href="{href}" />'
|