Skip to content

Commit

Permalink
fix: cleanup templates; add default entry points
Browse files Browse the repository at this point in the history
  • Loading branch information
cofin committed Dec 17, 2023
1 parent 77ec4cc commit 4489d58
Show file tree
Hide file tree
Showing 32 changed files with 742 additions and 848 deletions.
9 changes: 2 additions & 7 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ repos:
- id: mixed-line-ending
- id: trailing-whitespace
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.1.7"
rev: "v0.1.8"
hooks:
- id: ruff
args: ["--fix"]
Expand All @@ -26,11 +26,6 @@ repos:
rev: v2.2.6
hooks:
- id: codespell
- repo: https://github.com/psf/black
rev: 23.11.0
hooks:
- id: black
args: [--config=./pyproject.toml]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v1.7.1"
hooks:
Expand All @@ -52,6 +47,6 @@ repos:
"litestar[cli]",
]
- repo: https://github.com/sphinx-contrib/sphinx-lint
rev: "v0.9.0"
rev: "v0.9.1"
hooks:
- id: sphinx-lint
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ SHELL := /bin/bash
.DEFAULT_GOAL:=help
.ONESHELL:
USING_PDM = $(shell grep "tool.pdm" pyproject.toml && echo "yes")
ENV_PREFIX = $(shell python3 -c "if __import__('pathlib').Path('.venv/bin/pip').exists(): print('.venv/bin/')")
ENV_PREFIX = .venv/bin/
VENV_EXISTS = $(shell python3 -c "if __import__('pathlib').Path('.venv/bin/activate').exists(): print('yes')")
PDM_OPTS ?=
PDM ?= pdm $(PDM_OPTS)
Expand Down
2 changes: 1 addition & 1 deletion examples/vue/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
from pathlib import Path

from litestar import Litestar
from web.controllers import WebController

from examples.vue.web.controllers import WebController
from litestar_vite import ViteConfig, VitePlugin

here = Path(__file__).parent
Expand Down
706 changes: 161 additions & 545 deletions examples/vue/package-lock.json

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions examples/vue/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
"type": "module",
"scripts": {
"dev": "vite",
"watch": "vite build --watch",
"build": "vite build"
},
"dependencies": {},
"devDependencies": {"axios":"^1.6.2","typescript":"^5.3.3","vite":"^5.0.6","litestar-vite-plugin":"^0.3.0","@types/node":"^20.10.3"}
}
"dependencies": {"axios":"^1.6.2"},
"devDependencies": {"typescript":"^5.3.3","vite":"^5.0.6","litestar-vite-plugin":"^0.3.0","@types/node":"^20.10.3"}
}
14 changes: 7 additions & 7 deletions examples/vue/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
{
"compilerOptions": {
"target": "ESNext",
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "node",
"module": "ES2020",
"moduleResolution": "bundler",
"strict": true,
"jsx": "preserve",
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"noEmit": true,
"composite": true,
Expand All @@ -18,13 +18,13 @@
"paths": {
"@/*": ["./*"]
},
"types": ["vite/client", "node"]
"types": ["vite/client"]
},
"include": [

"**/*.d.ts",
"resources/**/*.js" ,
"resources/**/*.ts" ,
"vite.config.ts"
]
}
}
27 changes: 21 additions & 6 deletions examples/vue/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,36 @@
import { defineConfig } from "vite";


import litestar from "litestar-vite-plugin";

const ASSET_URL =
process.env.LITESTAR_ASSET_URL || process.env.ASSET_URL || "/static/";
const VITE_PORT = process.env.VITE_PORT || "5173";
const VITE_HOST = process.env.VITE_HOST || "localhost";
export default defineConfig({
root: "web",
base: `${ASSET_URL}`,
root: "web",
server: {
host: `${VITE_HOST}`,
port: +`${VITE_PORT}`,
cors: true,
},
plugins: [


litestar({
input: ["resources/assets/main.ts", "resources/assets/styles.css"],
assetUrl: "/static/",
assetDirectory: "resources/assets",
input: [
"web/resources/styles.css", "web/resources/main.ts"
],
assetUrl: `${ASSET_URL}`,
bundleDirectory: "public",
resourceDirectory: "resources",
hotFile: "web/public/hot"
}),
],
resolve: {
alias: {
"@": "resources",
"@": "resources"
},
},
});
});
Empty file removed examples/vue/web/public/.gitkeep
Empty file.
12 changes: 12 additions & 0 deletions examples/vue/web/public/.vite/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"resources/main.ts": {
"file": "assets/main-w40geAFS.js",
"isEntry": true,
"src": "resources/main.ts"
},
"resources/styles.css": {
"file": "assets/styles-w40geAFS.js",
"isEntry": true,
"src": "resources/styles.css"
}
}
1 change: 1 addition & 0 deletions examples/vue/web/public/assets/main-w40geAFS.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions examples/vue/web/public/assets/styles-w40geAFS.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

6 changes: 0 additions & 6 deletions examples/vue/web/resources/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +0,0 @@
import "vite/modulepreload-polyfill";
import { createApp } from "vue";
import "./style.css";
import App from "@/App.vue";

createApp(App).mount("#app");
29 changes: 17 additions & 12 deletions litestar_vite/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ def vite_init(
sys.exit(2)
for output_path in (bundle_path, resource_path):
output_path.mkdir(parents=True, exist_ok=True)

enable_ssr = (
True
if enable_ssr
Expand Down Expand Up @@ -146,14 +147,14 @@ def vite_install(app: Litestar, verbose: bool) -> None:
console,
)

from litestar_vite.commands import run_vite
from litestar_vite.commands import execute_command
from litestar_vite.plugin import VitePlugin

if verbose:
app.debug = True
console.rule("[yellow]Starting Vite package installation process[/]", align="left")
plugin = app.plugins.get(VitePlugin)
run_vite(" ".join(plugin._config.install_command), app) # noqa: SLF001
execute_command(plugin.config.install_command)


@vite_group.command( # type: ignore # noqa: PGH003
Expand All @@ -167,14 +168,19 @@ def vite_build(app: Litestar, verbose: bool) -> None:
console,
)

from litestar_vite.commands import run_vite
from litestar_vite.plugin import VitePlugin
from litestar_vite.commands import execute_command
from litestar_vite.plugin import VitePlugin, set_environment

if verbose:
app.debug = True
console.rule("[yellow]Starting Vite build process[/]", align="left")
plugin = app.plugins.get(VitePlugin)
run_vite(" ".join(plugin._config.build_command), app) # noqa: SLF001
set_environment(config=plugin.config)
p = execute_command(plugin.config.build_command)
if p.returncode == 0:
console.print("[bold green] Assets built.[/]")
else:
console.print("[bold red] There was an error building the assets.[/]")


@vite_group.command( # type: ignore # noqa: PGH003
Expand All @@ -188,18 +194,17 @@ def vite_serve(app: Litestar, verbose: bool) -> None:
console,
)

from litestar_vite.commands import run_vite
from litestar_vite.plugin import VitePlugin
from litestar_vite.commands import execute_command
from litestar_vite.plugin import VitePlugin, set_environment

if verbose:
app.debug = True

plugin = app.plugins.get(VitePlugin)
if plugin._config.hot_reload: # noqa: SLF001
set_environment(config=plugin.config)
if plugin.config.hot_reload:
console.rule("[yellow]Starting Vite process with HMR Enabled[/]", align="left")
else:
console.rule("[yellow]Starting Vite watch and build process[/]", align="left")
command_to_run = (
plugin._config.run_command if plugin._config.hot_reload else plugin._config.build_watch_command # noqa: SLF001
)
run_vite(" ".join(command_to_run), app)
command_to_run = plugin.config.run_command if plugin.config.hot_reload else plugin.config.build_watch_command
execute_command(command_to_run)
53 changes: 17 additions & 36 deletions litestar_vite/commands.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,26 @@
from __future__ import annotations

import contextlib
import subprocess
from pathlib import Path
from typing import TYPE_CHECKING, Any, MutableMapping

from anyio import create_task_group
from jinja2 import select_autoescape
from litestar.serialization import encode_json

if TYPE_CHECKING:
from anyio.abc import Process
from jinja2 import Environment, Template
from litestar import Litestar

VITE_INIT_TEMPLATES_PATH = f"{Path(__file__).parent}/templates/init"
VITE_INIT_TEMPLATES_PATH = f"{Path(__file__).parent}/templates"
VITE_INIT_TEMPLATES: set[str] = {"package.json.j2", "tsconfig.json.j2", "vite.config.ts.j2"}

DEFAULT_RESOURCES: set[str] = {"styles.css", "main.ts"}
DEFAULT_DEV_DEPENDENCIES: dict[str, str] = {
"axios": "^1.6.2",
"typescript": "^5.3.3",
"vite": "^5.0.6",
"litestar-vite-plugin": "^0.3.0",
"@types/node": "^20.10.3",
}
DEFAULT_DEPENDENCIES: dict[str, str] = {}
DEFAULT_DEPENDENCIES: dict[str, str] = {"axios": "^1.6.2"}


def to_json(value: Any) -> str:
Expand Down Expand Up @@ -60,12 +57,17 @@ def init_vite(

logger = app.get_logger()
enabled_templates: set[str] = VITE_INIT_TEMPLATES
enabled_resources: set[str] = DEFAULT_RESOURCES
dependencies: dict[str, str] = DEFAULT_DEPENDENCIES
dev_dependencies: dict[str, str] = DEFAULT_DEV_DEPENDENCIES
templates: dict[str, Template] = {
template_name: get_template(environment=vite_template_env, name=template_name)
for template_name in enabled_templates
}
entry_point = [
str(Path(resource_path / resource_name).relative_to(Path.cwd().absolute()))
for resource_name in enabled_resources
]
for template_name, template in templates.items():
target_file_name = template_name.removesuffix(".j2")
with Path(target_file_name).open(mode="w") as file:
Expand All @@ -76,17 +78,21 @@ def init_vite(
entry_point=entry_point,
enable_ssr=enable_ssr,
asset_url=asset_url,
root_path=str(root_path),
root_path=str(root_path.relative_to(Path.cwd().absolute())),
resource_path=str(resource_path.relative_to(root_path)),
bundle_path=str(bundle_path.relative_to(root_path)),
hot_file=str(hot_file.relative_to(root_path)),
hot_file=str(hot_file.relative_to(Path.cwd().absolute())),
vite_port=str(vite_port),
litestar_port=litestar_port,
dependencies=to_json(dependencies),
dev_dependencies=to_json(dev_dependencies),
),
)

for resource_name in enabled_resources:
with Path(resource_path / resource_name).open(mode="w") as file:
logger.info("Writing %s", resource_name)


def get_template(
environment: Environment,
Expand All @@ -97,31 +103,6 @@ def get_template(
return environment.get_template(name=name, parent=parent, globals=globals)


def run_vite(command_to_run: str, app: Litestar) -> None:
"""Run Vite in a subprocess."""

import anyio

with contextlib.suppress(KeyboardInterrupt):
anyio.run(_run_vite, command_to_run, app)


async def _run_vite(command_to_run: str, app: Litestar) -> None:
def execute_command(command_to_run: list[str]) -> subprocess.CompletedProcess[bytes]:
"""Run Vite in a subprocess."""

from anyio import open_process
from anyio.streams.text import TextReceiveStream

logger = app.get_logger("vite")

async def read_stdout(vite_process: Process) -> None:
async for stdout in TextReceiveStream(vite_process.stdout): # type: ignore[arg-type]
logger.info(stdout)

async def read_stderr(vite_process: Process) -> None:
async for stdout in TextReceiveStream(vite_process.stderr): # type: ignore[arg-type]
logger.warning(stdout)

async with await open_process(command_to_run) as vite_process, create_task_group() as tg:
tg.start_soon(read_stdout, vite_process)
tg.start_soon(read_stderr, vite_process)
return subprocess.run(command_to_run, check=False) # noqa: S603
14 changes: 5 additions & 9 deletions litestar_vite/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import os
from dataclasses import dataclass, field
from functools import cached_property
from inspect import isclass
Expand Down Expand Up @@ -42,7 +41,7 @@ class ViteConfig:
In a standalone Vue or React application, this would be equivalent to the ``./src`` directory.
"""
template_dir: Path | str = field(default="templates")
template_dir: Path | str | None = field(default=None)
"""Location of the Jinja2 template file.
"""
manifest_name: str = ".vite/manifest.json"
Expand Down Expand Up @@ -94,17 +93,14 @@ def __post_init__(self) -> None:
"""Ensure that directory is set if engine is a class."""
if self.root_dir is not None and isinstance(self.root_dir, str):
self.root_dir = Path(self.root_dir)
if self.template_dir is not None and isinstance(self.template_dir, str):
self.template_dir = Path(self.template_dir)
if isinstance(self.resource_dir, str):
self.resource_dir = Path(self.resource_dir)
if isinstance(self.bundle_dir, str):
self.bundle_dir = Path(self.bundle_dir)
if isinstance(self.ssr_output_dir, str):
self.ssr_output_dir = Path(self.ssr_output_dir)
os.environ.setdefault("LITESTAR_ASSET_URL", self.asset_url)
os.environ.setdefault("LITESTAR_VITE_ALLOW_REMOTE", str(True))
os.environ.setdefault("VITE_PORT", str(self.port))
os.environ.setdefault("VITE_HOST", self.host)
os.environ.setdefault("VITE_PROTOCOL", self.protocol)
if self.dev_mode:
os.environ.setdefault("VITE_DEV_MODE", str(self.dev_mode))


@dataclass
Expand Down
Loading

0 comments on commit 4489d58

Please sign in to comment.