@mvarble/mesearch-workflow 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +109 -2
  3. package/agents/reference/authoring.md +142 -0
  4. package/agents/reference/workflow.md +118 -0
  5. package/agents/skills/wf-abandon/SKILL.md +18 -0
  6. package/agents/skills/wf-approve/SKILL.md +24 -0
  7. package/agents/skills/wf-build/SKILL.md +45 -0
  8. package/agents/skills/wf-plan/SKILL.md +49 -0
  9. package/agents/skills/wf-publish/SKILL.md +42 -0
  10. package/agents/skills/wf-reopen/SKILL.md +22 -0
  11. package/agents/skills/wf-resume/SKILL.md +16 -0
  12. package/agents/skills/wf-start/SKILL.md +27 -0
  13. package/agents/skills/wf-status/SKILL.md +15 -0
  14. package/agents/skills/wf-writeup/SKILL.md +61 -0
  15. package/app/ambient.d.ts +71 -0
  16. package/app/lib/components/CopyCode.svelte +24 -0
  17. package/app/lib/components/DocumentMap.svelte +38 -0
  18. package/app/lib/components/DocumentPage.svelte +184 -0
  19. package/app/lib/components/Icon.svelte +35 -0
  20. package/app/lib/components/ImageFigure.svelte +213 -0
  21. package/app/lib/components/LinkList.svelte +46 -0
  22. package/app/lib/components/ModelGraph.svelte +169 -0
  23. package/app/lib/components/OpenEntry.svelte +35 -0
  24. package/app/lib/components/PageList.svelte +35 -0
  25. package/app/lib/components/PrevNext.svelte +24 -0
  26. package/app/lib/components/Proof.svelte +12 -0
  27. package/app/lib/components/Shell.svelte +55 -0
  28. package/app/lib/components/Sidebar.svelte +50 -0
  29. package/app/lib/components/StageRail.svelte +30 -0
  30. package/app/lib/components/Statement.svelte +41 -0
  31. package/app/lib/components/Tex.svelte +25 -0
  32. package/app/lib/components/ThemeToggle.svelte +17 -0
  33. package/app/lib/components/Timeline.svelte +31 -0
  34. package/app/lib/components/Toc.svelte +41 -0
  35. package/app/lib/components/TopBar.svelte +55 -0
  36. package/app/lib/components/TrackCard.svelte +19 -0
  37. package/app/lib/documents.ts +52 -0
  38. package/app/lib/graph/describe.ts +29 -0
  39. package/app/lib/graph/geometry.ts +296 -0
  40. package/app/lib/graph/spec.ts +158 -0
  41. package/app/lib/kit.ts +11 -0
  42. package/app/lib/load.ts +12 -0
  43. package/app/lib/map.ts +6 -0
  44. package/app/lib/nav.ts +59 -0
  45. package/app/lib/questions.ts +33 -0
  46. package/app/lib/server/document.ts +117 -0
  47. package/app/lib/server/map.ts +41 -0
  48. package/app/lib/server/markdown.ts +134 -0
  49. package/app/lib/server/open.ts +35 -0
  50. package/app/lib/server/repo.ts +6 -0
  51. package/app/lib/server/specs.ts +26 -0
  52. package/app/lib/server/title.ts +9 -0
  53. package/app/lib/state/persisted.svelte.ts +40 -0
  54. package/app/lib/state/theme.svelte.ts +24 -0
  55. package/app/lib/tex.ts +99 -0
  56. package/app/params/slug.ts +5 -0
  57. package/app/params/track.ts +5 -0
  58. package/app/routes/+layout.ts +2 -0
  59. package/app/routes/[...key].md/+server.ts +19 -0
  60. package/app/routes/[track=track]/+page.server.ts +14 -0
  61. package/app/routes/[track=track]/+page.svelte +24 -0
  62. package/app/routes/[track=track]/[slug=slug]/+page.server.ts +9 -0
  63. package/app/routes/[track=track]/[slug=slug]/+page.svelte +7 -0
  64. package/app/routes/[track=track]/[slug=slug]/+page.ts +4 -0
  65. package/app/routes/archive/+page.server.ts +18 -0
  66. package/app/routes/archive/+page.svelte +44 -0
  67. package/app/routes/archive/[entry=slug]/+page.server.ts +9 -0
  68. package/app/routes/archive/[entry=slug]/+page.svelte +7 -0
  69. package/app/routes/archive/[entry=slug]/+page.ts +4 -0
  70. package/app/routes/archive/[entry=slug]/[name=slug]/+page.server.ts +14 -0
  71. package/app/routes/archive/[entry=slug]/[name=slug]/+page.svelte +7 -0
  72. package/app/routes/archive/[entry=slug]/[name=slug]/+page.ts +4 -0
  73. package/app/routes/llms-full.txt/+server.ts +17 -0
  74. package/app/routes/llms.txt/+server.ts +50 -0
  75. package/app/routes/math/+page.server.ts +21 -0
  76. package/app/routes/math/+page.svelte +56 -0
  77. package/app/routes/math/[slug=slug]/+page.server.ts +8 -0
  78. package/app/routes/math/[slug=slug]/+page.svelte +7 -0
  79. package/app/routes/math/[slug=slug]/+page.ts +4 -0
  80. package/app/styles/base.css +98 -0
  81. package/app/styles/code.css +83 -0
  82. package/app/styles/index.css +17 -0
  83. package/app/styles/katex.css +14 -0
  84. package/app/styles/layout.css +526 -0
  85. package/app/styles/text.css +96 -0
  86. package/app/styles/tokens/dimensions.css +31 -0
  87. package/app/styles/tokens/typography.css +33 -0
  88. package/app/styles/tokens.css +2 -0
  89. package/app/styles/utils/archive.css +339 -0
  90. package/app/styles/utils/buttons.css +28 -0
  91. package/app/styles/utils/callouts.css +41 -0
  92. package/app/styles/utils/cards.css +95 -0
  93. package/app/styles/utils/graph.css +186 -0
  94. package/app/styles/utils/map.css +45 -0
  95. package/app/styles/utils/tables.css +25 -0
  96. package/dist/cli.d.ts +2 -0
  97. package/dist/cli.js +88 -0
  98. package/dist/cli.js.map +1 -0
  99. package/dist/engine/cli.d.ts +12 -0
  100. package/dist/engine/cli.js +744 -0
  101. package/dist/engine/cli.js.map +1 -0
  102. package/dist/engine/config.d.ts +40 -0
  103. package/dist/engine/config.js +16 -0
  104. package/dist/engine/config.js.map +1 -0
  105. package/dist/engine/lib.d.ts +108 -0
  106. package/dist/engine/lib.js +375 -0
  107. package/dist/engine/lib.js.map +1 -0
  108. package/dist/engine/main.d.ts +1 -0
  109. package/dist/engine/main.js +45 -0
  110. package/dist/engine/main.js.map +1 -0
  111. package/dist/index.d.ts +4 -0
  112. package/dist/index.js +3 -0
  113. package/dist/index.js.map +1 -0
  114. package/dist/site/hooks.d.ts +27 -0
  115. package/dist/site/hooks.js +2 -0
  116. package/dist/site/hooks.js.map +1 -0
  117. package/dist/site/index.d.ts +1 -0
  118. package/dist/site/index.js +2 -0
  119. package/dist/site/index.js.map +1 -0
  120. package/dist/site/preset/index.d.ts +15 -0
  121. package/dist/site/preset/index.js +556 -0
  122. package/dist/site/preset/index.js.map +1 -0
  123. package/dist/site/preset/runtime.d.ts +42 -0
  124. package/dist/site/preset/runtime.js +99 -0
  125. package/dist/site/preset/runtime.js.map +1 -0
  126. package/dist/site/preset/types.d.ts +87 -0
  127. package/dist/site/preset/types.js +2 -0
  128. package/dist/site/preset/types.js.map +1 -0
  129. package/dist/site/vite.d.ts +14 -0
  130. package/dist/site/vite.js +202 -0
  131. package/dist/site/vite.js.map +1 -0
  132. package/dist/sync/index.d.ts +17 -0
  133. package/dist/sync/index.js +175 -0
  134. package/dist/sync/index.js.map +1 -0
  135. package/dist/sync/init.d.ts +7 -0
  136. package/dist/sync/init.js +62 -0
  137. package/dist/sync/init.js.map +1 -0
  138. package/dist/sync/render.d.ts +3 -0
  139. package/dist/sync/render.js +115 -0
  140. package/dist/sync/render.js.map +1 -0
  141. package/dist/sync/site.d.ts +3 -0
  142. package/dist/sync/site.js +58 -0
  143. package/dist/sync/site.js.map +1 -0
  144. package/package.json +78 -3
  145. package/templates/.agents/reference/authoring.md +12 -0
  146. package/templates/.agents/reference/stages/README.md +5 -0
  147. package/templates/AGENTS.md +42 -0
  148. package/templates/site/content/landing.md +5 -0
  149. package/templates/site/katex.config.ts +5 -0
  150. package/templates/site/package.json +22 -0
  151. package/templates/site/src/app.d.ts +8 -0
  152. package/templates/site/src/app.html +23 -0
  153. package/templates/site/src/lib/components/Logo.svelte +12 -0
  154. package/templates/site/src/lib/site.ts +39 -0
  155. package/templates/site/src/routes/+layout.server.ts +3 -0
  156. package/templates/site/src/routes/+layout.svelte +11 -0
  157. package/templates/site/src/routes/+page.server.ts +3 -0
  158. package/templates/site/src/routes/+page.svelte +34 -0
  159. package/templates/site/src/routes/+page.ts +7 -0
  160. package/templates/site/src/styles/index.css +4 -0
  161. package/templates/site/src/styles/tokens/colors.css +107 -0
  162. package/templates/site/static/favicon.svg +1 -0
  163. package/templates/site/tsconfig.json +20 -0
  164. package/templates/site/vite.config.ts +4 -0
  165. package/templates/workflow.config.ts +40 -0
package/app/lib/nav.ts ADDED
@@ -0,0 +1,59 @@
1
+ // The navigation every page shows: each track's pages, the math notes, and the archive's entries.
2
+ // A site's `+layout.server.ts` builds it with `navigation()` and may add to it, as skoro lists
3
+ // each crate's page under its page of the crates.
4
+ import { cms } from '$cms';
5
+ import { ARCHIVE, MATH, NAV, TRACKS } from '$site';
6
+
7
+ import { resolve } from '$app/paths';
8
+ import { linkOf, type DocumentLink } from './documents';
9
+
10
+ /**
11
+ * A link in the navigation. `sub` indents it under the item before it, and `code` sets its title
12
+ * in the monospace face, as for a crate's page.
13
+ */
14
+ export type NavItem = Pick<DocumentLink, 'key' | 'title' | 'href' | 'status'> & {
15
+ sub?: boolean;
16
+ code?: boolean;
17
+ };
18
+
19
+ export interface NavSection {
20
+ id: string;
21
+ title: string;
22
+ short: string;
23
+ href: string;
24
+ items: NavItem[];
25
+ }
26
+
27
+ export interface NavigationOptions {
28
+ /** Rewrites the items of one track, as by inserting links under one of its pages. */
29
+ items?: (track: string, items: NavItem[]) => NavItem[];
30
+ }
31
+
32
+ // The tracks in their order, with the math notes placed before the track `NAV.mathBefore` names
33
+ // (after the last track when it names none, or one that is not there), and the archive last.
34
+ export function navigation(options: NavigationOptions = {}): NavSection[] {
35
+ const tracks: NavSection[] = TRACKS.map((track) => {
36
+ const items = cms.pages.list(track.id).map(linkOf);
37
+ return {
38
+ ...track,
39
+ href: resolve('/[track=track]', { track: track.id }),
40
+ items: options.items ? options.items(track.id, items) : items,
41
+ };
42
+ });
43
+ const math: NavSection = {
44
+ ...MATH,
45
+ href: resolve('/math'),
46
+ items: cms.math.list().map(linkOf),
47
+ };
48
+ const at = NAV.mathBefore ? tracks.findIndex((track) => track.id == NAV.mathBefore) : -1;
49
+ if (at < 0) tracks.push(math);
50
+ else tracks.splice(at, 0, math);
51
+ return [
52
+ ...tracks,
53
+ { ...ARCHIVE, href: resolve('/archive'), items: cms.archive.list().map(linkOf) },
54
+ ];
55
+ }
56
+
57
+ // Where the site is hosted, when the build knows it (`SITE_URL=https://example.org`): a link
58
+ // preview, such as LinkedIn's, takes only an absolute URL for its image.
59
+ export const siteOrigin = () => (process.env.SITE_URL ?? '').replace(/\/$/, '');
@@ -0,0 +1,33 @@
1
+ export interface OpenQuestion {
2
+ title: string;
3
+ href: string;
4
+ }
5
+
6
+ // A heading's anchor, as `.agents/reference/authoring.md` says the content database makes it.
7
+ const anchor = (heading: string) =>
8
+ heading
9
+ .toLowerCase()
10
+ .replace(/\$/g, '')
11
+ .replace(/[^a-z0-9]+/g, '-')
12
+ .replace(/^-|-$/g, '');
13
+
14
+ // The `[!TODO]` callouts in a Markdown source: each is a question that keeps a stage from being
15
+ // approved. A callout has no anchor of its own, so a question links to the heading above it. The
16
+ // marker is matched as `tools/wf/lib.ts` matches it, so the two count the same questions.
17
+ export function questionsIn(source: string, href: string): OpenQuestion[] {
18
+ const questions: OpenQuestion[] = [];
19
+ let heading: string | undefined;
20
+ const lines = source.split('\n');
21
+ lines.forEach((line, i) => {
22
+ const title = /^#{2,3}\s+(.*)$/.exec(line)?.[1];
23
+ if (title) heading = title;
24
+ const todo = /^>\s*\[!TODO\]\s*(.*)$/.exec(line);
25
+ if (!todo) return;
26
+ const body = /^>\s*(.*)$/.exec(lines[i + 1] ?? '')?.[1];
27
+ questions.push({
28
+ title: todo[1] || body || 'An open question',
29
+ href: heading ? `${href}#${anchor(heading)}` : href,
30
+ });
31
+ });
32
+ return questions;
33
+ }
@@ -0,0 +1,117 @@
1
+ import { error } from '@sveltejs/kit';
2
+ import { cms } from '$cms';
3
+ import { citationLabel } from '@mvarble/mesearch-cms/runtime';
4
+ import { referenceHtml } from '@mvarble/mesearch-ui/server';
5
+
6
+ import { resolve } from '$app/paths';
7
+ import { hrefOf, linkOf, type DocumentLink, type SiteDocument } from '../documents';
8
+ import { qualifiedTitle } from './title';
9
+ import { ARCHIVE, MATH, MATH_PARTS, SITE, TRACKS } from '$site';
10
+ import { hooks } from '$site/server';
11
+
12
+ export interface Crumb {
13
+ title: string;
14
+ href: string;
15
+ }
16
+
17
+ export interface Reference {
18
+ key: string;
19
+ label: string;
20
+ html: string;
21
+ }
22
+
23
+ // Everything a document's page shows besides its own body, which `+page.ts` attaches as a
24
+ // component. The lists are links, kept small: they travel with the page as data.
25
+ export function documentData(key: string) {
26
+ const doc = cms.get(key);
27
+ if (!doc) error(404, `No document ${key}.`);
28
+ const links = (records: SiteDocument[]) => records.map(linkOf);
29
+ const qualified = (records: SiteDocument[]) =>
30
+ records.map((record) => ({ ...linkOf(record), title: qualifiedTitle(record) }));
31
+ const keys = (list: string[]) =>
32
+ list.flatMap((k) => {
33
+ const record = cms.get(k);
34
+ return record ? [linkOf(record)] : [];
35
+ });
36
+
37
+ // What an entry amended, as links: a document by its own key, and a statement by the entry it
38
+ // belongs to, each once.
39
+ const amended = (list: string[]) => {
40
+ const records = [
41
+ ...new Set(
42
+ list.map((k) => (k.includes('/statements/') ? k.split('/statements/')[0]! : k)),
43
+ ),
44
+ ].flatMap((k) => cms.get(k) ?? []);
45
+ return qualified(records);
46
+ };
47
+
48
+ let crumbs: Crumb[];
49
+ let prev: DocumentLink | undefined;
50
+ let next: DocumentLink | undefined;
51
+ if (doc.kind == 'page') {
52
+ const track = TRACKS.find((t) => t.id == doc.track)!;
53
+ crumbs = [{ title: track.title, href: resolve('/[track=track]', { track: track.id }) }];
54
+ const neighbours = cms.pages.neighbours(key);
55
+ prev = neighbours.prev && linkOf(neighbours.prev);
56
+ next = neighbours.next && linkOf(neighbours.next);
57
+ } else if (doc.kind == 'math') {
58
+ const part = MATH_PARTS.find((p) => p.id == doc.part);
59
+ crumbs = [
60
+ { title: MATH.title, href: resolve('/math') },
61
+ ...(part ? [{ title: part.title, href: `${resolve('/math')}#${part.id}` }] : []),
62
+ ];
63
+ // Notes in parts are read in order, one after another; notes without are not.
64
+ if (MATH_PARTS.length) {
65
+ const neighbours = cms.math.neighbours(key);
66
+ prev = neighbours.prev && linkOf(neighbours.prev);
67
+ next = neighbours.next && linkOf(neighbours.next);
68
+ }
69
+ } else if (doc.kind == 'entry') {
70
+ crumbs = [{ title: ARCHIVE.title, href: resolve('/archive') }];
71
+ } else {
72
+ const entry = cms.get(doc.entry)!;
73
+ crumbs = [
74
+ { title: ARCHIVE.title, href: resolve('/archive') },
75
+ { title: entry.title, href: hrefOf(entry.key) },
76
+ ];
77
+ const siblings = cms.archive.documents(doc.entry);
78
+ const i = siblings.findIndex((sibling) => sibling.key == key);
79
+ prev = siblings[i - 1] && linkOf(siblings[i - 1]!);
80
+ next = siblings[i + 1] && linkOf(siblings[i + 1]!);
81
+ }
82
+
83
+ const references: Reference[] = cms.bibliography(key).map((citation) => ({
84
+ key: citation.key,
85
+ label: citationLabel(citation),
86
+ html: referenceHtml(citation),
87
+ }));
88
+
89
+ return {
90
+ doc,
91
+ headings: cms.headings(doc.filename),
92
+ crumbs,
93
+ prev,
94
+ next,
95
+ references,
96
+ // Both named as the map names them, since an archive document's own title ("Mathematics")
97
+ // says nothing of the entry it belongs to.
98
+ prerequisites: qualified(cms.prerequisites(key)),
99
+ dependents: qualified(cms.dependents(key)),
100
+ // A page: the development behind it. An entry: what it changed (its pages, and whatever
101
+ // else the site's `entryChanges` hook lists, as skoro's crates), and what it revises or
102
+ // is revised by. An entry's document: its siblings.
103
+ entries: doc.kind == 'page' ? keys(doc.entries) : [],
104
+ pages: doc.kind == 'entry' ? keys(doc.pages) : [],
105
+ changes: doc.kind == 'entry' ? (hooks.entryChanges?.(doc) ?? []) : [],
106
+ revises: doc.kind == 'entry' ? keys(doc.revises) : [],
107
+ revisedBy: doc.kind == 'entry' ? keys(doc.revisedBy) : [],
108
+ // An entry: the documents of done entries whose references it brought up to date. An
109
+ // entry or one of its documents: the later entries that did so to it.
110
+ amends: doc.kind == 'entry' ? amended(doc.amends) : [],
111
+ amendedBy: doc.kind == 'entry' || doc.kind == 'entry-document' ? keys(doc.amendedBy) : [],
112
+ documents: doc.kind == 'entry' ? links(cms.archive.documents(key)) : [],
113
+ source: `${SITE.repo}/blob/${SITE.branch}/site/${doc.filename}`,
114
+ };
115
+ }
116
+
117
+ export type DocumentData = ReturnType<typeof documentData>;
@@ -0,0 +1,41 @@
1
+ import { cms } from '$cms';
2
+ import { katex } from '$site';
3
+ import { inlineHtml, layoutGraph } from '@mvarble/mesearch-ui/server';
4
+ import type { GraphLink, GraphNode, IndexEntry } from '@mvarble/mesearch-ui';
5
+
6
+ import { hrefOf } from '../documents';
7
+ import { MAP_TUNING } from '../map';
8
+ import { qualifiedTitle } from './title';
9
+
10
+ export interface DocumentMapData {
11
+ nodes: GraphNode[];
12
+ links: GraphLink[];
13
+ entries: Record<string, IndexEntry>;
14
+ }
15
+
16
+ // The map of the math notes and the archive's documents, linked by what each builds on and links
17
+ // to. It is laid out here, at build time, so it is drawn before any script runs. An archive
18
+ // document is named by its entry and its own title ("The core: Mathematics").
19
+ export function documentMap(): DocumentMapData {
20
+ const macros = katex.macros as Record<string, string>;
21
+ const graph = cms.graph();
22
+ const entries: Record<string, IndexEntry> = {};
23
+ for (const key of graph.nodes) {
24
+ const doc = cms.get(key)!;
25
+ const title = qualifiedTitle(doc);
26
+ entries[key] = {
27
+ key,
28
+ kind: doc.kind,
29
+ url: hrefOf(key),
30
+ title,
31
+ titleHtml: inlineHtml(title, macros),
32
+ summary: doc.summary,
33
+ summaryHtml: inlineHtml(doc.summary, macros),
34
+ created: doc.created,
35
+ updated: doc.updated,
36
+ readingMinutes: doc.readingMinutes,
37
+ };
38
+ }
39
+ const links = graph.edges.map(({ from, to, style }) => ({ from, to, style }));
40
+ return { nodes: layoutGraph(Object.values(entries), links, MAP_TUNING), links, entries };
41
+ }
@@ -0,0 +1,134 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { base } from '$app/paths';
5
+ import type { SiteDocument } from '../documents';
6
+ import { describeGraph } from '../graph/describe';
7
+ import type { GraphSpec } from '../graph/spec';
8
+ import { expandFileRefs } from '@mvarble/mesearch-markdown';
9
+ import type { MarkdownContext } from '@mvarble/mesearch-workflow';
10
+ import { hooks } from '$site/server';
11
+
12
+ import { REPO_ROOT } from './repo';
13
+ import { importedSpecs } from './specs';
14
+
15
+ // Every `<ModelGraph>` spec, which by convention lives in a `*.graph.ts` file beside its page.
16
+ const graphModules = import.meta.glob<Record<string, GraphSpec>>('/content/**/*.graph.ts', {
17
+ eager: true,
18
+ });
19
+
20
+ // Every image beside a page, as the URL the build serves it from.
21
+ const imageUrls = import.meta.glob<string>('/content/**/*.{jpg,jpeg,png,webp,gif,svg}', {
22
+ eager: true,
23
+ query: '?url',
24
+ import: 'default',
25
+ });
26
+
27
+ // A document as Markdown for a reader without a browser: the raw source, with its frontmatter
28
+ // kept so its KaTeX macros stay visible, a `# title` heading added after it, the `<script>` block
29
+ // that imports components dropped, every `<ModelGraph spec={name} />` replaced by a text
30
+ // description of the figure, whatever the site's own `markdown` hooks replace (skoro's
31
+ // `<Walkthrough>`, by the code it quotes and a list of its steps), every statement quoted, every
32
+ // `<ImageFigure>` replaced by a Markdown image, every file reference replaced by the code it
33
+ // quotes, and every link to another document pointed at that document's Markdown.
34
+ //
35
+ // The build runs from `site/`, which is where the content database's filenames start.
36
+ export function markdownOf(doc: SiteDocument): string {
37
+ const file = path.resolve(process.cwd(), doc.filename);
38
+ const raw = fs.readFileSync(file, 'utf8');
39
+ const match = /^---\n[\s\S]*?\n---\n/.exec(raw);
40
+ const frontmatter = match ? match[0] : '';
41
+ const rest = raw.slice(frontmatter.length);
42
+ const script = /^\s*<script[\s\S]*?<\/script>\s*/.exec(rest)?.[0] ?? '';
43
+ const context: MarkdownContext = { doc, script, file };
44
+ const described = (hooks.markdown ?? []).reduce(
45
+ (text, transform) => transform(text, context),
46
+ describeGraphs(rest.slice(script.length).trim(), script, doc),
47
+ );
48
+ const body = imageSources(inlineStatements(described, script, file), script, doc);
49
+ const markdown = relinked(expandFileRefs(imageFigures(body), file, REPO_ROOT), doc);
50
+ return `${frontmatter}\n# ${doc.title}\n\n${markdown}\n`;
51
+ }
52
+
53
+ // Resolves each `<ModelGraph spec={name} />` through the document's own `import { name } from
54
+ // './x.graph'`, and replaces the tag with `describeGraph` of that spec.
55
+ function describeGraphs(body: string, script: string, doc: SiteDocument): string {
56
+ const specs = importedSpecs(script, doc, graphModules);
57
+ return body.replace(/<ModelGraph\s+spec=\{(\w+)\}\s*\/>/g, (tag, name: string) => {
58
+ const spec = specs.get(name);
59
+ if (!spec) throw new Error(`${doc.filename}: \`${tag}\` names no imported graph spec.`);
60
+ return describeGraph(spec);
61
+ });
62
+ }
63
+
64
+ // Replaces each `<Statement {...name} />` with the statement it spreads in, imported as
65
+ // `import * as name from './statements/x.md'`, as a quotation headed by its kind and title.
66
+ function inlineStatements(body: string, script: string, file: string): string {
67
+ const imports = new Map<string, string>();
68
+ for (const [, name, from] of script.matchAll(
69
+ /import\s*\*\s*as\s+(\w+)\s+from\s*['"](\.[^'"]+)['"]/g,
70
+ )) {
71
+ imports.set(name!, path.resolve(path.dirname(file), from!));
72
+ }
73
+ return body.replace(/<Statement\s+\{\.\.\.(\w+)\}[^>]*\/>/g, (tag, name: string) => {
74
+ const source = imports.get(name);
75
+ if (!source || !fs.existsSync(source)) return tag;
76
+ const raw = fs.readFileSync(source, 'utf8');
77
+ const frontmatter = /^---\n([\s\S]*?)\n---\n/.exec(raw);
78
+ const field = (key: string) =>
79
+ new RegExp(`^${key}:\\s*(.+)$`, 'm').exec(frontmatter?.[1] ?? '')?.[1]?.trim();
80
+ const kind = field('kind') ?? 'statement';
81
+ const title = field('title');
82
+ const heading = `**${kind.slice(0, 1).toUpperCase()}${kind.slice(1)}${title ? ` (${title})` : ''}.**`;
83
+ const text = raw.slice(frontmatter?.[0].length ?? 0).trim();
84
+ return `${heading} ${text}`
85
+ .split('\n')
86
+ .map((line) => (line ? `> ${line}` : '>'))
87
+ .join('\n');
88
+ });
89
+ }
90
+
91
+ // Replaces each `src={name}` whose `name` is an image the document imports, `import name from
92
+ // './x.jpg'`, with the URL the build serves that image from.
93
+ function imageSources(body: string, script: string, doc: SiteDocument): string {
94
+ const dir = path.posix.dirname(`/${doc.filename}`);
95
+ const urls = new Map<string, string>();
96
+ for (const [, name, from] of script.matchAll(/import\s+(\w+)\s+from\s*['"](\.[^'"]+)['"]/g)) {
97
+ const url = imageUrls[path.posix.join(dir, from!)];
98
+ if (url) urls.set(name!, url);
99
+ }
100
+ return body.replace(/src=\{(\w+)\}/g, (whole, name: string) => {
101
+ const url = urls.get(name);
102
+ return url ? `src="${url}"` : whole;
103
+ });
104
+ }
105
+
106
+ // Replaces each `<ImageFigure src="…" alt="…" …>caption</ImageFigure>`, once `imageSources` has
107
+ // resolved its `src`, with a Markdown image and its caption in italics.
108
+ function imageFigures(body: string): string {
109
+ return body.replace(
110
+ /<ImageFigure\s+src="([^"]+)"\s+alt="([^"]*)"[^>]*>([\s\S]*?)<\/ImageFigure>/g,
111
+ (_, src: string, alt: string, caption: string) => {
112
+ const text = caption.trim();
113
+ return `![${alt}](${src})` + (text ? `\n\n*${text}*` : '');
114
+ },
115
+ );
116
+ }
117
+
118
+ // Links are written the way the files sit on disk (`../../math/retraction/`, `plan.md`). Here they
119
+ // become absolute links to the Markdown of the document they name.
120
+ function relinked(markdown: string, doc: SiteDocument): string {
121
+ const dir = path.posix.dirname(doc.filename);
122
+ return markdown.replace(/\]\((\.{0,2}[^):\s]*?)(#[^)\s]*)?\)/g, (whole, href: string, hash) => {
123
+ if (!href || /^[a-z]+:/i.test(href) || href.startsWith('/')) return whole;
124
+ if (/\.(?!md$|svx$)[a-z0-9]+$/i.test(href)) return whole;
125
+ const target = path.posix.normalize(path.posix.join(dir, href));
126
+ const key = path.posix
127
+ .relative('content', target)
128
+ .replace(/\/+$/, '')
129
+ .replace(/(^|\/)index\.(md|svx)$/, '')
130
+ .replace(/\.(md|svx)$/, '');
131
+ if (key.startsWith('..')) return whole;
132
+ return `](${base}/${key}.md${hash ?? ''})`;
133
+ });
134
+ }
@@ -0,0 +1,35 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { cms } from '$cms';
5
+
6
+ import { hrefOf, linkOf, type DocumentLink } from '../documents';
7
+ import { questionsIn, type OpenQuestion } from '../questions';
8
+
9
+ export interface OpenEntryData {
10
+ link: DocumentLink;
11
+ kind: string;
12
+ stage: string;
13
+ approvals: Record<string, { stale?: boolean }>;
14
+ questions: OpenQuestion[];
15
+ }
16
+
17
+ // The entries in progress, with what is still open in each. The content database reads from
18
+ // `site/`, which is where its filenames start.
19
+ export function openEntries(): OpenEntryData[] {
20
+ return cms.archive
21
+ .list()
22
+ .filter((entry) => entry.status == 'active' && entry.workflow)
23
+ .map((entry) => ({
24
+ link: linkOf(entry),
25
+ kind: entry.workflow!.kind,
26
+ stage: entry.workflow!.stage,
27
+ approvals: entry.workflow!.approvals as Record<string, { stale?: boolean }>,
28
+ questions: [entry, ...cms.archive.documents(entry.key)].flatMap((doc) =>
29
+ questionsIn(
30
+ fs.readFileSync(path.resolve(process.cwd(), doc.filename), 'utf8'),
31
+ hrefOf(doc.key),
32
+ ),
33
+ ),
34
+ }));
35
+ }
@@ -0,0 +1,6 @@
1
+ import path from 'node:path';
2
+
3
+ // The repository the site documents, which file references quote from: the parent of `site/`,
4
+ // where the build runs. Resolved from the working directory rather than `import.meta.dirname`,
5
+ // because the prerendered `.md` endpoints run this module from inside the bundled server output.
6
+ export const REPO_ROOT = path.resolve(process.cwd(), '..');
@@ -0,0 +1,26 @@
1
+ import path from 'node:path';
2
+
3
+ import type { SiteDocument } from '../documents';
4
+
5
+ // The specs a document imports by name, `import { name } from './x.graph'`, from `modules`.
6
+ export function importedSpecs<T>(
7
+ script: string,
8
+ doc: SiteDocument,
9
+ modules: Record<string, Record<string, T>>,
10
+ ): Map<string, T> {
11
+ const dir = path.posix.dirname(`/${doc.filename}`);
12
+ const specs = new Map<string, T>();
13
+ for (const [, names, from] of script.matchAll(
14
+ /import\s*\{([^}]*)\}\s*from\s*['"](\.[^'"]+)['"]/g,
15
+ )) {
16
+ const module = modules[path.posix.join(dir, from!.replace(/(\.ts)?$/, '.ts'))];
17
+ if (!module) continue;
18
+ for (const name of names!
19
+ .split(',')
20
+ .map((n) => n.trim())
21
+ .filter(Boolean)) {
22
+ specs.set(name, module[name]!);
23
+ }
24
+ }
25
+ return specs;
26
+ }
@@ -0,0 +1,9 @@
1
+ import { cms } from '$cms';
2
+
3
+ import type { SiteDocument } from '../documents';
4
+
5
+ // A document's title where it is listed away from its entry: an archive document is named by its
6
+ // entry and its own title ("The core: Mathematics"), as the map names it; any other by its title.
7
+ export function qualifiedTitle(doc: SiteDocument): string {
8
+ return doc.kind == 'entry-document' ? `${cms.get(doc.entry)!.title}: ${doc.title}` : doc.title;
9
+ }
@@ -0,0 +1,40 @@
1
+ import { on } from 'svelte/events';
2
+ import { createSubscriber } from 'svelte/reactivity';
3
+
4
+ export class Persisted<T extends string = string> {
5
+ #key: string;
6
+ #storage: Storage | undefined;
7
+ #fallback: T;
8
+ #version = $state(0);
9
+
10
+ #subscribe = createSubscriber((update) => {
11
+ return on(window, 'storage', (e) => {
12
+ if (e.key === this.#key) {
13
+ update();
14
+ }
15
+ });
16
+ });
17
+
18
+ constructor(
19
+ key: string,
20
+ fallback: T,
21
+ storage = typeof localStorage === 'undefined' ? undefined : localStorage,
22
+ ) {
23
+ this.#key = key;
24
+ this.#fallback = fallback;
25
+ this.#storage = storage;
26
+ }
27
+
28
+ get current() {
29
+ this.#subscribe(); // handle cross-tab updates
30
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions -- a read subscribes
31
+ this.#version; // handle same-tab updates
32
+
33
+ return (this.#storage?.getItem(this.#key) as T) ?? this.#fallback;
34
+ }
35
+
36
+ set current(v: T) {
37
+ this.#storage?.setItem(this.#key, v);
38
+ this.#version += 1;
39
+ }
40
+ }
@@ -0,0 +1,24 @@
1
+ import { MediaQuery } from 'svelte/reactivity';
2
+ import { Persisted } from './persisted.svelte';
3
+
4
+ import { THEME_KEY } from '$site';
5
+
6
+ // Copied from the blog. The key (`<site name>:theme`, unless `src/lib/site.ts` sets `THEME_KEY`)
7
+ // must match the inline script in `app.html`, which applies the theme before first paint.
8
+ export { THEME_KEY };
9
+
10
+ class Theme {
11
+ #preference = new Persisted<'system' | 'light' | 'dark'>(THEME_KEY, 'system');
12
+ #query = new MediaQuery('prefers-color-scheme: dark');
13
+ #system = $derived<'dark' | 'light'>(this.#query.current ? 'dark' : 'light');
14
+
15
+ get current() {
16
+ return this.#preference.current === 'system' ? this.#system : this.#preference.current;
17
+ }
18
+
19
+ set current(value: 'light' | 'dark') {
20
+ this.#preference.current = value === this.#system ? 'system' : value;
21
+ }
22
+ }
23
+
24
+ export const theme = new Theme();
package/app/lib/tex.ts ADDED
@@ -0,0 +1,99 @@
1
+ import katex, { type KatexOptions } from 'katex';
2
+
3
+ import { katex as config } from '$site';
4
+
5
+ // KaTeX for components, as opposed to `$…$` in Markdown, which the build renders
6
+ // (`rehypeKatex`, from `@mvarble/mesearch-markdown`).
7
+ //
8
+ // Rendering is synchronous, so during prerendering the math is written into the static HTML and
9
+ // needs no JavaScript to display. In the browser the same call runs again: Svelte keeps the
10
+ // prerendered nodes while hydrating, but a client-side navigation renders the page fresh, so KaTeX
11
+ // ships in the chunk of any page that uses these helpers.
12
+
13
+ export type Macros = Record<string, string>;
14
+
15
+ export interface TexOptions {
16
+ display?: boolean;
17
+ /** Merged over the site-wide macros in the site's `katex.config.ts`. */
18
+ macros?: Macros;
19
+ }
20
+
21
+ export function renderTex(source: string, { display = false, macros }: TexOptions = {}): string {
22
+ // KaTeX writes `\gdef` definitions back into `macros`, so each call gets a fresh copy.
23
+ const settings: KatexOptions = {
24
+ ...config,
25
+ displayMode: display,
26
+ macros: { ...config.macros, ...macros },
27
+ };
28
+ try {
29
+ return katex.renderToString(source, { ...settings, throwOnError: true });
30
+ } catch (error) {
31
+ // As in the Markdown pipeline: render the broken formula in KaTeX's error colour and say so
32
+ // on the build's console, rather than failing the page.
33
+ if (import.meta.env.SSR) {
34
+ const message = error instanceof Error ? error.message : String(error);
35
+ console.warn(`katex: component\n ${message}\n in: ${source}`);
36
+ }
37
+ return katex.renderToString(source, { ...settings, throwOnError: false });
38
+ }
39
+ }
40
+
41
+ const escapeHtml = (text: string) =>
42
+ text.replace(
43
+ /[&<>"']/g,
44
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!,
45
+ );
46
+
47
+ /** Whether `text` contains inline math, i.e. an unescaped `$`. */
48
+ export const hasTex = (text: string) => /(^|[^\\])\$/.test(text);
49
+
50
+ /**
51
+ * Text with inline math, as HTML: `$…$` spans are rendered by KaTeX, and everything else is
52
+ * escaped. `\$` is a literal dollar sign.
53
+ */
54
+ export function renderMixed(text: string, macros?: Macros): string {
55
+ let html = '';
56
+ let rest = text;
57
+ while (rest) {
58
+ const open = findDollar(rest, 0);
59
+ if (open < 0) break;
60
+ const close = findDollar(rest, open + 1);
61
+ if (close < 0) break;
62
+ html += escapeHtml(unescapeDollars(rest.slice(0, open)));
63
+ html += renderTex(rest.slice(open + 1, close), { macros });
64
+ rest = rest.slice(close + 1);
65
+ }
66
+ return html + escapeHtml(unescapeDollars(rest));
67
+ }
68
+
69
+ function findDollar(text: string, from: number): number {
70
+ for (let i = from; i < text.length; i++) {
71
+ if (text[i] == '\\') i++;
72
+ else if (text[i] == '$') return i;
73
+ }
74
+ return -1;
75
+ }
76
+
77
+ const unescapeDollars = (text: string) => text.replaceAll('\\$', '$');
78
+
79
+ /**
80
+ * The opening of text with inline math, at most about `max` characters of its source: cut at the
81
+ * last space before `max` that is outside a `$…$` span, with an ellipsis. Text no longer than
82
+ * `max` is returned whole; text with no such space is cut at the first one after it.
83
+ */
84
+ export function excerpt(text: string, max: number): string {
85
+ if (text.length <= max) return text;
86
+ let math = false;
87
+ let cut = -1;
88
+ for (let i = 0; i < text.length; i++) {
89
+ const c = text[i];
90
+ if (c == '\\') i++;
91
+ else if (c == '$') math = !math;
92
+ else if (!math && /\s/.test(c)) {
93
+ if (i <= max || cut < 0) cut = i;
94
+ if (i > max) break;
95
+ }
96
+ }
97
+ if (cut < 0) return text;
98
+ return text.slice(0, cut).replace(/[\s,;:.—–-]+$/, '') + '…';
99
+ }
@@ -0,0 +1,5 @@
1
+ import type { ParamMatcher } from '@sveltejs/kit';
2
+
3
+ // A document's folder name: never a dot in it, so that `/math/retraction.md` is the Markdown
4
+ // export and not a note named `retraction.md`.
5
+ export const match: ParamMatcher = (param) => /^[a-z0-9]+(-[a-z0-9]+)*$/.test(param);
@@ -0,0 +1,5 @@
1
+ import type { ParamMatcher } from '@sveltejs/kit';
2
+
3
+ import { TRACKS } from '$site';
4
+
5
+ export const match: ParamMatcher = (param) => TRACKS.some((track) => track.id == param);
@@ -0,0 +1,2 @@
1
+ export const prerender = true;
2
+ export const trailingSlash = 'always';