fjkit 0.1.0__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 (129) 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 +501 -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 +99 -0
  20. fjkit/icons.py +60 -0
  21. fjkit/messages.py +227 -0
  22. fjkit/mounting.py +72 -0
  23. fjkit/plugins.py +301 -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 +418 -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/idiomorph-ext.min.js +1 -0
  105. fjkit/static/vendor/htmx/json-enc.js +38 -0
  106. fjkit/styles.py +30 -0
  107. fjkit/templates/errors/page.html +99 -0
  108. fjkit/templates/ui/attrs.html +18 -0
  109. fjkit/templates/ui/button.html +64 -0
  110. fjkit/templates/ui/data.html +362 -0
  111. fjkit/templates/ui/disclosure.html +94 -0
  112. fjkit/templates/ui/feedback.html +313 -0
  113. fjkit/templates/ui/form.html +595 -0
  114. fjkit/templates/ui/icon.html +13 -0
  115. fjkit/templates/ui/layout.html +256 -0
  116. fjkit/templates/ui/nav.html +110 -0
  117. fjkit/templates/ui/overlay.html +624 -0
  118. fjkit/templates/ui/shell.html +242 -0
  119. fjkit/templates/ui/sidebar.html +170 -0
  120. fjkit/templates/ui/swap.html +58 -0
  121. fjkit/templates/ui/table.html +427 -0
  122. fjkit/templates/ui/tabs.html +133 -0
  123. fjkit/templating.py +365 -0
  124. fjkit/vendored.py +64 -0
  125. fjkit-0.1.0.dist-info/METADATA +119 -0
  126. fjkit-0.1.0.dist-info/RECORD +129 -0
  127. fjkit-0.1.0.dist-info/WHEEL +4 -0
  128. fjkit-0.1.0.dist-info/entry_points.txt +2 -0
  129. fjkit-0.1.0.dist-info/licenses/LICENSE +21 -0
fjkit/messages.py ADDED
@@ -0,0 +1,227 @@
1
+ """A message shown to the person who made the current request.
2
+
3
+ Three layers deep, and this is the middle one:
4
+
5
+ 1. **The surface** — `ui/feedback.html`'s `toaster()` region and `toast()`
6
+ macro. Already core: `ui/shell.html` renders the region on every page,
7
+ whether or not anything is in it.
8
+ 2. **Getting a message onto this response** — here.
9
+ 3. **Surviving a redirect** — `fjkit.flash`, a plugin rather than core because
10
+ it needs a signing secret.
11
+
12
+ Layer 3 is not a superset of layer 2. `FlashPlugin` writes a signed cookie,
13
+ because a redirect replaces the page and the document that would have shown the
14
+ message is gone before it arrives. The reverse holds too: on a response that is
15
+ not a redirect, a cookie is a round trip for a message about to be rendered
16
+ anyway. So the two are layered rather than merged, and flash queues into this
17
+ module.
18
+
19
+ from fjkit import messages
20
+
21
+ messages.add(request, "Saved", category="success")
22
+
23
+ How it reaches the browser depends on what the response is, and the caller
24
+ never has to know which:
25
+
26
+ full page render -> the shell renders it, straight into the toaster
27
+ htmx swap -> `HX-Trigger`, and the shell's listener raises it
28
+
29
+ `HX-Trigger` rather than markup, because a fragment carries no toaster: an htmx
30
+ swap replaces one region, and the region a toast belongs in is elsewhere on the
31
+ page. It also works on a response htmx will not swap at all — htmx reads
32
+ `HX-Trigger` in `handleAjaxResponse` before it consults `responseHandling` for
33
+ the status code, so a 422 or a 500 can still raise a toast on the page the user
34
+ is looking at. That is the whole delivery mechanism for `fjkit.errors`.
35
+
36
+ A message is consumed by being **iterated**, not by being looked at. See
37
+ `_Queue`.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import json
43
+ from collections.abc import Iterator, Sequence
44
+ from dataclasses import dataclass
45
+ from typing import Any, Literal
46
+
47
+ from fastapi import Request
48
+
49
+ __all__ = [
50
+ "TOAST_EVENT",
51
+ "Category",
52
+ "Message",
53
+ "add",
54
+ "extend",
55
+ "queue",
56
+ "shown",
57
+ "trigger_header",
58
+ ]
59
+
60
+ #: What a message means, not what colour it is. `toast()` maps each to an icon
61
+ #: and a timeout, and `fjkit.css` maps each to a role token — so "error is red"
62
+ #: is decided once, in the stylesheet, and survives a rebrand.
63
+ Category = Literal["info", "success", "warning", "error"]
64
+
65
+ #: The DOM event `HX-Trigger` names, and the one `ui/shell.html` listens for.
66
+ #: Namespaced because it lands on `document.body`, where an app's own events
67
+ #: live too.
68
+ TOAST_EVENT = "fjkit:toast"
69
+
70
+ _SLOT = "fjkit_messages"
71
+ _SHOWN = "fjkit_messages_shown"
72
+
73
+
74
+ @dataclass(frozen=True, slots=True)
75
+ class Message:
76
+ """One message. `category` picks the icon, the timeout and the role colour."""
77
+
78
+ title: str
79
+ text: str | None = None
80
+ category: Category = "info"
81
+
82
+ def as_detail(self) -> dict[str, str]:
83
+ """Return the shape Basecoat's toaster constructor takes.
84
+
85
+ `text` is renamed to `description` here rather than in the dataclass:
86
+ the field is called `text` everywhere in fjkit and in `toast()`, and a
87
+ vendored library's parameter name is not a reason to rename a field
88
+ across the kit's own API.
89
+ """
90
+ detail: dict[str, str] = {"category": self.category, "title": self.title}
91
+ if self.text is not None:
92
+ detail["description"] = self.text
93
+ return detail
94
+
95
+
96
+ def queue(request: Request | None) -> _Queue:
97
+ """Return this request's messages, creating the queue on first use.
98
+
99
+ Lazy rather than built in middleware: core adds no middleware, so an app
100
+ that never raises a message pays nothing — not a stack frame, not an
101
+ attribute.
102
+
103
+ `request` may be `None`. The docs-site builder and the render benchmark
104
+ drive the same templates with `request=None`, and the shell reads this on
105
+ every page; a render with nowhere to put a message has none.
106
+ """
107
+ state = getattr(request, "state", None)
108
+ if state is None:
109
+ return _Queue(None)
110
+ existing = getattr(state, _SLOT, None)
111
+ if existing is None:
112
+ existing = _Queue(request)
113
+ setattr(state, _SLOT, existing)
114
+ return existing
115
+
116
+
117
+ def add(request: Request, title: str, text: str | None = None, *, category: Category = "info") -> None:
118
+ """Show a message on this response. The one-message form of `extend`."""
119
+ queue(request).append(Message(title=title, text=text, category=category))
120
+
121
+
122
+ def extend(request: Request, messages: Sequence[Message]) -> None:
123
+ """Queue several at once. `FlashPlugin` uses it to hand over its cookie."""
124
+ queue(request).extend(messages)
125
+
126
+
127
+ def shown(request: Request) -> bool:
128
+ """Whether this request's messages actually reached the browser.
129
+
130
+ True once they have been iterated into a template or serialised into an
131
+ `HX-Trigger`. `FlashPlugin` reads it to decide whether to clear its cookie:
132
+ a message queued but never rendered has not been shown, and clearing it
133
+ would lose it.
134
+ """
135
+ return bool(getattr(request.state, _SHOWN, False))
136
+
137
+
138
+ def trigger_header(request: Request, existing: str | None = None) -> str | None:
139
+ """The `HX-Trigger` value carrying this request's messages, or `None`.
140
+
141
+ Shaped as `{"fjkit:toast": {"messages": [...]}}`.
142
+
143
+ Merges rather than replaces. A handler may already have set `HX-Trigger`
144
+ for its own event, and dropping it because a toast happened to be queued is
145
+ a bug that surfaces only when both are in play. htmx accepts a bare event
146
+ name as well as a JSON object, so a plain string is promoted to
147
+ `{"<name>": null}` before ours is added.
148
+ """
149
+ pending = getattr(request.state, _SLOT, None)
150
+ if not pending:
151
+ return existing
152
+
153
+ events: dict[str, Any] = {}
154
+ if existing:
155
+ text = existing.strip()
156
+ if text.startswith("{"):
157
+ try:
158
+ events = json.loads(text)
159
+ except ValueError:
160
+ # Not ours to repair, and not ours to discard either: keep it
161
+ # as an event name so the handler's intent survives.
162
+ events = {text: None}
163
+ else:
164
+ events = {name.strip(): None for name in text.split(",") if name.strip()}
165
+
166
+ # `{"messages": [...]}` and not the bare list, because htmx unwraps the two
167
+ # differently: a plain object becomes `event.detail`, while anything else —
168
+ # an array included — is wrapped as `{value: …}`. Sending an object keeps
169
+ # the payload in the shape the listener reads, rather than making the shell
170
+ # depend on a rule inside a vendored file.
171
+ events[TOAST_EVENT] = {"messages": [message.as_detail() for message in pending.drain()]}
172
+ return json.dumps(events, separators=(",", ":"))
173
+
174
+
175
+ class _Queue:
176
+ """The messages, plus the fact of having been delivered.
177
+
178
+ Consumption is **iteration**. `{% for m in fjkit_messages(request) %}` marks
179
+ them shown; `{% if fjkit_messages(request) %}` does not, because asking
180
+ whether there is anything to show is not showing it.
181
+
182
+ That distinction is load-bearing for `FlashPlugin`, which clears its cookie
183
+ only once the message reached a page. A page load fires more requests than
184
+ the page — an htmx poll, a prefetch — and "this request carried the cookie"
185
+ would let any of them eat the message. "A render happened" is not enough
186
+ either: an htmx swap renders a partial, and a partial carries no toaster.
187
+ Django's messages framework draws the line in the same place, for the same
188
+ reason.
189
+ """
190
+
191
+ __slots__ = ("_messages", "_request")
192
+
193
+ def __init__(self, request: Request | None) -> None:
194
+ self._messages: list[Message] = []
195
+ self._request = request
196
+
197
+ def append(self, message: Message) -> None:
198
+ self._messages.append(message)
199
+
200
+ def extend(self, messages: Sequence[Message]) -> None:
201
+ self._messages.extend(messages)
202
+
203
+ def drain(self) -> tuple[Message, ...]:
204
+ """Take the messages for delivery down a channel that is not a template.
205
+
206
+ Emptying the queue stops a message being delivered twice when a
207
+ response both carries an `HX-Trigger` and renders a toaster.
208
+ """
209
+ self._mark()
210
+ taken = tuple(self._messages)
211
+ self._messages.clear()
212
+ return taken
213
+
214
+ def _mark(self) -> None:
215
+ if self._request is not None:
216
+ setattr(self._request.state, _SHOWN, True)
217
+
218
+ def __bool__(self) -> bool:
219
+ return bool(self._messages)
220
+
221
+ def __len__(self) -> int:
222
+ return len(self._messages)
223
+
224
+ def __iter__(self) -> Iterator[Message]:
225
+ if self._messages:
226
+ self._mark()
227
+ return iter(tuple(self._messages))
fjkit/mounting.py ADDED
@@ -0,0 +1,72 @@
1
+ """One call to wire fjkit into a FastAPI app.
2
+
3
+ Two things have to happen before a route can render: the kit's assets need a
4
+ URL, and the Jinja Environment needs building. Both read the same `FjkitConfig`
5
+ and neither is useful without the other, so they are one call rather than two
6
+ an app must keep in step.
7
+
8
+ The Environment is built here, at app construction, rather than in lifespan.
9
+ It is per-process either way — every worker constructs the app — and building
10
+ it here means a `TestClient` used without its context manager still has
11
+ templates, which is the failure this consolidation removes.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from fastapi import FastAPI
17
+ from fastapi.staticfiles import StaticFiles
18
+
19
+ from fjkit.config import STATIC_DIR, FjkitConfig
20
+ from fjkit.errors import install_error_handlers
21
+ from fjkit.plugins import install_plugins
22
+ from fjkit.styles import resolve_style
23
+ from fjkit.templating import Templates
24
+
25
+ __all__ = ["mount_fjkit"]
26
+
27
+
28
+ def mount_fjkit(app: FastAPI, config: FjkitConfig | None = None) -> Templates:
29
+ """Mount the kit's static assets and build the Environment. Call once.
30
+
31
+ Serves the stylesheet and the vendored htmx/Basecoat JS out of the
32
+ installed package at `config.static_url`, then puts the `Templates` on
33
+ `app.state.templates`, where `@render` looks for it.
34
+
35
+ Returns the same `Templates` it stored, for a caller that renders outside a
36
+ request — a build script, a test.
37
+ """
38
+ config = config or FjkitConfig()
39
+
40
+ # Check the resolved pack, not just any pack: a wheel built before this pack
41
+ # existed would otherwise pass the check and 404 on the page. Resolving here
42
+ # as well as in the Environment is deliberate — an app that mounts but never
43
+ # renders should still fail at startup rather than on its first request.
44
+ style = resolve_style(config.style)
45
+ stylesheet = STATIC_DIR / "dist" / f"fjkit-{style}.css"
46
+ if not stylesheet.exists():
47
+ raise RuntimeError(
48
+ f"fjkit's stylesheet for style={style!r} is missing from the "
49
+ f"installed package ({stylesheet}).\n"
50
+ "A released wheel ships all eight style packs. If you are working on "
51
+ "fjkit itself, build them once with: uv run fjkit build-css"
52
+ )
53
+
54
+ app.mount(
55
+ config.static_url,
56
+ StaticFiles(directory=STATIC_DIR),
57
+ name="fjkit_static",
58
+ )
59
+
60
+ # Before the plugins, because Starlette keys exception handlers by class and
61
+ # the last registration wins: going first lets a plugin — or the app —
62
+ # replace the kit's answer to a rejected form rather than be shadowed by it.
63
+ install_error_handlers(app, config)
64
+
65
+ # Before the Environment: a plugin's `mount` may refuse a configuration
66
+ # outright, and failing there is cheaper and clearer than failing after
67
+ # every template in the app has been compiled.
68
+ install_plugins(app, config)
69
+
70
+ templates = Templates.create(config)
71
+ app.state.templates = templates
72
+ return templates
fjkit/plugins.py ADDED
@@ -0,0 +1,301 @@
1
+ """The extension seam — one object that contributes to the app and to Jinja.
2
+
3
+ A plugin exists because some features need more than a macro: a middleware, an
4
+ exception handler, a value in every template's context. Wiring that by hand
5
+ means an app keeps four things in the right order and in step, which is the
6
+ failure `mount_fjkit()` removes one level down.
7
+
8
+ Two contribution points, because the kit has two moments:
9
+
10
+ * `mount(AppSetup)` runs when the app is constructed — middleware, exception
11
+ handlers, routes, static files.
12
+ * `extend(EnvSetup)` runs when the Environment is built — template directories,
13
+ globals, filters, and the per-request context.
14
+
15
+ Both are optional. A plugin that only puts a value in every template writes
16
+ only `extend`. Hiding the split would be friendlier right up until someone's
17
+ `mount` silently never ran.
18
+
19
+ A plugin that reads a sibling declares it — `uses = ("flash",)` — and reaches
20
+ it only through `setup.plugin("flash")`. The declaration is checked the way
21
+ `provides=` is: a lookup the plugin never declared, and a sibling listed after
22
+ the plugin that uses it, are both startup errors naming the plugin. The host
23
+ never reorders. `FjkitConfig.plugins` is the order middleware wraps in, and that
24
+ stays the app's to decide; what the host adds is a check that the order the
25
+ app wrote is one the plugins can live with.
26
+
27
+ A plugin deliberately **cannot** inject markup into the shell. Such a hook
28
+ would let any plugin put a `<script>` on every page, and both "no build step in
29
+ the app" and the closed vocabulary would leave through it.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import warnings
35
+ from collections.abc import Callable, Mapping, Sequence
36
+ from dataclasses import dataclass, field
37
+ from pathlib import Path
38
+ from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
39
+
40
+ from fastapi import APIRouter, FastAPI, Request
41
+ from fastapi.staticfiles import StaticFiles
42
+
43
+ if TYPE_CHECKING:
44
+ from fjkit.config import FjkitConfig
45
+
46
+ __all__ = [
47
+ "AppSetup",
48
+ "ContextProcessor",
49
+ "EnvSetup",
50
+ "Plugin",
51
+ "PluginWarning",
52
+ "collect_env",
53
+ "install_plugins",
54
+ ]
55
+
56
+ #: Called once per render with the live request, returning values to merge into
57
+ #: the template context. **Synchronous**: it runs inside `Templates.page()`,
58
+ #: which a `def` handler reaches from the threadpool. A plugin that needs I/O
59
+ #: does it in middleware and leaves the result on `request.state` for the
60
+ #: processor to read, which is what the auth plugin does.
61
+ ContextProcessor = Callable[[Request], Mapping[str, object]]
62
+
63
+
64
+ class PluginWarning(UserWarning):
65
+ """A plugin's install-time check found a configuration that fails later.
66
+
67
+ Its own category, so an app can turn it into an error:
68
+ `warnings.simplefilter("error", PluginWarning)`.
69
+ """
70
+
71
+
72
+ @runtime_checkable
73
+ class Plugin(Protocol):
74
+ """What `FjkitConfig.plugins` accepts.
75
+
76
+ `name` identifies the plugin rather than labelling it: it detects duplicate
77
+ registration, names the `request.state` field the plugin owns, and appears
78
+ in the error when two plugins claim one global or context key.
79
+
80
+ `uses` names the siblings this plugin may read through `setup.plugin()`.
81
+ Every entry is optional — a name nobody registered comes back as `None` —
82
+ but a registered one must be listed before its user. Declaring rather than
83
+ scanning is what lets the dependency be read off the class and checked at
84
+ startup, instead of found by reading the body of `mount`.
85
+ """
86
+
87
+ name: str
88
+ uses: tuple[str, ...] = ()
89
+
90
+ def mount(self, setup: AppSetup) -> None:
91
+ """App construction. Optional."""
92
+
93
+ def extend(self, setup: EnvSetup) -> None:
94
+ """Environment build. Optional."""
95
+
96
+
97
+ class AppSetup:
98
+ """What a plugin may do to the app. Handed to `Plugin.mount`.
99
+
100
+ A pass-through to FastAPI rather than a wrapper with opinions, except that
101
+ everything it does is attributed to the plugin, so a misbehaving one is
102
+ named in the traceback rather than found by elimination. The app itself is
103
+ not exposed: what a plugin can do is this list, and a plugin that needs
104
+ more asks for a method here rather than reaching around it.
105
+ """
106
+
107
+ __slots__ = ("_app", "config", "_name", "_plugins")
108
+
109
+ def __init__(self, app: FastAPI, config: FjkitConfig, name: str, plugins: Mapping[str, Plugin]) -> None:
110
+ self._app = app
111
+ self.config = config
112
+ self._name = name
113
+ self._plugins = plugins
114
+
115
+ def add_middleware(self, cls: type, /, **options: Any) -> None:
116
+ """Starlette runs middleware in reverse registration order, so a plugin
117
+ listed later in `FjkitConfig.plugins` wraps the earlier ones."""
118
+ self._app.add_middleware(cls, **options)
119
+
120
+ def add_exception_handler(self, exc: type[Exception] | int, handler: Callable) -> None:
121
+ self._app.add_exception_handler(exc, handler)
122
+
123
+ def include_router(self, router: APIRouter) -> None:
124
+ """Add the plugin's routes, warning first if their prefix is already
125
+ routed.
126
+
127
+ Starlette matches the first route that fits, so a plugin mounted under
128
+ a path the app or FastAPI already claimed — `/docs`, say — would never
129
+ render and never say why. Every plugin with a router needs this check
130
+ and none of them should have to remember it.
131
+ """
132
+ prefix = router.prefix
133
+ if prefix:
134
+ taken = next((r for r in self._app.routes if getattr(r, "path", None) == prefix), None)
135
+ if taken is not None:
136
+ self.warn(
137
+ f"{prefix} is already routed by {getattr(taken, 'name', taken)!r}. Starlette matches "
138
+ "the first route that fits, so the routes this plugin adds there will never be "
139
+ "reached. Pass a different `url=`, or remove the route that holds it."
140
+ )
141
+ self._app.include_router(router)
142
+
143
+ def mount_static(self, url: str, directory: Path) -> None:
144
+ self._app.mount(url, StaticFiles(directory=directory), name=f"fjkit_{self._name}_static")
145
+
146
+ def plugin(self, name: str) -> Plugin | None:
147
+ """A sibling this plugin declared in `uses`, or `None` if the app did
148
+ not register one."""
149
+ return _lookup(self._plugins, self._name, name)
150
+
151
+ def warn(self, message: str) -> None:
152
+ """Report at startup a configuration that misbehaves later.
153
+
154
+ For the combinations only the plugin recognises — an in-memory store
155
+ under a production config, a token source that cannot refresh. Each
156
+ surfaces days later on another machine.
157
+ """
158
+ warnings.warn(f"[fjkit:{self._name}] {message}", PluginWarning, stacklevel=2)
159
+
160
+
161
+ class EnvSetup:
162
+ """What a plugin may contribute to Jinja. Handed to `Plugin.extend`.
163
+
164
+ Collects rather than mutates: the Environment does not exist yet, because
165
+ template directories have to be in the search path before it is built.
166
+ """
167
+
168
+ __slots__ = ("config", "_current", "_owners", "_plugins", "contributions")
169
+
170
+ def __init__(self, config: FjkitConfig, plugins: Mapping[str, Plugin]) -> None:
171
+ self.config = config
172
+ self.contributions = EnvContributions()
173
+ self._current = ""
174
+ self._plugins = plugins
175
+ #: key -> the plugin that claimed it, for the collision message.
176
+ self._owners: dict[str, str] = {}
177
+
178
+ def add_template_dir(self, directory: Path) -> None:
179
+ """Add a template directory, searched after the app's and before the
180
+ kit's.
181
+
182
+ After the app's, so a plugin can never shadow a file the app wrote —
183
+ that would break `fjkit eject` (CHARTER A5) from a direction the app
184
+ cannot see. Before the kit's, so a plugin can replace a kit macro.
185
+ """
186
+ self.contributions.template_dirs.append(directory)
187
+
188
+ def add_global(self, name: str, value: object) -> None:
189
+ self._claim(f"global {name!r}", name)
190
+ self.contributions.globals[name] = value
191
+
192
+ def add_filter(self, name: str, fn: Callable[..., Any]) -> None:
193
+ self._claim(f"filter {name!r}", f"filter:{name}")
194
+ self.contributions.filters[name] = fn
195
+
196
+ def add_context_processor(self, fn: ContextProcessor, *, provides: Sequence[str]) -> None:
197
+ """Merge values into every template's context, once per render.
198
+
199
+ `provides` lists the keys the processor returns. Required rather than
200
+ inferred: without it, two plugins fighting over `user` show up only by
201
+ rendering a page and noticing. With it, the clash is a startup error
202
+ naming both plugins.
203
+ """
204
+ for key in provides:
205
+ self._claim(f"context key {key!r}", key)
206
+ self.contributions.processors.append((self._current, tuple(provides), fn))
207
+
208
+ def plugin(self, name: str) -> Plugin | None:
209
+ """A sibling this plugin declared in `uses`, or `None` if the app did
210
+ not register one."""
211
+ return _lookup(self._plugins, self._current, name)
212
+
213
+ def _claim(self, what: str, key: str) -> None:
214
+ owner = self._owners.get(key)
215
+ if owner is not None:
216
+ raise ValueError(
217
+ f"fjkit plugins {owner!r} and {self._current!r} both provide {what}. "
218
+ "Rename one, or drop one from FjkitConfig.plugins."
219
+ )
220
+ self._owners[key] = self._current
221
+
222
+
223
+ @dataclass(slots=True)
224
+ class EnvContributions:
225
+ """Everything the plugins added, ready for `build_environment` to apply."""
226
+
227
+ template_dirs: list[Path] = field(default_factory=list)
228
+ globals: dict[str, object] = field(default_factory=dict)
229
+ filters: dict[str, Callable[..., Any]] = field(default_factory=dict)
230
+ #: (plugin name, declared keys, callable) — the first two exist only to name
231
+ #: a processor that returns a key it never declared.
232
+ processors: list[tuple[str, tuple[str, ...], ContextProcessor]] = field(default_factory=list)
233
+
234
+
235
+ def collect_env(config: FjkitConfig) -> EnvContributions:
236
+ """Run every plugin's `extend`, in `FjkitConfig.plugins` order."""
237
+ registry = _ordered(config)
238
+ setup = EnvSetup(config, registry)
239
+ for plugin in registry.values():
240
+ setup._current = plugin.name
241
+ extend = getattr(plugin, "extend", None)
242
+ if extend is not None:
243
+ extend(setup)
244
+ return setup.contributions
245
+
246
+
247
+ def install_plugins(app: FastAPI, config: FjkitConfig) -> None:
248
+ """Run every plugin's `mount`, in `FjkitConfig.plugins` order."""
249
+ registry = _ordered(config)
250
+ for plugin in registry.values():
251
+ mount = getattr(plugin, "mount", None)
252
+ if mount is not None:
253
+ mount(AppSetup(app, config, plugin.name, registry))
254
+
255
+
256
+ def _lookup(plugins: Mapping[str, Plugin], current: str, name: str) -> Plugin | None:
257
+ """`setup.plugin()` for both setups: the declaration is the permission.
258
+
259
+ Refusing an undeclared name is what keeps `uses` honest. Without the check
260
+ it would be documentation, and the one plugin that forgot it would be the
261
+ one whose dependency nobody can see.
262
+ """
263
+ declared = getattr(plugins[current], "uses", ())
264
+ if name not in declared:
265
+ raise ValueError(
266
+ f"fjkit plugin {current!r} looked up {name!r} without declaring it. "
267
+ f"Add it to `uses`: uses = {tuple(declared) + (name,)!r}."
268
+ )
269
+ return plugins.get(name)
270
+
271
+
272
+ def _ordered(config: FjkitConfig) -> dict[str, Plugin]:
273
+ """The configured plugins by name, in `FjkitConfig.plugins` order, with
274
+ duplicate names and unusable orders rejected.
275
+
276
+ Two plugins under one name would collide on `request.state.<name>` and make
277
+ every later error message ambiguous, so the duplicate is refused at startup
278
+ rather than resolved by last-one-wins.
279
+
280
+ A plugin listed before one it `uses` is refused rather than moved: its
281
+ `mount` would run before the sibling's, and reordering silently would
282
+ change which middleware wraps which — an order the app wrote on purpose.
283
+ """
284
+ registry: dict[str, Plugin] = {}
285
+ for plugin in config.plugins:
286
+ name = getattr(plugin, "name", None)
287
+ if not name:
288
+ raise ValueError(f"fjkit plugin {plugin!r} has no `name`.")
289
+ if name in registry:
290
+ raise ValueError(f"fjkit plugin {name!r} is registered twice in FjkitConfig.plugins.")
291
+ registry[name] = plugin
292
+
293
+ position = {name: index for index, name in enumerate(registry)}
294
+ for name, plugin in registry.items():
295
+ for used in getattr(plugin, "uses", ()):
296
+ if used in position and position[used] > position[name]:
297
+ raise ValueError(
298
+ f"fjkit plugin {name!r} uses {used!r}, which is listed after it. "
299
+ f"List {used!r} before {name!r} in FjkitConfig.plugins."
300
+ )
301
+ return registry
fjkit/py.typed ADDED
File without changes