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/wikilinks.py ADDED
@@ -0,0 +1,314 @@
1
+ """Wikilink parsing and candidate resolution for md2site."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from collections.abc import Sequence
7
+ from dataclasses import dataclass
8
+ from pathlib import PurePosixPath
9
+
10
+ from markdown_it import MarkdownIt
11
+ from markdown_it.rules_inline import StateInline
12
+ from markdown_it.token import Token
13
+
14
+ from md2site.model import Page
15
+
16
+
17
+ def _shared_dir_prefix_len(a: PurePosixPath, b: PurePosixPath) -> int:
18
+ """Return number of leading directory segments shared by ``a`` and ``b``."""
19
+ a_parts = () if a == PurePosixPath(".") else a.parts
20
+ b_parts = () if b == PurePosixPath(".") else b.parts
21
+ count = 0
22
+ for pa, pb in zip(a_parts, b_parts, strict=False):
23
+ if pa != pb:
24
+ break
25
+ count += 1
26
+ return count
27
+
28
+
29
+ def _nearest_sort_key(
30
+ source_dir: PurePosixPath,
31
+ candidate_rel: PurePosixPath,
32
+ ) -> tuple[int, int, str]:
33
+ """Tie-breaker: longest shared dir prefix, then shallowest, then alphabetical."""
34
+ shared = _shared_dir_prefix_len(source_dir, candidate_rel.parent)
35
+ depth = len(candidate_rel.parts)
36
+ return (-shared, depth, candidate_rel.as_posix())
37
+
38
+
39
+ @dataclass
40
+ class WikilinkIndex:
41
+ """Lookup tables for resolving wikilink targets against scanned pages."""
42
+
43
+ by_rel: dict[str, Page]
44
+ by_rel_no_ext: dict[str, Page]
45
+ by_rel_lower: dict[str, list[Page]]
46
+ by_rel_no_ext_lower: dict[str, list[Page]]
47
+ by_stem_lower: dict[str, list[Page]]
48
+ by_title_lower: dict[str, list[Page]]
49
+ by_alias_lower: dict[str, list[Page]]
50
+
51
+
52
+ def build_wikilink_index(pages: Sequence[Page]) -> WikilinkIndex:
53
+ """Construct lookup tables for wikilink resolution in deterministic order."""
54
+ by_rel: dict[str, Page] = {}
55
+ by_rel_no_ext: dict[str, Page] = {}
56
+ by_rel_lower: dict[str, list[Page]] = defaultdict(list)
57
+ by_rel_no_ext_lower: dict[str, list[Page]] = defaultdict(list)
58
+ by_stem_lower: dict[str, list[Page]] = defaultdict(list)
59
+ by_title_lower: dict[str, list[Page]] = defaultdict(list)
60
+ by_alias_lower: dict[str, list[Page]] = defaultdict(list)
61
+
62
+ for page in sorted(pages, key=lambda p: p.rel.as_posix()):
63
+ rel_str = page.rel.as_posix()
64
+ no_ext = page.rel.with_suffix("").as_posix()
65
+
66
+ by_rel[rel_str] = page
67
+ by_rel_no_ext.setdefault(no_ext, page)
68
+ by_rel_lower[rel_str.lower()].append(page)
69
+ by_rel_no_ext_lower[no_ext.lower()].append(page)
70
+ by_stem_lower[page.rel.stem.lower()].append(page)
71
+
72
+ if page.title.strip():
73
+ by_title_lower[page.title.strip().lower()].append(page)
74
+
75
+ for alias in page.aliases:
76
+ cleaned = alias.strip().lower()
77
+ if cleaned:
78
+ by_alias_lower[cleaned].append(page)
79
+
80
+ return WikilinkIndex(
81
+ by_rel=by_rel,
82
+ by_rel_no_ext=by_rel_no_ext,
83
+ by_rel_lower=dict(by_rel_lower),
84
+ by_rel_no_ext_lower=dict(by_rel_no_ext_lower),
85
+ by_stem_lower=dict(by_stem_lower),
86
+ by_title_lower=dict(by_title_lower),
87
+ by_alias_lower=dict(by_alias_lower),
88
+ )
89
+
90
+
91
+ def _dedupe_and_pick(
92
+ source_page: Page,
93
+ candidates: Sequence[Page],
94
+ ) -> tuple[Page, list[str]]:
95
+ unique: dict[PurePosixPath, Page] = {}
96
+ for cand in candidates:
97
+ unique[cand.rel] = cand
98
+ ordered = sorted(
99
+ unique.values(),
100
+ key=lambda c: _nearest_sort_key(source_page.rel.parent, c.rel),
101
+ )
102
+ winner = ordered[0]
103
+ others = [c.rel.as_posix() for c in ordered[1:]]
104
+ return winner, others
105
+
106
+
107
+ def resolve_wikilink_page(
108
+ source_page: Page,
109
+ raw_target: str,
110
+ index: WikilinkIndex,
111
+ ) -> tuple[Page | None, list[str], str | None]:
112
+ """Resolve a page wikilink target per PRD §6.3 precedence.
113
+
114
+ Returns ``(winner_page, other_candidate_rels, case_mismatch_actual_rel)``.
115
+ """
116
+ norm = raw_target.strip().replace("\\", "/").lstrip("/")
117
+ if norm.startswith("./"):
118
+ norm = norm[2:]
119
+ if not norm:
120
+ return None, [], None
121
+
122
+ lower = norm.lower()
123
+ has_slash = "/" in norm
124
+ has_md_ext = lower.endswith((".md", ".markdown"))
125
+
126
+ # 1. Exact path (when folder path or explicit .md/.markdown extension is given)
127
+ if has_slash or has_md_ext:
128
+ if has_md_ext:
129
+ if norm in index.by_rel:
130
+ return index.by_rel[norm], [], None
131
+ ci_matches = index.by_rel_lower.get(lower, [])
132
+ if ci_matches:
133
+ winner, others = _dedupe_and_pick(source_page, ci_matches)
134
+ return winner, others, winner.rel.as_posix()
135
+ else:
136
+ if norm in index.by_rel_no_ext:
137
+ return index.by_rel_no_ext[norm], [], None
138
+ ci_matches = index.by_rel_no_ext_lower.get(lower, [])
139
+ if ci_matches:
140
+ winner, others = _dedupe_and_pick(source_page, ci_matches)
141
+ return winner, others, winner.rel.with_suffix("").as_posix()
142
+
143
+ # Also check directory/index when folder path is given (e.g. [[guide/]] or [[guide]])
144
+ dir_norm = norm.rstrip("/")
145
+ for idx_name in ("index.md", "index.markdown", "README.md", "README.markdown"):
146
+ cand_rel = f"{dir_norm}/{idx_name}"
147
+ if cand_rel in index.by_rel:
148
+ return index.by_rel[cand_rel], [], None
149
+ ci_dir = index.by_rel_lower.get(cand_rel.lower(), [])
150
+ if ci_dir:
151
+ winner, others = _dedupe_and_pick(source_page, ci_dir)
152
+ return winner, others, winner.rel.as_posix()
153
+
154
+ # 2. Filename stem (case-insensitive)
155
+ stem_key = PurePosixPath(norm).stem.lower() if has_md_ext else lower
156
+ if not has_slash:
157
+ stem_matches = index.by_stem_lower.get(stem_key, [])
158
+ if stem_matches:
159
+ winner, others = _dedupe_and_pick(source_page, stem_matches)
160
+ return winner, others, None
161
+
162
+ # 3. Page title (case-insensitive)
163
+ title_matches = index.by_title_lower.get(lower, [])
164
+ if title_matches:
165
+ winner, others = _dedupe_and_pick(source_page, title_matches)
166
+ return winner, others, None
167
+
168
+ # 4. Front-matter alias (case-insensitive)
169
+ alias_matches = index.by_alias_lower.get(lower, [])
170
+ if alias_matches:
171
+ winner, others = _dedupe_and_pick(source_page, alias_matches)
172
+ return winner, others, None
173
+
174
+ return None, [], None
175
+
176
+
177
+ def resolve_wikilink_embed(
178
+ source_page: Page,
179
+ raw_target: str,
180
+ docs_files: Sequence[PurePosixPath],
181
+ ) -> tuple[PurePosixPath | None, list[str], str | None]:
182
+ """Resolve an embedded asset wikilink ``![[file.png]]`` within ``docs_dir``.
183
+
184
+ Returns ``(winner_rel, other_candidate_rels, case_mismatch_actual_rel)``.
185
+ """
186
+ norm = raw_target.strip().replace("\\", "/").lstrip("/")
187
+ if norm.startswith("./"):
188
+ norm = norm[2:]
189
+ if not norm:
190
+ return None, [], None
191
+
192
+ file_set = {f.as_posix(): f for f in docs_files}
193
+ by_lower: dict[str, list[PurePosixPath]] = defaultdict(list)
194
+ by_name_lower: dict[str, list[PurePosixPath]] = defaultdict(list)
195
+ for f in sorted(docs_files, key=lambda p: p.as_posix()):
196
+ by_lower[f.as_posix().lower()].append(f)
197
+ by_name_lower[f.name.lower()].append(f)
198
+
199
+ if "/" in norm:
200
+ # Check relative to current page directory first, then docs root.
201
+ rel_from_page = (
202
+ norm
203
+ if source_page.rel.parent == PurePosixPath(".")
204
+ else (source_page.rel.parent / norm).as_posix()
205
+ )
206
+ for cand in (rel_from_page, norm):
207
+ if cand in file_set:
208
+ return file_set[cand], [], None
209
+ ci = by_lower.get(cand.lower(), [])
210
+ if ci:
211
+ ordered = sorted(ci, key=lambda p: _nearest_sort_key(source_page.rel.parent, p))
212
+ winner = ordered[0]
213
+ return winner, [p.as_posix() for p in ordered[1:]], winner.as_posix()
214
+ return None, [], None
215
+
216
+ matches = by_name_lower.get(norm.lower(), [])
217
+ if not matches:
218
+ return None, [], None
219
+
220
+ ordered = sorted(matches, key=lambda p: _nearest_sort_key(source_page.rel.parent, p))
221
+ winner = ordered[0]
222
+ others = [p.as_posix() for p in ordered[1:]]
223
+ mismatch = winner.as_posix() if winner.name != norm else None
224
+ return winner, others, mismatch
225
+
226
+
227
+ def _wikilink_inline_rule(state: StateInline, silent: bool) -> bool:
228
+ """Parse ``[[...]]`` and ``![[...]]`` wikilink syntax into markdown-it tokens."""
229
+ pos = state.pos
230
+ src = state.src
231
+ max_pos = state.posMax
232
+
233
+ is_embed = False
234
+ if pos + 4 <= max_pos and src[pos : pos + 3] == "![[":
235
+ is_embed = True
236
+ start = pos + 3
237
+ elif pos + 3 <= max_pos and src[pos : pos + 2] == "[[":
238
+ start = pos + 2
239
+ else:
240
+ return False
241
+
242
+ # Avoid matching triple brackets like [[[x]]].
243
+ if start < max_pos and src[start] == "[":
244
+ return False
245
+
246
+ close_pos = src.find("]]", start, max_pos)
247
+ if close_pos == -1:
248
+ return False
249
+
250
+ raw_inner = src[start:close_pos]
251
+ if not raw_inner or "\n" in raw_inner or "[[" in raw_inner:
252
+ return False
253
+
254
+ if "|" in raw_inner:
255
+ target_spec, custom_label = raw_inner.split("|", 1)
256
+ label = custom_label.strip()
257
+ else:
258
+ target_spec = raw_inner
259
+ label = ""
260
+
261
+ target_spec = target_spec.strip()
262
+ if not target_spec:
263
+ return False
264
+
265
+ if "#" in target_spec:
266
+ target_part, frag_part = target_spec.split("#", 1)
267
+ target_part = target_part.strip()
268
+ frag_part = frag_part.strip() or None
269
+ else:
270
+ target_part = target_spec
271
+ frag_part = None
272
+
273
+ if not target_part and frag_part is None:
274
+ return False
275
+
276
+ state.pos = close_pos + 2
277
+ if silent:
278
+ return True
279
+
280
+ display_label = label or target_spec
281
+ meta_payload = {
282
+ "raw": raw_inner,
283
+ "target": target_part,
284
+ "fragment": frag_part,
285
+ "label": display_label,
286
+ "embed": is_embed,
287
+ }
288
+
289
+ if is_embed:
290
+ tok = state.push("image", "img", 0)
291
+ tok.attrSet("src", target_spec)
292
+ tok.attrSet("alt", "")
293
+ tok.content = display_label
294
+ child = Token("text", "", 0)
295
+ child.content = display_label
296
+ tok.children = [child]
297
+ tok.meta["wikilink"] = meta_payload
298
+ else:
299
+ open_tok = state.push("link_open", "a", 1)
300
+ open_tok.attrSet("href", target_spec)
301
+ open_tok.meta["wikilink"] = meta_payload
302
+
303
+ text_tok = state.push("text", "", 0)
304
+ text_tok.content = display_label
305
+
306
+ close_tok = state.push("link_close", "a", -1)
307
+ close_tok.meta["wikilink_close"] = True
308
+
309
+ return True
310
+
311
+
312
+ def wikilinks_plugin(md: MarkdownIt) -> None:
313
+ """Register the wikilink inline rule before standard Markdown ``link``."""
314
+ md.inline.ruler.before("link", "wikilink", _wikilink_inline_rule)
@@ -0,0 +1,280 @@
1
+ Metadata-Version: 2.5
2
+ Name: md2site-cli
3
+ Version: 0.2.0
4
+ Summary: Compile a folder of Markdown into a static, offline-capable HTML docs site.
5
+ Project-URL: Homepage, https://github.com/Jayfraggs/md2site
6
+ Project-URL: Repository, https://github.com/Jayfraggs/md2site
7
+ Project-URL: Issues, https://github.com/Jayfraggs/md2site/issues
8
+ Author: Jayfraggs
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ License-File: THIRD_PARTY_LICENSES.md
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Documentation
22
+ Classifier: Topic :: Software Development :: Documentation
23
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
24
+ Requires-Python: >=3.11
25
+ Requires-Dist: jinja2>=3.1
26
+ Requires-Dist: markdown-it-py>=3
27
+ Requires-Dist: mdit-py-plugins>=0.4
28
+ Requires-Dist: pygments>=2.17
29
+ Requires-Dist: watchdog>=4
30
+ Provides-Extra: dev
31
+ Requires-Dist: build; extra == 'dev'
32
+ Requires-Dist: pytest-cov; extra == 'dev'
33
+ Requires-Dist: pytest>=8; extra == 'dev'
34
+ Requires-Dist: ruff; extra == 'dev'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # md2site
38
+
39
+ Turn a folder of Markdown into a static, offline-capable HTML docs site — with build-time link checking for humans and AI coding agents.
40
+
41
+ [![CI](https://github.com/Jayfraggs/md2site/actions/workflows/ci.yml/badge.svg)](https://github.com/Jayfraggs/md2site/actions/workflows/ci.yml)
42
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
43
+ ![Python 3.11 | 3.12 | 3.13](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13-blue)
44
+
45
+ ## How it works
46
+
47
+ <p align="center">
48
+ <img src="docs/assets/md2site-overview.jpg" width="900"
49
+ alt="Hand-drawn engineering-style sketch. On the left, a folder labelled docs/ and a stack of Markdown pages labelled raw docs and .md. In the middle, a pipe feeding a gear-and-crank machine labelled transform, with a small terminal prompt showing $_. On the right, a tilted browser window labelled live HTML showing a purple sidebar, an article column, a dark syntax-highlighted code block, a Mermaid flowchart, and a search bar with a magnifying glass. The word md2site is written at the bottom.">
50
+ </p>
51
+ <p align="center"><em>md2site at a glance — sketch by Jayfraggs.</em></p>
52
+
53
+ Read the sketch left to right:
54
+
55
+ 1. **`docs/` → "raw docs": your Markdown stays the source of truth.** The folder and the stack of `.md` pages on the left are ordinary files with headings, lists and fenced code — the things you commit and the things AI agents write. Any folder depth, any filenames; nothing is converted into a proprietary format.
56
+ 2. **"transform": a small build machine.** The pipe feeds Markdown into the gears. The terminal prompt (`$_`) is the CLI — `md2site build` — and the gears are the pipeline stages: **scan → parse → resolve links → render**. The hand crank is `md2site watch`, which re-runs the machine whenever a file changes.
57
+ 3. **"live HTML": a themed reading experience, right in the browser.** The window on the right shows what comes out:
58
+ - **Purple sidebar** — the navigation tree, generated from your folder structure with zero routing config (the purple is the default accent colour and is configurable).
59
+ - **Article column** — one standalone HTML page per Markdown file, titled from its first `# H1`, with a sticky "On this page" outline.
60
+ - **Dark code panel** — syntax highlighting done at build time, so no highlighting JavaScript ships to readers.
61
+ - **Mermaid panel** — ` ```mermaid ` blocks become diagrams, loaded only on pages that use them.
62
+ - **Search bar and magnifier** — instant offline full-text search (Ctrl/Cmd+K).
63
+ - Everything opens straight from disk (`file://`), from `localhost` during `watch`, or from any static host.
64
+ 4. **The blueprint dimension lines** (the arrows labelled `m` and `l`) are purely decorative — a nod to an engineering drawing. They don't correspond to any setting.
65
+
66
+ ## Why md2site
67
+
68
+ - **Authoring vs. reading friction:** AI agents and developers write Markdown fast, while dense multi-file Markdown is tiring to read raw.
69
+ - **No heavy generator toolchain:** No Node runtime, no framework boilerplate, no rigid directory layout — zero-config builds work out of the box.
70
+ - **Dead local references solved:** Relative `.md` cross-links, Obsidian `[[wikilinks]]`, `#anchors`, doc assets, and links to repo source files outside `docs/` all resolve cleanly for `file://`, editor URIs, or remote repository URLs.
71
+ - **Agent-friendly reference checker:** `md2site check --json` returns structured diagnostics (`file`, `line`, `code`, `suggestion`) so an agent can fix broken references in the same loop that wrote them.
72
+
73
+ ## Features
74
+
75
+ - **Navigation:** Recursive sorted scan, front matter `order`/`hidden`/`draft` support, numeric-prefix stripping, acronym-aware title humanization, collapsible `<details>/<summary>` sidebar (works without JS), breadcrumbs, and document-order Previous/Next links.
76
+ - **Links & references:** Relative/root-relative `.md` links, directory `index.md`/`README.md` resolution, `[[Wikilinks]]` and `![[embeds]]` with nearest-match tie-breaking, heading `#anchor` validation, case-mismatch detection (`MD2S006`), repo source-file modes (`relative`, `editor`, `remote`, `auto`), and opt-in inline-code path autolinking.
77
+ - **Reading experience:** Flicker-free light/dark toggle (`localStorage` + `prefers-color-scheme`), configurable CSS tokens, build-time Pygments syntax highlighting with one-click Copy buttons, GitHub alerts (`> [!NOTE]`–`[!CAUTION]`), task lists, footnotes, scrollable tables, responsive mobile drawer, and print stylesheet.
78
+ - **Search & diagrams:** Offline `assets/search-index.js` loaded lazily on `Ctrl/Cmd+K` with Unicode prefix matching and `<mark>` highlights; vendored `mermaid@12.3.0` loaded only on pages containing ` ```mermaid ` fences and re-rendered on theme switch.
79
+ - **Agent integration:** Bundled `SKILL.md` (`md2site init --with-skill`), `md2site hook` post-edit stdin validator, `md2site check --json`, and `md2site watch` with Server-Sent Events live reload.
80
+
81
+ ## Install
82
+
83
+ Note: the PyPI distribution name is `md2site-cli` (the `md2site` name on PyPI belongs to an unrelated project), while the CLI command and Python package remain `md2site`. (`md2site-cli` will be published to PyPI once trusted publishing is enabled; until then, install directly from Git.)
84
+
85
+ ```bash
86
+ pipx install git+https://github.com/Jayfraggs/md2site.git
87
+ ```
88
+
89
+ Or run without installing:
90
+
91
+ ```bash
92
+ uvx --from git+https://github.com/Jayfraggs/md2site md2site build
93
+ ```
94
+
95
+ ## Quick start
96
+
97
+ ```text
98
+ $ md2site init docs
99
+ Initialized md2site in /path/to/repo/docs
100
+ created /path/to/repo/docs/md2site.config.json
101
+ created /path/to/repo/docs/custom.css
102
+ ensured /path/to/repo/docs/_site
103
+ added docs/_site/ to /path/to/repo/.gitignore
104
+
105
+ $ md2site build docs
106
+ Built 2 pages (8 written, 0 unchanged, 0 removed) in 40 ms [0 errors, 0 warnings]
107
+
108
+ $ md2site check docs --json
109
+ {
110
+ "version": 1,
111
+ "summary": {
112
+ "pages": 2,
113
+ "errors": 0,
114
+ "warnings": 0,
115
+ "duration_ms": 5
116
+ },
117
+ "diagnostics": []
118
+ }
119
+ ```
120
+
121
+ Open `docs/_site/index.html` directly in your browser (`file://`), or start live reload while editing:
122
+
123
+ ```bash
124
+ md2site watch docs --open
125
+ ```
126
+
127
+ ## Commands
128
+
129
+ | Command | Arguments & flags | Description |
130
+ |---|---|---|
131
+ | `init` | `[PATH] [--force] [--with-skill]` | Create `md2site.config.json`, `custom.css`, `_site/`, `.gitignore` entry, and optional `SKILL.md` |
132
+ | `build` | `[PATH] [--config FILE] [--mode relative\|editor\|remote\|auto] [--out DIR] [--strict] [--json] [--quiet] [--drafts]` | Build the static HTML documentation site |
133
+ | `check` | `[PATH] [--config FILE] [--strict] [--json]` | Resolve and validate links without writing files |
134
+ | `watch` | `[PATH] [--config FILE] [--host 127.0.0.1] [--port 8000] [--open]` | Serve `_site/` locally with SSE live reload and incremental rebuilds |
135
+ | `hook` | *(reads JSON on stdin)* | Post-edit agent hook; prints diagnostics to stderr and exits `2` on issues |
136
+
137
+ Run `md2site --version` or `md2site <command> --help` for full details.
138
+
139
+ ## Configuration
140
+
141
+ `md2site` works with zero configuration. Place an optional `md2site.config.json` inside your docs directory to customize behavior (see [docs/configuration.md](docs/configuration.md)):
142
+
143
+ | Key | Default | Purpose |
144
+ |---|---|---|
145
+ | `site_title` | `"Project Documentation"` | Site title shown in header, browser title, and landing page |
146
+ | `docs_dir` | `"."` | Source Markdown root relative to the config file |
147
+ | `output_dir` | `"_site"` | Generated HTML output directory |
148
+ | `repo_root` | `"auto"` | Ancestor `.git` root (or config dir) used to resolve source links |
149
+ | `exclude` | `[]` | POSIX glob patterns excluded from scanning |
150
+ | `source_link_mode` | `"relative"` | One of `relative`, `editor`, `remote`, or `auto` |
151
+ | `wikilinks` | `true` | Enable `[[Wikilinks]]` and `![[embeds]]` |
152
+ | `max_highlight_bytes` | `262144` | Max fence bytes for Pygments highlighting (`0` = unlimited) |
153
+ | `nav` | `null` | Optional explicit sidebar ordering override (`null` = auto tree) |
154
+ | `search.enabled` | `true` | Emit offline `assets/search-index.js` and enable `Ctrl/Cmd+K` modal |
155
+ | `search.max_index_bytes` | `0` | Optional byte budget for `assets/search-index.js` (`0` = unlimited) |
156
+
157
+ <details>
158
+ <summary>Full default md2site.config.json</summary>
159
+
160
+ ```json
161
+ {
162
+ "site_title": "Project Documentation",
163
+ "docs_dir": ".",
164
+ "output_dir": "_site",
165
+ "repo_root": "auto",
166
+ "exclude": [],
167
+ "source_link_mode": "relative",
168
+ "remote_repo_url": "",
169
+ "remote_branch": "main",
170
+ "editor_scheme": "vscode",
171
+ "autolink_code_paths": false,
172
+ "wikilinks": true,
173
+ "allow_html": true,
174
+ "mermaid": true,
175
+ "max_highlight_bytes": 262144,
176
+ "nav": null,
177
+ "search": { "enabled": true, "body_chars": 6000, "max_index_bytes": 0 },
178
+ "theme": {
179
+ "default_mode": "system",
180
+ "accent_color": "#7c3aed",
181
+ "accent_color_dark": "#a78bfa",
182
+ "code_theme_light": "default",
183
+ "code_theme_dark": "github-dark",
184
+ "light": { "bg_primary": "#ffffff", "bg_sidebar": "#f8fafc", "text_primary": "#0f172a" },
185
+ "dark": { "bg_primary": "#0b0f19", "bg_sidebar": "#111827", "text_primary": "#f1f5f9" },
186
+ "font_sans": "system-ui, -apple-system, sans-serif",
187
+ "font_mono": "'JetBrains Mono', 'Fira Code', monospace"
188
+ }
189
+ }
190
+ ```
191
+
192
+ </details>
193
+
194
+ ## How links are resolved
195
+
196
+ | Source syntax | Target | Output |
197
+ |---|---|---|
198
+ | `[x](./a.md#h)` | `.md` in docs | Relative `.html#h`; anchor validated |
199
+ | `[x](dir/)` | Directory with `index.md` / `README.md` | `dir/index.html` |
200
+ | `[[Note]]`, `[[Note#H]]`, `[[Note\|Label]]`, `[[folder/Note]]` | Page | Relative HTML link (path → stem → title → alias) |
201
+ | `![[img.png]]`, `![](./img.png)` | Asset in docs | Copied to mirrored path, relative URL |
202
+ | `[x](../src/server.py#L42)` | File outside docs, inside `repo_root` | Rewritten per `source_link_mode` |
203
+ | `![](../assets/logo.png)` | Image outside docs | Copied to `_site/_external/<repo-relative path>` |
204
+ | `http(s)://`, `mailto:`, `tel:` | External | Untouched; `http(s)://` gets `class="external"` and `rel="noopener"` |
205
+ | `#anchor` | Same page | Validated against heading IDs |
206
+ | `/abs/path` | Root-relative | Treated as relative to `docs_dir` |
207
+
208
+ ### `source_link_mode`
209
+
210
+ - `relative` — exact relative path back to the file on disk (e.g. `../../src/server.py#L42`).
211
+ - `editor` — IDE URI (e.g. `vscode://file/<abs-path>:42`).
212
+ - `remote` — repository blob URL (`{remote_repo_url}/blob/{remote_branch}/src/server.py#L42`).
213
+ - `auto` — emits `href` as `relative` plus `data-remote`, swapping to remote on non-local HTTP hosts.
214
+
215
+ ### Diagnostics codes
216
+
217
+ | Code | Meaning |
218
+ |---|---|
219
+ | `MD2S001` | Broken Markdown link (target `.md` not found) or missing explicit `nav` target |
220
+ | `MD2S002` | Broken file/asset link |
221
+ | `MD2S003` | Ambiguous wikilink (resolved to nearest) |
222
+ | `MD2S004` | Unresolved wikilink |
223
+ | `MD2S005` | Broken `#anchor` heading fragment |
224
+ | `MD2S006` | Case mismatch (works on case-insensitive FS, breaks on Linux) |
225
+ | `MD2S007` | Target escapes `repo_root` |
226
+ | `MD2S008` | Output path or asset collision |
227
+ | `MD2S009` | Bad front matter or invalid UTF-8 bytes |
228
+ | `MD2S010` | `remote`/`auto` mode without `remote_repo_url` |
229
+ | `MD2S011` | Cross-filesystem `relative` repo-file fallback when `--out` cannot reach `repo_root` |
230
+
231
+ ## Works offline, from `file://`
232
+
233
+ Browsers enforce strict restrictions when opening HTML files straight from disk:
234
+
235
+ - **No `fetch()` of local JSON:** search emits `assets/search-index.js` (`window.__MD2SITE_INDEX__=[...];`) and injects it via a classic `<script>` tag instead of fetching JSON.
236
+ - **No ES modules or `<base>` tags:** scripts use classic `<script defer>` and every link/asset uses explicit relative paths (`./`, `../`).
237
+ - **No bare directory links:** folder links always resolve to explicit `…/index.html` files.
238
+ - **Zero runtime network requests:** system font stacks by default, build-time Pygments CSS, and vendored `mermaid.min.js`.
239
+
240
+ ## For AI agents
241
+
242
+ - Install the skill with `md2site init docs --with-skill` (copies [SKILL.md](src/md2site/skill/SKILL.md) to `.claude/skills/md2site/SKILL.md`).
243
+ - Or add a post-edit hook (`md2site hook`) and `AGENTS.md` snippet — see [docs/agents.md](docs/agents.md).
244
+ - Typical agent loop: edit Markdown → `md2site check --json` → fix diagnostics via `suggestion` → `md2site build`.
245
+
246
+ ## Performance
247
+
248
+ - Cold build of **100 pages** (~2 KB each with Python code blocks, cross-links, and GFM tables): **~468 ms** (0.47 s) on a Linux x86_64 VM (Python 3.12).
249
+ - Incremental `watch` re-renders only the edited page and `search-index.js` when headings, metadata, and outgoing link targets are unchanged; unchanged outputs are skipped by content comparison.
250
+
251
+ ## Non-goals
252
+
253
+ Plugin API, versioned docs, i18n, hosting/deployment tooling, WYSIWYG editing, server-side search, Node build toolchain, MDX, theme marketplace, and built-in PDF export (use browser print).
254
+
255
+ ## Development
256
+
257
+ ```bash
258
+ git clone https://github.com/Jayfraggs/md2site.git
259
+ cd md2site
260
+ python -m venv .venv
261
+ .venv/bin/pip install -e ".[dev]"
262
+ .venv/bin/ruff check .
263
+ .venv/bin/ruff format --check .
264
+ .venv/bin/pytest -q --cov=md2site --cov-report=term-missing
265
+ .venv/bin/md2site build docs --strict
266
+ ```
267
+
268
+ See [tests/README.md](tests/README.md) for fixture and golden snapshot instructions, and [docs/architecture.md](docs/architecture.md) for the pipeline overview.
269
+
270
+ ## Contributing
271
+
272
+ Issues and pull requests are welcome. Please run `ruff check .`, `ruff format --check .`, and `pytest -q` before submitting changes, and follow [Conventional Commits](https://www.conventionalcommits.org/).
273
+
274
+ ## License
275
+
276
+ [MIT](LICENSE) © 2026 Jayfraggs. See [THIRD_PARTY_LICENSES.md](THIRD_PARTY_LICENSES.md) for vendored Mermaid license details.
277
+
278
+ ## Credits
279
+
280
+ Built on [markdown-it-py](https://github.com/executablebooks/markdown-it-py), [mdit-py-plugins](https://github.com/executablebooks/mdit-py-plugins), [Pygments](https://pygments.org/), [Jinja2](https://jinja.palletsprojects.com/), [watchdog](https://github.com/gorakhargosh/watchdog), and [Mermaid](https://mermaid.js.org/).
@@ -0,0 +1,43 @@
1
+ md2site/__init__.py,sha256=Zjx4yszzVQ9LbglG_075HWSOSg34vOeEehDdwre0j2I,177
2
+ md2site/__main__.py,sha256=TBRzS_cz4txtRpNejv_O_JjjRrPQl0HG-wCRqecllDo,172
3
+ md2site/assets.py,sha256=TTOotgvoUGMzVCZ-5cuG_6yI8vKmKvq7w1525VtdQbA,7538
4
+ md2site/build.py,sha256=CC8vabsitz2oGvS1VEwC6_td1NcwdDbu5uG4aM2WOks,4674
5
+ md2site/cli.py,sha256=1FKkw59JfIRHcfJAaWNT7psKtwrJUfNe8jAQI8E0IF0,11015
6
+ md2site/config.py,sha256=lMHZgZ5wgIKQPeGAHSnOWxirH7nfRSrJL6JhlUYik5s,16746
7
+ md2site/diagnostics.py,sha256=FyAme8X8hCClMYjRwXx1_Zv-ljGET55WxLouJNVUmD8,5224
8
+ md2site/frontmatter.py,sha256=QA79p6TeVpznQypXUyPGN2FGzpvoANoi8AfggGu5DBQ,7760
9
+ md2site/hook.py,sha256=tMXRcuIBFXCpO3KFlcApNo2unqu8ZkUULy7VFwLwkqE,4042
10
+ md2site/init_cmd.py,sha256=1l1jH9IPBUkdKQI-of7L9OilrvdkfsS1FM_IR-b0xJs,5309
11
+ md2site/links.py,sha256=lFf8tFEdLNNC3X3gEaBqMs8C3HhqCTlXeCEgLjz1S9U,55432
12
+ md2site/markdown.py,sha256=3UIdwuCUV7iVCNY0zoUmLGxC5WBkuBx_-kVyZzBnCno,14956
13
+ md2site/model.py,sha256=VLF2ZWz4pPEMBWsWVu0HPTPXRY5R-Bf6ar-wQcCFEkA,1652
14
+ md2site/nav.py,sha256=VggjnkEscUOw4jUix-gw1zoWFP5NDlT7ED6pSRTdPWM,10750
15
+ md2site/paths.py,sha256=t7SHUBSBHGbHXIolXvyHgHB6F-WN8IjbOTpolrijhH4,4484
16
+ md2site/render.py,sha256=uw3E2Pil_IkkiEFR8IgGZWMXzhWsJXUxUODrgXO6bCk,10202
17
+ md2site/scanner.py,sha256=8CyTkF3JNgpg5sQj6e871xlZyfjZ7EKTlbSEceuO9Zw,9038
18
+ md2site/search.py,sha256=3GgJt6TSkU1EX08Vze0OMpydEX13Y9mRPJRpd3KLuAI,3316
19
+ md2site/server.py,sha256=iNuCYMa6xnkzk4WzsPa93zzwBsxaV8TPB84qtGiaitY,8597
20
+ md2site/slug.py,sha256=b4b-n2cOI9d35mfSjhAS31OhCRkN0MqNyCBzj3lpQjs,1264
21
+ md2site/titles.py,sha256=wpIL7pSwd-bj7KnePFj5G63LOStrteGgsCwQzSTe6Ls,2682
22
+ md2site/watcher.py,sha256=yoPqRV7lvma8Pknpd6rCOW8VYkO_etmOK582ioZLvuk,15857
23
+ md2site/wikilinks.py,sha256=86McC489kMLVETuJI2jl4lvhJEV9ICLoa3yEKOQbaxM,10764
24
+ md2site/skill/SKILL.md,sha256=7eyhF0Yg1yfozhRvYcEbN4GyJk33Lg8kUdT2bVekFIg,2929
25
+ md2site/static/css/md2site.css,sha256=P0IS5lsQjDjFxxVpdMb1n8EyMTQ5j_tAG5nryCb0v5g,17336
26
+ md2site/static/js/app.js,sha256=FOuNBZaqy-ivAhVfqmXUzqQxko0l9sm5qxJ_pEW5Yuw,8130
27
+ md2site/static/js/mermaid-init.js,sha256=hGIiH4JRj9kjkJZ6aneQmUnblIcVrgnr_xG3Gpoe0-w,3043
28
+ md2site/static/js/search.js,sha256=PTp-x0ROe5ze9pdFYY62pFUZG8F3OGXN4oQjoRv7AgQ,16856
29
+ md2site/static/js/theme-init.js,sha256=AR78UrU0UGameRFtqqmoI2OEmOCk4V4Q6nsrMGBOOLM,670
30
+ md2site/static/vendor/mermaid.min.js,sha256=M234A9h6OLcKAec25mbI92AdLOQvXkfI-v5dchB0uaM,5537838
31
+ md2site/templates/base.html,sha256=Yq4IgkRgeyCwV2eBpkxAwTb8Z5Uc7GuDAQEmc6xU7TM,2617
32
+ md2site/templates/landing.html,sha256=AFZ4oKTrZXq0PPHHihzkla3c_GYaIuTid8KN2sESH1o,916
33
+ md2site/templates/page.html,sha256=WoZMRY-JRkdYCJJc9-iNIiZN_JGKNABFAnZoONxXIfw,286
34
+ md2site/templates/partials/breadcrumbs.html,sha256=vdIaB-RoTvLn0AoEPLOKoC1j64giAL1fnn_P3lXoGhM,435
35
+ md2site/templates/partials/nav.html,sha256=VtL-HWTSJCKo_5y1zC5SaanCU-GBFmO54Xk7NGHoh-w,1103
36
+ md2site/templates/partials/prevnext.html,sha256=dIGrZKP33eWVAaqa3kx6Lk5kVZMvAqSTBlAgDmufGAU,625
37
+ md2site/templates/partials/toc.html,sha256=o4MxwqVVqC7kQ6NdQNOZ0ak4G__qo38zimDHicFpRLw,364
38
+ md2site_cli-0.2.0.dist-info/METADATA,sha256=eNnnO99IUlXEvzQZkVuq8zah9YJSzb-swl87b4xLp-Q,15416
39
+ md2site_cli-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
40
+ md2site_cli-0.2.0.dist-info/entry_points.txt,sha256=zfjBmfDTmROGUnbFM2ESFIe1vOQVbAnIMM16_v0vGlU,76
41
+ md2site_cli-0.2.0.dist-info/licenses/LICENSE,sha256=bIw1JZwDFbmswIcLgKl-BXwrQK0kFW6rYSFuIPcEer8,1081
42
+ md2site_cli-0.2.0.dist-info/licenses/THIRD_PARTY_LICENSES.md,sha256=WTWnymsiZZXYwL2KIdZrvppzKo4cY8AwQ7cL-mOa2qQ,1617
43
+ md2site_cli-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ md2site = md2site.cli:main
3
+ md2site-cli = md2site.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Folajimi Joshua Olabode
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.