md2site-cli 0.2.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.
- md2site/__init__.py +7 -0
- md2site/__main__.py +10 -0
- md2site/assets.py +211 -0
- md2site/build.py +152 -0
- md2site/cli.py +354 -0
- md2site/config.py +444 -0
- md2site/diagnostics.py +167 -0
- md2site/frontmatter.py +245 -0
- md2site/hook.py +129 -0
- md2site/init_cmd.py +153 -0
- md2site/links.py +1403 -0
- md2site/markdown.py +408 -0
- md2site/model.py +80 -0
- md2site/nav.py +286 -0
- md2site/paths.py +130 -0
- md2site/render.py +306 -0
- md2site/scanner.py +273 -0
- md2site/search.py +96 -0
- md2site/server.py +267 -0
- md2site/skill/SKILL.md +50 -0
- md2site/slug.py +40 -0
- md2site/static/css/md2site.css +974 -0
- md2site/static/js/app.js +301 -0
- md2site/static/js/mermaid-init.js +93 -0
- md2site/static/js/search.js +577 -0
- md2site/static/js/theme-init.js +24 -0
- md2site/static/vendor/mermaid.min.js +4329 -0
- md2site/templates/base.html +82 -0
- md2site/templates/landing.html +30 -0
- md2site/templates/page.html +13 -0
- md2site/templates/partials/breadcrumbs.html +15 -0
- md2site/templates/partials/nav.html +37 -0
- md2site/templates/partials/prevnext.html +20 -0
- md2site/templates/partials/toc.html +14 -0
- md2site/titles.py +96 -0
- md2site/watcher.py +447 -0
- md2site/wikilinks.py +314 -0
- md2site_cli-0.2.0.dist-info/METADATA +280 -0
- md2site_cli-0.2.0.dist-info/RECORD +43 -0
- md2site_cli-0.2.0.dist-info/WHEEL +4 -0
- md2site_cli-0.2.0.dist-info/entry_points.txt +3 -0
- md2site_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
- md2site_cli-0.2.0.dist-info/licenses/THIRD_PARTY_LICENSES.md +36 -0
md2site/server.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""Local HTTP preview server with Server-Sent Events live reload."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import mimetypes
|
|
6
|
+
import queue
|
|
7
|
+
import threading
|
|
8
|
+
from http import HTTPStatus
|
|
9
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
from urllib.parse import unquote, urlsplit
|
|
13
|
+
|
|
14
|
+
SSE_ENDPOINT = "/__md2site/events"
|
|
15
|
+
|
|
16
|
+
_SSE_RELOAD_SNIPPET = (
|
|
17
|
+
"<script>\n"
|
|
18
|
+
"(function () {\n"
|
|
19
|
+
f' var es = new EventSource("{SSE_ENDPOINT}");\n'
|
|
20
|
+
' es.addEventListener("reload", function () { window.location.reload(); });\n'
|
|
21
|
+
"})();\n"
|
|
22
|
+
"</script>\n"
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SSEBroadcaster:
|
|
27
|
+
"""Thread-safe hub managing active SSE client queues."""
|
|
28
|
+
|
|
29
|
+
def __init__(self) -> None:
|
|
30
|
+
self._lock = threading.Lock()
|
|
31
|
+
self._clients: set[queue.Queue[str | None]] = set()
|
|
32
|
+
|
|
33
|
+
def subscribe(self) -> queue.Queue[str | None]:
|
|
34
|
+
q: queue.Queue[str | None] = queue.Queue()
|
|
35
|
+
with self._lock:
|
|
36
|
+
self._clients.add(q)
|
|
37
|
+
return q
|
|
38
|
+
|
|
39
|
+
def unsubscribe(self, q: queue.Queue[str | None]) -> None:
|
|
40
|
+
with self._lock:
|
|
41
|
+
self._clients.discard(q)
|
|
42
|
+
|
|
43
|
+
def broadcast(self, event: str = "reload") -> None:
|
|
44
|
+
with self._lock:
|
|
45
|
+
clients = list(self._clients)
|
|
46
|
+
for q in clients:
|
|
47
|
+
q.put(event)
|
|
48
|
+
|
|
49
|
+
def close_all(self) -> None:
|
|
50
|
+
with self._lock:
|
|
51
|
+
clients = list(self._clients)
|
|
52
|
+
for q in clients:
|
|
53
|
+
q.put(None)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def inject_live_reload(html_text: str) -> str:
|
|
57
|
+
"""Inject the SSE live-reload script into an HTML response string."""
|
|
58
|
+
lower = html_text.lower()
|
|
59
|
+
idx = lower.rfind("</body>")
|
|
60
|
+
if idx != -1:
|
|
61
|
+
return f"{html_text[:idx]}{_SSE_RELOAD_SNIPPET}{html_text[idx:]}"
|
|
62
|
+
return f"{html_text}{_SSE_RELOAD_SNIPPET}"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _guess_content_type(path: Path) -> str:
|
|
66
|
+
ext = path.suffix.lower()
|
|
67
|
+
if ext in (".html", ".htm"):
|
|
68
|
+
return "text/html; charset=utf-8"
|
|
69
|
+
if ext == ".css":
|
|
70
|
+
return "text/css; charset=utf-8"
|
|
71
|
+
if ext in (".js", ".mjs"):
|
|
72
|
+
return "application/javascript; charset=utf-8"
|
|
73
|
+
if ext == ".svg":
|
|
74
|
+
return "image/svg+xml"
|
|
75
|
+
if ext == ".json":
|
|
76
|
+
return "application/json; charset=utf-8"
|
|
77
|
+
ctype, _ = mimetypes.guess_type(str(path))
|
|
78
|
+
return ctype or "application/octet-stream"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _resolve_request_path(output_dir: Path, url_path: str) -> tuple[Path | None, HTTPStatus]:
|
|
82
|
+
"""Safely resolve a URL path strictly inside ``output_dir``."""
|
|
83
|
+
raw = unquote(url_path)
|
|
84
|
+
if "\x00" in raw or "\\" in raw:
|
|
85
|
+
return None, HTTPStatus.FORBIDDEN
|
|
86
|
+
|
|
87
|
+
parts = [part for part in raw.split("/") if part]
|
|
88
|
+
if any(part in (".", "..") for part in parts):
|
|
89
|
+
return None, HTTPStatus.FORBIDDEN
|
|
90
|
+
|
|
91
|
+
root_resolved = output_dir.resolve()
|
|
92
|
+
target = root_resolved
|
|
93
|
+
for part in parts:
|
|
94
|
+
target = target / part
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
resolved = target.resolve()
|
|
98
|
+
resolved.relative_to(root_resolved)
|
|
99
|
+
except (OSError, ValueError):
|
|
100
|
+
return None, HTTPStatus.FORBIDDEN
|
|
101
|
+
|
|
102
|
+
if resolved.is_dir():
|
|
103
|
+
resolved = resolved / "index.html"
|
|
104
|
+
try:
|
|
105
|
+
resolved = resolved.resolve()
|
|
106
|
+
resolved.relative_to(root_resolved)
|
|
107
|
+
except (OSError, ValueError):
|
|
108
|
+
return None, HTTPStatus.FORBIDDEN
|
|
109
|
+
|
|
110
|
+
if not resolved.is_file():
|
|
111
|
+
return None, HTTPStatus.NOT_FOUND
|
|
112
|
+
|
|
113
|
+
return resolved, HTTPStatus.OK
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class LiveReloadHTTPServer(ThreadingHTTPServer):
|
|
117
|
+
"""ThreadingHTTPServer bound to an output directory with SSE live reload."""
|
|
118
|
+
|
|
119
|
+
daemon_threads = True
|
|
120
|
+
allow_reuse_address = True
|
|
121
|
+
|
|
122
|
+
def __init__(
|
|
123
|
+
self,
|
|
124
|
+
server_address: tuple[str, int],
|
|
125
|
+
output_dir: Path,
|
|
126
|
+
broadcaster: SSEBroadcaster | None = None,
|
|
127
|
+
) -> None:
|
|
128
|
+
self.output_dir = output_dir.resolve()
|
|
129
|
+
self.broadcaster = broadcaster or SSEBroadcaster()
|
|
130
|
+
self.keepalive_interval_s = 5.0
|
|
131
|
+
super().__init__(server_address, _PreviewRequestHandler)
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def url(self) -> str:
|
|
135
|
+
host, port = self.server_address[:2]
|
|
136
|
+
return f"http://{host}:{port}/index.html"
|
|
137
|
+
|
|
138
|
+
def shutdown(self) -> None:
|
|
139
|
+
self.broadcaster.close_all()
|
|
140
|
+
super().shutdown()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class _PreviewRequestHandler(BaseHTTPRequestHandler):
|
|
144
|
+
"""HTTP handler serving static files and ``/__md2site/events`` SSE stream."""
|
|
145
|
+
|
|
146
|
+
protocol_version = "HTTP/1.1"
|
|
147
|
+
|
|
148
|
+
def log_message(self, format: str, *args: object) -> None: # noqa: A002
|
|
149
|
+
return
|
|
150
|
+
|
|
151
|
+
def do_HEAD(self) -> None:
|
|
152
|
+
self._serve(head_only=True)
|
|
153
|
+
|
|
154
|
+
def do_GET(self) -> None:
|
|
155
|
+
self._serve(head_only=False)
|
|
156
|
+
|
|
157
|
+
def _serve(self, *, head_only: bool) -> None:
|
|
158
|
+
srv = self.server
|
|
159
|
+
assert isinstance(srv, LiveReloadHTTPServer)
|
|
160
|
+
url_path = urlsplit(self.path).path
|
|
161
|
+
|
|
162
|
+
if url_path == SSE_ENDPOINT:
|
|
163
|
+
self._serve_sse(srv, head_only=head_only)
|
|
164
|
+
return
|
|
165
|
+
|
|
166
|
+
resolved, status = _resolve_request_path(srv.output_dir, url_path)
|
|
167
|
+
if resolved is None:
|
|
168
|
+
body = f"{status.value} {status.phrase}\n".encode()
|
|
169
|
+
self.send_response(status)
|
|
170
|
+
self.send_header("Content-Type", "text/plain; charset=utf-8")
|
|
171
|
+
self.send_header("Content-Length", str(len(body)))
|
|
172
|
+
self.send_header("Cache-Control", "no-store")
|
|
173
|
+
self.end_headers()
|
|
174
|
+
if not head_only:
|
|
175
|
+
self.wfile.write(body)
|
|
176
|
+
return
|
|
177
|
+
|
|
178
|
+
ctype = _guess_content_type(resolved)
|
|
179
|
+
data = resolved.read_bytes()
|
|
180
|
+
if resolved.suffix.lower() in (".html", ".htm"):
|
|
181
|
+
html_str = inject_live_reload(data.decode("utf-8", errors="replace"))
|
|
182
|
+
data = html_str.encode("utf-8")
|
|
183
|
+
|
|
184
|
+
self.send_response(HTTPStatus.OK)
|
|
185
|
+
self.send_header("Content-Type", ctype)
|
|
186
|
+
self.send_header("Content-Length", str(len(data)))
|
|
187
|
+
self.send_header("Cache-Control", "no-store")
|
|
188
|
+
self.end_headers()
|
|
189
|
+
if not head_only:
|
|
190
|
+
self.wfile.write(data)
|
|
191
|
+
|
|
192
|
+
def _serve_sse(self, srv: LiveReloadHTTPServer, *, head_only: bool) -> None:
|
|
193
|
+
self.send_response(HTTPStatus.OK)
|
|
194
|
+
self.send_header("Content-Type", "text/event-stream; charset=utf-8")
|
|
195
|
+
self.send_header("Cache-Control", "no-store")
|
|
196
|
+
self.send_header("Connection", "keep-alive")
|
|
197
|
+
self.end_headers()
|
|
198
|
+
if head_only:
|
|
199
|
+
return
|
|
200
|
+
|
|
201
|
+
q = srv.broadcaster.subscribe()
|
|
202
|
+
try:
|
|
203
|
+
self.wfile.write(b": connected\n\n")
|
|
204
|
+
self.wfile.flush()
|
|
205
|
+
while True:
|
|
206
|
+
try:
|
|
207
|
+
msg = q.get(timeout=srv.keepalive_interval_s)
|
|
208
|
+
except queue.Empty:
|
|
209
|
+
self.wfile.write(b": keepalive\n\n")
|
|
210
|
+
self.wfile.flush()
|
|
211
|
+
continue
|
|
212
|
+
if msg is None:
|
|
213
|
+
break
|
|
214
|
+
payload = f"event: {msg}\ndata: {msg}\n\n".encode()
|
|
215
|
+
self.wfile.write(payload)
|
|
216
|
+
self.wfile.flush()
|
|
217
|
+
except (BrokenPipeError, ConnectionResetError, OSError):
|
|
218
|
+
pass
|
|
219
|
+
finally:
|
|
220
|
+
srv.broadcaster.unsubscribe(q)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def start_server(
|
|
224
|
+
output_dir: Path,
|
|
225
|
+
*,
|
|
226
|
+
host: str = "127.0.0.1",
|
|
227
|
+
port: int = 8000,
|
|
228
|
+
) -> tuple[LiveReloadHTTPServer, threading.Thread]:
|
|
229
|
+
"""Bind and start ``LiveReloadHTTPServer`` on a daemon thread.
|
|
230
|
+
|
|
231
|
+
If ``port`` is non-zero and busy, retries up to 20 subsequent ports.
|
|
232
|
+
"""
|
|
233
|
+
attempts = [0] if port == 0 else [port + offset for offset in range(21)]
|
|
234
|
+
last_exc: OSError | None = None
|
|
235
|
+
server: LiveReloadHTTPServer | None = None
|
|
236
|
+
|
|
237
|
+
for candidate in attempts:
|
|
238
|
+
try:
|
|
239
|
+
server = LiveReloadHTTPServer((host, candidate), output_dir)
|
|
240
|
+
break
|
|
241
|
+
except OSError as exc:
|
|
242
|
+
last_exc = exc
|
|
243
|
+
|
|
244
|
+
if server is None:
|
|
245
|
+
assert last_exc is not None
|
|
246
|
+
raise last_exc
|
|
247
|
+
|
|
248
|
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
249
|
+
thread.start()
|
|
250
|
+
return server, thread
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def stop_server(server: LiveReloadHTTPServer, thread: threading.Thread | None = None) -> None:
|
|
254
|
+
"""Gracefully shut down a running ``LiveReloadHTTPServer``."""
|
|
255
|
+
server.shutdown()
|
|
256
|
+
server.server_close()
|
|
257
|
+
if thread is not None:
|
|
258
|
+
thread.join(timeout=2.0)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def first_page_url(server: LiveReloadHTTPServer, first_out_rel: Any = None) -> str:
|
|
262
|
+
"""Return the local HTTP URL for the first page (defaulting to ``index.html``)."""
|
|
263
|
+
host, port = server.server_address[:2]
|
|
264
|
+
if first_out_rel is not None:
|
|
265
|
+
rel_str = str(first_out_rel).lstrip("/")
|
|
266
|
+
return f"http://{host}:{port}/{rel_str}"
|
|
267
|
+
return f"http://{host}:{port}/index.html"
|
md2site/skill/SKILL.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: md2site
|
|
3
|
+
description: "Use when creating or editing Markdown files in a repository that contains md2site.config.json or a docs/ directory, or when the user asks to check, build, or preview documentation as static HTML."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# md2site Agent Skill
|
|
7
|
+
|
|
8
|
+
Use `md2site` to keep Markdown as the single source of truth, catch broken
|
|
9
|
+
references immediately, and emit an offline `file://`-ready HTML site.
|
|
10
|
+
|
|
11
|
+
## Workflow
|
|
12
|
+
|
|
13
|
+
1. Create or edit `.md` / `.markdown` source files (never hand-edit `_site/`).
|
|
14
|
+
2. Run `md2site check --json` (or `md2site check <docs_dir> --json`).
|
|
15
|
+
3. Fix every reported diagnostic using `file`, `line`, `code`, and `suggestion`.
|
|
16
|
+
4. Run `md2site build` to regenerate `_site/`.
|
|
17
|
+
5. Never commit `_site/` (keep it in `.gitignore`).
|
|
18
|
+
|
|
19
|
+
## Writing Link-Safe Docs
|
|
20
|
+
|
|
21
|
+
- **Page links:** use relative `.md` links (`[Setup](./setup.md#install)`, `[API](../api/tools.md)`).
|
|
22
|
+
- **Wikilinks:** use `[[Note]]`, `[[Note#Heading|Label]]`, or `![[img.png]]` only if the repo already uses wikilinks.
|
|
23
|
+
- **Repo source files:** link with relative paths and optional line refs (`[server](../src/server.py#L42)` or `:42`).
|
|
24
|
+
- **Images & assets:** store next to the doc or under `docs/assets/`; reference with relative paths.
|
|
25
|
+
- **Diagrams & alerts:** use fenced ```` ```mermaid ```` blocks and GitHub alerts (`> [!NOTE]`, `> [!TIP]`, `> [!IMPORTANT]`, `> [!WARNING]`, `> [!CAUTION]`).
|
|
26
|
+
- **Front matter:** optional YAML subset keys `title`, `order`, `hidden`, `draft`, `aliases`, `tags`, `search`.
|
|
27
|
+
|
|
28
|
+
## Diagnostics Cheat-Sheet
|
|
29
|
+
|
|
30
|
+
| Code | Meaning | Usual fix |
|
|
31
|
+
|---|---|---|
|
|
32
|
+
| `MD2S001` | Broken Markdown link | Fix relative `.md` path (check `suggestion`) |
|
|
33
|
+
| `MD2S002` | Broken file/asset link | Fix asset/source path or add missing file |
|
|
34
|
+
| `MD2S003` | Ambiguous wikilink | Qualify with folder path (`[[folder/Note]]`) |
|
|
35
|
+
| `MD2S004` | Unresolved wikilink | Create target note or fix spelling/alias |
|
|
36
|
+
| `MD2S005` | Broken `#anchor` | Match heading slug (check `suggestion`) |
|
|
37
|
+
| `MD2S006` | Case mismatch | Match exact filename casing on disk |
|
|
38
|
+
| `MD2S007` | Target escapes `repo_root` | Keep links inside repo or set `repo_root` |
|
|
39
|
+
| `MD2S008` | Output path collision | Rename colliding file or `index.md`/`README.md` |
|
|
40
|
+
| `MD2S009` | Bad front matter / UTF-8 | Fix YAML subset syntax (`key: value`, lists) |
|
|
41
|
+
| `MD2S010` | Missing `remote_repo_url` | Set `remote_repo_url` or use `relative` mode |
|
|
42
|
+
|
|
43
|
+
## Commands
|
|
44
|
+
|
|
45
|
+
- `md2site init [PATH] [--with-skill]` — create config, `custom.css`, `_site/`, `.gitignore` entry
|
|
46
|
+
- `md2site check [PATH] --json` — validate all links and anchors without writing files
|
|
47
|
+
- `md2site build [PATH] [--strict] [--drafts]` — build static HTML site into `_site/`
|
|
48
|
+
- `md2site watch [PATH] [--open]` — serve locally with live reload on edits
|
|
49
|
+
- `md2site hook` — post-edit agent hook reading JSON on stdin (exit `2` + stderr on diagnostics)
|
|
50
|
+
- Zero-install (once published): `uvx --from md2site-cli md2site check --json`
|
md2site/slug.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""GitHub-compatible heading anchor slugification utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import unicodedata
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _base_slug(text: str) -> str:
|
|
9
|
+
"""Convert heading text into a base GitHub-style anchor slug."""
|
|
10
|
+
normalized = text.strip().lower().replace("\t", " ")
|
|
11
|
+
chars: list[str] = []
|
|
12
|
+
for ch in normalized:
|
|
13
|
+
if ch in ("-", "_", " "):
|
|
14
|
+
chars.append(ch)
|
|
15
|
+
continue
|
|
16
|
+
cat = unicodedata.category(ch)
|
|
17
|
+
if cat and cat[0] in ("L", "N", "M"):
|
|
18
|
+
chars.append(ch)
|
|
19
|
+
slug = "".join(chars).strip().replace(" ", "-")
|
|
20
|
+
return slug or "section"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Slugger:
|
|
24
|
+
"""Stateful per-document slug generator ensuring unique heading IDs."""
|
|
25
|
+
|
|
26
|
+
def __init__(self) -> None:
|
|
27
|
+
self._used: set[str] = set()
|
|
28
|
+
self._counts: dict[str, int] = {}
|
|
29
|
+
|
|
30
|
+
def slug(self, text: str) -> str:
|
|
31
|
+
"""Generate a unique GitHub-compatible slug for ``text``."""
|
|
32
|
+
base = _base_slug(text)
|
|
33
|
+
count = self._counts.get(base, 0)
|
|
34
|
+
candidate = base if count == 0 else f"{base}-{count}"
|
|
35
|
+
while candidate in self._used:
|
|
36
|
+
count += 1
|
|
37
|
+
candidate = f"{base}-{count}"
|
|
38
|
+
self._counts[base] = count + 1
|
|
39
|
+
self._used.add(candidate)
|
|
40
|
+
return candidate
|