1 // 🐙🕸️ GitWikiWeb ∷ build.js
2 // ====================================================================
4 // Copyright © 2023 Lady [@ Lady’s Computer].
6 // This Source Code Form is subject to the terms of the Mozilla Public
7 // License, v. 2.0. If a copy of the MPL was not distributed with this
8 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
10 // --------------------------------------------------------------------
12 // A script for generating static wiki pages from a git repository.
14 // First, clone this repository to your machine in an accessible
15 // location (for example, `/srv/git/GitWikiWeb`). A bare repository is
16 // fine; customize the templates and stylesheets as you like. Then, use
17 // this file as the post‐receive hook for your wiki as follows :—
19 // #!/usr/bin/env -S sh
20 // export GITWIKIWEB=/srv/git/GitWikiWeb
21 // git archive --remote=$GITWIKIWEB HEAD build.js \
23 // | deno run -A - ~/public/wiki $GITWIKIWEB current
25 // The directory `~/public/wiki` (or whatever you specify as the first
26 // argument to `deno run -A -`) **will be deleted** and a new static
27 // wiki will be generated in its place. This script is not very smart
28 // (yet) and cannot selectively determine which pages will need
29 // updating. It just wipes and regenerates the whole thing.
31 // This script will make a number of requests to `$GITWIKIWEB` to
32 // download the latest templates, stylesheets, ⁊·c from this
33 // repository. Consequently, it is best that you set it to a repository
34 // you control and can ensure uptime for—ideally one local to the
35 // computer hosting the wiki.
40 } from "https://deno.land/std@0.196.0/fs/mod.ts";
44 } from "https://deno.land/std@0.196.0/yaml/mod.ts";
45 import djot
from "npm:@djot/djot@0.2.3";
46 import { Parser
} from "npm:htmlparser2@9.0.0";
47 import { DomHandler
, Element
, Text
} from "npm:domhandler@5.0.3";
48 import * as domutils
from "npm:domutils@3.1.0";
49 import domSerializer
from "npm:dom-serializer@2.0.0";
51 const DESTINATION
= Deno
.args
[0] ?? "~/public/wiki";
52 const REMOTE
= Deno
.args
[1] ?? "/srv/git/GitWikiWeb";
53 const REV
= Deno
.args
[2] ?? "HEAD";
61 const NIL
= Object
.preventExtensions(Object
.create(null));
63 const rawBlock
= (strings
, ...substitutions
) => ({
66 text
: String
.raw(strings
, substitutions
),
68 const rawInline
= (strings
, ...substitutions
) => ({
71 text
: String
.raw(strings
, substitutions
),
73 const str
= (strings
, ...substitutions
) => ({
75 text
: String
.raw(strings
, substitutions
),
78 const getDOM
= (source
) => {
80 const handler
= new DomHandler((error
, dom
) => {
82 throw new Error("GitWikiWeb: Failed to process DOM.", {
89 const parser
= new Parser(handler
);
95 const getRemoteContent
= async (pathName
) => {
96 const getArchive
= new Deno
.Command("git", {
97 args
: ["archive", `--remote=${REMOTE}`, REV
, pathName
],
101 const untar
= new Deno
.Command("tar", {
107 getArchive
.stdout
.pipeTo(untar
.stdin
);
114 ] = await Promise
.allSettled([
115 new Response(getArchive
.stderr
).text(),
117 new Response(untar
.stdout
).text(),
118 new Response(untar
.stderr
).text(),
120 ]).then(logErrorsAndCollectResults
);
122 console
.error(err1
+ err2
);
126 if (!getArchiveStatus
.success
) {
128 `GitWikiWeb: git archive returned nonzero exit code: ${getArchiveStatus.code}.`,
130 } else if (!untarStatus
.success
) {
132 `GitWikiWeb: tar returned nonzero exit code: ${untarStatus.code}.`,
139 const logErrorsAndCollectResults
= (results
) =>
140 results
.map(({ value
, reason
}) => {
142 console
.error(reason
);
149 const getReferenceFromPath
= (path
) =>
150 /Sources\/([A-Z][0-9A-Za-z]*(?:\/[A-Z][0-9A-Za-z]*)+)\.djot$/u
151 .exec(path
)?.[1]?.replace
?.("/", ":"); // only replaces first slash
153 const listOfInternalLinks
= (references
, wrapper
= ($) => $) => ({
157 children
: Array
.from(
160 const [namespace, pageName
] = splitReference(reference
);
168 "data-realm": "internal",
169 "data-pagename": pageName
,
170 "data-namespace": namespace,
181 const diffReferences
= async (hash
, againstHead
= false) => {
182 const diff
= new Deno
.Command("git", {
190 ...(againstHead
? [hash
, "HEAD"] : [hash
]),
195 const [diffNames
] = await Promise
.allSettled([
196 new Response(diff
.stdout
).text(),
197 new Response(diff
.stderr
).text(),
198 ]).then(logErrorsAndCollectResults
);
199 return references(diffNames
.split("\0")); // returns an iterable
202 function* references(paths
) {
203 for (const path
of paths
) {
204 const reference
= getReferenceFromPath(path
);
213 const splitReference
= (reference
) => {
214 const colonIndex
= reference
.indexOf(":");
216 reference
.substring(0, colonIndex
),
217 reference
.substring(colonIndex
+ 1),
221 class GitWikiWebPage
{
222 #internalLinks
= new Set();
223 #externalLinks
= new Map();
225 constructor(namespace, name
, ast
, source
, config
) {
226 const internalLinks
= this.#internalLinks
;
227 const externalLinks
= this.#externalLinks
;
228 const sections
= Object
.create(null);
229 djot
.applyFilter(ast
, () => {
230 let titleSoFar
= null; // used to collect strs from headings
235 const links_section
= [];
236 if (internalLinks
.size
|| externalLinks
.size
) {
238 rawBlock
`<nav id="links">`,
242 children
: [str
`this page contains links`],
245 if (internalLinks
.size
) {
247 rawBlock
`<details open="">`,
248 rawBlock
`<summary>on this wiki</summary>`,
249 listOfInternalLinks(internalLinks
),
250 rawBlock
`</details>`,
255 if (externalLinks
.size
) {
257 rawBlock
`<details open="">`,
258 rawBlock
`<summary>elsewhere on the Web</summary>`,
263 children
: Array
.from(
265 ([destination
, text
]) => ({
271 attributes
: { "data-realm": "external" },
289 rawBlock
`</details>`,
302 rawBlock
`${"\uFFFF"}`, // footnote placeholder
310 if (titleSoFar
!= null) {
324 const { attributes
} = e
;
325 attributes
.title
??= titleSoFar
;
332 const { attributes
, reference
, destination
} = e
;
334 /^(?:[A-Z][0-9A-Za-z]*|[@#])?:(?:[A-Z][0-9A-Za-z]*(?:\/[A-Z][0-9A-Za-z]*)*)?$/u
335 .test(reference
?? "")
337 const [namespacePrefix
, pageName
] = splitReference(
340 const expandedNamespace
= {
344 }[namespacePrefix
] ?? namespacePrefix
;
345 const resolvedReference
= pageName
== ""
346 ? `Namespace:${expandedNamespace}`
347 : `${expandedNamespace}:${pageName}`;
348 e
.reference
= resolvedReference
;
349 attributes
["data-realm"] = "internal";
350 attributes
["data-pagename"] = pageName
;
351 attributes
["data-namespace"] = expandedNamespace
;
353 resolvedReference
.startsWith("Editor:") &&
354 (attributes
.class ?? "").split(/\s/gu).includes("sig")
356 // This is a special internal link; do not record it.
359 // This is a non‐special internal link; record it.
360 internalLinks
.add(resolvedReference
);
363 attributes
["data-realm"] = "external";
364 const remote
= destination
??
365 ast
.references
[reference
]?.destination
;
367 externalLinks
.set(remote
, attributes
?.title
);
374 non_breaking_space
: {
376 if (titleSoFar
!= null) {
377 titleSoFar
+= "\xA0";
388 const { attributes
, children
} = e
;
389 const heading
= children
.find(({ tag
}) =>
392 const title
= (() => {
393 if (heading
?.attributes
?.title
) {
394 const result
= heading
.attributes
.title
;
395 delete heading
.attributes
.title
;
398 return heading
.level
== 1
399 ? `${namespace}:${name}`
400 : "untitled section";
403 const variantTitles
= Object
.create(null);
404 for (const attr
in attributes
) {
405 if (attr
.startsWith("v-")) {
406 Object
.defineProperty(
409 { ...READ_ONLY
, value
: attributes
[attr
] },
411 delete attributes
[attr
];
416 const definition
= Object
.create(null, {
417 title
: { ...READ_ONLY
, value
: title
},
420 value
: Object
.preventExtensions(variantTitles
),
423 if (heading
.level
== 1 && !("main" in sections
)) {
424 attributes
.id
= "main";
425 heading
.attributes
??= {};
426 heading
.attributes
.class = "main";
431 Object
.defineProperty(
437 value
: Object
.preventExtensions(definition
),
442 `GitWikiWeb: A section with the provided @id already exists: ${attributes.id}`,
450 if (titleSoFar
!= null) {
459 enter
: ({ text
}) => {
460 if (titleSoFar
!= null) {
471 const codepoint
= /^U\+([0-9A-Fa-f]+)$/u.exec(alias
)?.[1];
474 String.fromCodePoint(parseInt(codepoint, 16))
477 const resolved
= config
.symbols
?.[alias
];
478 return resolved
!= null ? str
`${resolved}` : e
;
484 Object
.defineProperties(this, {
485 ast
: { ...READ_ONLY
, value
: ast
},
486 namespace: { ...READ_ONLY
, value
: namespace },
487 name
: { ...READ_ONLY
, value
: name
},
490 value
: Object
.preventExtensions(sections
),
492 source
: { ...READ_ONLY
, value
: source
},
497 yield* this.#externalLinks
;
501 yield* this.#internalLinks
;
506 // Patches for Djot HTML renderer.
507 const { HTMLRenderer
: { prototype: htmlRendererPrototype
} } = djot
;
508 const { inTags
: upstreamInTags
} = htmlRendererPrototype
;
509 htmlRendererPrototype
.inTags = function (
513 extraAttrs
= undefined,
515 const attributes
= node
.attributes
?? NIL
;
516 if ("as" in attributes
) {
517 const newTag
= attributes
.as
;
518 delete attributes
.as
;
519 return upstreamInTags
.call(
527 return upstreamInTags
.call(
538 const config
= await
getRemoteContent("config.yaml").then((yaml
) =>
539 parseYaml(yaml
, { schema
: JSON_SCHEMA
})
541 const ls
= new Deno
.Command("git", {
542 args
: ["ls-tree", "-rz", "HEAD"],
550 ] = await Promise
.allSettled([
551 new Response(ls
.stdout
).text().then((lsout
) =>
554 .slice(0, -1) // drop the last entry; it is empty
555 .map(($) => $.split(/\s+/g))
557 new Response(ls
.stderr
).text(),
559 ]).then(logErrorsAndCollectResults
);
561 console
.error(lserr
);
565 if (!lsstatus
.success
) {
567 `GitWikiWeb: git ls-tree returned nonzero exit code: ${lsstatus.code}.`,
570 const requiredButMissingPages
= new Map([
571 ["Special:FrontPage", "front page"],
572 ["Special:NotFound", "not found"],
573 ["Special:RecentlyChanged", "recently changed"],
575 const pages
= new Map();
576 const promises
= [emptyDir(DESTINATION
)];
577 for (const object
of objects
) {
578 const hash
= object
[2];
579 const path
= object
[3];
580 const reference
= getReferenceFromPath(path
);
581 if (reference
== null) {
584 const [namespace, pageName
] = splitReference(reference
);
585 const cat
= new Deno
.Command("git", {
586 args
: ["cat-file", "blob", hash
],
590 const promise
= Promise
.allSettled([
591 new Response(cat
.stdout
).text(),
592 new Response(cat
.stderr
).text(),
594 ]).then(logErrorsAndCollectResults
).then(
595 ([source
, caterr
, catstatus
]) => {
597 console
.error(caterr
);
601 if (!catstatus
.success
) {
603 `GitWikiWeb: git cat-file returned nonzero exit code: ${catstatus.code}.`,
606 const reference
= `${namespace}:${pageName}`;
607 const page
= new GitWikiWebPage(
612 console
.warn(`Djot(${reference}): ${$.render()}`),
617 pages
.set(reference
, page
);
618 requiredButMissingPages
.delete(reference
);
622 promises
.push(promise
);
625 for (const [reference
, defaultTitle
] of requiredButMissingPages
) {
626 const [namespace, pageName
] = splitReference(reference
);
627 const source
= `# ${defaultTitle}\n`;
628 const page
= new GitWikiWebPage(
633 console
.warn(`Djot(${reference}): ${$.render()}`),
638 pages
.set(reference
, page
);
640 await Promise
.allSettled(promises
).then(
641 logErrorsAndCollectResults
,
643 const [template
, recentlyChanged
] = await Promise
.allSettled([
644 getRemoteContent("template.html"),
646 const dateParse
= new Deno
.Command("git", {
647 args
: ["rev-parse", "--after=1 week ago"],
651 const [maxAge
] = await Promise
.allSettled([
652 new Response(dateParse
.stdout
).text(),
653 new Response(dateParse
.stderr
).text(),
654 ]).then(logErrorsAndCollectResults
);
659 const revList
= new Deno
.Command("git", {
660 args
: ["rev-list", maxAge
, "--reverse", "HEAD"],
664 [commit
] = await Promise
.allSettled([
665 new Response(revList
.stdout
).text().then((list
) =>
668 new Response(revList
.stderr
).text(),
669 ]).then(logErrorsAndCollectResults
);
672 const revList2
= new Deno
.Command("git", {
673 args
: ["rev-list", "--max-count=1", "HEAD^"],
677 [commit
] = await Promise
.allSettled([
678 new Response(revList2
.stdout
).text().then((list
) =>
681 new Response(revList2
.stderr
).text(),
682 ]).then(logErrorsAndCollectResults
);
686 const results
= new Array(6);
687 const seen
= new Set();
688 const maxRecency
= Math
.max(config
.max_recency
| 0, 0);
689 let recency
= maxRecency
;
692 const show
= new Deno
.Command("git", {
696 "--format=%H%x00%cI%x00%cD",
697 recency
? `HEAD~${maxRecency - recency}` : commit
,
703 [hash
, dateTime
, humanReadable
],
704 ] = await Promise
.allSettled([
705 new Response(show
.stdout
).text().then((rev
) =>
706 rev
.trim().split("\0")
708 new Response(show
.stderr
).text(),
709 ]).then(logErrorsAndCollectResults
);
713 const ref
of (await
diffReferences(current
, !recency
))
722 results
[recency
] = { dateTime
, hash
, humanReadable
, refs
};
723 } while (recency
-- > 0 && current
&& current
!= commit
);
728 (name
) => ensureDir(`${DESTINATION}/${name}`),
730 ["style.css"].map((dependency
) =>
731 getRemoteContent(dependency
).then((source
) =>
733 `${DESTINATION}/${dependency}`,
739 ]).then(logErrorsAndCollectResults
);
741 const redLinks
= (() => {
742 const result
= new Set();
743 for (const page
of pages
.values()) {
744 for (const link
of page
.internalLinks()) {
745 if (pages
.has(link
)) {
755 const [pageRef
, { ast
, namespace, sections
, source
}] of pages
757 const title
= sections
.main
?.title
?? pageRef
;
758 djot
.applyFilter(ast
, () => {
759 let isNavigationPage
= true;
763 const { content
, navigation
} = (() => {
764 const navigation
= [];
765 if (pageRef
== "Special:RecentlyChanged") {
768 attributes
: { class: "recent-changes" },
771 children
: Array
.from(function* () {
773 const [index
, result
] of recentlyChanged
776 if (result
!= null) {
782 yield* listOfInternalLinks(refs
, (link
) => ({
783 tag
: index
== 0 ? "span" : "strong",
784 attributes
: { "data-recency": `${index}` },
787 ...(index
== 0 ? [] : [
789 rawInline
`<small>(<time dateTime="${dateTime}">`,
790 str
`${humanReadable}`,
791 rawInline
`</time>)</small>`,
802 isNavigationPage
= false;
803 return { content
: e
.children
, navigation
};
811 generated
: "", // will be removed later
814 children
: [str
`${title}`],
816 rawBlock
`<details id="navigation-about" open="">`,
817 rawBlock
`<summary>about this listing</summary>`,
820 rawBlock
`</article>`,
821 rawBlock
`</details>`,
824 rawBlock
`<nav id="navigation">`,
834 rawBlock
`</article>`,
841 const attributes
= e
.attributes
?? NIL
;
843 isNavigationPage
&& e
.level
== 1 &&
844 attributes
?.class == "main"
846 if ("generated" in attributes
) {
847 delete attributes
.generated
;
856 if (e
.level
== 1 && e
.attributes
?.class == "main") {
858 rawBlock
`<header class="main">`,
860 { tag
: "verbatim", text
: pageRef
},
872 const { attributes
, children
, reference
} = e
;
873 if (attributes
["data-realm"] == "internal") {
875 if (redLinks
.has(reference
)) {
877 `/Special:NotFound?path=/${reference}`;
878 attributes
["data-notfound"] = "";
880 e
.destination
= `/${reference}`;
882 if (children
.length
== 0) {
884 pages
.get(reference
)?.sections
?.main
?? NIL
;
885 const { v
} = attributes
;
888 str
`${section.title ?? reference}`,
894 section.variantTitles?.[v] ?? section.title ??
901 if (children
.length
== 0 && "title" in attributes
) {
904 str
`${attributes.title}`,
910 (attributes
.class ?? "").split(/\s/gu).includes("sig")
914 attributes
: { class: "sig" },
915 children
: [str
`—${"\xA0"}`, e
],
925 if (e
.children
.length
< 1) {
926 // The heading for this section was removed and it had
927 // no other children.
936 const renderedAST
= djot
.renderAST(ast
);
937 const doc
= getDOM(template
);
938 const result
= getDOM(djot
.renderHTML(ast
, {
940 raw_block
: (node
, context
) => {
941 if (node
.format
== "html" && node
.text
== "\uFFFF") {
942 if (context
.nextFootnoteIndex
> 1) {
943 const result
= context
.renderNotes(ast
.footnotes
);
944 context
.nextFootnoteIndex
= 1;
950 return context
.renderAstNodeDefault(node
);
955 const headElement
= domutils
.findOne(
956 (node
) => node
.name
== "head",
959 const titleElement
= domutils
.findOne(
960 (node
) => node
.name
== "title",
963 const contentElement
= domutils
.findOne(
964 (node
) => node
.name
== "gitwikiweb-content",
967 if (headElement
== null) {
969 "GitWikiWeb: Template must explicitly include a <head> element.",
972 domutils
.appendChild(
974 new Element("link", {
977 href
: `/${pageRef}/source.djot`,
980 if (titleElement
== null) {
981 domutils
.prependChild(
983 new Element("title", {}, [new Text(title
)]),
986 domutils
.prependChild(titleElement
, new Text(`${title} | `));
989 if (contentElement
== null) {
991 "GitWikiWeb: Template did not include a <gitwikiweb-content> element.",
994 for (const node
of [...result
]) {
995 domutils
.prepend(contentElement
, node
);
997 domutils
.removeElement(contentElement
);
1001 `${DESTINATION}/${pageRef}/index.html`,
1002 domSerializer(doc
, {
1004 encodeEntities
: "utf8",
1005 selfClosingTags
: true,
1008 { createNew
: true },
1013 `${DESTINATION}/${pageRef}/index.ast`,
1015 { createNew
: true },
1020 `${DESTINATION}/${pageRef}/source.djot`,
1022 { createNew
: true },
1026 await Promise
.allSettled(promises
).then(
1027 logErrorsAndCollectResults
,
1029 console
.log(`GitWikiWeb: Wrote ${pages.size} page(s).`);