litestar-vite-plugin 0.13.2 → 0.15.0-alpha.1

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.
package/README.md CHANGED
@@ -1,137 +1,93 @@
1
1
  # Litestar Vite
2
2
 
3
- ## Installation
3
+ Litestar Vite connects the Litestar backend to a Vite toolchain. It supports SPA, Template, and Inertia flows, and can proxy Vite dev traffic through your ASGI port or run Vite directly.
4
4
 
5
- ```shell
6
- pip install litestar-vite
7
- ```
8
-
9
- ## Usage
10
-
11
- Here is a basic application that demonstrates how to use the plugin.
12
-
13
- ```python
14
- from __future__ import annotations
15
-
16
- from pathlib import Path
17
-
18
- from litestar import Controller, get, Litestar
19
- from litestar.response import Template
20
- from litestar.status_codes import HTTP_200_OK
21
- from litestar.template.config import TemplateConfig
22
- from litestar.contrib.jinja import JinjaTemplateEngine
23
- from litestar_vite import ViteConfig, VitePlugin
5
+ ## Features
24
6
 
25
- class WebController(Controller):
7
+ - One-port dev: proxies Vite HTTP + WS/HMR through Litestar by default; switch to two-port with `VITE_PROXY_MODE=direct`.
8
+ - Production assets: reads Vite manifest from `public/manifest.json` (configurable) and serves under `asset_url`.
9
+ - Type-safe frontends: optional OpenAPI/routes export + `@hey-api/openapi-ts` via the Vite plugin.
10
+ - Inertia support: v2 protocol with session middleware and optional SPA mode.
26
11
 
27
- opt = {"exclude_from_auth": True}
28
- include_in_schema = False
12
+ ## Quick start (SPA)
29
13
 
30
- @get(["/", "/{path:str}"],status_code=HTTP_200_OK)
31
- async def index(self) -> Template:
32
- return Template(template_name="index.html.j2")
14
+ ```bash
15
+ pip install litestar-vite
16
+ litestar assets install # installs frontend deps via configured executor
17
+ ```
33
18
 
34
- template_config = TemplateConfig(engine=JinjaTemplateEngine(directory='templates/'))
35
- vite = VitePlugin(config=ViteConfig())
36
- app = Litestar(plugins=[vite], template_config=template_config, route_handlers=[WebController])
19
+ ```python
20
+ from litestar import Litestar
21
+ from litestar_vite import VitePlugin, ViteConfig
37
22
 
23
+ app = Litestar(plugins=[VitePlugin(config=ViteConfig(dev_mode=True))])
38
24
  ```
39
25
 
40
- Create a template to serve the application in `./templates/index.html.h2`:
41
-
42
- ```html
43
- <!DOCTYPE html>
44
- <html>
45
- <head>
46
- <meta charset="utf-8" />
47
- <!--IE compatibility-->
48
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
49
- <meta
50
- name="viewport"
51
- content="width=device-width, initial-scale=1.0, maximum-scale=1.0"
52
- />
53
- </head>
54
-
55
- <body>
56
- <div id="app"></div>
57
- {{ vite_hmr() }} {{ vite('resources/main.ts') }}
58
- </body>
59
- </html>
26
+ ```bash
27
+ litestar run # starts Litestar; Vite dev is proxied automatically
60
28
  ```
61
29
 
62
- ### Template initialization (Optional)
63
-
64
- This is a command to help initialize Vite for your project. This is generally only needed a single time. You may also manually configure Vite and skip this step.
30
+ ## Template / HTMX
65
31
 
66
- to initialize a Vite configuration:
32
+ ```python
33
+ from litestar import Litestar
34
+ from litestar.contrib.jinja import JinjaTemplateEngine
35
+ from litestar.template.config import TemplateConfig
36
+ from litestar_vite import VitePlugin, ViteConfig
67
37
 
68
- ```shell
69
- ❯ litestar assets init
70
- Using Litestar app from app:app
71
- Initializing Vite ──────────────────────────────────────────────────────────────────────────────────────────
72
- Do you intend to use Litestar with any SSR framework? [y/n]: n
73
- INFO - 2023-12-11 12:33:41,455 - root - commands - Writing vite.config.ts
74
- INFO - 2023-12-11 12:33:41,456 - root - commands - Writing package.json
75
- INFO - 2023-12-11 12:33:41,456 - root - commands - Writing tsconfig.json
38
+ app = Litestar(
39
+ template_config=TemplateConfig(engine=JinjaTemplateEngine(directory="templates")),
40
+ plugins=[VitePlugin(config=ViteConfig(mode="template", dev_mode=True))],
41
+ )
76
42
  ```
77
43
 
78
- ### Install Javascript/Typescript Packages
79
-
80
- Install the packages required for development:
44
+ ## Inertia (v2)
81
45
 
82
- **Note** This is equivalent to the the `npm install` by default. This command is configurable.
46
+ Requires session middleware.
83
47
 
84
- ```shell
85
- litestar assets install
86
- Using Litestar app from app:app
87
- Starting Vite package installation process ──────────────────────────────────────────────────────────────────────────────────────────
88
-
89
- added 25 packages, and audited 26 packages in 1s
90
-
91
-
92
- 5 packages are looking for funding
93
- run `npm fund` for details
94
-
95
-
96
- found 0 vulnerabilities
48
+ ```python
49
+ from litestar import Litestar
50
+ from litestar.middleware.session.server_side import ServerSideSessionConfig, ServerSideSessionMiddleware
51
+ from litestar_vite import VitePlugin, ViteConfig
52
+ from litestar_vite.inertia import InertiaPlugin
53
+ from litestar_vite.inertia.config import InertiaConfig
54
+
55
+ app = Litestar(
56
+ middleware=[ServerSideSessionMiddleware(config=ServerSideSessionConfig(secret="secret"))],
57
+ plugins=[
58
+ VitePlugin(config=ViteConfig(mode="template", inertia=True, dev_mode=True)),
59
+ InertiaPlugin(InertiaConfig()),
60
+ ],
61
+ )
97
62
  ```
98
63
 
99
- ### Development
100
-
101
- To automatically start and stop the Vite instance with the Litestar application, you can enable the `use_server_lifespan` hooks in the `ViteConfig`.
102
-
103
- Alternately, to start the development server manually, you can run the following
104
-
105
- ```shell
106
- ❯ litestar assets serve
107
- Using Litestar app from app:app
108
- Starting Vite build process ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
109
-
110
- > build
111
- > vite build
112
-
113
-
114
- vite v5.0.7 building for production...
115
-
116
- ✓ 0 modules transformed.
64
+ ## Type generation
117
65
 
66
+ ```python
67
+ VitePlugin(config=ViteConfig(types=True)) # enable exports
118
68
  ```
119
69
 
120
- **Note** This is equivalent to the the `npm run dev` command when `hot_reload` is enabled. Otherwise it is equivalent to `npm run build -- --watch`. This command is configurable.
121
-
122
- ### Building for Production
70
+ ```bash
71
+ litestar assets generate-types # one-off or CI
72
+ ```
123
73
 
124
- ```shell
125
- ❯ litestar assets build
126
- Using Litestar app from app:app
127
- Starting Vite build process ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
74
+ ## CLI cheat sheet
128
75
 
129
- > build
130
- > vite build
76
+ - `litestar assets doctor` — diagnose/fix config
77
+ - `litestar assets init --template react|vue|svelte|...` — scaffold frontend
78
+ - `litestar assets build` / `serve` — build or watch
79
+ - `litestar assets deploy --storage gcs://bucket/assets` — upload via fsspec
80
+ - `litestar assets generate-types` — OpenAPI + routes → TS types
81
+ - `litestar assets install` — install frontend deps with the configured executor
131
82
 
83
+ ### Doctor command highlights
132
84
 
133
- vite v5.0.7 building for production...
85
+ - Prints Python vs Vite config snapshot (asset URLs, bundle/hot paths, ports, modes).
86
+ - Flags missing hot file (dev proxy), missing manifest (prod), type-gen exports, env/config mismatches, and plugin install issues.
87
+ - `--fix` can rewrite simple vite.config values (assetUrl, bundleDirectory, hotFile, type paths) after creating a backup.
134
88
 
135
- 0 modules transformed.
89
+ ## Links
136
90
 
137
- ```
91
+ - Docs: <https://litestar-org.github.io/litestar-vite/>
92
+ - Examples: `examples/` (basic, inertia, spa-react)
93
+ - Issues: <https://github.com/litestar-org/litestar-vite/issues/>
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Astro integration for Litestar-Vite.
3
+ *
4
+ * This integration enables seamless development with Astro as the frontend framework
5
+ * and Litestar as the API backend. It provides:
6
+ * - API proxy configuration for dev server
7
+ * - Type generation integration (shares @hey-api/openapi-ts output)
8
+ * - Route helper generation compatible with Astro's static paths
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * // astro.config.mjs
13
+ * import { defineConfig } from 'astro/config';
14
+ * import litestar from 'litestar-vite-plugin/astro';
15
+ *
16
+ * export default defineConfig({
17
+ * integrations: [
18
+ * litestar({
19
+ * apiProxy: 'http://localhost:8000',
20
+ * typesPath: './src/generated/api',
21
+ * }),
22
+ * ],
23
+ * });
24
+ * ```
25
+ *
26
+ * @module
27
+ */
28
+ import type { Plugin, ViteDevServer } from "vite";
29
+ /**
30
+ * Astro integration interface.
31
+ * This is a minimal type definition to avoid requiring astro as a dependency.
32
+ * When using this integration, Astro will be available in the project.
33
+ */
34
+ interface AstroIntegration {
35
+ name: string;
36
+ hooks: {
37
+ "astro:config:setup"?: (options: {
38
+ config: unknown;
39
+ command: "dev" | "build" | "preview" | "sync";
40
+ isRestart: boolean;
41
+ updateConfig: (newConfig: {
42
+ vite?: {
43
+ plugins?: Plugin[];
44
+ };
45
+ }) => unknown;
46
+ logger: AstroIntegrationLogger;
47
+ }) => void | Promise<void>;
48
+ "astro:server:setup"?: (options: {
49
+ server: ViteDevServer;
50
+ logger: AstroIntegrationLogger;
51
+ }) => void | Promise<void>;
52
+ "astro:build:start"?: (options: {
53
+ logger: AstroIntegrationLogger;
54
+ }) => void | Promise<void>;
55
+ };
56
+ }
57
+ /**
58
+ * Astro integration logger interface.
59
+ */
60
+ interface AstroIntegrationLogger {
61
+ info: (message: string) => void;
62
+ warn: (message: string) => void;
63
+ error: (message: string) => void;
64
+ }
65
+ /**
66
+ * Configuration options for the Litestar Astro integration.
67
+ */
68
+ export interface LitestarAstroConfig {
69
+ /**
70
+ * URL of the Litestar API backend for proxying requests during development.
71
+ *
72
+ * @example 'http://localhost:8000'
73
+ * @default 'http://localhost:8000'
74
+ */
75
+ apiProxy?: string;
76
+ /**
77
+ * API route prefix to proxy to the Litestar backend.
78
+ * Requests matching this prefix will be forwarded to the apiProxy URL.
79
+ *
80
+ * @example '/api'
81
+ * @default '/api'
82
+ */
83
+ apiPrefix?: string;
84
+ /**
85
+ * Path where TypeScript types are generated.
86
+ * This should match the output path configured in your Litestar ViteConfig.
87
+ *
88
+ * @example './src/generated/api'
89
+ * @default './src/types/api'
90
+ */
91
+ typesPath?: string;
92
+ /**
93
+ * Path to the OpenAPI schema file exported by Litestar.
94
+ *
95
+ * @default 'openapi.json'
96
+ */
97
+ openapiPath?: string;
98
+ /**
99
+ * Path to the routes metadata file exported by Litestar.
100
+ *
101
+ * @default 'routes.json'
102
+ */
103
+ routesPath?: string;
104
+ /**
105
+ * Enable verbose logging for debugging.
106
+ *
107
+ * @default false
108
+ */
109
+ verbose?: boolean;
110
+ }
111
+ /**
112
+ * Litestar integration for Astro.
113
+ *
114
+ * This integration configures Astro to work seamlessly with a Litestar backend,
115
+ * providing API proxying during development and type generation support.
116
+ *
117
+ * @param userConfig - Configuration options for the integration
118
+ * @returns An Astro integration object
119
+ *
120
+ * @example
121
+ * ```typescript
122
+ * // astro.config.mjs
123
+ * import { defineConfig } from 'astro/config';
124
+ * import litestar from 'litestar-vite-plugin/astro';
125
+ *
126
+ * export default defineConfig({
127
+ * integrations: [
128
+ * litestar({
129
+ * apiProxy: 'http://localhost:8000',
130
+ * apiPrefix: '/api',
131
+ * typesPath: './src/generated/api',
132
+ * }),
133
+ * ],
134
+ * });
135
+ * ```
136
+ *
137
+ * @example Using with generated types
138
+ * ```typescript
139
+ * // src/pages/users/[id].astro
140
+ * ---
141
+ * import type { User } from '../generated/api/types.gen';
142
+ * import { route } from '../generated/api/routes';
143
+ *
144
+ * const { id } = Astro.params;
145
+ * const response = await fetch(route('users.show', { id }));
146
+ * const user: User = await response.json();
147
+ * ---
148
+ *
149
+ * <html>
150
+ * <body>
151
+ * <h1>{user.name}</h1>
152
+ * </body>
153
+ * </html>
154
+ * ```
155
+ */
156
+ export default function litestarAstro(userConfig?: LitestarAstroConfig): AstroIntegration;
157
+ export {};
@@ -0,0 +1,70 @@
1
+ function resolveConfig(config = {}) {
2
+ return {
3
+ apiProxy: config.apiProxy ?? "http://localhost:8000",
4
+ apiPrefix: config.apiPrefix ?? "/api",
5
+ typesPath: config.typesPath ?? "./src/types/api",
6
+ openapiPath: config.openapiPath ?? "openapi.json",
7
+ routesPath: config.routesPath ?? "routes.json",
8
+ verbose: config.verbose ?? false
9
+ };
10
+ }
11
+ function createProxyPlugin(config) {
12
+ return {
13
+ name: "litestar-astro-proxy",
14
+ config() {
15
+ return {
16
+ server: {
17
+ proxy: {
18
+ [config.apiPrefix]: {
19
+ target: config.apiProxy,
20
+ changeOrigin: true,
21
+ secure: false
22
+ }
23
+ }
24
+ }
25
+ };
26
+ }
27
+ };
28
+ }
29
+ function litestarAstro(userConfig = {}) {
30
+ const config = resolveConfig(userConfig);
31
+ return {
32
+ name: "litestar-vite",
33
+ hooks: {
34
+ "astro:config:setup": ({ updateConfig, logger }) => {
35
+ if (config.verbose) {
36
+ logger.info("Configuring Litestar integration");
37
+ logger.info(` API Proxy: ${config.apiProxy}`);
38
+ logger.info(` API Prefix: ${config.apiPrefix}`);
39
+ logger.info(` Types Path: ${config.typesPath}`);
40
+ }
41
+ updateConfig({
42
+ vite: {
43
+ plugins: [createProxyPlugin(config)]
44
+ }
45
+ });
46
+ logger.info(`Litestar integration configured - proxying ${config.apiPrefix}/* to ${config.apiProxy}`);
47
+ },
48
+ "astro:server:setup": ({ server, logger }) => {
49
+ if (config.verbose) {
50
+ logger.info("Litestar dev server integration active");
51
+ }
52
+ if (config.verbose) {
53
+ server.middlewares.use((req, _res, next) => {
54
+ if (req.url?.startsWith(config.apiPrefix)) {
55
+ logger.info(`Proxying: ${req.method} ${req.url} -> ${config.apiProxy}${req.url}`);
56
+ }
57
+ next();
58
+ });
59
+ }
60
+ },
61
+ "astro:build:start": ({ logger }) => {
62
+ logger.info("Building with Litestar integration");
63
+ logger.info(` Make sure your Litestar backend is accessible at: ${config.apiProxy}`);
64
+ }
65
+ }
66
+ };
67
+ }
68
+ export {
69
+ litestarAstro as default
70
+ };