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/render.py ADDED
@@ -0,0 +1,306 @@
1
+ """Jinja2 HTML rendering and theme CSS generation for md2site."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import re
7
+ from dataclasses import dataclass
8
+ from pathlib import Path, PurePosixPath
9
+ from typing import Any
10
+
11
+ from jinja2 import Environment, PackageLoader, StrictUndefined, Undefined
12
+ from markupsafe import Markup
13
+
14
+ from md2site.config import ThemeConfig
15
+ from md2site.model import NavNode, Page, Site
16
+ from md2site.nav import breadcrumbs as compute_breadcrumbs
17
+ from md2site.nav import flatten
18
+ from md2site.paths import quote_posix_path, rel_url, root_prefix
19
+
20
+ _STATIC_DIR = Path(__file__).resolve().parent / "static"
21
+ _UNSAFE_STYLE_RE = re.compile(r"</style", re.IGNORECASE)
22
+ _UNSAFE_SCRIPT_RE = re.compile(r"</script", re.IGNORECASE)
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class NavViewNode:
27
+ """Page-relative navigation view model for Jinja rendering."""
28
+
29
+ label: str
30
+ href: str | None
31
+ is_dir: bool
32
+ is_current: bool
33
+ is_open: bool
34
+ children: list[NavViewNode]
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class LandingCard:
39
+ """Top-level section card shown on generated landing pages."""
40
+
41
+ label: str
42
+ href: str | None
43
+ children: list[tuple[str, str]]
44
+
45
+
46
+ @functools.lru_cache(maxsize=2)
47
+ def get_jinja_env(*, strict: bool = False) -> Environment:
48
+ """Return a cached Jinja2 Environment configured with ``PackageLoader``."""
49
+ return Environment(
50
+ loader=PackageLoader("md2site", "templates"),
51
+ autoescape=True,
52
+ undefined=StrictUndefined if strict else Undefined,
53
+ trim_blocks=True,
54
+ lstrip_blocks=True,
55
+ )
56
+
57
+
58
+ @functools.lru_cache(maxsize=1)
59
+ def _load_theme_init_js() -> str:
60
+ raw = (_STATIC_DIR / "js" / "theme-init.js").read_text(encoding="utf-8").strip()
61
+ return _UNSAFE_SCRIPT_RE.sub("<\\/script", raw)
62
+
63
+
64
+ def _sanitize_css_value(value: str) -> str:
65
+ """Strip sequences that could break out of an inline ``<style>`` tag."""
66
+ return _UNSAFE_STYLE_RE.sub("", value).replace("\n", " ").replace("\r", " ")
67
+
68
+
69
+ def build_theme_style_css(theme: ThemeConfig) -> Markup:
70
+ """Build inline ``<style>`` CSS defining light/dark custom properties."""
71
+ light = theme.light
72
+ dark = theme.dark
73
+ lines = [
74
+ ":root {",
75
+ " color-scheme: light;",
76
+ f" --bg-primary: {_sanitize_css_value(light.bg_primary)};",
77
+ f" --bg-sidebar: {_sanitize_css_value(light.bg_sidebar)};",
78
+ f" --text-primary: {_sanitize_css_value(light.text_primary)};",
79
+ f" --accent: {_sanitize_css_value(theme.accent_color)};",
80
+ f" --font-sans: {_sanitize_css_value(theme.font_sans)};",
81
+ f" --font-mono: {_sanitize_css_value(theme.font_mono)};",
82
+ "}",
83
+ '[data-theme="dark"] {',
84
+ " color-scheme: dark;",
85
+ f" --bg-primary: {_sanitize_css_value(dark.bg_primary)};",
86
+ f" --bg-sidebar: {_sanitize_css_value(dark.bg_sidebar)};",
87
+ f" --text-primary: {_sanitize_css_value(dark.text_primary)};",
88
+ f" --accent: {_sanitize_css_value(theme.accent_color_dark)};",
89
+ "}",
90
+ ]
91
+ return Markup("\n".join(lines))
92
+
93
+
94
+ @dataclass
95
+ class RenderSession:
96
+ """Per-build precomputed render helpers shared across all pages."""
97
+
98
+ site: Site
99
+ flat_nav: list[Page]
100
+ flat_index: dict[PurePosixPath, int]
101
+ theme_css: Markup
102
+ theme_init_js: Markup
103
+ has_custom_css: bool
104
+ quoted_out_rels: dict[PurePosixPath, str]
105
+ nav_hrefs_by_dir: dict[PurePosixPath, dict[PurePosixPath, str]]
106
+
107
+ @classmethod
108
+ def create(cls, site: Site) -> RenderSession:
109
+ flat_nav = flatten(site.nav)
110
+ flat_index = {p.rel: i for i, p in enumerate(flat_nav)}
111
+ quoted_out_rels = {p.out_rel: quote_posix_path(p.out_rel) for p in site.pages}
112
+ return cls(
113
+ site=site,
114
+ flat_nav=flat_nav,
115
+ flat_index=flat_index,
116
+ theme_css=build_theme_style_css(site.config.theme),
117
+ theme_init_js=Markup(_load_theme_init_js()),
118
+ has_custom_css=_has_custom_css(site),
119
+ quoted_out_rels=quoted_out_rels,
120
+ nav_hrefs_by_dir={},
121
+ )
122
+
123
+ def hrefs_for(self, from_out: PurePosixPath) -> dict[PurePosixPath, str]:
124
+ from_dir = from_out.parent
125
+ cached = self.nav_hrefs_by_dir.get(from_dir)
126
+ if cached is not None:
127
+ return cached
128
+ mapping: dict[PurePosixPath, str] = {}
129
+ if from_dir == PurePosixPath("."):
130
+ for p in self.site.pages:
131
+ out_rel = p.out_rel
132
+ quoted = self.quoted_out_rels.get(out_rel)
133
+ if quoted is not None and len(out_rel.parts) == 1:
134
+ mapping[out_rel] = f"./{quoted}"
135
+ elif quoted is not None:
136
+ mapping[out_rel] = quoted
137
+ else:
138
+ mapping[out_rel] = rel_url(from_out, out_rel)
139
+ else:
140
+ for p in self.site.pages:
141
+ mapping[p.out_rel] = rel_url(from_out, p.out_rel)
142
+ self.nav_hrefs_by_dir[from_dir] = mapping
143
+ return mapping
144
+
145
+
146
+ def _build_nav_view(
147
+ nodes: list[NavNode],
148
+ from_out: PurePosixPath,
149
+ current_rel: PurePosixPath | None,
150
+ href_map: dict[PurePosixPath, str] | None = None,
151
+ ) -> list[NavViewNode]:
152
+ view_nodes: list[NavViewNode] = []
153
+ for node in nodes:
154
+ children = _build_nav_view(node.children, from_out, current_rel, href_map)
155
+ is_current = (
156
+ current_rel is not None and node.page is not None and node.page.rel == current_rel
157
+ )
158
+ is_open = is_current or any(child.is_open for child in children)
159
+ if node.page is not None:
160
+ href = (
161
+ href_map[node.page.out_rel]
162
+ if href_map is not None and node.page.out_rel in href_map
163
+ else rel_url(from_out, node.page.out_rel)
164
+ )
165
+ else:
166
+ href = None
167
+ view_nodes.append(
168
+ NavViewNode(
169
+ label=node.label,
170
+ href=href,
171
+ is_dir=node.is_dir,
172
+ is_current=is_current,
173
+ is_open=is_open,
174
+ children=children,
175
+ )
176
+ )
177
+ return view_nodes
178
+
179
+
180
+ def _has_custom_css(site: Site) -> bool:
181
+ return (site.config.docs_dir / "custom.css").is_file()
182
+
183
+
184
+ def _base_context(
185
+ site: Site,
186
+ *,
187
+ from_out: PurePosixPath,
188
+ current_rel: PurePosixPath | None,
189
+ has_mermaid: bool,
190
+ session: RenderSession | None = None,
191
+ ) -> dict[str, Any]:
192
+ href_map = session.hrefs_for(from_out) if session is not None else None
193
+ return {
194
+ "site_title": site.config.site_title,
195
+ "root": root_prefix(from_out),
196
+ "nav": _build_nav_view(site.nav, from_out, current_rel, href_map),
197
+ "has_mermaid": has_mermaid,
198
+ "theme": site.config.theme,
199
+ "theme_css": session.theme_css
200
+ if session is not None
201
+ else build_theme_style_css(site.config.theme),
202
+ "theme_init_js": (
203
+ session.theme_init_js if session is not None else Markup(_load_theme_init_js())
204
+ ),
205
+ "has_custom_css": session.has_custom_css if session is not None else _has_custom_css(site),
206
+ "search_enabled": site.config.search.enabled,
207
+ }
208
+
209
+
210
+ def render_page(
211
+ site: Site,
212
+ page: Page,
213
+ body_html: str,
214
+ *,
215
+ strict: bool = False,
216
+ session: RenderSession | None = None,
217
+ ) -> str:
218
+ """Render a documentation page into a full standalone HTML document."""
219
+ env = get_jinja_env(strict=strict)
220
+ template = env.get_template("page.html")
221
+
222
+ flat = session.flat_nav if session is not None else flatten(site.nav)
223
+ prev_ctx: dict[str, str] | None = None
224
+ next_ctx: dict[str, str] | None = None
225
+ idx = (
226
+ session.flat_index.get(page.rel)
227
+ if session is not None
228
+ else next((i for i, item in enumerate(flat) if item.rel == page.rel), None)
229
+ )
230
+ if idx is not None:
231
+ if idx > 0:
232
+ prev_page = flat[idx - 1]
233
+ prev_ctx = {
234
+ "title": prev_page.title,
235
+ "href": rel_url(page.out_rel, prev_page.out_rel),
236
+ }
237
+ if idx + 1 < len(flat):
238
+ next_page = flat[idx + 1]
239
+ next_ctx = {
240
+ "title": next_page.title,
241
+ "href": rel_url(page.out_rel, next_page.out_rel),
242
+ }
243
+
244
+ raw_crumbs = compute_breadcrumbs(site.nav, page)
245
+ crumb_items = [
246
+ (label, rel_url(page.out_rel, crumb_page.out_rel) if crumb_page is not None else None)
247
+ for label, crumb_page in raw_crumbs
248
+ ]
249
+ toc = [h for h in page.headings if h.level in (2, 3)]
250
+ has_mermaid = bool(site.config.mermaid and page.meta.get("_has_mermaid", False))
251
+
252
+ ctx = _base_context(
253
+ site,
254
+ from_out=page.out_rel,
255
+ current_rel=page.rel,
256
+ has_mermaid=has_mermaid,
257
+ session=session,
258
+ )
259
+ ctx.update(
260
+ {
261
+ "page": page,
262
+ "body_html": Markup(body_html),
263
+ "breadcrumbs": crumb_items,
264
+ "prev": prev_ctx,
265
+ "next": next_ctx,
266
+ "toc": toc,
267
+ "is_landing": False,
268
+ }
269
+ )
270
+ return str(template.render(**ctx))
271
+
272
+
273
+ def render_landing(site: Site, *, strict: bool = False) -> str:
274
+ """Render the generated landing page when no root index page exists."""
275
+ env = get_jinja_env(strict=strict)
276
+ template = env.get_template("landing.html")
277
+ root_out = PurePosixPath("index.html")
278
+
279
+ cards: list[LandingCard] = []
280
+ for node in site.nav:
281
+ href = rel_url(root_out, node.page.out_rel) if node.page is not None else None
282
+ child_links = [
283
+ (child.label, rel_url(root_out, child.page.out_rel))
284
+ for child in node.children
285
+ if child.page is not None
286
+ ]
287
+ cards.append(LandingCard(label=node.label, href=href, children=child_links))
288
+
289
+ ctx = _base_context(
290
+ site,
291
+ from_out=root_out,
292
+ current_rel=None,
293
+ has_mermaid=False,
294
+ )
295
+ ctx.update(
296
+ {
297
+ "page": {"title": site.config.site_title, "headings": []},
298
+ "cards": cards,
299
+ "breadcrumbs": [],
300
+ "prev": None,
301
+ "next": None,
302
+ "toc": [],
303
+ "is_landing": True,
304
+ }
305
+ )
306
+ return str(template.render(**ctx))
md2site/scanner.py ADDED
@@ -0,0 +1,273 @@
1
+ """Deterministic recursive Markdown directory scanner."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ from pathlib import Path, PurePosixPath
8
+ from typing import Any
9
+
10
+ from md2site.config import Config, ConfigError
11
+ from md2site.frontmatter import split_front_matter
12
+ from md2site.model import Diagnostic, Page
13
+ from md2site.paths import assign_out_rels
14
+ from md2site.titles import page_title
15
+
16
+ DEFAULT_EXCLUDE_DIRS = frozenset({".git", "node_modules", ".venv", "__pycache__"})
17
+ MARKDOWN_EXTENSIONS = frozenset({".md", ".markdown"})
18
+
19
+
20
+ def _glob_to_regex(pattern: str) -> re.Pattern[str]:
21
+ """Compile a POSIX glob pattern supporting ``**``, ``*``, ``?``, and ``[...]``."""
22
+ parts: list[str] = ["^"]
23
+ i = 0
24
+ n = len(pattern)
25
+ while i < n:
26
+ ch = pattern[i]
27
+ if ch == "*":
28
+ if i + 1 < n and pattern[i + 1] == "*":
29
+ if i + 2 < n and pattern[i + 2] == "/":
30
+ parts.append("(?:.+/)?")
31
+ i += 3
32
+ else:
33
+ parts.append(".*")
34
+ i += 2
35
+ else:
36
+ parts.append("[^/]*")
37
+ i += 1
38
+ elif ch == "?":
39
+ parts.append("[^/]")
40
+ i += 1
41
+ elif ch == "[":
42
+ end = pattern.find("]", i + 1)
43
+ if end == -1:
44
+ parts.append(re.escape(ch))
45
+ i += 1
46
+ else:
47
+ parts.append(pattern[i : end + 1])
48
+ i = end + 1
49
+ else:
50
+ parts.append(re.escape(ch))
51
+ i += 1
52
+ parts.append("$")
53
+ return re.compile("".join(parts))
54
+
55
+
56
+ class _ExcludeMatcher:
57
+ """Compiled matcher for config exclude globs."""
58
+
59
+ def __init__(self, patterns: tuple[str, ...]) -> None:
60
+ self._dir_patterns: list[tuple[bool, re.Pattern[str]]] = []
61
+ self._file_patterns: list[tuple[bool, re.Pattern[str]]] = []
62
+ for raw in patterns:
63
+ norm = raw.strip().replace("\\", "/")
64
+ if not norm:
65
+ continue
66
+ is_dir_only = norm.endswith("/")
67
+ pat = norm.rstrip("/")
68
+ has_slash = "/" in pat
69
+ compiled = _glob_to_regex(pat)
70
+ if is_dir_only:
71
+ self._dir_patterns.append((has_slash, compiled))
72
+ else:
73
+ self._file_patterns.append((has_slash, compiled))
74
+ self._dir_patterns.append((has_slash, compiled))
75
+
76
+ def matches_dir(self, rel: PurePosixPath) -> bool:
77
+ posix = rel.as_posix()
78
+ name = rel.name
79
+ for has_slash, regex in self._dir_patterns:
80
+ target = posix if has_slash else name
81
+ if regex.match(target) or regex.match(posix):
82
+ return True
83
+ return False
84
+
85
+ def matches_file(self, rel: PurePosixPath) -> bool:
86
+ posix = rel.as_posix()
87
+ name = rel.name
88
+ for has_slash, regex in self._file_patterns:
89
+ target = posix if has_slash else name
90
+ if regex.match(target) or regex.match(posix):
91
+ return True
92
+ return False
93
+
94
+
95
+ def _coerce_order(meta: dict[str, Any], rel_str: str, diags: list[Diagnostic]) -> float | None:
96
+ if "order" not in meta or meta["order"] is None:
97
+ return None
98
+ val = meta["order"]
99
+ if isinstance(val, (int, float)) and not isinstance(val, bool):
100
+ return float(val)
101
+ diags.append(
102
+ Diagnostic(
103
+ level="warning",
104
+ code="MD2S009",
105
+ file=rel_str,
106
+ line=1,
107
+ message=f"Invalid front matter 'order': expected number, got {type(val).__name__}",
108
+ )
109
+ )
110
+ return None
111
+
112
+
113
+ def _coerce_bool(meta: dict[str, Any], key: str, rel_str: str, diags: list[Diagnostic]) -> bool:
114
+ if key not in meta or meta[key] is None:
115
+ return False
116
+ val = meta[key]
117
+ if isinstance(val, bool):
118
+ return val
119
+ diags.append(
120
+ Diagnostic(
121
+ level="warning",
122
+ code="MD2S009",
123
+ file=rel_str,
124
+ line=1,
125
+ message=f"Invalid front matter '{key}': expected boolean, got {type(val).__name__}",
126
+ )
127
+ )
128
+ return False
129
+
130
+
131
+ def _coerce_str_tuple(
132
+ meta: dict[str, Any], key: str, rel_str: str, diags: list[Diagnostic]
133
+ ) -> tuple[str, ...]:
134
+ if key not in meta or meta[key] is None:
135
+ return ()
136
+ val = meta[key]
137
+ if isinstance(val, list):
138
+ return tuple(str(item) for item in val if item is not None and str(item) != "")
139
+ if isinstance(val, str):
140
+ return (val,) if val else ()
141
+ diags.append(
142
+ Diagnostic(
143
+ level="warning",
144
+ code="MD2S009",
145
+ file=rel_str,
146
+ line=1,
147
+ message=f"Invalid front matter '{key}': expected list of strings",
148
+ )
149
+ )
150
+ return ()
151
+
152
+
153
+ def _is_inside_output(path: Path, output_dir: Path) -> bool:
154
+ resolved = path.resolve()
155
+ return resolved == output_dir or output_dir in resolved.parents
156
+
157
+
158
+ def scan(config: Config, *, include_drafts: bool = False) -> tuple[list[Page], list[Diagnostic]]:
159
+ """Deterministically scan ``config.docs_dir`` for Markdown pages."""
160
+ docs_dir = config.docs_dir.resolve()
161
+ if not docs_dir.is_dir():
162
+ raise ConfigError(f"docs_dir does not exist or is not a directory: {docs_dir}")
163
+
164
+ output_dir = config.output_dir.resolve()
165
+ matcher = _ExcludeMatcher(config.exclude)
166
+ diagnostics: list[Diagnostic] = []
167
+
168
+ raw_entries: list[tuple[PurePosixPath, Path]] = []
169
+
170
+ def _walk(current_dir: Path, rel_dir: PurePosixPath | None) -> None:
171
+ if _is_inside_output(current_dir, output_dir):
172
+ return
173
+ with os.scandir(current_dir) as it:
174
+ entries = sorted(it, key=lambda e: e.name)
175
+
176
+ for entry in entries:
177
+ name = entry.name
178
+ entry_rel = PurePosixPath(name) if rel_dir is None else rel_dir / name
179
+ entry_path = Path(entry.path)
180
+
181
+ if entry.is_dir(follow_symlinks=False):
182
+ if name in DEFAULT_EXCLUDE_DIRS or name.startswith("."):
183
+ continue
184
+ if _is_inside_output(entry_path, output_dir):
185
+ continue
186
+ if matcher.matches_dir(entry_rel):
187
+ continue
188
+ _walk(entry_path, entry_rel)
189
+ elif entry.is_file(follow_symlinks=True):
190
+ if Path(name).suffix.lower() not in MARKDOWN_EXTENSIONS:
191
+ continue
192
+ if _is_inside_output(entry_path, output_dir):
193
+ continue
194
+ if matcher.matches_file(entry_rel):
195
+ continue
196
+ raw_entries.append((entry_rel, entry_path))
197
+
198
+ _walk(docs_dir, None)
199
+
200
+ candidates: list[dict[str, Any]] = []
201
+ for rel, src_path in raw_entries:
202
+ rel_str = rel.as_posix()
203
+ raw_bytes = src_path.read_bytes()
204
+ try:
205
+ text = raw_bytes.decode("utf-8-sig")
206
+ except UnicodeDecodeError:
207
+ text = raw_bytes.decode("utf-8-sig", errors="replace")
208
+ diagnostics.append(
209
+ Diagnostic(
210
+ level="warning",
211
+ code="MD2S009",
212
+ file=rel_str,
213
+ line=None,
214
+ message="File is not valid UTF-8; invalid byte sequences were replaced",
215
+ )
216
+ )
217
+
218
+ meta, body, _offset, fm_err = split_front_matter(text)
219
+ if fm_err is not None:
220
+ diagnostics.append(
221
+ Diagnostic(
222
+ level="warning",
223
+ code="MD2S009",
224
+ file=rel_str,
225
+ line=1,
226
+ message=fm_err,
227
+ )
228
+ )
229
+
230
+ draft = _coerce_bool(meta, "draft", rel_str, diagnostics)
231
+ if draft and not include_drafts:
232
+ continue
233
+
234
+ hidden = _coerce_bool(meta, "hidden", rel_str, diagnostics)
235
+ order = _coerce_order(meta, rel_str, diagnostics)
236
+ aliases = _coerce_str_tuple(meta, "aliases", rel_str, diagnostics)
237
+ tags = _coerce_str_tuple(meta, "tags", rel_str, diagnostics)
238
+ title = page_title(meta, body, rel.name)
239
+
240
+ candidates.append(
241
+ {
242
+ "src": src_path.resolve(),
243
+ "rel": rel,
244
+ "title": title,
245
+ "order": order,
246
+ "hidden": hidden,
247
+ "draft": draft,
248
+ "aliases": aliases,
249
+ "tags": tags,
250
+ "meta": meta,
251
+ }
252
+ )
253
+
254
+ out_map, path_diags = assign_out_rels([c["rel"] for c in candidates])
255
+ diagnostics.extend(path_diags)
256
+
257
+ pages = [
258
+ Page(
259
+ src=c["src"],
260
+ rel=c["rel"],
261
+ out_rel=out_map[c["rel"]],
262
+ title=c["title"],
263
+ order=c["order"],
264
+ hidden=c["hidden"],
265
+ draft=c["draft"],
266
+ aliases=c["aliases"],
267
+ tags=c["tags"],
268
+ meta=c["meta"],
269
+ )
270
+ for c in candidates
271
+ ]
272
+ pages.sort(key=lambda p: p.rel.as_posix())
273
+ return pages, diagnostics
md2site/search.py ADDED
@@ -0,0 +1,96 @@
1
+ """Static JavaScript search index generator for offline file:// support."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Sequence
7
+ from typing import Any
8
+
9
+ from md2site.model import Site
10
+
11
+
12
+ def build_index(site: Site) -> list[dict[str, Any]]:
13
+ """Build deterministic search index entries for all searchable non-draft pages."""
14
+ body_chars = site.config.search.body_chars
15
+ entries: list[dict[str, Any]] = []
16
+
17
+ for page in sorted(site.pages, key=lambda p: p.out_rel.as_posix()):
18
+ if page.draft:
19
+ continue
20
+ if page.meta.get("search") is False:
21
+ continue
22
+
23
+ entries.append(
24
+ {
25
+ "t": page.title,
26
+ "u": page.out_rel.as_posix(),
27
+ "h": [[h.text, h.id] for h in page.headings],
28
+ "b": page.text[:body_chars],
29
+ }
30
+ )
31
+
32
+ return entries
33
+
34
+
35
+ def render_search_index_js(entries: Sequence[dict[str, Any]]) -> str:
36
+ """Serialize search entries into a classic-script ``window.__MD2SITE_INDEX__`` assignment."""
37
+ raw_json = json.dumps(list(entries), ensure_ascii=False, separators=(",", ":"))
38
+ safe_json = (
39
+ raw_json.replace("</", "<\\/").replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")
40
+ )
41
+ return f"window.__MD2SITE_INDEX__={safe_json};"
42
+
43
+
44
+ def _payload_bytes(entries: Sequence[dict[str, Any]]) -> tuple[str, int]:
45
+ js = render_search_index_js(entries)
46
+ return js, len(js.encode("utf-8"))
47
+
48
+
49
+ def _bound_entries(entries: list[dict[str, Any]], max_index_bytes: int) -> str:
50
+ js, size = _payload_bytes(entries)
51
+ if max_index_bytes <= 0 or size <= max_index_bytes:
52
+ return js
53
+
54
+ # Stage 1: preserve titles, URLs, and headings; binary-search uniform body char limit.
55
+ no_body = [{**e, "b": ""} for e in entries]
56
+ js_no_body, size_no_body = _payload_bytes(no_body)
57
+ if size_no_body <= max_index_bytes:
58
+ low = 0
59
+ high = max((len(e["b"]) for e in entries), default=0)
60
+ best_js = js_no_body
61
+ while low <= high:
62
+ mid = (low + high) // 2
63
+ candidate = [{**e, "b": e["b"][:mid]} for e in entries]
64
+ cand_js, cand_size = _payload_bytes(candidate)
65
+ if cand_size <= max_index_bytes:
66
+ best_js = cand_js
67
+ low = mid + 1
68
+ else:
69
+ high = mid - 1
70
+ return best_js
71
+
72
+ # Stage 2: strip headings if metadata alone exceeds budget.
73
+ no_headings = [{"t": e["t"], "u": e["u"], "h": [], "b": ""} for e in entries]
74
+ js_min, size_min = _payload_bytes(no_headings)
75
+ if size_min <= max_index_bytes:
76
+ return js_min
77
+
78
+ # Stage 3: binary-search maximum count of entries that fits within max_index_bytes.
79
+ low = 0
80
+ high = len(no_headings)
81
+ best_js = "window.__MD2SITE_INDEX__=[];"
82
+ while low <= high:
83
+ mid = (low + high) // 2
84
+ cand_js, cand_size = _payload_bytes(no_headings[:mid])
85
+ if cand_size <= max_index_bytes:
86
+ best_js = cand_js
87
+ low = mid + 1
88
+ else:
89
+ high = mid - 1
90
+ return best_js
91
+
92
+
93
+ def build_search_index_js(site: Site) -> str:
94
+ """Build and serialize the search index JS payload for ``site``."""
95
+ entries = build_index(site)
96
+ return _bound_entries(entries, site.config.search.max_index_bytes)