-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmain.jac
More file actions
3869 lines (3536 loc) · 136 KB
/
Copy pathmain.jac
File metadata and controls
3869 lines (3536 loc) · 136 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Jaseci Blogs backend.
Walkers that parse markdown posts and author metadata from the content
directory and serve them as JSON to the editorial frontend.
Content layout (read-only from this app's perspective):
content/posts/*.md — published + draft posts (draft: true is filtered)
content/authors.yml — author profiles
docs/assets/ — images; posts reference them relatively and the
renderer rewrites onto asset_base_url() (GitHub raw)
Posts identify by the `slug:` frontmatter field, not filename. Files starting
with `_` are skipped (templates).
"""
import os;
import re;
import yaml;
import json;
import time;
import uuid;
import base64;
import hashlib;
import requests;
import from urllib.request { Request, urlopen }
import from urllib.parse { urlparse, parse_qs }
import markdown as md;
import from cryptography.fernet { Fernet }
import from jaclang.scale.identity.user_manager { JacScaleUserManager }
import from datetime { date as date_cls }
import from pathlib { Path }
glob JACLANG_ZIP = "docs/playground/jaclang.zip";
cl {
def:pub app(props: any) -> JsxElement {
can with entry {
document.title = "Jaseci Blogs · engineering writing from the Jaseci & Jac ecosystem";
existing: any = document.querySelector("link[rel='icon']");
if not existing {
icon: any = document.createElement("link");
icon.rel = "icon";
icon.type = "image/png";
icon.href = "https://www.jaseci.org/images/logo.png";
document.head.appendChild(icon); # jac:ignore[E1030]
}
# Google Analytics (gtag.js). Injected once at the app root so the
# tag loads on every route. Idempotent guard keeps a remount from
# double-adding it. GA4 enhanced measurement tracks SPA route
# changes via History events, so no per-navigation page_view here.
existing_ga: any = document.querySelector("script[data-ga='G-RCKQSQP438']");
if not existing_ga {
ga_loader: any = document.createElement("script");
ga_loader.setAttribute("async", "");
ga_loader.src = "https://www.googletagmanager.com/gtag/js?id=G-RCKQSQP438";
ga_loader.setAttribute("data-ga", "G-RCKQSQP438");
document.head.appendChild(ga_loader); # jac:ignore[E1030]
ga_init: any = document.createElement("script");
ga_init.text = "window.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\ngtag('config', 'G-RCKQSQP438');";
document.head.appendChild(ga_init); # jac:ignore[E1030]
}
}
return <>{props.children}</>;
}
}
# Content roots. During the migration we read from the legacy docs/blog/
# location so the mkdocs site keeps working as a reference. Step 10 of the
# migration moves these to content/posts/ + content/authors.yml.
glob POSTS_DIR = "docs/blog/posts";
glob AUTHORS_PATH = "docs/blog/.authors.yml";
glob EXCERPT_MARKER = "<!-- more -->";
glob READING_WPM = 220;
glob PEEK_LINES = 3;
def:priv format_date_long(date_str: str) -> str {
try {
parsed = date_cls.fromisoformat(date_str);
return parsed.strftime("%B %d, %Y");
} except Exception {
return date_str;
}
}
def:priv format_date_short(date_str: str) -> str {
try {
parsed = date_cls.fromisoformat(date_str);
return parsed.strftime("%b %d, %Y");
} except Exception {
return date_str;
}
}
def:priv _add_md_attr(m: any) -> str {
tag = m.group(1);
attrs = m.group(2) or "";
return "<" + str(tag) + str(attrs) + ' markdown="1">';
}
def:priv inject_markdown_attr(body: str) -> str {
# Lets authors mix raw HTML with markdown inside divs / figures / anchors,
# matching the python-markdown md_in_html behavior used by mkdocs-material.
# Skip tags that already carry an explicit markdown="..." attribute — we
# use markdown="0" on mermaid blocks so their source survives unmodified.
def _maybe_inject(m: any) -> str {
tag = m.group(1);
attrs = m.group(2) or "";
if "markdown=" in attrs {
return m.group(0);
}
return "<" + str(tag) + str(attrs) + ' markdown="1">';
}
return re.sub(r"<(div|figure|a)(\s+[^>]*)?>", _maybe_inject, body);
}
def:priv _escape_html(text: str) -> str {
return text.replace("&", "&").replace("<", "<").replace(">", ">");
}
def:priv convert_mermaid_fences(body: str) -> str {
# Replace ```mermaid …``` fenced blocks with raw HTML that survives the
# python-markdown pipeline (markdown="0" tells md_in_html to leave the
# body alone). The client then calls mermaid.run on .mermaid-block.
def _replace(m: any) -> str {
source = m.group(1);
return f'<div class="mermaid-block" markdown="0">{_escape_html(source)}</div>';
}
return re.sub(r"(?ms)^[ \t]*```mermaid[ \t]*\n(.*?)\n[ \t]*```[ \t]*$", _replace, body);
}
def:priv rewrite_asset_paths(body: str) -> str {
# Posts authored against the mkdocs layout use relative links like
# ../../assets/foo.png (from docs/blog/posts/) or ../assets/foo.png; some
# posts instead hardcode the root-relative /assets/foo.png. Both forms are
# normalised onto asset_base_url() so a post renders the same either way.
base = asset_base_url() + "/";
body = re.sub(r"(!\[[^\]]*\]\()(?:\.\./)+assets/", r"\1" + base, body);
body = re.sub(r"(<img[^>]+src=[\"'])(?:\.\./)+assets/", r"\1" + base, body);
body = body.replace("](/assets/", f"]({base}");
body = body.replace('src="/assets/', f'src="{base}');
body = body.replace("src='/assets/", f"src='{base}");
return body;
}
def:priv strip_markdown_inline(text: str) -> str {
# Used when deriving plain-text titles from a markdown H1 — drops bold,
# italic, inline-code, and link syntax while preserving the visible text.
text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text);
text = re.sub(r"__([^_]+)__", r"\1", text);
text = re.sub(r"(?<!\*)\*([^*]+)\*(?!\*)", r"\1", text);
text = re.sub(r"(?<!_)_([^_]+)_(?!_)", r"\1", text);
text = re.sub(r"`([^`]+)`", r"\1", text);
text = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", text);
return text.strip();
}
def:priv estimate_reading_minutes(body: str) -> int {
word_count = len(re.findall(r"\w+", body));
minutes = max(1, round(word_count / READING_WPM));
return int(minutes);
}
def:priv split_excerpt(body: str) -> tuple[str, str] {
# Returns (excerpt_md, full_md). The excerpt is everything before the
# <!-- more --> marker, falling back to the first paragraph.
if EXCERPT_MARKER in body {
parts = body.split(EXCERPT_MARKER, 1);
return (parts[0].strip(), body.replace(EXCERPT_MARKER, "").strip());
}
# Fallback: first non-heading paragraph.
paragraphs = re.split(r"\n\s*\n", body.strip());
for p in paragraphs {
stripped = p.strip();
if stripped and not stripped.startswith("#") { # jac:ignore[E1032]
return (stripped, body);
}
}
return ("", body);
}
def:priv extract_peek_markdown(body: str) -> str {
# Mirror of scripts/inject_excerpt_peek.py:_extract_peek_markdown — the
# next PEEK_LINES non-blank, non-heading lines after the <!-- more -->
# marker, used as a faded teaser on the index card.
if EXCERPT_MARKER not in body {
return "";
}
after = body.split(EXCERPT_MARKER, 1)[1];
kept: list[str] = [];
non_blank = 0;
in_fence = False;
for raw in after.split("\n") {
line = raw.rstrip();
stripped = line.strip();
# Skip fenced code blocks entirely — a partial fence renders as raw
# "```" text in the teaser, and code is noise in a prose peek anyway.
if stripped.startswith("```") or stripped.startswith("~~~") {
in_fence = not in_fence;
continue;
}
if in_fence {
continue;
}
if not stripped {
if kept {
kept.append("");
}
continue;
}
# Skip structural noise and HTML/markup-only lines.
if stripped.startswith("---") or stripped.startswith("#") or stripped.startswith("<!--") or stripped.startswith("<") {
continue;
}
kept.append(line);
non_blank = non_blank + 1;
if non_blank >= PEEK_LINES {
break;
}
}
return "\n".join(kept).strip();
}
# Exact prefix python-markdown + codehilite (Pygments) emits for every
# highlighted block. We splice the source language back onto each one — see
# tag_code_languages.
glob HL_MARKER = "<div class=\"highlight\"><pre><span></span><code>";
def:priv parse_info_lang(info: str) -> str {
# Normalize a fence info string into a bare language name:
# "jac" -> "jac", "{.jac}" -> "jac", "python title=x" -> "python".
parts = info.strip().split();
if not parts {
return "";
}
token = parts[0].strip("{}").lstrip(".");
if not token or ("=" in token) {
return "";
}
return token;
}
def:priv extract_fence_langs(body: str) -> list {
# Languages of each fenced code block, in source order. codehilite emits
# one HL_MARKER per fence in the same order, so the lists align 1:1.
langs = [];
in_fence = False;
fence = "";
for raw in body.split("\n") {
line = raw.strip();
if not in_fence {
if line.startswith("```") or line.startswith("~~~") {
in_fence = True;
fence = line[:3];
langs.append(parse_info_lang(line[3:]));
}
} elif line.startswith(fence) {
in_fence = False;
fence = "";
}
}
return langs;
}
def:priv tag_code_languages(html: str, body: str) -> str {
# codehilite drops the fence language from its output, leaving jac and
# python blocks indistinguishable. Splice `language-<lang>` back onto the
# wrapper div and inner <code> so the frontend can label + style each.
langs = extract_fence_langs(body);
parts = html.split(HL_MARKER);
if len(parts) <= 1 {
return html;
}
out = parts[0];
for i in range(1, len(parts)) {
lang = "";
if (i - 1) < len(langs) {
lang = str(langs[i - 1]);
}
if lang {
out = out + f"<div class=\"highlight language-{lang}\"><pre><span></span><code class=\"language-{lang}\">" + parts[i];
} else {
out = out + HL_MARKER + parts[i];
}
}
return out;
}
def:priv render_markdown(body: str) -> str {
html = md.markdown(
body,
extensions=[
"fenced_code",
"codehilite",
"tables",
"attr_list",
"md_in_html",
"footnotes",
"toc",
"admonition",
],
extension_configs={
"codehilite": {"guess_lang": False, "css_class": "highlight"},
"toc": {"permalink": True, "permalink_class": "headerlink"},
},
);
return tag_code_languages(html, body);
}
def:priv load_authors() -> dict {
path = Path(AUTHORS_PATH);
if not path.exists() {
return {};
}
try {
text = path.read_text(encoding="utf-8");
data = yaml.safe_load(text);
} except Exception {
return {};
}
if not isinstance(data, dict) {
return {};
}
authors = data.get("authors", {});
if not isinstance(authors, dict) {
return {};
}
return authors;
}
def:priv normalize_avatar(avatar: str) -> str {
# Absolute URLs and root-relative paths pass through. Bare "assets/..."
# (or "./assets/...") from .authors.yml is resolved against asset_base_url()
# so it works regardless of the current page path.
if not avatar {
return "";
}
if avatar.startswith("http://") or avatar.startswith("https://") or avatar.startswith("/") {
return avatar;
}
cleaned = avatar;
while cleaned.startswith("./") or cleaned.startswith("../") {
cleaned = cleaned.split("/", 1)[1];
}
if cleaned.startswith("assets/") {
cleaned = cleaned.split("/", 1)[1];
}
return asset_base_url() + "/" + cleaned;
}
def:priv resolve_authors(author_ids: list, registry: dict) -> list {
resolved = [];
for aid in author_ids {
key = str(aid);
entry = registry.get(key);
if isinstance(entry, dict) {
resolved.append({
"id": key,
"name": str(entry.get("name", key)),
"description": str(entry.get("description", "")),
"avatar": normalize_avatar(str(entry.get("avatar", ""))),
});
} else {
resolved.append({"id": key, "name": key, "description": "", "avatar": ""});
}
}
return resolved;
}
def:priv parse_post_file(path: Path, registry: dict) -> dict | None {
try {
text = path.read_text(encoding="utf-8");
} except Exception {
return None;
}
if not text.startswith("---") {
return None;
}
parts = text.split("---", 2);
if len(parts) < 3 {
return None;
}
frontmatter_text = parts[1];
raw_body = parts[2].strip();
try {
meta = yaml.safe_load(frontmatter_text);
} except Exception {
return None;
}
if not isinstance(meta, dict) {
return None;
}
if meta.get("draft", False) {
return None;
}
slug = str(meta.get("slug", path.stem));
raw_date = str(meta.get("date", ""));
author_ids = meta.get("authors", []);
if not isinstance(author_ids, list) {
author_ids = [author_ids];
}
authors = resolve_authors(author_ids, registry);
categories = meta.get("categories", []);
if not isinstance(categories, list) {
categories = [categories];
}
categories = [str(c) for c in categories];
(excerpt_md, full_md) = split_excerpt(raw_body);
peek_md = extract_peek_markdown(raw_body);
full_md = rewrite_asset_paths(full_md);
excerpt_md = rewrite_asset_paths(excerpt_md);
peek_md = rewrite_asset_paths(peek_md);
# Replace ```mermaid fences with markdown="0" raw HTML so the source
# survives through python-markdown to the browser.
full_md = convert_mermaid_fences(full_md);
excerpt_md = convert_mermaid_fences(excerpt_md);
peek_md = convert_mermaid_fences(peek_md);
full_md_html_ready = inject_markdown_attr(full_md);
excerpt_md_html_ready = inject_markdown_attr(excerpt_md);
peek_md_html_ready = inject_markdown_attr(peek_md);
# Derive title from first H1 if frontmatter doesn't give one.
title = str(meta.get("title", ""));
if not title {
h1_found = re.search(r"(?m)^#\s+(.+)$", raw_body);
title = h1_found.group(1).strip() if h1_found else slug.replace("-", " ").title();
}
title = strip_markdown_inline(title);
description = str(meta.get("description", ""));
# Repost support: a post can be a short write-up that links out to an
# external article. `repost: true` is the author-facing "checkbox"; the
# external link lives in `repost_url`. A post only counts as a repost if it
# actually carries a link — the checkbox alone does nothing.
repost_url = str(meta.get("repost_url", "")).strip();
is_repost = bool(meta.get("repost", False)) and bool(repost_url);
repost_source = str(meta.get("repost_source", "")).strip();
return {
"slug": slug,
"filename": path.stem,
"title": title,
"date": raw_date,
"date_long": format_date_long(raw_date),
"date_short": format_date_short(raw_date),
"authors": authors,
"categories": categories,
"description": description,
"excerpt_md": excerpt_md_html_ready,
"peek_md": peek_md_html_ready,
"body_md": full_md_html_ready,
"reading_minutes": estimate_reading_minutes(raw_body),
"cover": str(meta.get("cover", "")),
"is_repost": is_repost,
"repost_url": repost_url,
"repost_source": repost_source,
};
}
def:priv list_all_posts() -> list {
dir_path = Path(POSTS_DIR);
if not dir_path.exists() {
return [];
}
registry = load_authors();
items = [];
for path in sorted(dir_path.glob("*.md")) {
if path.name.startswith("_") {
continue;
}
parsed = parse_post_file(path, registry);
if parsed is None {
continue;
}
items.append(parsed);
}
# Newest first.
items.sort(key=lambda(x: dict) -> str { return x["date"]; }, reverse=True);
return items;
}
def:priv post_summary(post: dict) -> dict {
excerpt_html = md.markdown(
post["excerpt_md"],
extensions=["fenced_code", "attr_list", "md_in_html"],
) if post["excerpt_md"] else "";
peek_html = md.markdown(
post["peek_md"],
extensions=["fenced_code", "attr_list", "md_in_html"],
) if post["peek_md"] else "";
return {
"slug": post["slug"],
"title": post["title"],
"date": post["date"],
"date_long": post["date_long"],
"date_short": post["date_short"],
"authors": post["authors"],
"categories": post["categories"],
"description": post["description"],
"excerpt_html": excerpt_html,
"peek_html": peek_html,
"reading_minutes": post["reading_minutes"],
"cover": post["cover"],
"is_repost": post["is_repost"],
"repost_url": post["repost_url"],
"repost_source": post["repost_source"],
};
}
walker:pub GetPosts {
has page: int = 1;
has per_page: int = 10;
has category: str = "";
has author: str = "";
can get with Root entry {
all_posts = list_all_posts();
if self.category {
all_posts = [p for p in all_posts if self.category in p["categories"]];
}
if self.author {
all_posts = [
p for p in all_posts
if any(a["id"] == self.author for a in p["authors"])
];
}
total = len(all_posts);
per = max(1, self.per_page);
page_num = max(1, self.page);
start = (page_num - 1) * per;
end = start + per;
window = all_posts[start:end];
report {
"ok": True,
"total": total,
"page": page_num,
"per_page": per,
"has_prev": page_num > 1,
"has_next": end < total,
"posts": [post_summary(p) for p in window],
};
}
}
def:priv peek_unpublished(slug: str) -> dict | None {
# parse_post_file drops drafts entirely (returns None), so GetPost can't
# otherwise tell an unpublished post apart from a genuinely missing one.
# This does a lightweight frontmatter-only scan for a draft whose slug
# matches, returning just enough to render the "coming soon" page.
dir_path = Path(POSTS_DIR);
if not dir_path.exists() {
return None;
}
for path in sorted(dir_path.glob("*.md")) {
if path.name.startswith("_") {
continue;
}
try {
text = path.read_text(encoding="utf-8");
} except Exception {
continue;
}
if not text.startswith("---") {
continue;
}
parts = text.split("---", 2);
if len(parts) < 3 {
continue;
}
try {
meta = yaml.safe_load(parts[1]);
} except Exception {
continue;
}
if not isinstance(meta, dict) {
continue;
}
if not meta.get("draft", False) {
continue; # published posts are served by the normal path
}
file_slug = str(meta.get("slug", path.stem));
if file_slug != slug {
continue;
}
raw_body = parts[2].strip();
title = str(meta.get("title", ""));
if not title {
h1_found = re.search(r"(?m)^#\s+(.+)$", raw_body);
title = h1_found.group(1).strip() if h1_found else slug.replace("-", " ").title();
}
return {"slug": slug, "title": strip_markdown_inline(title)};
}
return None;
}
walker:pub GetPost {
has slug: str = "";
has preview: str = "";
can get with Root entry {
if not self.slug {
report {"ok": False, "status": "error", "error": "missing slug"};
return;
}
# Shareable draft preview: a valid token serves the PR's post even though
# it is still draft:true. The doc re-pulls the PR head's current content
# on view (refresh_preview_doc; usually already fresh from the
# GetPreview redirect seconds earlier), so a persistent link tracks the
# branch instead of freezing at creation time.
if self.preview {
shared_root = root.shared; # jac:ignore[E1030] runtime attr, no static stub
doc = match_preview([shared_root -->][?:PreviewDoc], self.preview);
if doc is not None {
refresh_preview_doc(doc);
if doc.slug == self.slug {
report doc.data;
return;
}
}
}
registry = load_authors();
dir_path = Path(POSTS_DIR);
if not dir_path.exists() {
report {"ok": False, "status": "error", "error": "posts directory not found"};
return;
}
found = None;
for path in dir_path.glob("*.md") {
if path.name.startswith("_") {
continue;
}
parsed = parse_post_file(path, registry);
if parsed is None {
continue;
}
if parsed["slug"] == self.slug {
found = parsed;
break;
}
}
if found is None {
pending = peek_unpublished(self.slug);
if pending is not None {
report {
"ok": False,
"status": "coming_soon",
"slug": pending["slug"],
"title": pending["title"],
"error": "not yet published",
};
return;
}
report {"ok": False, "status": "not_found", "error": "not found"};
return;
}
html = render_markdown(found["body_md"]);
# For reposts, fetch the external article's card metadata (og:title,
# description, image) so the page can render a rich link card up top on
# first paint. link_meta is cached and never raises.
repost_meta: dict = {};
if found["is_repost"] and found["repost_url"] {
repost_meta = link_meta(str(found["repost_url"]));
}
# Adjacent posts (prev/next by date).
all_posts = list_all_posts();
prev_post = None;
next_post = None;
for (i, p) in enumerate(all_posts) {
if p["slug"] == found["slug"] { # jac:ignore[E1040]
if i + 1 < len(all_posts) {
nxt = all_posts[i + 1];
next_post = {
"slug": nxt["slug"],
"title": nxt["title"],
"date_short": nxt["date_short"],
};
}
if i > 0 {
prv = all_posts[i - 1];
prev_post = {
"slug": prv["slug"],
"title": prv["title"],
"date_short": prv["date_short"],
};
}
break;
}
}
# Related: same primary category, excluding self, capped at 3.
related = [];
if found["categories"] {
primary = found["categories"][0];
for p in all_posts {
if p["slug"] == found["slug"] {
continue;
}
if primary in p["categories"] {
related.append(post_summary(p));
}
if len(related) >= 3 {
break;
}
}
}
report {
"ok": True,
"slug": found["slug"],
"title": found["title"],
"date": found["date"],
"date_long": found["date_long"],
"authors": found["authors"],
"categories": found["categories"],
"description": found["description"],
"cover": found["cover"],
"reading_minutes": found["reading_minutes"],
"html": html,
"prev": prev_post,
"next": next_post,
"related": related,
"is_repost": found["is_repost"],
"repost_url": found["repost_url"],
"repost_source": found["repost_source"],
"repost_meta": repost_meta,
};
}
}
walker:pub GetAuthor {
has id: str = "";
can get with Root entry {
if not self.id {
report {"ok": False, "error": "missing author id"};
return;
}
registry = load_authors();
entry = registry.get(self.id);
if not isinstance(entry, dict) {
report {"ok": False, "error": "not found"};
return;
}
all_posts = list_all_posts();
authored = [
post_summary(p) for p in all_posts
if any(a["id"] == self.id for a in p["authors"])
];
report {
"ok": True,
"id": self.id,
"name": str(entry.get("name", self.id)),
"description": str(entry.get("description", "")),
"avatar": str(entry.get("avatar", "")),
"posts": authored,
};
}
}
walker:pub GetCategories {
can get with Root entry {
all_posts = list_all_posts();
counts: dict = {};
for p in all_posts {
for c in p["categories"] {
counts[c] = counts.get(c, 0) + 1;
}
}
items = [{"name": k, "count": v} for (k, v) in counts.items()];
items.sort(key=lambda(x: dict) -> int { return x["count"]; }, reverse=True);
report {"ok": True, "categories": items};
}
}
walker:pub GetArchive {
can get with Root entry {
all_posts = list_all_posts();
# Group by year.
years: dict = {};
for p in all_posts {
year = p["date"][:4] if len(p["date"]) >= 4 else "Undated"; # jac:ignore[E1053]
if year not in years {
years[year] = [];
}
years[year].append({
"slug": p["slug"],
"title": p["title"],
"date_short": p["date_short"],
"categories": p["categories"],
});
}
grouped = [
{"year": y, "posts": years[y]}
for y in sorted(years.keys(), reverse=True)
];
report {"ok": True, "years": grouped, "total": len(all_posts)};
}
}
# ───────────────────────── Community timeline ─────────────────────────
#
# /blog/community renders ONE chronological spine that interleaves two kinds of
# entry:
# • event — curated, from docs/blog/.events.yml (hand-edited, like
# .authors.yml — NOT bot-owned the way .schedule.yml is)
# • post — a published "Community" post that no event claims
#
# An event claims a post by listing its slug under `posts:`; a claimed post
# renders inside the event card rather than as its own spine entry, so a
# hackathon and its three write-ups read as one moment instead of four. Nothing
# has to be registered in .events.yml for a Community post to show up — the file
# only adds event scaffolding around posts that have some.
glob EVENTS_PATH = "docs/blog/.events.yml";
glob COMMUNITY_CATEGORY = "Community";
def:priv load_events() -> list {
path = Path(EVENTS_PATH);
if not path.exists() {
return [];
}
try {
data = yaml.safe_load(path.read_text(encoding="utf-8"));
} except Exception {
return [];
}
if not isinstance(data, dict) {
return [];
}
items = data.get("events", []);
if not isinstance(items, list) {
return [];
}
return [e for e in items if isinstance(e, dict)];
}
def:priv event_asset(raw: str) -> str {
# Event imagery lives in docs/assets alongside post imagery, so it has to be
# served from the repo and not the pod's public/ mount — see asset_base_url()
# for why. Differs from normalize_avatar() in that "/assets/…" is rewritten
# too: an avatar may legitimately be a root-relative path, an event cover
# never is.
val = str(raw or "").strip();
if not val {
return "";
}
if val.startswith("http://") or val.startswith("https://") {
return val;
}
while val.startswith("./") or val.startswith("../") {
val = val.split("/", 1)[1];
}
val = val.lstrip("/");
if val.startswith("assets/") {
val = val.split("/", 1)[1];
}
return asset_base_url() + "/" + val;
}
def:priv event_sort_key(ev: dict) -> str {
# Sortable YYYY-MM-DD. A month- or year-precision entry sorts to the END of
# its period, so a dated post from the same month can't jump above the event
# it belongs beside.
raw = str(ev.get("start", "")).strip();
if len(raw) == 7 {
return raw + "-31";
}
if len(raw) == 4 {
return raw + "-12-31";
}
return raw;
}
def:priv event_date_label(ev: dict) -> str {
override = str(ev.get("date_label", "")).strip();
if override {
return override;
}
start = str(ev.get("start", "")).strip();
end = str(ev.get("end", "")).strip();
if len(start) == 4 {
return start;
}
if len(start) == 7 {
try {
return date_cls.fromisoformat(start + "-01").strftime("%B %Y");
} except Exception {
return start;
}
}
if not end or end == start {
return format_date_long(start);
}
try {
s = date_cls.fromisoformat(start);
e = date_cls.fromisoformat(end);
} except Exception {
return format_date_long(start);
}
if s.year == e.year and s.month == e.month {
return s.strftime("%B") + " " + str(s.day) + "–" + str(e.day) + ", " + str(s.year);
}
if s.year == e.year {
return (
s.strftime("%b") + " " + str(s.day) + " – "
+ e.strftime("%b") + " " + str(e.day) + ", " + str(e.year)
);
}
return format_date_short(start) + " – " + format_date_short(end);
}
def:priv timeline_post_ref(p: dict) -> dict {
# Deliberately lighter than post_summary(): the timeline links out to posts,
# it never renders their bodies, so no excerpt/peek HTML is built.
return {
"slug": p["slug"],
"title": p["title"],
"date": p["date"],
"date_long": p["date_long"],
"date_short": p["date_short"],
"description": p["description"],
"authors": p["authors"],
"categories": p["categories"],
"reading_minutes": p["reading_minutes"],
"is_repost": p["is_repost"],
"repost_url": p["repost_url"],
"repost_source": p["repost_source"],
};
}
def:priv event_entry(ev: dict, by_slug: dict, claimed: dict) -> dict {
raw_slugs = ev.get("posts", []);
slugs: list = [];
if isinstance(raw_slugs, list) {
slugs = raw_slugs;
} else {
slugs = [raw_slugs];
}
refs: list = [];
for s in slugs {
key = str(s);