fasthtml-tailwindcss 4.3.3__tar.gz
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.
- fasthtml_tailwindcss-4.3.3/.gitignore +29 -0
- fasthtml_tailwindcss-4.3.3/LICENSE +21 -0
- fasthtml_tailwindcss-4.3.3/PKG-INFO +133 -0
- fasthtml_tailwindcss-4.3.3/README.md +105 -0
- fasthtml_tailwindcss-4.3.3/TAILWIND-LICENSE +21 -0
- fasthtml_tailwindcss-4.3.3/binaries.json +12 -0
- fasthtml_tailwindcss-4.3.3/hatch_build.py +73 -0
- fasthtml_tailwindcss-4.3.3/pyproject.toml +45 -0
- fasthtml_tailwindcss-4.3.3/src/fasthtml_tailwindcss/__init__.py +33 -0
- fasthtml_tailwindcss-4.3.3/src/fasthtml_tailwindcss/_client.py +156 -0
- fasthtml_tailwindcss-4.3.3/src/fasthtml_tailwindcss/_worker.py +133 -0
- fasthtml_tailwindcss-4.3.3/src/fasthtml_tailwindcss/py.typed +0 -0
- fasthtml_tailwindcss-4.3.3/tests/conftest.py +51 -0
- fasthtml_tailwindcss-4.3.3/tests/test_component.py +83 -0
- fasthtml_tailwindcss-4.3.3/tests/test_sessions.py +95 -0
- fasthtml_tailwindcss-4.3.3/tests/test_uvicorn.py +102 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
.venv/
|
|
4
|
+
venv/
|
|
5
|
+
build/
|
|
6
|
+
dist/
|
|
7
|
+
*.egg-info/
|
|
8
|
+
.pytest_cache/
|
|
9
|
+
.ruff_cache/
|
|
10
|
+
.mypy_cache/
|
|
11
|
+
.cache/
|
|
12
|
+
.coverage*
|
|
13
|
+
coverage.xml
|
|
14
|
+
htmlcov/
|
|
15
|
+
.env
|
|
16
|
+
.envrc
|
|
17
|
+
.pypirc
|
|
18
|
+
.env.*
|
|
19
|
+
!.env.example
|
|
20
|
+
*.log
|
|
21
|
+
*.swp
|
|
22
|
+
*.swo
|
|
23
|
+
.idea/
|
|
24
|
+
.vscode/
|
|
25
|
+
.DS_Store
|
|
26
|
+
Thumbs.db
|
|
27
|
+
/src/fasthtml_tailwindcss/bin/
|
|
28
|
+
/source-dist/
|
|
29
|
+
/unpacked/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SpaceShaman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fasthtml-tailwindcss
|
|
3
|
+
Version: 4.3.3
|
|
4
|
+
Summary: Tailwind CSS for FastHTML with a persistent compiler across server reloads and watch mode for automatic CSS rebuilds.
|
|
5
|
+
Project-URL: Documentation, https://github.com/SpaceShaman/fasthtml-tailwindcss#readme
|
|
6
|
+
Project-URL: Homepage, https://github.com/SpaceShaman/fasthtml-tailwindcss
|
|
7
|
+
Project-URL: Issues, https://github.com/SpaceShaman/fasthtml-tailwindcss/issues
|
|
8
|
+
Project-URL: Repository, https://github.com/SpaceShaman/fasthtml-tailwindcss
|
|
9
|
+
Author-email: SpaceShaman <spaceshaman@tuta.io>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
License-File: TAILWIND-LICENSE
|
|
13
|
+
Keywords: components,css,fasthtml,tailwindcss,web
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Requires-Dist: filelock>=3.16
|
|
25
|
+
Requires-Dist: platformdirs>=4
|
|
26
|
+
Requires-Dist: python-fasthtml>=0.14.13
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# fasthtml-tailwindcss
|
|
30
|
+
|
|
31
|
+
[](LICENSE)
|
|
32
|
+
[](https://github.com/SpaceShaman/fasthtml-tailwindcss/actions/workflows/release.yml)
|
|
33
|
+
[](https://pypi.org/project/fasthtml-tailwindcss/)
|
|
34
|
+
[](https://pypi.org/project/fasthtml-tailwindcss/)
|
|
35
|
+
[](https://github.com/AnswerDotAI/fasthtml)
|
|
36
|
+
[](https://tailwindcss.com/)
|
|
37
|
+
[](https://github.com/astral-sh/uv)
|
|
38
|
+
[](https://docs.pytest.org/)
|
|
39
|
+
[](https://github.com/astral-sh/ruff)
|
|
40
|
+
|
|
41
|
+
Tailwind CSS for [FastHTML](https://github.com/AnswerDotAI/fasthtml) with a persistent compiler across server reloads and watch mode for automatic CSS rebuilds.
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
Install with uv:
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
uv add fasthtml-tailwindcss
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Or with pip:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
pip install fasthtml-tailwindcss
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
On Alpine Linux, the standalone compiler also requires the system C++ runtime:
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
apk add --no-cache libstdc++ libgcc
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Usage
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from fasthtml.common import Div, FastHTML
|
|
67
|
+
from fasthtml_tailwindcss import TailwindHead
|
|
68
|
+
|
|
69
|
+
app = FastHTML(hdrs=[TailwindHead(watch=True)])
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@app.route("/")
|
|
73
|
+
def get():
|
|
74
|
+
return Div("Hello", cls="rounded-lg bg-blue-500 p-4 text-white")
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Run your application normally, for example with `uv run uvicorn main:app --reload`. The package bundles the official standalone Tailwind compiler: no Node.js, npm, CDN, CSS endpoint or additional command is needed.
|
|
78
|
+
|
|
79
|
+
`TailwindHead` builds CSS when the component is constructed, usually while importing your application module, and waits for the first successful compilation. It embeds the result in a `<style>` element. Each full page receives the latest completed CSS. Refresh the browser to see updates; automatic browser refresh and updating styles during HTMX fragment swaps are not included.
|
|
80
|
+
|
|
81
|
+
- `watch=True`: compile once, then watch source files. The compiler survives application reloads.
|
|
82
|
+
- `watch=False` (default): compile once with minification, then reuse the result across reloads. Source changes do not rebuild CSS during that session.
|
|
83
|
+
|
|
84
|
+
A local helper keeps the session alive while applications renew a shared heartbeat file, and shuts down 15 seconds after the last heartbeat. A quick manual restart is treated like a reload. A later start creates a fresh session and builds again. The session stays active while the component exists in a running Python process; it does not depend on ASGI lifespan.
|
|
85
|
+
|
|
86
|
+
## Options
|
|
87
|
+
|
|
88
|
+
All configuration is passed to `TailwindHead`:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
TailwindHead(
|
|
92
|
+
watch=True,
|
|
93
|
+
sources=["app"],
|
|
94
|
+
css="@theme { --color-brand: #7854f7; }",
|
|
95
|
+
)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
For a custom input stylesheet:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
TailwindHead(watch=True, input="assets/app.css")
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
- `sources`: source files or directories. Defaults to the project directory with the built-in input; with a custom input, its own source detection is used unless extra sources are supplied.
|
|
105
|
+
- `input`: optional stylesheet replacing the built-in `@import "tailwindcss"`. Relative CSS imports resolve from that file.
|
|
106
|
+
- `css`: optional inline CSS appended after the input. Useful for `@theme`, variants and explicit `@source inline(...)` declarations.
|
|
107
|
+
|
|
108
|
+
Paths are resolved relative to the nearest `pyproject.toml` above the working directory, or the working directory if none exists. Sessions are shared by project, configuration and OS user. Reloads and application workers with identical options reuse the same session. Changing options, including `watch`, starts a separate session immediately; the unused session shuts down after 15 seconds.
|
|
109
|
+
|
|
110
|
+
Tailwind scans complete class names in source files. Use `"bg-red-500"` rather than constructing names such as `f"bg-{color}-500"`. Classes inside installed component libraries need explicit sources or safelisting.
|
|
111
|
+
|
|
112
|
+
Generated files and compiler diagnostics (`compiler.log`) live in the OS user cache under `fasthtml-tailwindcss`. Nothing is written into your application or installed package. Inline CSS requires an appropriate Content Security Policy if your application sets one.
|
|
113
|
+
|
|
114
|
+
## Development
|
|
115
|
+
|
|
116
|
+
```sh
|
|
117
|
+
uv sync --group test
|
|
118
|
+
uv run --group test pytest
|
|
119
|
+
uv build
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Wheel builds download and verify the matching official standalone executable. Wheels target Linux x64/ARM64 (glibc 2.28+ or musl 1.2+), macOS 13+ (Intel/Apple Silicon), and Windows x64. Source distributions contain the build hook and checksum manifest; building one requires network access unless the verified compiler is already present locally.
|
|
123
|
+
|
|
124
|
+
The package version follows Tailwind, with `.postN` for Python-only fixes. The release workflow checks upstream daily, tests the platform wheels and publishes through PyPI Trusted Publishing. Configure the publisher for `SpaceShaman/fasthtml-tailwindcss`, workflow `release.yml`, environment `pypi`; allow workflow version commits on the default branch.
|
|
125
|
+
|
|
126
|
+
## Links
|
|
127
|
+
|
|
128
|
+
- [GitHub repository](https://github.com/SpaceShaman/fasthtml-tailwindcss)
|
|
129
|
+
- [PyPI package](https://pypi.org/project/fasthtml-tailwindcss/)
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
The wrapper and Tailwind CSS are MIT licensed. Both license notices are included in distributions.
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# fasthtml-tailwindcss
|
|
2
|
+
|
|
3
|
+
[](LICENSE)
|
|
4
|
+
[](https://github.com/SpaceShaman/fasthtml-tailwindcss/actions/workflows/release.yml)
|
|
5
|
+
[](https://pypi.org/project/fasthtml-tailwindcss/)
|
|
6
|
+
[](https://pypi.org/project/fasthtml-tailwindcss/)
|
|
7
|
+
[](https://github.com/AnswerDotAI/fasthtml)
|
|
8
|
+
[](https://tailwindcss.com/)
|
|
9
|
+
[](https://github.com/astral-sh/uv)
|
|
10
|
+
[](https://docs.pytest.org/)
|
|
11
|
+
[](https://github.com/astral-sh/ruff)
|
|
12
|
+
|
|
13
|
+
Tailwind CSS for [FastHTML](https://github.com/AnswerDotAI/fasthtml) with a persistent compiler across server reloads and watch mode for automatic CSS rebuilds.
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
Install with uv:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
uv add fasthtml-tailwindcss
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Or with pip:
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pip install fasthtml-tailwindcss
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
On Alpine Linux, the standalone compiler also requires the system C++ runtime:
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
apk add --no-cache libstdc++ libgcc
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from fasthtml.common import Div, FastHTML
|
|
39
|
+
from fasthtml_tailwindcss import TailwindHead
|
|
40
|
+
|
|
41
|
+
app = FastHTML(hdrs=[TailwindHead(watch=True)])
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@app.route("/")
|
|
45
|
+
def get():
|
|
46
|
+
return Div("Hello", cls="rounded-lg bg-blue-500 p-4 text-white")
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Run your application normally, for example with `uv run uvicorn main:app --reload`. The package bundles the official standalone Tailwind compiler: no Node.js, npm, CDN, CSS endpoint or additional command is needed.
|
|
50
|
+
|
|
51
|
+
`TailwindHead` builds CSS when the component is constructed, usually while importing your application module, and waits for the first successful compilation. It embeds the result in a `<style>` element. Each full page receives the latest completed CSS. Refresh the browser to see updates; automatic browser refresh and updating styles during HTMX fragment swaps are not included.
|
|
52
|
+
|
|
53
|
+
- `watch=True`: compile once, then watch source files. The compiler survives application reloads.
|
|
54
|
+
- `watch=False` (default): compile once with minification, then reuse the result across reloads. Source changes do not rebuild CSS during that session.
|
|
55
|
+
|
|
56
|
+
A local helper keeps the session alive while applications renew a shared heartbeat file, and shuts down 15 seconds after the last heartbeat. A quick manual restart is treated like a reload. A later start creates a fresh session and builds again. The session stays active while the component exists in a running Python process; it does not depend on ASGI lifespan.
|
|
57
|
+
|
|
58
|
+
## Options
|
|
59
|
+
|
|
60
|
+
All configuration is passed to `TailwindHead`:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
TailwindHead(
|
|
64
|
+
watch=True,
|
|
65
|
+
sources=["app"],
|
|
66
|
+
css="@theme { --color-brand: #7854f7; }",
|
|
67
|
+
)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
For a custom input stylesheet:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
TailwindHead(watch=True, input="assets/app.css")
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
- `sources`: source files or directories. Defaults to the project directory with the built-in input; with a custom input, its own source detection is used unless extra sources are supplied.
|
|
77
|
+
- `input`: optional stylesheet replacing the built-in `@import "tailwindcss"`. Relative CSS imports resolve from that file.
|
|
78
|
+
- `css`: optional inline CSS appended after the input. Useful for `@theme`, variants and explicit `@source inline(...)` declarations.
|
|
79
|
+
|
|
80
|
+
Paths are resolved relative to the nearest `pyproject.toml` above the working directory, or the working directory if none exists. Sessions are shared by project, configuration and OS user. Reloads and application workers with identical options reuse the same session. Changing options, including `watch`, starts a separate session immediately; the unused session shuts down after 15 seconds.
|
|
81
|
+
|
|
82
|
+
Tailwind scans complete class names in source files. Use `"bg-red-500"` rather than constructing names such as `f"bg-{color}-500"`. Classes inside installed component libraries need explicit sources or safelisting.
|
|
83
|
+
|
|
84
|
+
Generated files and compiler diagnostics (`compiler.log`) live in the OS user cache under `fasthtml-tailwindcss`. Nothing is written into your application or installed package. Inline CSS requires an appropriate Content Security Policy if your application sets one.
|
|
85
|
+
|
|
86
|
+
## Development
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
uv sync --group test
|
|
90
|
+
uv run --group test pytest
|
|
91
|
+
uv build
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Wheel builds download and verify the matching official standalone executable. Wheels target Linux x64/ARM64 (glibc 2.28+ or musl 1.2+), macOS 13+ (Intel/Apple Silicon), and Windows x64. Source distributions contain the build hook and checksum manifest; building one requires network access unless the verified compiler is already present locally.
|
|
95
|
+
|
|
96
|
+
The package version follows Tailwind, with `.postN` for Python-only fixes. The release workflow checks upstream daily, tests the platform wheels and publishes through PyPI Trusted Publishing. Configure the publisher for `SpaceShaman/fasthtml-tailwindcss`, workflow `release.yml`, environment `pypi`; allow workflow version commits on the default branch.
|
|
97
|
+
|
|
98
|
+
## Links
|
|
99
|
+
|
|
100
|
+
- [GitHub repository](https://github.com/SpaceShaman/fasthtml-tailwindcss)
|
|
101
|
+
- [PyPI package](https://pypi.org/project/fasthtml-tailwindcss/)
|
|
102
|
+
|
|
103
|
+
## License
|
|
104
|
+
|
|
105
|
+
The wrapper and Tailwind CSS are MIT licensed. Both license notices are included in distributions.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Tailwind Labs, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": "4.3.3",
|
|
3
|
+
"sha256": {
|
|
4
|
+
"tailwindcss-linux-arm64": "55fd0b241214eff3de1e8ee4f22796662f2d2e7a49bcfca7477cfd0bac398195",
|
|
5
|
+
"tailwindcss-linux-arm64-musl": "71ea4be79c9de9827545682df3e040053fb535d37c71ed2cfdedf9385a0868e0",
|
|
6
|
+
"tailwindcss-linux-x64": "dc61b3ac6b8c9ca874c0cc4c57b2409791a64c5540404ca5f5367360babc313a",
|
|
7
|
+
"tailwindcss-linux-x64-musl": "a04d34ceacc8f52cbe8920ad846cdeb61d3d0021dba32db0d1f77c9d9fad7a6c",
|
|
8
|
+
"tailwindcss-macos-arm64": "cdf646702987a743464dff4d9c60fd4480d1c1e73dd819a9a67f1078815dce9d",
|
|
9
|
+
"tailwindcss-macos-x64": "7922e0953f2110c05976e3bf58f14e643d90427575e766b7d433f5f80cbee7e1",
|
|
10
|
+
"tailwindcss-windows-x64.exe": "e0e260ce048014e9268f6237ff18f8ccf02cef521cbd0ae04e82c2cdf7aa3955"
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import platform
|
|
5
|
+
import shutil
|
|
6
|
+
import tempfile
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from urllib.request import urlopen
|
|
9
|
+
|
|
10
|
+
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
|
|
11
|
+
|
|
12
|
+
TARGETS = {
|
|
13
|
+
"linux-x64": "manylinux_2_28_x86_64",
|
|
14
|
+
"linux-arm64": "manylinux_2_28_aarch64",
|
|
15
|
+
"linux-x64-musl": "musllinux_1_2_x86_64",
|
|
16
|
+
"linux-arm64-musl": "musllinux_1_2_aarch64",
|
|
17
|
+
"macos-x64": "macosx_13_0_x86_64",
|
|
18
|
+
"macos-arm64": "macosx_13_0_arm64",
|
|
19
|
+
"windows-x64": "win_amd64",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def native_target():
|
|
24
|
+
system = {"Linux": "linux", "Darwin": "macos", "Windows": "windows"}.get(
|
|
25
|
+
platform.system()
|
|
26
|
+
)
|
|
27
|
+
arch = {"x86_64": "x64", "AMD64": "x64", "arm64": "arm64", "aarch64": "arm64"}.get(
|
|
28
|
+
platform.machine()
|
|
29
|
+
)
|
|
30
|
+
target = f"{system}-{arch}"
|
|
31
|
+
if system == "linux" and (
|
|
32
|
+
platform.libc_ver()[0] == "musl" or any(Path("/lib").glob("ld-musl-*.so.1"))
|
|
33
|
+
):
|
|
34
|
+
target += "-musl"
|
|
35
|
+
return target
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def download_binary(url, binary, expected):
|
|
39
|
+
if binary.exists() and hashlib.sha256(binary.read_bytes()).hexdigest() == expected:
|
|
40
|
+
return
|
|
41
|
+
with tempfile.TemporaryDirectory() as temporary:
|
|
42
|
+
download = Path(temporary) / binary.name
|
|
43
|
+
with urlopen(url, timeout=120) as response, download.open("wb") as destination:
|
|
44
|
+
shutil.copyfileobj(response, destination)
|
|
45
|
+
if hashlib.sha256(download.read_bytes()).hexdigest() != expected:
|
|
46
|
+
raise RuntimeError(f"Checksum mismatch for {url}")
|
|
47
|
+
shutil.copyfile(download, binary)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class CustomBuildHook(BuildHookInterface):
|
|
51
|
+
def initialize(self, version, build_data):
|
|
52
|
+
if self.target_name != "wheel":
|
|
53
|
+
return
|
|
54
|
+
root = Path(self.root)
|
|
55
|
+
manifest = json.loads((root / "binaries.json").read_text())
|
|
56
|
+
if self.metadata.version.split(".post")[0] != manifest["version"]:
|
|
57
|
+
raise ValueError("Package version must match binaries.json")
|
|
58
|
+
target = os.environ.get("TAILWIND_BUILD_TARGET", native_target())
|
|
59
|
+
if target not in TARGETS:
|
|
60
|
+
raise RuntimeError(f"No official standalone Tailwind binary for {target}")
|
|
61
|
+
suffix = ".exe" if target.startswith("windows-") else ""
|
|
62
|
+
asset = f"tailwindcss-{target}{suffix}"
|
|
63
|
+
expected = manifest["sha256"][asset]
|
|
64
|
+
binary = root / "src" / "fasthtml_tailwindcss" / "bin" / f"tailwindcss{suffix}"
|
|
65
|
+
binary.parent.mkdir(parents=True, exist_ok=True)
|
|
66
|
+
url = f"https://github.com/tailwindlabs/tailwindcss/releases/download/v{manifest['version']}/{asset}"
|
|
67
|
+
download_binary(url, binary, expected)
|
|
68
|
+
binary.chmod(0o755)
|
|
69
|
+
build_data["pure_python"] = False
|
|
70
|
+
build_data["tag"] = f"py3-none-{TARGETS[target]}"
|
|
71
|
+
build_data["artifacts"].append(
|
|
72
|
+
f"src/fasthtml_tailwindcss/bin/tailwindcss{suffix}"
|
|
73
|
+
)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fasthtml-tailwindcss"
|
|
3
|
+
version = "4.3.3"
|
|
4
|
+
description = "Tailwind CSS for FastHTML with a persistent compiler across server reloads and watch mode for automatic CSS rebuilds."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE", "TAILWIND-LICENSE"]
|
|
9
|
+
authors = [{ name = "SpaceShaman", email = "spaceshaman@tuta.io" }]
|
|
10
|
+
keywords = ["components", "css", "fasthtml", "tailwindcss", "web"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
14
|
+
"Programming Language :: Python :: 3.11",
|
|
15
|
+
"Programming Language :: Python :: 3.12",
|
|
16
|
+
"Programming Language :: Python :: 3.13",
|
|
17
|
+
"Programming Language :: Python :: 3.14",
|
|
18
|
+
"Programming Language :: Python :: 3.15",
|
|
19
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
dependencies = ["filelock>=3.16", "platformdirs>=4", "python-fasthtml>=0.14.13"]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Documentation = "https://github.com/SpaceShaman/fasthtml-tailwindcss#readme"
|
|
26
|
+
Homepage = "https://github.com/SpaceShaman/fasthtml-tailwindcss"
|
|
27
|
+
Issues = "https://github.com/SpaceShaman/fasthtml-tailwindcss/issues"
|
|
28
|
+
Repository = "https://github.com/SpaceShaman/fasthtml-tailwindcss"
|
|
29
|
+
|
|
30
|
+
[dependency-groups]
|
|
31
|
+
test = ["httpx", "pytest", "uvicorn"]
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["hatchling>=1.27"]
|
|
35
|
+
build-backend = "hatchling.build"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.wheel]
|
|
38
|
+
packages = ["src/fasthtml_tailwindcss"]
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.sdist]
|
|
41
|
+
include = ["/src", "/hatch_build.py", "/binaries.json", "/pyproject.toml", "/README.md", "/LICENSE", "/TAILWIND-LICENSE", "/tests"]
|
|
42
|
+
exclude = ["/src/fasthtml_tailwindcss/bin"]
|
|
43
|
+
|
|
44
|
+
[tool.hatch.build.hooks.custom]
|
|
45
|
+
path = "hatch_build.py"
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from weakref import finalize
|
|
4
|
+
|
|
5
|
+
from fasthtml.common import Style
|
|
6
|
+
|
|
7
|
+
from ._client import Session, configuration
|
|
8
|
+
|
|
9
|
+
__all__ = ["TailwindHead"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TailwindHead:
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
*,
|
|
16
|
+
watch: bool = False,
|
|
17
|
+
sources: Sequence[str | Path] | None = None,
|
|
18
|
+
input: str | Path | None = None,
|
|
19
|
+
css: str | None = None,
|
|
20
|
+
) -> None:
|
|
21
|
+
config = configuration(watch=watch, sources=sources, input=input, css=css)
|
|
22
|
+
self._session = Session(config)
|
|
23
|
+
self._session.start()
|
|
24
|
+
finalize(self, self._session.close)
|
|
25
|
+
|
|
26
|
+
def __deepcopy__(self, memo):
|
|
27
|
+
return self
|
|
28
|
+
|
|
29
|
+
def __ft__(self):
|
|
30
|
+
if self._session.error:
|
|
31
|
+
raise RuntimeError(self._session.error)
|
|
32
|
+
css = self._session.output.read_text(encoding="utf-8")
|
|
33
|
+
return Style(css.replace("</", "<\\/"))
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
import time
|
|
7
|
+
from importlib.metadata import version
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from threading import Event, Thread
|
|
10
|
+
|
|
11
|
+
from filelock import FileLock, Timeout
|
|
12
|
+
from platformdirs import user_cache_path
|
|
13
|
+
|
|
14
|
+
IDLE_TIMEOUT = 15
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def configuration(*, watch, sources, input, css):
|
|
18
|
+
if isinstance(sources, (str, Path)):
|
|
19
|
+
raise TypeError("sources must be a sequence of paths, for example ['app']")
|
|
20
|
+
cwd = Path.cwd().resolve()
|
|
21
|
+
root = next(
|
|
22
|
+
(p for p in (cwd, *cwd.parents) if (p / "pyproject.toml").is_file()), cwd
|
|
23
|
+
)
|
|
24
|
+
input_path = (root / input).resolve() if input is not None else None
|
|
25
|
+
if input_path is not None and not input_path.is_file():
|
|
26
|
+
raise FileNotFoundError(input_path)
|
|
27
|
+
if sources is None:
|
|
28
|
+
sources = [root] if input is None else []
|
|
29
|
+
return {
|
|
30
|
+
"root": str(root),
|
|
31
|
+
"watch": watch,
|
|
32
|
+
"sources": [str((root / path).resolve()) for path in sources],
|
|
33
|
+
"input": str(input_path) if input_path is not None else None,
|
|
34
|
+
"css": css or "",
|
|
35
|
+
"version": version("fasthtml-tailwindcss"),
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def cache_directory(config):
|
|
40
|
+
settings = json.dumps(config, sort_keys=True).encode()
|
|
41
|
+
key = hashlib.sha256(settings).hexdigest()[:24]
|
|
42
|
+
return user_cache_path("fasthtml-tailwindcss", appauthor=False) / key
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def running(directory):
|
|
46
|
+
try:
|
|
47
|
+
with FileLock(str(directory / "worker.lock"), timeout=0):
|
|
48
|
+
return False
|
|
49
|
+
except Timeout:
|
|
50
|
+
return True
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def stop_process(process):
|
|
54
|
+
if process.poll() is not None:
|
|
55
|
+
return
|
|
56
|
+
process.terminate()
|
|
57
|
+
try:
|
|
58
|
+
process.wait(timeout=5)
|
|
59
|
+
except subprocess.TimeoutExpired:
|
|
60
|
+
process.kill()
|
|
61
|
+
process.wait()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Session:
|
|
65
|
+
def __init__(self, config):
|
|
66
|
+
self.config = config
|
|
67
|
+
self.directory = cache_directory(config)
|
|
68
|
+
self.output = self.directory / "style.css"
|
|
69
|
+
self.error = ""
|
|
70
|
+
self._closed = Event()
|
|
71
|
+
self._thread = Thread(target=self.heartbeat, daemon=True)
|
|
72
|
+
|
|
73
|
+
def connect(self):
|
|
74
|
+
self.directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
75
|
+
with FileLock(str(self.directory / "startup.lock"), timeout=30):
|
|
76
|
+
self.wait_for_previous_worker()
|
|
77
|
+
if not running(self.directory):
|
|
78
|
+
self.start_worker()
|
|
79
|
+
(self.directory / "heartbeat").touch()
|
|
80
|
+
|
|
81
|
+
def wait_for_previous_worker(self):
|
|
82
|
+
deadline = time.monotonic() + 10
|
|
83
|
+
while running(self.directory) and not (self.directory / "pid").exists():
|
|
84
|
+
if time.monotonic() > deadline:
|
|
85
|
+
raise RuntimeError("Tailwind helper is not responding")
|
|
86
|
+
time.sleep(0.05)
|
|
87
|
+
|
|
88
|
+
def start_worker(self):
|
|
89
|
+
for name in ("style.css", "error", "pid"):
|
|
90
|
+
(self.directory / name).unlink(missing_ok=True)
|
|
91
|
+
(self.directory / "config.json").write_text(
|
|
92
|
+
json.dumps(self.config), encoding="utf-8"
|
|
93
|
+
)
|
|
94
|
+
(self.directory / "heartbeat").touch()
|
|
95
|
+
flags = 0
|
|
96
|
+
if os.name == "nt":
|
|
97
|
+
flags = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
|
|
98
|
+
with (self.directory / "helper.log").open("w") as log:
|
|
99
|
+
process = subprocess.Popen(
|
|
100
|
+
[
|
|
101
|
+
sys.executable,
|
|
102
|
+
"-m",
|
|
103
|
+
"fasthtml_tailwindcss._worker",
|
|
104
|
+
str(self.directory),
|
|
105
|
+
],
|
|
106
|
+
stdin=subprocess.DEVNULL,
|
|
107
|
+
stdout=log,
|
|
108
|
+
stderr=log,
|
|
109
|
+
start_new_session=os.name != "nt",
|
|
110
|
+
creationflags=flags,
|
|
111
|
+
)
|
|
112
|
+
deadline = time.monotonic() + 10
|
|
113
|
+
while not (self.directory / "pid").exists():
|
|
114
|
+
if process.poll() is not None or time.monotonic() > deadline:
|
|
115
|
+
stop_process(process)
|
|
116
|
+
raise RuntimeError(
|
|
117
|
+
(self.directory / "helper.log").read_text()
|
|
118
|
+
or "Cannot start Tailwind helper"
|
|
119
|
+
)
|
|
120
|
+
time.sleep(0.05)
|
|
121
|
+
|
|
122
|
+
def wait_for_css(self):
|
|
123
|
+
deadline = time.monotonic() + 120
|
|
124
|
+
while not self.output.exists():
|
|
125
|
+
if self.error:
|
|
126
|
+
raise RuntimeError(self.error)
|
|
127
|
+
if time.monotonic() > deadline:
|
|
128
|
+
raise RuntimeError(
|
|
129
|
+
"Tailwind initial build timed out; see compiler.log in the cache"
|
|
130
|
+
)
|
|
131
|
+
time.sleep(0.05)
|
|
132
|
+
|
|
133
|
+
def heartbeat(self):
|
|
134
|
+
while not self._closed.is_set():
|
|
135
|
+
error = self.directory / "error"
|
|
136
|
+
if error.exists():
|
|
137
|
+
self.error = error.read_text(encoding="utf-8")
|
|
138
|
+
elif not running(self.directory):
|
|
139
|
+
self.error = "Tailwind helper stopped; restart the application"
|
|
140
|
+
if self.error:
|
|
141
|
+
return
|
|
142
|
+
(self.directory / "heartbeat").touch()
|
|
143
|
+
self._closed.wait(2)
|
|
144
|
+
|
|
145
|
+
def start(self):
|
|
146
|
+
self.connect()
|
|
147
|
+
self._thread.start()
|
|
148
|
+
try:
|
|
149
|
+
self.wait_for_css()
|
|
150
|
+
except BaseException:
|
|
151
|
+
self.close()
|
|
152
|
+
raise
|
|
153
|
+
|
|
154
|
+
def close(self):
|
|
155
|
+
self._closed.set()
|
|
156
|
+
self._thread.join()
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import signal
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from filelock import FileLock
|
|
11
|
+
|
|
12
|
+
from ._client import IDLE_TIMEOUT, stop_process
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def input_css(config):
|
|
16
|
+
def quote(path):
|
|
17
|
+
return json.dumps(Path(path).as_posix(), ensure_ascii=False)
|
|
18
|
+
|
|
19
|
+
base = (
|
|
20
|
+
f"@import {quote(config['input'])};"
|
|
21
|
+
if config["input"]
|
|
22
|
+
else '@import "tailwindcss" source(none);'
|
|
23
|
+
)
|
|
24
|
+
sources = "\n".join(f"@source {quote(path)};" for path in config["sources"])
|
|
25
|
+
return f"{base}\n{sources}\n{config['css']}\n"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Worker:
|
|
29
|
+
def __init__(self, directory):
|
|
30
|
+
self.directory = directory
|
|
31
|
+
self.config = json.loads((directory / "config.json").read_text())
|
|
32
|
+
self.output = directory / "style.css"
|
|
33
|
+
self.stopping = False
|
|
34
|
+
|
|
35
|
+
def stop(self, *_):
|
|
36
|
+
self.stopping = True
|
|
37
|
+
|
|
38
|
+
def start_compiler(self):
|
|
39
|
+
source = self.directory / "input.css"
|
|
40
|
+
source.write_text(input_css(self.config), encoding="utf-8")
|
|
41
|
+
executable = "tailwindcss.exe" if os.name == "nt" else "tailwindcss"
|
|
42
|
+
binary = Path(__file__).parent / "bin" / executable
|
|
43
|
+
mode = "--watch=always" if self.config["watch"] else "--minify"
|
|
44
|
+
command = [
|
|
45
|
+
str(binary),
|
|
46
|
+
"-i",
|
|
47
|
+
str(source),
|
|
48
|
+
"-o",
|
|
49
|
+
str(self.directory / "building.css"),
|
|
50
|
+
mode,
|
|
51
|
+
]
|
|
52
|
+
with (self.directory / "compiler.log").open("w") as log:
|
|
53
|
+
return subprocess.Popen(
|
|
54
|
+
command,
|
|
55
|
+
cwd=self.config["root"],
|
|
56
|
+
stdin=subprocess.DEVNULL,
|
|
57
|
+
stdout=log,
|
|
58
|
+
stderr=log,
|
|
59
|
+
env={**os.environ, "NO_COLOR": "1"},
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
def publish_css(self):
|
|
63
|
+
css = (self.directory / "building.css").read_bytes()
|
|
64
|
+
if self.output.exists() and self.output.read_bytes() == css:
|
|
65
|
+
return
|
|
66
|
+
temporary = self.directory / "published.tmp"
|
|
67
|
+
temporary.write_bytes(css)
|
|
68
|
+
temporary.replace(self.output)
|
|
69
|
+
|
|
70
|
+
def idle(self):
|
|
71
|
+
heartbeat = (self.directory / "heartbeat").stat().st_mtime
|
|
72
|
+
return time.time() - heartbeat > IDLE_TIMEOUT
|
|
73
|
+
|
|
74
|
+
def expired(self):
|
|
75
|
+
if not self.idle():
|
|
76
|
+
return False
|
|
77
|
+
with FileLock(str(self.directory / "startup.lock"), timeout=30):
|
|
78
|
+
if not self.idle():
|
|
79
|
+
return False
|
|
80
|
+
(self.directory / "pid").unlink(missing_ok=True)
|
|
81
|
+
return True
|
|
82
|
+
|
|
83
|
+
def check_exit(self, code):
|
|
84
|
+
if code is None:
|
|
85
|
+
return
|
|
86
|
+
if code == 0 and not self.config["watch"] and self.output.exists():
|
|
87
|
+
return
|
|
88
|
+
details = (self.directory / "compiler.log").read_text(
|
|
89
|
+
encoding="utf-8", errors="replace"
|
|
90
|
+
)
|
|
91
|
+
raise RuntimeError(f"Tailwind stopped (exit {code}):\n{details}")
|
|
92
|
+
|
|
93
|
+
def monitor(self, process):
|
|
94
|
+
with (self.directory / "compiler.log").open(
|
|
95
|
+
encoding="utf-8", errors="replace"
|
|
96
|
+
) as log:
|
|
97
|
+
pending = ""
|
|
98
|
+
while not self.stopping:
|
|
99
|
+
code = process.poll()
|
|
100
|
+
pending += log.read()
|
|
101
|
+
message, _, pending = pending.rpartition("\n")
|
|
102
|
+
if re.search(r"\bDone in\b", message):
|
|
103
|
+
self.publish_css()
|
|
104
|
+
self.check_exit(code)
|
|
105
|
+
if self.expired():
|
|
106
|
+
return
|
|
107
|
+
time.sleep(0.1)
|
|
108
|
+
|
|
109
|
+
def run(self):
|
|
110
|
+
process = None
|
|
111
|
+
(self.directory / "pid").write_text(str(os.getpid()))
|
|
112
|
+
try:
|
|
113
|
+
process = self.start_compiler()
|
|
114
|
+
self.monitor(process)
|
|
115
|
+
except (OSError, RuntimeError) as error:
|
|
116
|
+
(self.directory / "error").write_text(str(error), encoding="utf-8")
|
|
117
|
+
finally:
|
|
118
|
+
if process is not None:
|
|
119
|
+
stop_process(process)
|
|
120
|
+
(self.directory / "pid").unlink(missing_ok=True)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def main(directory):
|
|
124
|
+
worker = Worker(directory)
|
|
125
|
+
for name in ("SIGTERM", "SIGINT", "SIGBREAK"):
|
|
126
|
+
if signum := getattr(signal, name, None):
|
|
127
|
+
signal.signal(signum, worker.stop)
|
|
128
|
+
with FileLock(str(directory / "worker.lock"), timeout=0):
|
|
129
|
+
worker.run()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if __name__ == "__main__":
|
|
133
|
+
main(Path(sys.argv[1]))
|
|
File without changes
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import gc
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
from fasthtml.common import Div, FastHTML
|
|
6
|
+
|
|
7
|
+
from fasthtml_tailwindcss import TailwindHead, _client
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.fixture(scope="session")
|
|
11
|
+
def helpers():
|
|
12
|
+
directories = []
|
|
13
|
+
yield directories
|
|
14
|
+
deadline = time.monotonic() + 25
|
|
15
|
+
while any((p / "pid").exists() for p in directories):
|
|
16
|
+
assert time.monotonic() < deadline, (
|
|
17
|
+
"Helper did not shut down after losing clients"
|
|
18
|
+
)
|
|
19
|
+
time.sleep(0.1)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@pytest.fixture
|
|
23
|
+
def project(tmp_path, monkeypatch, helpers):
|
|
24
|
+
monkeypatch.chdir(tmp_path)
|
|
25
|
+
monkeypatch.setattr(_client, "user_cache_path", lambda *a, **kw: tmp_path / "cache")
|
|
26
|
+
(tmp_path / "pyproject.toml").write_text(
|
|
27
|
+
'[project]\nname="example"\nversion="0.1.0"\n'
|
|
28
|
+
)
|
|
29
|
+
(tmp_path / "components.py").write_text('classes = "p-4 bg-blue-500"\n')
|
|
30
|
+
config = _client.configuration(
|
|
31
|
+
watch=False, sources=["components.py"], input=None, css=None
|
|
32
|
+
)
|
|
33
|
+
helpers.append(_client.cache_directory(config))
|
|
34
|
+
yield tmp_path
|
|
35
|
+
gc.collect()
|
|
36
|
+
helpers.extend(path.parent for path in (tmp_path / "cache").glob("*/pid"))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@pytest.fixture
|
|
40
|
+
def application(project):
|
|
41
|
+
def create_app(**options):
|
|
42
|
+
head = TailwindHead(sources=["components.py"], **options)
|
|
43
|
+
app = FastHTML(sess_cls=None, hdrs=[head])
|
|
44
|
+
|
|
45
|
+
@app.get("/") # ty: ignore[unresolved-attribute] # FastHTML registers HTTP methods dynamically.
|
|
46
|
+
def get():
|
|
47
|
+
return Div("Hello", cls="p-4 bg-blue-500")
|
|
48
|
+
|
|
49
|
+
return app, head
|
|
50
|
+
|
|
51
|
+
return create_app
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import gc
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
from fasthtml.common import Div, FastHTML
|
|
6
|
+
from starlette.testclient import TestClient
|
|
7
|
+
|
|
8
|
+
from fasthtml_tailwindcss import TailwindHead
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_custom_input_relative_imports_and_inline_css(project, application):
|
|
12
|
+
assets = project / "assets"
|
|
13
|
+
assets.mkdir()
|
|
14
|
+
(assets / "theme.css").write_text(".custom { color: red; }\n")
|
|
15
|
+
(assets / "app.css").write_text(
|
|
16
|
+
'@import "tailwindcss" source(none);\n@import "./theme.css";\n'
|
|
17
|
+
)
|
|
18
|
+
app, _head = application(input="assets/app.css", css=".extra { color: blue; }")
|
|
19
|
+
with TestClient(app) as client:
|
|
20
|
+
html = client.get("/").text
|
|
21
|
+
assert ".custom{" in html
|
|
22
|
+
assert ".extra{" in html
|
|
23
|
+
assert ".p-4{" in html
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_first_compilation_error_blocks_construction(project):
|
|
27
|
+
with pytest.raises(RuntimeError, match="Tailwind stopped"):
|
|
28
|
+
TailwindHead(css=".broken { @apply definitely-not-a-tailwind-utility; }")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_constructor_builds_without_asgi_lifespan(project):
|
|
32
|
+
head = TailwindHead(sources=["components.py"])
|
|
33
|
+
assert head._session.output.exists()
|
|
34
|
+
app = FastHTML(sess_cls=None, hdrs=[head])
|
|
35
|
+
|
|
36
|
+
@app.route("/")
|
|
37
|
+
def get():
|
|
38
|
+
return Div("Hello", cls="p-4")
|
|
39
|
+
|
|
40
|
+
client = TestClient(app)
|
|
41
|
+
assert ".p-4{" in client.get("/").text
|
|
42
|
+
client.close()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_releasing_component_stops_heartbeat(project):
|
|
46
|
+
head = TailwindHead(sources=["components.py"])
|
|
47
|
+
session = head._session
|
|
48
|
+
del head
|
|
49
|
+
gc.collect()
|
|
50
|
+
assert not session._thread.is_alive()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_default_sources_and_css_escaping(project):
|
|
54
|
+
head = TailwindHead(css='.closing::after { content: "</style>"; }')
|
|
55
|
+
app = FastHTML(sess_cls=None, hdrs=[head])
|
|
56
|
+
with TestClient(app):
|
|
57
|
+
from fasthtml.common import to_xml
|
|
58
|
+
|
|
59
|
+
result = str(to_xml(head))
|
|
60
|
+
assert ".p-4{" in result
|
|
61
|
+
assert result.count("</style>") == 1
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_invalid_sources_argument(project):
|
|
65
|
+
with pytest.raises(TypeError, match="sequence"):
|
|
66
|
+
TailwindHead(sources="app")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_existing_lifespan_and_heartbeat(project):
|
|
70
|
+
events = []
|
|
71
|
+
head = TailwindHead(sources=["components.py"])
|
|
72
|
+
app = FastHTML(
|
|
73
|
+
hdrs=[head],
|
|
74
|
+
sess_cls=None,
|
|
75
|
+
on_startup=lambda: events.append("startup"),
|
|
76
|
+
on_shutdown=lambda: events.append("shutdown"),
|
|
77
|
+
)
|
|
78
|
+
with TestClient(app):
|
|
79
|
+
assert events == ["startup"]
|
|
80
|
+
time.sleep(16)
|
|
81
|
+
assert not head._session.error # ty: ignore[unresolved-attribute] # FastHTML defines hdrs dynamically.
|
|
82
|
+
assert head._session.output.exists() # ty: ignore[unresolved-attribute] # FastHTML defines hdrs dynamically.
|
|
83
|
+
assert events == ["startup", "shutdown"]
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import concurrent.futures
|
|
2
|
+
import copy
|
|
3
|
+
import time
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from starlette.testclient import TestClient
|
|
8
|
+
|
|
9
|
+
from fasthtml_tailwindcss import _client
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_once_build_survives_reload(project, application):
|
|
13
|
+
app, head = application()
|
|
14
|
+
with TestClient(app) as client:
|
|
15
|
+
assert ".p-4{" in client.get("/").text
|
|
16
|
+
output = head._session.output
|
|
17
|
+
original = output.read_bytes()
|
|
18
|
+
timestamp = output.stat().st_mtime_ns
|
|
19
|
+
assert copy.deepcopy(head) is head
|
|
20
|
+
(project / "components.py").write_text('classes = "text-7xl"\n')
|
|
21
|
+
app, head = application()
|
|
22
|
+
with TestClient(app) as client:
|
|
23
|
+
assert head._session.output == output
|
|
24
|
+
assert output.stat().st_mtime_ns == timestamp
|
|
25
|
+
assert output.read_bytes() == original
|
|
26
|
+
assert "text-7xl" not in client.get("/").text
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_watch_rebuilds_and_survives_reload(project, application):
|
|
30
|
+
app, head = application(watch=True)
|
|
31
|
+
with TestClient(app) as client:
|
|
32
|
+
output = head._session.output
|
|
33
|
+
assert ".p-4" in client.get("/").text
|
|
34
|
+
(project / "components.py").write_text('classes = "text-7xl"\n')
|
|
35
|
+
deadline = time.monotonic() + 10
|
|
36
|
+
while ".text-7xl" not in output.read_text():
|
|
37
|
+
assert time.monotonic() < deadline, "Watcher did not rebuild"
|
|
38
|
+
time.sleep(0.05)
|
|
39
|
+
assert ".text-7xl" in client.get("/").text
|
|
40
|
+
before = output.stat().st_mtime_ns
|
|
41
|
+
app, head = application(watch=True)
|
|
42
|
+
with TestClient(app):
|
|
43
|
+
assert head._session.output == output
|
|
44
|
+
assert output.stat().st_mtime_ns == before
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@pytest.mark.parametrize("watch", [True, False])
|
|
48
|
+
def test_immediate_restart_with_changed_watch(project, watch):
|
|
49
|
+
import json
|
|
50
|
+
import subprocess
|
|
51
|
+
import sys
|
|
52
|
+
|
|
53
|
+
script = """import json, sys
|
|
54
|
+
from pathlib import Path
|
|
55
|
+
from fasthtml.common import FastHTML
|
|
56
|
+
from fasthtml_tailwindcss import TailwindHead, _client
|
|
57
|
+
_client.user_cache_path = lambda *args, **kwargs: Path("cache").resolve()
|
|
58
|
+
head = TailwindHead(watch=sys.argv[1] == "True", sources=["components.py"])
|
|
59
|
+
app = FastHTML(hdrs=[head], sess_cls=None)
|
|
60
|
+
print(json.dumps(str(head._session.directory)))
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def start(mode):
|
|
64
|
+
result = subprocess.run(
|
|
65
|
+
[sys.executable, "-c", script, str(mode)],
|
|
66
|
+
cwd=project,
|
|
67
|
+
capture_output=True,
|
|
68
|
+
text=True,
|
|
69
|
+
timeout=10,
|
|
70
|
+
check=False,
|
|
71
|
+
)
|
|
72
|
+
assert result.returncode == 0, result.stderr
|
|
73
|
+
return Path(json.loads(result.stdout))
|
|
74
|
+
|
|
75
|
+
previous = start(watch)
|
|
76
|
+
assert _client.running(previous)
|
|
77
|
+
(project / "components.py").write_text('classes = "text-7xl"\n')
|
|
78
|
+
current = start(not watch)
|
|
79
|
+
assert current != previous
|
|
80
|
+
assert ".text-7xl" in (current / "style.css").read_text()
|
|
81
|
+
assert _client.running(previous)
|
|
82
|
+
assert _client.running(current)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_concurrent_workers_share_one_build(project):
|
|
86
|
+
config = _client.configuration(
|
|
87
|
+
watch=False, sources=["components.py"], input=None, css=None
|
|
88
|
+
)
|
|
89
|
+
sessions = [_client.Session(config) for _ in range(4)]
|
|
90
|
+
with concurrent.futures.ThreadPoolExecutor() as pool:
|
|
91
|
+
list(pool.map(lambda s: s.connect(), sessions))
|
|
92
|
+
assert len({s.output for s in sessions}) == 1
|
|
93
|
+
directory = _client.cache_directory(config)
|
|
94
|
+
assert (directory / "config.json").is_file()
|
|
95
|
+
assert int((directory / "pid").read_text()) > 0
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from fasthtml_tailwindcss import _client
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@pytest.mark.skipif(
|
|
9
|
+
__import__("os").name == "nt",
|
|
10
|
+
reason="POSIX process-group shutdown for this reload test",
|
|
11
|
+
)
|
|
12
|
+
@pytest.mark.parametrize("watch", [False, True])
|
|
13
|
+
def test_real_uvicorn_reload(project, helpers, watch):
|
|
14
|
+
import os
|
|
15
|
+
import signal
|
|
16
|
+
import socket
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
from urllib.error import URLError
|
|
20
|
+
from urllib.request import urlopen
|
|
21
|
+
|
|
22
|
+
source = project / "main.py"
|
|
23
|
+
source.write_text(f"""import os
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from fasthtml.common import FastHTML, Div
|
|
26
|
+
from fasthtml_tailwindcss import TailwindHead, _client
|
|
27
|
+
_client.user_cache_path = lambda *a, **kw: Path({str(project / "cache")!r})
|
|
28
|
+
app = FastHTML(sess_cls=None, hdrs=[TailwindHead(watch={watch!r}, sources=["main.py"])])
|
|
29
|
+
@app.get("/")
|
|
30
|
+
def get():
|
|
31
|
+
return Div("first", cls="p-4")
|
|
32
|
+
@app.get("/pid")
|
|
33
|
+
def pid():
|
|
34
|
+
return str(os.getpid())
|
|
35
|
+
""")
|
|
36
|
+
with socket.socket() as sock:
|
|
37
|
+
sock.bind(("127.0.0.1", 0))
|
|
38
|
+
port = sock.getsockname()[1]
|
|
39
|
+
base = f"http://127.0.0.1:{port}"
|
|
40
|
+
|
|
41
|
+
def response(path="/"):
|
|
42
|
+
try:
|
|
43
|
+
with urlopen(base + path, timeout=1) as res:
|
|
44
|
+
return res.read().decode()
|
|
45
|
+
except (OSError, URLError):
|
|
46
|
+
return ""
|
|
47
|
+
|
|
48
|
+
config = _client.configuration(
|
|
49
|
+
watch=watch, sources=["main.py"], input=None, css=None
|
|
50
|
+
)
|
|
51
|
+
directory = _client.cache_directory(config)
|
|
52
|
+
with (project / "uvicorn.log").open("w") as log:
|
|
53
|
+
process = subprocess.Popen(
|
|
54
|
+
[
|
|
55
|
+
sys.executable,
|
|
56
|
+
"-m",
|
|
57
|
+
"uvicorn",
|
|
58
|
+
"main:app",
|
|
59
|
+
"--reload",
|
|
60
|
+
"--port",
|
|
61
|
+
str(port),
|
|
62
|
+
],
|
|
63
|
+
cwd=project,
|
|
64
|
+
stdout=log,
|
|
65
|
+
stderr=log,
|
|
66
|
+
start_new_session=True,
|
|
67
|
+
)
|
|
68
|
+
try:
|
|
69
|
+
deadline = time.monotonic() + 20
|
|
70
|
+
while ">first</div>" not in response():
|
|
71
|
+
assert process.poll() is None, (project / "uvicorn.log").read_text()
|
|
72
|
+
assert time.monotonic() < deadline, (
|
|
73
|
+
project / "uvicorn.log"
|
|
74
|
+
).read_text()
|
|
75
|
+
time.sleep(0.1)
|
|
76
|
+
pid = response("/pid")
|
|
77
|
+
helper_pid = (directory / "pid").read_text()
|
|
78
|
+
output = directory / "style.css"
|
|
79
|
+
timestamp = output.stat().st_mtime_ns
|
|
80
|
+
source.write_text(
|
|
81
|
+
source.read_text().replace(
|
|
82
|
+
'"first", cls="p-4"', '"second", cls="text-7xl"'
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
deadline = time.monotonic() + 20
|
|
86
|
+
while ">second</div>" not in response():
|
|
87
|
+
assert time.monotonic() < deadline, (
|
|
88
|
+
project / "uvicorn.log"
|
|
89
|
+
).read_text()
|
|
90
|
+
time.sleep(0.1)
|
|
91
|
+
assert response("/pid") != pid
|
|
92
|
+
assert (directory / "pid").read_text() == helper_pid
|
|
93
|
+
if watch:
|
|
94
|
+
while ".text-7xl" not in response():
|
|
95
|
+
assert time.monotonic() < deadline
|
|
96
|
+
time.sleep(0.1)
|
|
97
|
+
else:
|
|
98
|
+
assert output.stat().st_mtime_ns == timestamp
|
|
99
|
+
assert ".text-7xl" not in response()
|
|
100
|
+
finally:
|
|
101
|
+
os.killpg(process.pid, signal.SIGTERM)
|
|
102
|
+
process.wait(timeout=15)
|