fjkit 0.1.0.dev0__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.
Files changed (127) hide show
  1. fjkit/__init__.py +49 -0
  2. fjkit/auth/__init__.py +54 -0
  3. fjkit/auth/csrf.py +88 -0
  4. fjkit/auth/errors.py +31 -0
  5. fjkit/auth/plugin.py +496 -0
  6. fjkit/auth/sources.py +24 -0
  7. fjkit/auth/stores.py +141 -0
  8. fjkit/auth/types.py +141 -0
  9. fjkit/cli/__init__.py +67 -0
  10. fjkit/cli/build_css.py +135 -0
  11. fjkit/cli/check.py +193 -0
  12. fjkit/cli/eject.py +562 -0
  13. fjkit/cli/ejected.py +202 -0
  14. fjkit/cli/vocabulary.py +85 -0
  15. fjkit/config.py +130 -0
  16. fjkit/errors.py +156 -0
  17. fjkit/flash.py +189 -0
  18. fjkit/forms.py +145 -0
  19. fjkit/htmx.py +76 -0
  20. fjkit/icons.py +60 -0
  21. fjkit/messages.py +227 -0
  22. fjkit/mounting.py +72 -0
  23. fjkit/plugins.py +223 -0
  24. fjkit/py.typed +0 -0
  25. fjkit/rendering.py +554 -0
  26. fjkit/signing.py +63 -0
  27. fjkit/static/brand/torii-bolt.png +0 -0
  28. fjkit/static/dist/fjkit-luma.css +2 -0
  29. fjkit/static/dist/fjkit-lyra.css +2 -0
  30. fjkit/static/dist/fjkit-maia.css +2 -0
  31. fjkit/static/dist/fjkit-mira.css +2 -0
  32. fjkit/static/dist/fjkit-nova.css +2 -0
  33. fjkit/static/dist/fjkit-rhea.css +2 -0
  34. fjkit/static/dist/fjkit-sera.css +2 -0
  35. fjkit/static/dist/fjkit-vega.css +2 -0
  36. fjkit/static/icons/lucide.json +1 -0
  37. fjkit/static/js/errors.js +117 -0
  38. fjkit/static/js/multiselect.js +126 -0
  39. fjkit/static/js/reveal.js +51 -0
  40. fjkit/static/js/select.js +113 -0
  41. fjkit/static/src/fjkit.css +385 -0
  42. fjkit/static/vendor/basecoat/base/base.css +136 -0
  43. fjkit/static/vendor/basecoat/basecoat-base.css +2 -0
  44. fjkit/static/vendor/basecoat/basecoat-components.css +39 -0
  45. fjkit/static/vendor/basecoat/basecoat-luma.css +2 -0
  46. fjkit/static/vendor/basecoat/basecoat-lyra.css +2 -0
  47. fjkit/static/vendor/basecoat/basecoat-maia.css +2 -0
  48. fjkit/static/vendor/basecoat/basecoat-mira.css +2 -0
  49. fjkit/static/vendor/basecoat/basecoat-nova.css +2 -0
  50. fjkit/static/vendor/basecoat/basecoat-rhea.css +2 -0
  51. fjkit/static/vendor/basecoat/basecoat-sera.css +2 -0
  52. fjkit/static/vendor/basecoat/basecoat-vega.css +2 -0
  53. fjkit/static/vendor/basecoat/basecoat.all.css +1 -0
  54. fjkit/static/vendor/basecoat/basecoat.css +1 -0
  55. fjkit/static/vendor/basecoat/components/accordion.css +27 -0
  56. fjkit/static/vendor/basecoat/components/alert.css +38 -0
  57. fjkit/static/vendor/basecoat/components/avatar.css +47 -0
  58. fjkit/static/vendor/basecoat/components/badge.css +6 -0
  59. fjkit/static/vendor/basecoat/components/breadcrumb.css +30 -0
  60. fjkit/static/vendor/basecoat/components/button-group.css +54 -0
  61. fjkit/static/vendor/basecoat/components/button.css +6 -0
  62. fjkit/static/vendor/basecoat/components/card.css +26 -0
  63. fjkit/static/vendor/basecoat/components/chart.css +56 -0
  64. fjkit/static/vendor/basecoat/components/checkbox.css +12 -0
  65. fjkit/static/vendor/basecoat/components/collapsible.css +21 -0
  66. fjkit/static/vendor/basecoat/components/combobox.css +99 -0
  67. fjkit/static/vendor/basecoat/components/command.css +140 -0
  68. fjkit/static/vendor/basecoat/components/dialog.css +101 -0
  69. fjkit/static/vendor/basecoat/components/drawer.css +89 -0
  70. fjkit/static/vendor/basecoat/components/dropdown-menu.css +56 -0
  71. fjkit/static/vendor/basecoat/components/empty.css +26 -0
  72. fjkit/static/vendor/basecoat/components/field.css +82 -0
  73. fjkit/static/vendor/basecoat/components/form.css +9 -0
  74. fjkit/static/vendor/basecoat/components/input-group.css +74 -0
  75. fjkit/static/vendor/basecoat/components/input.css +32 -0
  76. fjkit/static/vendor/basecoat/components/item.css +50 -0
  77. fjkit/static/vendor/basecoat/components/kbd.css +6 -0
  78. fjkit/static/vendor/basecoat/components/label.css +13 -0
  79. fjkit/static/vendor/basecoat/components/native-select.css +12 -0
  80. fjkit/static/vendor/basecoat/components/popover.css +107 -0
  81. fjkit/static/vendor/basecoat/components/progress.css +14 -0
  82. fjkit/static/vendor/basecoat/components/radio.css +11 -0
  83. fjkit/static/vendor/basecoat/components/range.css +50 -0
  84. fjkit/static/vendor/basecoat/components/scrollbar.css +46 -0
  85. fjkit/static/vendor/basecoat/components/select.css +64 -0
  86. fjkit/static/vendor/basecoat/components/sidebar.css +101 -0
  87. fjkit/static/vendor/basecoat/components/skeleton.css +6 -0
  88. fjkit/static/vendor/basecoat/components/switch.css +8 -0
  89. fjkit/static/vendor/basecoat/components/table.css +34 -0
  90. fjkit/static/vendor/basecoat/components/tabs.css +31 -0
  91. fjkit/static/vendor/basecoat/components/textarea.css +7 -0
  92. fjkit/static/vendor/basecoat/components/toast.css +57 -0
  93. fjkit/static/vendor/basecoat/components/tooltip.css +82 -0
  94. fjkit/static/vendor/basecoat/js/all.min.js +1 -0
  95. fjkit/static/vendor/basecoat/styles/luma.css +1376 -0
  96. fjkit/static/vendor/basecoat/styles/lyra.css +1379 -0
  97. fjkit/static/vendor/basecoat/styles/maia.css +1364 -0
  98. fjkit/static/vendor/basecoat/styles/mira.css +1373 -0
  99. fjkit/static/vendor/basecoat/styles/nova.css +1387 -0
  100. fjkit/static/vendor/basecoat/styles/rhea.css +1381 -0
  101. fjkit/static/vendor/basecoat/styles/sera.css +1397 -0
  102. fjkit/static/vendor/basecoat/styles/vega.css +1386 -0
  103. fjkit/static/vendor/htmx/htmx.min.js +1 -0
  104. fjkit/static/vendor/htmx/json-enc.js +38 -0
  105. fjkit/styles.py +30 -0
  106. fjkit/templates/errors/page.html +92 -0
  107. fjkit/templates/ui/attrs.html +18 -0
  108. fjkit/templates/ui/button.html +64 -0
  109. fjkit/templates/ui/data.html +362 -0
  110. fjkit/templates/ui/disclosure.html +89 -0
  111. fjkit/templates/ui/feedback.html +313 -0
  112. fjkit/templates/ui/form.html +595 -0
  113. fjkit/templates/ui/icon.html +13 -0
  114. fjkit/templates/ui/layout.html +189 -0
  115. fjkit/templates/ui/nav.html +110 -0
  116. fjkit/templates/ui/overlay.html +624 -0
  117. fjkit/templates/ui/shell.html +170 -0
  118. fjkit/templates/ui/sidebar.html +170 -0
  119. fjkit/templates/ui/table.html +427 -0
  120. fjkit/templates/ui/tabs.html +133 -0
  121. fjkit/templating.py +365 -0
  122. fjkit/vendored.py +46 -0
  123. fjkit-0.1.0.dev0.dist-info/METADATA +119 -0
  124. fjkit-0.1.0.dev0.dist-info/RECORD +127 -0
  125. fjkit-0.1.0.dev0.dist-info/WHEEL +4 -0
  126. fjkit-0.1.0.dev0.dist-info/entry_points.txt +2 -0
  127. fjkit-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
fjkit/auth/types.py ADDED
@@ -0,0 +1,141 @@
1
+ """The three seams an app can replace, and the record they all move around.
2
+
3
+ Storage and credential exchange are separate protocols because they vary
4
+ independently: swapping password login for OpenID Connect (OIDC) should not
5
+ touch a Redis call, and moving from memory to Redis should not touch login code.
6
+ One combined interface would force both rewrites.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections.abc import Mapping
13
+ from dataclasses import dataclass, field
14
+ from datetime import datetime
15
+ from typing import Any, Protocol, runtime_checkable
16
+
17
+ from fastapi import Request, Response
18
+
19
+ __all__ = [
20
+ "Csrf",
21
+ "RefreshableTokenSource",
22
+ "Session",
23
+ "SessionStore",
24
+ "TokenSource",
25
+ "decode",
26
+ "encode",
27
+ ]
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class Session:
32
+ """One login, as the server holds it. Nothing here reaches the browser.
33
+
34
+ `access is None` is the ordinary state for an app with no upstream API, and
35
+ is what `LocalSource` produces. `claims` is the app's own data and must be
36
+ JSON-serialisable: the payload is encoded with the standard library, which
37
+ is the price of fjkit's two runtime dependencies (CHARTER §7) and the only
38
+ place that price shows.
39
+
40
+ `expires_at` must carry a timezone, and is what enables refresh. A source
41
+ that reports none gets no refresh, because nothing triggers it.
42
+ """
43
+
44
+ claims: Mapping[str, Any] = field(default_factory=dict)
45
+ access: str | None = None
46
+ refresh: str | None = None
47
+ expires_at: datetime | None = None
48
+
49
+
50
+ def encode(session: Session) -> bytes:
51
+ """Serialise a `Session` to the bytes a store keeps."""
52
+ return json.dumps(
53
+ {
54
+ "claims": dict(session.claims),
55
+ "access": session.access,
56
+ "refresh": session.refresh,
57
+ "expires_at": session.expires_at.isoformat() if session.expires_at else None,
58
+ },
59
+ separators=(",", ":"),
60
+ ).encode("utf-8")
61
+
62
+
63
+ def decode(payload: bytes) -> Session:
64
+ """Invert `encode`. Raises `ValueError` on anything else."""
65
+ data = json.loads(payload)
66
+ expires_at = data.get("expires_at")
67
+ return Session(
68
+ claims=data.get("claims") or {},
69
+ access=data.get("access"),
70
+ refresh=data.get("refresh"),
71
+ expires_at=datetime.fromisoformat(expires_at) if expires_at else None,
72
+ )
73
+
74
+
75
+ @runtime_checkable
76
+ class SessionStore(Protocol):
77
+ """Where sessions live. Moves opaque bytes, not `Session` objects.
78
+
79
+ Encoding belongs to the plugin, so no backend reimplements it, and a store
80
+ that never inspects the payload cannot grow an opinion about its contents.
81
+
82
+ Every method is `async`, and there is no synchronous variant: two parallel
83
+ hierarchies would make every implementer pick a side, while `MemoryStore`
84
+ shows an async signature over synchronous work costs nothing. Wrap a
85
+ blocking implementation in `SyncStore`.
86
+ """
87
+
88
+ async def get(self, sid: str) -> bytes | None: ...
89
+
90
+ async def put(self, sid: str, payload: bytes, ttl: int) -> None:
91
+ """Store `payload`, expiring after `ttl` seconds."""
92
+
93
+ async def delete(self, sid: str) -> None: ...
94
+
95
+ async def acquire_refresh_lock(self, sid: str, ttl: int) -> bool:
96
+ """Return True if this caller may refresh, False if another already is.
97
+
98
+ Without the lock, a page firing four htmx swaps at once sends four
99
+ refreshes, and an upstream that rotates refresh tokens revokes the whole
100
+ family when the second arrives, logging the user out mid-click.
101
+
102
+ The loser does not block here. The plugin polls `get` until the winner
103
+ writes, which keeps this protocol at five methods and the waiting policy
104
+ in one place.
105
+
106
+ `ttl` bounds the damage when the winner dies: the lock expires and the
107
+ next request tries again.
108
+ """
109
+
110
+ async def release_refresh_lock(self, sid: str) -> None: ...
111
+
112
+
113
+ class TokenSource(Protocol):
114
+ """Turns whatever the user submitted into a `Session`."""
115
+
116
+ async def exchange(self, credentials: Any) -> Session: ...
117
+
118
+
119
+ class RefreshableTokenSource(TokenSource, Protocol):
120
+ """A source that can also renew.
121
+
122
+ Split from `TokenSource` so `AuthPlugin` can report at startup, rather than
123
+ at the first expiry in production, that a source handing out expiring tokens
124
+ has no way to replace them.
125
+ """
126
+
127
+ async def refresh(self, session: Session) -> Session: ...
128
+
129
+
130
+ class Csrf(Protocol):
131
+ """How a cookie-authenticated write proves it came from this site."""
132
+
133
+ async def verify(self, request: Request) -> None:
134
+ """Return if the request is trusted, raise `CsrfRejected` if not."""
135
+
136
+ def on_issue(self, response: Response, sid: str) -> None:
137
+ """Run when a session is issued.
138
+
139
+ `OriginCsrf` does nothing here. The hook exists so a token-based
140
+ strategy can plant its token later without changing this protocol.
141
+ """
fjkit/cli/__init__.py ADDED
@@ -0,0 +1,67 @@
1
+ """The `fjkit` command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ from fjkit.vendored import STYLE_PACKS
9
+
10
+
11
+ def main(argv: list[str] | None = None) -> int:
12
+ parser = argparse.ArgumentParser(prog="fjkit", description="Server-rendered UI kit for FastAPI")
13
+ sub = parser.add_subparsers(dest="command", required=True)
14
+
15
+ check = sub.add_parser("check", help="fail if a template steps outside the fjkit vocabulary")
16
+ check.add_argument(
17
+ "template_dir",
18
+ nargs="?",
19
+ default="app/templates",
20
+ type=Path,
21
+ help="your app's template directory (default: app/templates)",
22
+ )
23
+
24
+ build = sub.add_parser("build-css", help="compile fjkit's stylesheets (fjkit development only)")
25
+ build.add_argument("--watch", action="store_true", help="rebuild on change")
26
+ build.add_argument(
27
+ "--style",
28
+ choices=STYLE_PACKS,
29
+ help="build only this style pack (default: all eight)",
30
+ )
31
+
32
+ eject = sub.add_parser(
33
+ "eject",
34
+ help="take one macro (or a whole component) into your app so you can edit it",
35
+ description=(
36
+ "Write an override into your template directory. Name a macro (`badge`) to own just "
37
+ "that one — the rest of its file is re-exported from the kit and keeps receiving "
38
+ "upstream fixes. Name a component file (`data`) to take all of it. Where two "
39
+ "components define the same macro, say which: `data.badge`."
40
+ ),
41
+ )
42
+ eject.add_argument("name", help="a macro (badge), a component file (data), or both (data.badge)")
43
+ eject.add_argument(
44
+ "--into",
45
+ default="app/templates",
46
+ type=Path,
47
+ help="your app's template directory (default: app/templates)",
48
+ )
49
+
50
+ args = parser.parse_args(argv)
51
+
52
+ if args.command == "check":
53
+ from fjkit.cli.check import main as check_main
54
+
55
+ return check_main(args.template_dir)
56
+
57
+ if args.command == "build-css":
58
+ from fjkit.cli.build_css import main as build_main
59
+
60
+ return build_main(watch=args.watch, style=args.style)
61
+
62
+ if args.command == "eject":
63
+ from fjkit.cli.eject import main as eject_main
64
+
65
+ return eject_main(args.name, args.into)
66
+
67
+ return 2
fjkit/cli/build_css.py ADDED
@@ -0,0 +1,135 @@
1
+ """`fjkit build-css` — compile the kit's stylesheets, one per style pack.
2
+
3
+ Runs when fjkit is released, not when an app runs. Consumers get the built files
4
+ in the wheel and never install Tailwind. That asymmetry is the point of
5
+ CHARTER.md A1, so this command lives in the `build` dependency group.
6
+
7
+ Eight packs, eight stylesheets, one served. The browser downloads only the one
8
+ `FjkitConfig.style` names; the other seven are bytes in the wheel no request
9
+ touches. Compressed they are ~24 KB each, so shipping all eight costs the
10
+ installer around 190 KB and costs the page nothing, which is what makes the
11
+ choice a config value rather than a reinstall.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import gzip
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ from fjkit.config import STATIC_DIR
24
+ from fjkit.vendored import DEFAULT_STYLE, STYLE_PACKS, StylePack
25
+
26
+ SRC = STATIC_DIR / "src" / "fjkit.css"
27
+ DIST = STATIC_DIR / "dist"
28
+
29
+ #: The one line in `src/fjkit.css` that names a pack. Anchored on the marker
30
+ #: comment rather than the filename, so a reformatted import breaks the build
31
+ #: loudly instead of silently compiling eight identical stylesheets.
32
+ _PACK_IMPORT = re.compile(r'^@import\s+"[^"]*basecoat-\w+\.css";\s*/\*\s*fjkit:style-pack\s*\*/\s*$', re.MULTILINE)
33
+
34
+
35
+ def output_for(style: str) -> Path:
36
+ """Give the path a pack's stylesheet lands at. `mount_fjkit` and the shell
37
+ read it too, so the URL a page requests and the file the build wrote cannot
38
+ drift apart."""
39
+ return DIST / f"fjkit-{style}.css"
40
+
41
+
42
+ def _entry_for(style: str) -> Path:
43
+ """Write the per-pack Tailwind entry point.
44
+
45
+ `src/fjkit.css` is the real source and stays readable and buildable on its
46
+ own; this is that file with one import swapped. It is written next to the
47
+ original because every other path in it — the `@source` globs, the vendor
48
+ imports — is relative to the file's own directory.
49
+ """
50
+ text = SRC.read_text(encoding="utf-8")
51
+ swapped, count = _PACK_IMPORT.subn(
52
+ f'@import "../vendor/basecoat/basecoat-{style}.css"; /* fjkit:style-pack */',
53
+ text,
54
+ )
55
+ if count != 1:
56
+ raise SystemExit(
57
+ f"{SRC} has {count} lines carrying the `fjkit:style-pack` marker, expected exactly 1.\n"
58
+ "The builder rewrites that line to select a pack — restore the marker comment on the "
59
+ "Basecoat import and try again."
60
+ )
61
+
62
+ entry = SRC.with_name(f".build-{style}.css")
63
+ entry.write_text(swapped, encoding="utf-8")
64
+ return entry
65
+
66
+
67
+ def _compile(style: str, watch: bool) -> int:
68
+ entry = _entry_for(style)
69
+ cmd = ["tailwindcss", "--input", str(entry), "--output", str(output_for(style))]
70
+ cmd += ["--watch"] if watch else ["--minify"]
71
+ try:
72
+ return subprocess.run(cmd, cwd=STATIC_DIR.parent).returncode
73
+ finally:
74
+ # Kept alive for the whole of `--watch`, which only returns on Ctrl-C.
75
+ entry.unlink(missing_ok=True)
76
+
77
+
78
+ def main(watch: bool = False, style: str | None = None) -> int:
79
+ if shutil.which("tailwindcss") is None:
80
+ print(
81
+ "tailwindcss not found. It is a build-time dependency of fjkit itself:\n uv sync --group build",
82
+ file=sys.stderr,
83
+ )
84
+ return 2
85
+
86
+ if style is not None and style not in STYLE_PACKS:
87
+ print(f"unknown style pack {style!r}. Available: {', '.join(STYLE_PACKS)}", file=sys.stderr)
88
+ return 2
89
+
90
+ DIST.mkdir(parents=True, exist_ok=True)
91
+
92
+ if watch:
93
+ # One pack at a time: Tailwind's watcher owns the terminal, and a
94
+ # rebuild loop over eight of them would report nothing useful.
95
+ return _compile(style or DEFAULT_STYLE, watch=True)
96
+
97
+ targets: tuple[StylePack, ...] = (style,) if style else STYLE_PACKS # type: ignore[assignment]
98
+ failed = 0
99
+ for pack in targets:
100
+ if _compile(pack, watch=False) != 0:
101
+ return 1
102
+ failed |= report(output_for(pack), default=pack == DEFAULT_STYLE)
103
+ return failed
104
+
105
+
106
+ #: CHARTER.md §7. The budget is written in gzip because that is what a browser
107
+ #: downloads, and stdlib gzip measures it with no extra dependency. The raw
108
+ #: ceiling only catches a runaway.
109
+ #:
110
+ #: Per stylesheet, not per wheel: a page loads one pack, so one pack is what the
111
+ #: budget covers. Eight in the wheel is an install-size question, and an install
112
+ #: is not a page load.
113
+ GZIP_BUDGET = 28 * 1024
114
+ RAW_BUDGET = 260 * 1024
115
+
116
+
117
+ def report(path: Path, default: bool = False) -> int:
118
+ """Print the size and return 1 if it is over budget. A budget nobody
119
+ measures is a wish."""
120
+ raw = path.stat().st_size
121
+ compressed = len(gzip.compress(path.read_bytes(), 9))
122
+
123
+ mark = " (default)" if default else ""
124
+ print(f"{path.name} {raw:,} bytes raw · {compressed:,} bytes gzip ({compressed / 1024:.1f} KB){mark}")
125
+
126
+ over = []
127
+ if compressed > GZIP_BUDGET:
128
+ over.append(f"gzip over budget by {(compressed - GZIP_BUDGET) / 1024:.1f} KB")
129
+ if raw > RAW_BUDGET:
130
+ over.append(f"raw over budget by {(raw - RAW_BUDGET) / 1024:.1f} KB")
131
+
132
+ if over:
133
+ print(" " + "; ".join(over), file=sys.stderr)
134
+ return 1
135
+ return 0
fjkit/cli/check.py ADDED
@@ -0,0 +1,193 @@
1
+ """`fjkit check` — fail if an app template steps outside the vocabulary.
2
+
3
+ An enforced convention outlasts a documented one, so this ships as a CLI and as
4
+ a pytest assertion an app can put in its own suite.
5
+
6
+ Two families of violation:
7
+
8
+ 1. **Colour literals** — a hex code, `oklch()`, a Tailwind palette hue,
9
+ `text-white`. Colours belong to the token layer; a hue in markup breaks a
10
+ later rebrand.
11
+ 2. **Non-component classes** — anything outside the published component
12
+ vocabulary. Layout is a component too (`stack`, `row`, `grid`), so an app
13
+ template has no reason to say `flex gap-4`.
14
+
15
+ Two things are not checked.
16
+
17
+ **Jinja comments.** `{# … #}` never reaches the browser, so a colour named
18
+ inside one cannot break a rebrand. Scanning them stopped the rule describing
19
+ itself: `nav.html`'s signature comment explains why the brand tile must not say
20
+ `text-white`, and that sentence counted as a violation.
21
+
22
+ **An ejected file's classes.** The kit's rules judge a copy made by `fjkit
23
+ eject`, not the app's — see `_ejected_paths`.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import re
29
+ from dataclasses import dataclass
30
+ from pathlib import Path
31
+
32
+ from fjkit.cli.ejected import find_ejected, stale_ejects
33
+ from fjkit.cli.vocabulary import component_classes, emitted_classes
34
+
35
+ #: Tailwind palette hues used as a colour utility: bg-blue-600, text-red-500 …
36
+ PALETTE = re.compile(
37
+ r"\b(?:bg|text|border|ring|outline|fill|stroke|from|via|to|divide|shadow|accent|caret|decoration)"
38
+ r"-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|"
39
+ r"blue|indigo|violet|purple|fuchsia|pink|rose)-\d{2,3}\b"
40
+ )
41
+ HEX = re.compile(r"#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b")
42
+ FUNCS = re.compile(r"\b(?:rgb|rgba|hsl|hsla|oklch|oklab|lab|lch)\(")
43
+ ABSOLUTES = re.compile(r"\b(?:bg|text|border|ring|fill|stroke)-(?:white|black)\b")
44
+
45
+ COLOUR_CHECKS = [
46
+ (PALETTE, "Tailwind palette hue — name a role instead (primary / muted / destructive / success …)"),
47
+ (HEX, "hex literal — colours live in the token layer, not in markup"),
48
+ (FUNCS, "raw colour function — colours live in the token layer, not in markup"),
49
+ (ABSOLUTES, "absolute white/black — use the matching -foreground token"),
50
+ ]
51
+
52
+ #: `class="…"` including the multi-line form, which templates use a lot.
53
+ CLASS_ATTR = re.compile(r"""class\s*=\s*"([^"]*)\"""", re.DOTALL)
54
+
55
+ #: Jinja expressions are removed from a class attribute before it is split into
56
+ #: tokens. Splitting first is wrong: `class="card {{ extra }}"` tokenises to
57
+ #: `card`, `{{`, `extra`, `}}`, and `extra` then looks like a hand-written class
58
+ #: name. The checker cannot evaluate what an expression produces; the "never
59
+ #: build a class by interpolation" rule covers that case.
60
+ _JINJA_EXPR = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
61
+
62
+ #: A Jinja comment, blanked out before either family of check runs.
63
+ _JINJA_COMMENT = re.compile(r"\{#.*?#\}", re.DOTALL)
64
+ _NOT_NEWLINE = re.compile(r"[^\n]")
65
+
66
+
67
+ def _without_comments(text: str) -> str:
68
+ """Replace every `{# … #}` with spaces of the same shape.
69
+
70
+ Blanked rather than removed so every remaining character keeps its line
71
+ number; the violation report is useful only if it points at the right line.
72
+ """
73
+ return _JINJA_COMMENT.sub(lambda m: _NOT_NEWLINE.sub(" ", m.group(0)), text)
74
+
75
+
76
+ @dataclass(frozen=True, slots=True)
77
+ class Violation:
78
+ path: Path
79
+ line: int
80
+ token: str
81
+ reason: str
82
+
83
+ def render(self, root: Path) -> str:
84
+ rel = self.path.relative_to(root).as_posix()
85
+ return f" {rel}:{self.line} {self.token!r}\n {self.reason}"
86
+
87
+
88
+ def _ejected_paths(template_dir: Path) -> frozenset[Path]:
89
+ """Return the files `fjkit eject` wrote, exempt from the class rule.
90
+
91
+ The escape hatch has to be usable. A kit macro writes utility classes — that
92
+ is its job, and why an app never has to — so a copy of one fails the
93
+ closed-vocabulary rule the moment it lands. Judging an ejected file by the
94
+ app's rules would make the supported way to change a component produce a red
95
+ build, which amounts to not supporting it.
96
+
97
+ So the kit's rules judge a stamped file instead. Colours still belong to the
98
+ token layer, which survives an eject: a hue in an ejected macro breaks a
99
+ rebrand as it would anywhere else. The closed vocabulary does not apply,
100
+ because it is a promise the kit makes to the app about classes the app did
101
+ not write.
102
+
103
+ The whole class family is dropped rather than only the utilities: without a
104
+ built stylesheet `emitted_classes()` is empty and every utility looks like a
105
+ typo, so allowing utilities while still catching typos would report a clean
106
+ eject as broken on any machine that has not run `fjkit build-css`.
107
+ """
108
+ return frozenset(e.path for e in find_ejected(template_dir))
109
+
110
+
111
+ def check_templates(template_dir: Path) -> list[Violation]:
112
+ """Collect every violation in an app's template directory, in file order."""
113
+ allowed = component_classes()
114
+ emitted = emitted_classes()
115
+ ejected = _ejected_paths(template_dir)
116
+ violations: list[Violation] = []
117
+
118
+ paths = sorted(template_dir.rglob("*.html")) + sorted(template_dir.rglob("*.jinja"))
119
+ for path in paths:
120
+ text = _without_comments(path.read_text(encoding="utf-8"))
121
+
122
+ for lineno, line in enumerate(text.splitlines(), 1):
123
+ for pattern, reason in COLOUR_CHECKS:
124
+ for match in pattern.finditer(line):
125
+ violations.append(Violation(path, lineno, match.group(0), reason))
126
+
127
+ if path in ejected:
128
+ continue
129
+
130
+ for match in CLASS_ATTR.finditer(text):
131
+ lineno = text.count("\n", 0, match.start()) + 1
132
+ for token in _JINJA_EXPR.sub(" ", match.group(1)).split():
133
+ if "{" in token or "}" in token:
134
+ continue # an unbalanced fragment of an expression
135
+ # Strip Tailwind variant prefixes so `sm:grid-cols-2` is judged
136
+ # on `grid-cols-2` rather than treated as an unknown name.
137
+ bare = token.rsplit(":", 1)[-1]
138
+ if bare in allowed or bare.lstrip("-") in allowed:
139
+ continue
140
+ if bare in emitted:
141
+ reason = (
142
+ "utility class in an app template — use a fjkit layout or component macro "
143
+ "(stack / row / grid / split / card / table …). Utilities that fjkit happens "
144
+ "to emit today are not part of its public vocabulary."
145
+ )
146
+ else:
147
+ reason = (
148
+ "not a fjkit class — it is absent from the shipped stylesheet, so it has no "
149
+ "effect. Check the spelling, or use a component macro."
150
+ )
151
+ violations.append(Violation(path, lineno, token, reason))
152
+
153
+ return violations
154
+
155
+
156
+ def assert_templates_clean(template_dir: Path) -> None:
157
+ """Raise `AssertionError` listing every violation. For an app's own suite.
158
+
159
+ from fjkit.cli.check import assert_templates_clean
160
+
161
+ def test_templates_stay_in_the_vocabulary():
162
+ assert_templates_clean(Path("app/templates"))
163
+ """
164
+ violations = check_templates(template_dir)
165
+ if violations:
166
+ listing = "\n".join(v.render(template_dir) for v in violations)
167
+ raise AssertionError(f"{len(violations)} fjkit vocabulary violation(s):\n{listing}")
168
+
169
+
170
+ def main(template_dir: Path) -> int:
171
+ if not template_dir.is_dir():
172
+ print(f"fjkit check: {template_dir} is not a directory")
173
+ return 2
174
+
175
+ violations = check_templates(template_dir)
176
+ stale = stale_ejects(template_dir)
177
+
178
+ if violations:
179
+ print(f"{len(violations)} violation(s) in {template_dir}:\n")
180
+ print("\n".join(v.render(template_dir) for v in violations))
181
+ else:
182
+ count = len(list(template_dir.rglob("*.html")))
183
+ print(f"{count} template(s) clean — every class is part of the fjkit vocabulary")
184
+
185
+ # Printed either way, and never changes the exit code. Ejecting is a
186
+ # supported escape hatch, so a diverged copy is the feature working, not a
187
+ # fault. Failing a build on it would push people back to editing the kit in
188
+ # place, which eject exists to avoid.
189
+ if stale:
190
+ print(f"\nnote: {len(stale)} ejected component(s) behind the kit:\n")
191
+ print("\n".join(e.render(template_dir) for e in stale))
192
+
193
+ return 1 if violations else 0