litestar-vite 0.1.20__py3-none-any.whl → 0.1.22__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/cli.py CHANGED
@@ -144,6 +144,8 @@ def vite_init(
144
144
  console.print("Skipping Vite initialization")
145
145
  sys.exit(2)
146
146
  for output_path in (bundle_path, resource_path, root_path):
147
+ if output_path.exists():
148
+ console.print(f" * Creating {output_path!s}")
147
149
  output_path.mkdir(parents=True, exist_ok=True)
148
150
 
149
151
  enable_ssr = (
litestar_vite/commands.py CHANGED
@@ -5,16 +5,12 @@ import subprocess
5
5
  from pathlib import Path
6
6
  from typing import TYPE_CHECKING, Any, MutableMapping
7
7
 
8
- from jinja2 import select_autoescape
9
- from litestar.serialization import encode_json
10
-
11
8
  if TYPE_CHECKING:
12
9
  from jinja2 import Environment, Template
13
10
  from litestar import Litestar
14
11
 
15
- VITE_INIT_TEMPLATES_PATH = f"{Path(__file__).parent}/templates"
16
12
  VITE_INIT_TEMPLATES: set[str] = {"package.json.j2", "tsconfig.json.j2", "vite.config.ts.j2"}
17
- DEFAULT_RESOURCES: set[str] = {"styles.css", "main.ts"}
13
+ DEFAULT_RESOURCES: set[str] = {"styles.css.j2", "main.ts.j2"}
18
14
  DEFAULT_DEV_DEPENDENCIES: dict[str, str] = {
19
15
  "typescript": "^5.3.3",
20
16
  "vite": "^5.0.6",
@@ -33,6 +29,8 @@ def to_json(value: Any) -> str:
33
29
  Returns:
34
30
  JSON string.
35
31
  """
32
+ from litestar.serialization import encode_json
33
+
36
34
  return encode_json(value).decode("utf-8")
37
35
 
38
36
 
@@ -49,12 +47,13 @@ def init_vite(
49
47
  litestar_port: int,
50
48
  ) -> None:
51
49
  """Initialize a new vite project."""
52
- from jinja2 import Environment, FileSystemLoader
50
+ from jinja2 import Environment, FileSystemLoader, select_autoescape
53
51
  from litestar.cli._utils import console
52
+ from litestar.utils import module_loader
54
53
 
55
- entry_point: list[str] = []
54
+ template_path = module_loader.module_to_os_path("litestar_vite.templates")
56
55
  vite_template_env = Environment(
57
- loader=FileSystemLoader([VITE_INIT_TEMPLATES_PATH]),
56
+ loader=FileSystemLoader([template_path]),
58
57
  autoescape=select_autoescape(),
59
58
  )
60
59
 
@@ -66,25 +65,23 @@ def init_vite(
66
65
  template_name: get_template(environment=vite_template_env, name=template_name)
67
66
  for template_name in enabled_templates
68
67
  }
69
- entry_point = [
70
- str(Path(resource_path / resource_name).relative_to(Path.cwd().absolute()))
71
- for resource_name in enabled_resources
72
- ]
73
68
  for template_name, template in templates.items():
74
69
  target_file_name = template_name.removesuffix(".j2")
75
70
  with Path(target_file_name).open(mode="w") as file:
76
- console.print(f" * Writing {target_file_name} to {Path(target_file_name).absolute()}")
71
+ console.print(f" * Writing {target_file_name} to {Path(target_file_name)!s}")
77
72
 
78
73
  file.write(
79
74
  template.render(
80
- entry_point=entry_point,
75
+ entry_point=[
76
+ f"{resource_path!s}/{resource_name.removesuffix('.j2')}" for resource_name in enabled_resources
77
+ ],
81
78
  enable_ssr=enable_ssr,
82
79
  asset_url=asset_url,
83
- root_path=str(root_path.relative_to(Path.cwd().absolute())),
80
+ root_path=root_path,
84
81
  resource_path=str(resource_path.relative_to(root_path)),
85
82
  public_path=str(public_path.relative_to(root_path)),
86
83
  bundle_path=str(bundle_path.relative_to(root_path)),
87
- hot_file=str(hot_file.relative_to(Path.cwd().absolute())),
84
+ hot_file=str(hot_file.relative_to(root_path)),
88
85
  vite_port=str(vite_port),
89
86
  litestar_port=litestar_port,
90
87
  dependencies=to_json(dependencies),
@@ -93,8 +90,11 @@ def init_vite(
93
90
  )
94
91
 
95
92
  for resource_name in enabled_resources:
96
- with Path(resource_path / resource_name).open(mode="w") as file:
97
- console.print(f" * Writing {resource_name} to {Path(resource_path / resource_name).absolute()}")
93
+ template = get_template(environment=vite_template_env, name=resource_name)
94
+ target_file_name = f"{resource_path}/{resource_name.removesuffix('.j2')}"
95
+ with Path(target_file_name).open(mode="w") as file:
96
+ console.print(f" * Writing {resource_name.removesuffix('.j2')} to {Path(target_file_name)!s}")
97
+ file.write(template.render())
98
98
  console.print("[yellow]Vite initialization completed.[/]")
99
99
 
100
100
 
litestar_vite/config.py CHANGED
@@ -18,9 +18,8 @@ if TYPE_CHECKING:
18
18
 
19
19
  from litestar.types import PathType
20
20
 
21
- from litestar_vite.template_engine import ViteTemplateEngine
22
21
 
23
- T = TypeVar("T", bound=TemplateEngineProtocol)
22
+ EngineType = TypeVar("EngineType", bound=TemplateEngineProtocol)
24
23
 
25
24
 
26
25
  @dataclass
@@ -127,7 +126,7 @@ class ViteConfig:
127
126
 
128
127
 
129
128
  @dataclass
130
- class ViteTemplateConfig(Generic[T]):
129
+ class ViteTemplateConfig(Generic[EngineType]):
131
130
  """Configuration for Templating.
132
131
 
133
132
  To enable templating, pass an instance of this class to the
@@ -135,27 +134,30 @@ class ViteTemplateConfig(Generic[T]):
135
134
  'template_config' key.
136
135
  """
137
136
 
138
- engine: type[ViteTemplateEngine]
139
- """A template engine adhering to the :class:`TemplateEngineProtocol
140
- <litestar.template.base.TemplateEngineProtocol>`."""
141
137
  config: ViteConfig
142
138
  """A a config for the vite engine`."""
143
- directory: PathType | None = field(default=None)
139
+ engine: type[EngineType] | EngineType | None = field(default=None)
140
+ """A template engine adhering to the :class:`TemplateEngineProtocol
141
+ <litestar.template.base.TemplateEngineProtocol>`."""
142
+ directory: PathType | list[PathType] | None = field(default=None)
144
143
  """A directory or list of directories from which to serve templates."""
145
- engine_callback: Callable[[T], None] | None = field(default=None)
144
+ engine_callback: Callable[[EngineType], None] | None = field(default=None)
146
145
  """A callback function that allows modifying the instantiated templating
147
146
  protocol."""
148
147
 
148
+ instance: EngineType | None = field(default=None)
149
+ """An instance of the templating protocol."""
150
+
149
151
  def __post_init__(self) -> None:
150
152
  """Ensure that directory is set if engine is a class."""
151
153
  if isclass(self.engine) and not self.directory:
152
154
  msg = "directory is a required kwarg when passing a template engine class"
153
155
  raise ImproperlyConfiguredException(msg)
154
156
 
155
- def to_engine(self) -> T:
157
+ def to_engine(self) -> EngineType:
156
158
  """Instantiate the template engine."""
157
159
  template_engine = cast(
158
- "T",
160
+ "EngineType",
159
161
  self.engine(directory=self.directory, config=self.config) if isclass(self.engine) else self.engine,
160
162
  )
161
163
  if callable(self.engine_callback):
@@ -163,6 +165,6 @@ class ViteTemplateConfig(Generic[T]):
163
165
  return template_engine
164
166
 
165
167
  @cached_property
166
- def engine_instance(self) -> T:
168
+ def engine_instance(self) -> EngineType:
167
169
  """Return the template engine instance."""
168
170
  return self.to_engine()
litestar_vite/loader.py CHANGED
@@ -5,7 +5,6 @@ from pathlib import Path
5
5
  from typing import TYPE_CHECKING, Any, ClassVar, TypeVar
6
6
  from urllib.parse import urljoin
7
7
 
8
- from litestar.cli._utils import console
9
8
  from litestar.template import TemplateEngineProtocol
10
9
 
11
10
  if TYPE_CHECKING:
@@ -65,27 +64,27 @@ class ViteAssetLoader:
65
64
  RuntimeError: if cannot load the file or JSON in file is malformed.
66
65
  """
67
66
  if self._config.hot_reload and self._config.dev_mode:
68
- if Path(
67
+ hot_file_path = Path(
69
68
  f"{self._config.bundle_dir}/{self._config.hot_file}",
70
- ).exists():
71
- with Path(f"{self._config.bundle_dir}/{self._config.hot_file}").open() as hot_file:
69
+ )
70
+ if hot_file_path.exists():
71
+ with hot_file_path.open() as hot_file:
72
72
  self._vite_base_path = hot_file.read()
73
73
 
74
74
  else:
75
+ manifest_path = Path(f"{self._config.bundle_dir}/{self._config.manifest_name}")
75
76
  try:
76
- with Path(f"{self._config.bundle_dir}/{self._config.manifest_name}").open() as manifest_file:
77
- manifest_content = manifest_file.read()
78
- self._manifest = json.loads(manifest_content)
79
- except FileNotFoundError:
80
- console.print(
81
- f"[bold red]Cannot read Vite manifest file at {self._config.bundle_dir}/{self._config.manifest_name}. Did you forget to build your assets?",
82
- )
83
- self._manifest = {}
77
+ if manifest_path.exists():
78
+ with manifest_path.open() as manifest_file:
79
+ manifest_content = manifest_file.read()
80
+ self._manifest = json.loads(manifest_content)
81
+ else:
82
+ self._manifest = {}
84
83
  except Exception as exc: # noqa: BLE001
85
84
  msg = "There was an issue reading the Vite manifest file at %s. Did you forget to build your assets?"
86
85
  raise RuntimeError(
87
86
  msg,
88
- Path(f"{self._config.bundle_dir}/{self._config.manifest_name}"),
87
+ manifest_path,
89
88
  ) from exc
90
89
 
91
90
  def generate_ws_client_tags(self) -> str:
litestar_vite/plugin.py CHANGED
@@ -8,13 +8,13 @@ from typing import TYPE_CHECKING, Iterator, cast
8
8
  from litestar.plugins import CLIPlugin, InitPluginProtocol
9
9
  from litestar.static_files import create_static_files_router
10
10
 
11
+ from litestar_vite.config import ViteConfig
12
+
11
13
  if TYPE_CHECKING:
12
14
  from click import Group
13
15
  from litestar import Litestar
14
16
  from litestar.config.app import AppConfig
15
17
 
16
- from litestar_vite.config import ViteConfig
17
-
18
18
 
19
19
  def set_environment(config: ViteConfig) -> None:
20
20
  """Configure environment for easier integration"""
@@ -32,12 +32,14 @@ class VitePlugin(InitPluginProtocol, CLIPlugin):
32
32
 
33
33
  __slots__ = ("_config",)
34
34
 
35
- def __init__(self, config: ViteConfig) -> None:
35
+ def __init__(self, config: ViteConfig | None = None) -> None:
36
36
  """Initialize ``Vite``.
37
37
 
38
38
  Args:
39
- config: configure and start Vite.
39
+ config: configuration to use for starting Vite. The default configuration will be used if it is not provided.
40
40
  """
41
+ if config is None:
42
+ config = ViteConfig()
41
43
  self._config = config
42
44
 
43
45
  @property
@@ -60,11 +62,12 @@ class VitePlugin(InitPluginProtocol, CLIPlugin):
60
62
  from litestar_vite.config import ViteTemplateConfig
61
63
  from litestar_vite.template_engine import ViteTemplateEngine
62
64
 
63
- app_config.template_config = ViteTemplateConfig( # type: ignore[assignment]
64
- engine=ViteTemplateEngine,
65
- config=self._config,
66
- directory=self._config.template_dir,
67
- )
65
+ if self._config.template_dir is not None:
66
+ app_config.template_config = ViteTemplateConfig[ViteTemplateEngine]( # type: ignore[assignment]
67
+ engine=ViteTemplateEngine,
68
+ config=self._config,
69
+ directory=self._config.template_dir,
70
+ )
68
71
 
69
72
  if self._config.set_static_folders:
70
73
  static_dirs = [Path(self._config.bundle_dir), Path(self._config.resource_dir)]
@@ -116,4 +119,9 @@ class VitePlugin(InitPluginProtocol, CLIPlugin):
116
119
  console.print("[yellow]Vite process stopped.[/]")
117
120
 
118
121
  else:
122
+ manifest_path = Path(f"{self._config.bundle_dir}/{self._config.manifest_name}")
123
+ if manifest_path.exists():
124
+ console.rule(f"[yellow]Serving assets using manifest at `{manifest_path!s}`.[/]", align="left")
125
+ else:
126
+ console.rule(f"[yellow]Serving assets without manifest at `{manifest_path!s}`.[/]", align="left")
119
127
  yield
@@ -0,0 +1 @@
1
+ import "./styles.css"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: litestar-vite
3
- Version: 0.1.20
3
+ Version: 0.1.22
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
@@ -30,7 +30,7 @@ Classifier: Topic :: Database :: Database Engines/Servers
30
30
  Classifier: Topic :: Software Development
31
31
  Classifier: Typing :: Typed
32
32
  Requires-Python: >=3.8
33
- Requires-Dist: litestar[cli,jinja]>=2.4.0
33
+ Requires-Dist: litestar[jinja]>=2.4.0
34
34
  Provides-Extra: nodeenv
35
35
  Requires-Dist: nodeenv; extra == 'nodeenv'
36
36
  Description-Content-Type: text/markdown
@@ -0,0 +1,20 @@
1
+ litestar_vite/__init__.py,sha256=9X3i67Q8DJN2lQYAMa9NSPTZGzHASGn8X8yeWJqBvWg,357
2
+ litestar_vite/__metadata__.py,sha256=Eml1c9xezV-GSodmysksrT8jPWqE__x0ENO1wM5g6q0,319
3
+ litestar_vite/cli.py,sha256=BsYvMPcE8rFZGO8xnEwEXtrXhILgizN3JDVO_KH_FE8,9618
4
+ litestar_vite/commands.py,sha256=S2oY1z1IMFPG58qD5FzDF4hjZvoKycj3Hl9XeSw3_hM,4236
5
+ litestar_vite/config.py,sha256=uBbdV0INcChMOoGzVf60baovtuwkUkqkbVhwTFFw804,6978
6
+ litestar_vite/loader.py,sha256=cxDwrViZJR2F7H6OTkZLwQhG0uw9VadUh-vxc91tJZs,7481
7
+ litestar_vite/plugin.py,sha256=pw9ianec85DdXWnBFvhcZp7Ag4lu-3MIVP8mFzOFOg8,4843
8
+ litestar_vite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ litestar_vite/template_engine.py,sha256=UIxphAoAKrAcpAuV_CJmZgsN9GOFfqq0azQdId6yofg,2995
10
+ litestar_vite/templates/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ litestar_vite/templates/index.html.j2,sha256=GobZbXgrlFRf3sCoS-416iWfV8lBP_v3AXPQX_QVzZA,381
12
+ litestar_vite/templates/main.ts.j2,sha256=Nzr5m_hXMAjeDL_4yQNP3DMCf7Blh3dwg5m-67GJVbY,22
13
+ litestar_vite/templates/package.json.j2,sha256=0JWgdTuaSZ25EmCltF_zbqDdpxfvCLeYuzBjXrziXNw,299
14
+ litestar_vite/templates/styles.css.j2,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ litestar_vite/templates/tsconfig.json.j2,sha256=q1REIuVyXUHCy4Zi2kgTkmrhdT98vyY89k-WTrImOj8,843
16
+ litestar_vite/templates/vite.config.ts.j2,sha256=FZ4OJaB8Kjby_nlx4_LCP8eCe1LRi8kW2GspCiVMfDY,1115
17
+ litestar_vite-0.1.22.dist-info/METADATA,sha256=aSQ7qnkNkw39YYPUf2vaNRqjowtw2ub6IzmfT_ZohNs,6437
18
+ litestar_vite-0.1.22.dist-info/WHEEL,sha256=bq9SyP5NxIRA9EpQgMCd-9RmPHWvbH-4lTDGwxgIR64,87
19
+ litestar_vite-0.1.22.dist-info/licenses/LICENSE,sha256=HeTiEfEgvroUXZe_xAmYHxtTBgw--mbXyZLsWDYabHc,1069
20
+ litestar_vite-0.1.22.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.22.2
2
+ Generator: hatchling 1.22.3
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,19 +0,0 @@
1
- litestar_vite/__init__.py,sha256=9X3i67Q8DJN2lQYAMa9NSPTZGzHASGn8X8yeWJqBvWg,357
2
- litestar_vite/__metadata__.py,sha256=Eml1c9xezV-GSodmysksrT8jPWqE__x0ENO1wM5g6q0,319
3
- litestar_vite/cli.py,sha256=6SmKu_wdduotTsx1xbmQFooQqG8SZyHwIDvZrr3KMJI,9527
4
- litestar_vite/commands.py,sha256=jLwnIenDUzyGYmufdsRn3weU1q08vuI4obQx-sUOxzg,4121
5
- litestar_vite/config.py,sha256=L93F0CrghlNrAHlmTPqYtZxtZoLPf5kOJebqFxAlVOE,6824
6
- litestar_vite/loader.py,sha256=3BFvcsXdaTwyym6bHaGhTkNDFaAcdjQDUHRfuKHj2vM,7699
7
- litestar_vite/plugin.py,sha256=nNB62gqRXv6x1nxJNxZZPd67zOaw9XvGQxP_AxDyPbk,4230
8
- litestar_vite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
- litestar_vite/template_engine.py,sha256=UIxphAoAKrAcpAuV_CJmZgsN9GOFfqq0azQdId6yofg,2995
10
- litestar_vite/templates/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
- litestar_vite/templates/index.html.j2,sha256=GobZbXgrlFRf3sCoS-416iWfV8lBP_v3AXPQX_QVzZA,381
12
- litestar_vite/templates/main.css.j2,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
- litestar_vite/templates/package.json.j2,sha256=0JWgdTuaSZ25EmCltF_zbqDdpxfvCLeYuzBjXrziXNw,299
14
- litestar_vite/templates/tsconfig.json.j2,sha256=q1REIuVyXUHCy4Zi2kgTkmrhdT98vyY89k-WTrImOj8,843
15
- litestar_vite/templates/vite.config.ts.j2,sha256=FZ4OJaB8Kjby_nlx4_LCP8eCe1LRi8kW2GspCiVMfDY,1115
16
- litestar_vite-0.1.20.dist-info/METADATA,sha256=k-JRBSUUxCrReb8BQQCJwfRUPeFyZIf6OjsHdoJE3QI,6441
17
- litestar_vite-0.1.20.dist-info/WHEEL,sha256=LL0B1KxSLwaTWceo7tT-0aDLd-qq9dmbnsnk1DnXlg8,87
18
- litestar_vite-0.1.20.dist-info/licenses/LICENSE,sha256=HeTiEfEgvroUXZe_xAmYHxtTBgw--mbXyZLsWDYabHc,1069
19
- litestar_vite-0.1.20.dist-info/RECORD,,
File without changes