]> Lady’s Gitweb - Beorn/blob - build.js
Support hooks for transforming build script output
[Beorn] / build.js
1 #!/usr/bin/env -S deno run --allow-read --allow-write
2 // 🧸📔 Bjørn ∷ build.js
3 // ====================================================================
4 //
5 // Copyright © 2022‐2023 Lady [@ Lady’s Computer].
6 //
7 // This Source Code Form is subject to the terms of the Mozilla Public
8 // License, v. 2.0. If a copy of the MPL was not distributed with this
9 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
10
11 // As the shebang at the top of this file indicates, it must be run via
12 // Deno with read and write permissions. You can get Deno from
13 // <https://deno.land/>.
14 //
15 // This file generates a minimal, Atom‐supporting blog from a handful
16 // of R·D·F∕X·M·L files and a couple of templates. It will silently
17 // overwrite the files it generates. This is usually what you want.
18 //
19 // ※ The actual run script is at the very end of this file. It is
20 // preceded by a number of helper function definitions, of which the
21 // most important is `applyMetadata` (which is used to generate the
22 // HTML and Atom elements from the processed metadata).
23 //
24 // ※ The list of supported metadata properties and their R·D·F
25 // representations is provided by `context`. You can add support for
26 // new metadata fields simply by adding them to the `context` and then
27 // handling them appropriately in `applyMetadata`.
28 //
29 // This script is a bit of a mess and you shouldn’t bother trying to
30 // understand the whole thing before you start hacking on it. Just find
31 // the parts relevant to whatever you want to change, and assume that
32 // things will work in sensible (if cumbersome) browser‐like ways.
33
34 // This import polyfills a (mediocre but sufficient) D·O·M environment
35 // onto the global object.
36 import "https://git.ladys.computer/Lemon/blob_plain/0.2.2:/window/mod.js";
37
38 // Much of the H·T·M·L generation in this script uses the 🍋🏷 Lemon
39 // library for convenience (<https://git.ladys.computer/Lemon>).
40 //
41 // Frequently this will be bound to a different document than the
42 // global one and called as `LMN`.
43 import Lemon from "https://git.ladys.computer/Lemon/blob_plain/0.2.2:/mod.js";
44
45 // Markdown processing uses rusty_markdown, which uses Rust’s
46 // pulldown-cmark behind the scenes via WebAssembly.
47 import {
48 html as markdownTokensToHTML,
49 tokens as markdownTokens,
50 } from "https://deno.land/x/rusty_markdown@v0.4.1/mod.ts";
51
52 // Various namespaces.
53 const AWOL = "http://bblfish.net/work/atom-owl/2006-06-06/";
54 const DC11 = "http://purl.org/dc/elements/1.1/";
55 const FOAF = "http://xmlns.com/foaf/0.1/";
56 const RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
57 const RDFS = "http://www.w3.org/2000/01/rdf-schema#";
58 const SIOC = "http://rdfs.org/sioc/ns#";
59 const XML = "http://www.w3.org/XML/1998/namespace";
60 const XHTML = "http://www.w3.org/1999/xhtml";
61
62 /**
63 * Adds the provided content to the provided element.
64 *
65 * Content may be either nullish (in which case nothing is added), a
66 * string (object or literal), a NodeList, or an array of zero or more
67 * of these values. Nodes need not belong to the same document as the
68 * provided element; they will be imported. During this process,
69 * special care is taken to ensure that the resulting content is
70 * correctly language‐tagged for its new context.
71 *
72 * ☡ If the provided element is not attached to anything, then it won’t
73 * be possible to walk its parent nodes in search of language
74 * information. Generally, it is best to attach elements to a document
75 * BEFORE calling this function.
76 */
77 const addContent = (element, content) => {
78 const { ownerDocument: document } = element;
79 const LMN = Lemon.bind({ document });
80 if (content == null) {
81 // The provided content is nullish.
82 /* do nothing */
83 } else if (Array.isArray(content)) {
84 // The provided content is an array.
85 content.forEach(addContent.bind(null, element));
86 } else if (Object(content) instanceof String) {
87 // The provided content is a string (object or literal).
88 const { lang } = content;
89 if (lang && lang != getLanguage(element)) {
90 const newChild = element.appendChild(LMN.span`${content}`);
91 setLanguage(newChild, lang);
92 } else {
93 element.appendChild(document.createTextNode(`${content}`));
94 }
95 } else {
96 // Assume the provided content is a NodeList.
97 if (element.hasAttribute("property")) {
98 // The provided element has an R·D·F∕A property; note that its
99 // datatype is `XMLLiteral`.
100 element.setAttribute("datatype", "XMLLiteral");
101 } else {
102 // The provided element does not have an R·D·F∕A property.
103 /* do nothing */
104 }
105 for (const child of Array.from(content)) {
106 // Iterate over the nodes in the provided NodeList and handle
107 // them appropriately.
108 const lang = getLanguage(child);
109 const newChild = (() => {
110 const imported = document.importNode(child, true);
111 if (lang && lang != getLanguage(element)) {
112 // The imported node’s language would change if it were just
113 // imported directly into the provided element.
114 if (imported.nodeType == 1) {
115 // The imported node is an element node.
116 setLanguage(imported, lang);
117 return imported;
118 } else if (imported.nodeType <= 4) {
119 // The imported node is a text node.
120 const result = LMN.span`${imported}`;
121 setLanguage(result, lang);
122 return result;
123 } else {
124 // The imported node is not an element or text.
125 return imported;
126 }
127 } else {
128 // The imported node’s language will not change if imported
129 // directly into the provided element.
130 return imported;
131 }
132 })();
133 element.appendChild(newChild);
134 }
135 }
136 return element;
137 };
138
139 /**
140 * Adds HTML for the provided people to the provided element, tagging
141 * them with the provided property.
142 *
143 * ☡ As with `addContent`, it is best to attach elements to a document
144 * PRIOR to providing them to this function, for language‐detection
145 * reasons.
146 */
147 const addPeople = (element, people, property) => {
148 const { ownerDocument: document } = element;
149 const LMN = Lemon.bind({ document });
150 const { length } = people;
151 for (const [index, { uri, name }] of people.entries()) {
152 const personElement = element.appendChild(
153 uri
154 ? LMN.a.rel(`${property}`).href(`${uri}`)``
155 : LMN.span.rel(`${property}`)``,
156 );
157 if (name == null) {
158 // The current person has no name; provide its `uri`.
159 personElement.appendChild(LMN.code`${uri}`);
160 } else {
161 // The current person has a name.
162 addContent(
163 personElement.appendChild(
164 LMN.span.property(`${FOAF}name`)``,
165 ),
166 name,
167 );
168 }
169 if (index < length - 2) {
170 // The current person is two or greater from the end.
171 addContent(element, ", ");
172 } else if (index < length - 1) {
173 // The current person is one from the end.
174 addContent(element, " & ");
175 } else {
176 // The current person is the last.
177 /* do nothing */
178 }
179 }
180 return element;
181 };
182
183 /**
184 * Applies the provided metadata to the provided node by creating and
185 * inserting the appropriate elements, then returns the provided node.
186 *
187 * If the provided node is a document, it is assumed to be an entry
188 * template, and full entry H·T·M·L is generated. If it is a document
189 * fragment, it is assumed to be a document fragment collecting entries
190 * for the H·T·M·L feed index page, and entry H·T·M·L links are
191 * generated. Otherwise, the provided node is assumed to be an Atom
192 * element, and Atom metadata elements are generated.
193 */
194 const applyMetadata = (node, metadata) => {
195 if (node.nodeType == 9) {
196 // The provided node is a document.
197 //
198 // Assume it is an entry template document and insert the full
199 // entry H·T·M·L accordingly.
200 const document = node;
201 const { documentElement } = document;
202 if (hasExpandedName(documentElement, XHTML, "html")) {
203 // This is an XHTML template.
204 const LMN = Lemon.bind({ document });
205 const {
206 id,
207 title,
208 author,
209 contributor,
210 published,
211 content,
212 rights,
213 updated,
214 } = metadata;
215 fillOutHead(document, metadata, "entry");
216 const contentPlaceholder = document.getElementsByTagNameNS(
217 XHTML,
218 "bjørn-content",
219 ).item(0);
220 if (contentPlaceholder != null) {
221 // The content placeholder exists; replace it with the content
222 // nodes.
223 const { parentNode: contentParent } = contentPlaceholder;
224 const contentElement = contentParent.insertBefore(
225 LMN.article.about(`${id}`)`${"\n"}`,
226 contentPlaceholder,
227 );
228
229 // Handle the entry content header.
230 contentElement.appendChild(
231 document.createComment(" BEGIN ENTRY HEADER "),
232 );
233 addContent(contentElement, "\n");
234 const contentHeader = contentElement.appendChild(
235 LMN.header.id("entry.header")`${"\n\t"}`,
236 );
237 addContent(
238 contentHeader.appendChild(
239 LMN.h1.id("entry.title").property(`${DC11}title`)``,
240 ),
241 title,
242 );
243 if (author.length > 0) {
244 // This entry has authors.
245 addContent(contentHeader, "\n\t");
246 addPeople(
247 contentHeader.appendChild(
248 LMN.p.id("entry.author")``,
249 ),
250 author,
251 `${DC11}creator`,
252 );
253 } else {
254 // This entry does not have authors.
255 /* do nothing */
256 }
257 if (contributor.length > 0) {
258 // This entry has contributors.
259 addContent(contentHeader, "\n\t");
260 addContent(
261 addPeople(
262 contentHeader.appendChild(
263 LMN.p.id(
264 "entry.contributor",
265 )`With contributions from `,
266 ),
267 contributor,
268 `${DC11}contributor`,
269 ),
270 ".",
271 );
272 } else {
273 // This entry does not have contributors.
274 /* do nothing */
275 }
276 if (published) {
277 // This entry has a publication date.
278 addContent(contentHeader, "\n\t");
279 contentHeader.appendChild(
280 LMN.p.id("entry.published")`Published: ${LMN.time.property(
281 `${DC11}date`,
282 )`${published}`}.`,
283 );
284 } else {
285 // This entry does not have a publication date.
286 /* do nothing */
287 }
288 addContent(contentHeader, "\n");
289 addContent(contentElement, "\n");
290 contentElement.appendChild(
291 document.createComment(" END ENTRY HEADER "),
292 );
293 addContent(contentElement, "\n");
294
295 // Handle the entry content.
296 contentElement.appendChild(
297 document.createComment(" BEGIN ENTRY CONTENT "),
298 );
299 addContent(contentElement, "\n");
300 addContent(
301 contentElement.appendChild(
302 LMN.div.id("entry.content").property(`${SIOC}content`)``,
303 ),
304 content,
305 );
306 addContent(contentElement, "\n");
307 contentElement.appendChild(
308 document.createComment(" END ENTRY CONTENT "),
309 );
310 addContent(contentElement, "\n");
311
312 // Handle the entry content footer.
313 contentElement.appendChild(
314 document.createComment(" BEGIN ENTRY FOOTER "),
315 );
316 addContent(contentElement, "\n");
317 const contentFooter = contentElement.appendChild(
318 LMN.footer.id("entry.footer")`${"\n\t"}`,
319 );
320 if (rights) {
321 addContent(
322 contentFooter.appendChild(
323 LMN.div.id("entry.rights").property(`${DC11}rights`)``,
324 ),
325 rights,
326 );
327 addContent(contentFooter, "\n\t");
328 }
329 contentFooter.appendChild(
330 LMN.p.id("entry.updated")`Last updated: ${LMN.time.property(
331 `${AWOL}updated`,
332 )`${updated}`}.`,
333 );
334 addContent(contentFooter, "\n");
335 addContent(contentElement, "\n");
336 contentElement.appendChild(
337 document.createComment(" END ENTRY FOOTER "),
338 );
339 addContent(contentElement, "\n");
340
341 // Remove the placeholder.
342 contentParent.removeChild(contentPlaceholder);
343 } else {
344 // There is no content placeholder.
345 /* do nothing */
346 }
347 globalThis.bjørnTransformEntryHTML?.(document, metadata);
348 } else {
349 // This is not an XHTML template.
350 /* do nothing */
351 }
352 } else if (node.nodeType == 11) {
353 // The provided node is a document fragment.
354 //
355 // Assume it is collecting H·T·M·L feed entry links and insert a
356 // new one for the provided metadata.
357 const { ownerDocument: document } = node;
358 const LMN = Lemon.bind({ document });
359 const {
360 id,
361 title,
362 author,
363 published,
364 summary,
365 } = metadata;
366 // The content placeholder exists; replace it with the content
367 // nodes.
368 node.appendChild(
369 document.createComment(` <${id}> `),
370 );
371 addContent(node, "\n");
372 const contentElement = node.appendChild(
373 LMN.li.resource(`${id}`)`${"\n"}`,
374 );
375 addContent(
376 contentElement.appendChild(
377 LMN.a.href(`${id}`)``,
378 ).appendChild(
379 LMN.h3.property(`${DC11}title`)``,
380 ),
381 title,
382 );
383 if (author.length > 0) {
384 // This entry has authors.
385 addContent(contentElement, "\n");
386 addPeople(
387 contentElement.appendChild(
388 LMN.p``,
389 ),
390 author,
391 `${DC11}creator`,
392 );
393 } else {
394 // This entry does not have authors.
395 /* do nothing */
396 }
397 if (published) {
398 // This entry has a publication date.
399 addContent(contentElement, "\n");
400 contentElement.appendChild(
401 LMN.time.property(`${DC11}date`)`${published}`,
402 );
403 } else {
404 // This entry does not have a publication date.
405 /* do nothing */
406 }
407 if (summary) {
408 // This entry has a summary.
409 addContent(contentElement, "\n");
410 addContent(
411 contentElement.appendChild(
412 LMN.div.property(`${DC11}abstract`)``,
413 ),
414 summary,
415 );
416 } else {
417 // This entry does not have a summary.
418 /* do nothing */
419 }
420 addContent(contentElement, "\n");
421 addContent(node, "\n");
422 } else {
423 // The provided node is not a document or document fragment.
424 //
425 // Assume it is an Atom element of some sort and add the
426 // the appropriate metadata as child elements.
427 const { ownerDocument: document } = node;
428 const alternateLink = node.appendChild(
429 document.createElement("link"),
430 );
431 alternateLink.setAttribute("rel", "alternate");
432 alternateLink.setAttribute("type", "application/xhtml+xml");
433 alternateLink.setAttribute("href", metadata.id);
434 for (const [property, values] of Object.entries(metadata)) {
435 for (const value of Array.isArray(values) ? values : [values]) {
436 const propertyNode = document.createElement(property);
437 switch (context[property]?.type) {
438 case "person": {
439 // The property describes a person.
440 const { name, uri } = value;
441 if (uri) {
442 // The person has a U·R·I.
443 const subnode = document.createElement("uri");
444 subnode.textContent = uri;
445 propertyNode.appendChild(subnode);
446 } else {
447 // The person does not have a U·R·I.
448 /* do nothing */
449 }
450 if (name != null) {
451 // The person has a name.
452 const subnode = document.createElement("name");
453 subnode.textContent = name;
454 propertyNode.appendChild(subnode);
455 } else {
456 // The person does not have a name.
457 /* do nothing */
458 }
459 if (propertyNode.childNodes.length == 0) {
460 // Neither a U·R·I nor a name was added; skip adding this
461 // property.
462 continue;
463 } else {
464 break;
465 }
466 }
467 default: {
468 // The property describes (potentially rich) text.
469 if (value == null) {
470 // The property has no value; skip appending it to the node.
471 continue;
472 } else if (Object(value) instanceof String) {
473 // The property has a string value.
474 propertyNode.textContent = value;
475 break;
476 } else {
477 // The property value is a list of nodes.
478 propertyNode.setAttribute("type", "xhtml");
479 const div = document.createElementNS(XHTML, "div");
480 for (const child of Array.from(value)) {
481 div.appendChild(document.importNode(child, true));
482 }
483 propertyNode.appendChild(div);
484 break;
485 }
486 }
487 }
488 node.appendChild(propertyNode);
489 }
490 }
491 }
492 return node;
493 };
494
495 /**
496 * The base path from which to pull files and generate resulting
497 * documents.
498 */
499 const basePath = `./${Deno.args[0] ?? ""}`;
500
501 /**
502 * Mappings from Atom concepts to R·D·F∕X·M·L ones.
503 *
504 * `namespace` and `localName` give the R·D·F representation for the
505 * concept. Three `type`s are supported :—
506 *
507 * - "person": Has a `name` (`foaf:name`) and an `iri` (`rdf:about`).
508 * Emails are NOT supported.
509 *
510 * - "text": Can be string, markdown, or X·M·L content.
511 *
512 * - "literal": This is a plaintext field.
513 */
514 const context = {
515 author: { namespace: DC11, localName: "creator", type: "person" },
516 // category is not supported at this time
517 content: { namespace: SIOC, localName: "content", type: "text" },
518 contributor: {
519 namespace: DC11,
520 localName: "contributor",
521 type: "person",
522 },
523 // generator is provided by the build script
524 icon: { namespace: AWOL, localName: "icon", type: "literal" },
525 // link is provided by the build script
526 logo: { namespace: AWOL, localName: "logo", type: "literal" },
527 published: {
528 namespace: DC11,
529 localName: "date",
530 type: "literal",
531 },
532 rights: { namespace: DC11, localName: "rights", type: "text" },
533 // source is not supported at this time
534 subtitle: { namespace: RDFS, localName: "label", type: "text" },
535 summary: { namespace: DC11, localName: "abstract", type: "text" },
536 title: { namespace: DC11, localName: "title", type: "text" },
537 // updated is provided by the build script
538 };
539
540 const {
541 /**
542 * Returns a new document created from the source code of the named
543 * template.
544 */
545 documentFromTemplate,
546 } = (() => {
547 const cache = Object.create(null);
548 return {
549 documentFromTemplate: async (name) =>
550 parser.parseFromString(
551 name in cache ? cache[name] : (
552 cache[name] = await Deno.readTextFile(
553 `${basePath}/index#${name}.xhtml`,
554 )
555 ),
556 "application/xml",
557 ),
558 };
559 })();
560
561 /**
562 * Fills out the `head` of the provided H·T·M·L document with the
563 * appropriate metadata.
564 */
565 const fillOutHead = (document, metadata, type) => {
566 const { documentElement } = document;
567 const LMN = Lemon.bind({ document });
568 const head =
569 Array.from(documentElement.childNodes).find(($) =>
570 hasExpandedName($, XHTML, "head")
571 ) ?? documentElement.insertBefore(
572 LMN.head``,
573 documentElement.childNodes.item(0),
574 );
575 const titleElement =
576 Array.from(head.childNodes).find(($) =>
577 hasExpandedName($, XHTML, "title")
578 ) ?? head.appendChild(LMN.title``);
579 const {
580 title,
581 author,
582 subtitle,
583 summary,
584 } = metadata;
585 titleElement.textContent = Object(title) instanceof String
586 ? title
587 : Array.from(title ?? []).map(($) => $.textContent).join("");
588 for (const person of author) {
589 // Iterate over authors and add appropriate meta tags.
590 head.appendChild(
591 LMN.meta({
592 name: "author",
593 content: person.name ?? person.uri,
594 })``,
595 );
596 }
597 head.appendChild(
598 LMN.meta({ name: "generator", content: "🧸📔 Bjørn" })``,
599 );
600 if (type == "entry") {
601 // The provided document is an entry document.
602 if (summary) {
603 // The entry has a summary.
604 head.appendChild(
605 LMN.meta({
606 name: "description",
607 content: Object(summary) instanceof String
608 ? summary
609 : Array.from(summary).map(($) => $.textContent).join(""),
610 })``,
611 );
612 } else {
613 /* do nothing */
614 }
615 head.appendChild(
616 LMN.link
617 .rel("alternate")
618 .type("application/atom+xml")
619 .href("../../feed.atom")``,
620 );
621 } else {
622 // The provided document is not an entry document.
623 if (subtitle) {
624 // The entry has a subtitle.
625 head.appendChild(
626 LMN.meta({
627 name: "description",
628 content: Object(subtitle) instanceof String
629 ? summary
630 : Array.from(subtitle).map(($) => $.textContent).join(""),
631 })``,
632 );
633 } else {
634 /* do nothing */
635 }
636 head.appendChild(
637 LMN.link
638 .rel("alternate")
639 .type("application/atom+xml")
640 .href("./feed.atom")``,
641 );
642 }
643 globalThis.bjørnTransformHead?.(head, metadata, type);
644 };
645
646 /**
647 * Returns the language of the provided node, or null if it has no
648 * language.
649 *
650 * ※ This function returns null regardless of whether a node has no
651 * language implicitly (because no parent element had a language set)
652 * or explicitly (because the value of the @xml:lang attribute was "").
653 *
654 * ※ If no language is set, the language of the node is ambiguous.
655 * Because this typically occurs when a node is expected to inherit its
656 * language from some parent context, this lack of language information
657 * SHOULD NOT be preserved when inserting the node into a document
658 * where language information is present (instead allowing the node to
659 * inherit language information from the node it is being inserted
660 * into). There are explicit language codes which may be used if this
661 * behaviour is undesirable: If you want to signal that a node does not
662 * contain linguistic content, use the language code `zxx`. If you want
663 * to signal that a node’s language is undetermined in a way which will
664 * never inherit from a parent node, use the language code `und`.
665 */
666 const getLanguage = (node) => {
667 const { nodeType } = node;
668 if (nodeType == 1) {
669 // The provided node is an element.
670 const ownLanguage =
671 node.namespaceURI == XHTML && node.hasAttribute("lang") &&
672 node.getAttribute("lang") ||
673 node.hasAttributeNS(XML, "lang") &&
674 node.getAttributeNS(XML, "lang");
675 if (ownLanguage) {
676 // The element has a recognized language attribute set to a
677 // nonempty value.
678 return ownLanguage;
679 } else if (ownLanguage === "") {
680 // The element explicitly has no language.
681 return null;
682 } else {
683 // The element has no language attribute, but may inherit a
684 // language from its parent.
685 const { parentNode } = node;
686 if (parentNode != null && parentNode.nodeType != 9) {
687 // The provided node has a nondocument parent; get the language
688 // from there.
689 return getLanguage(parentNode);
690 } else {
691 // The provided node has no parent and consequently no language.
692 return null;
693 }
694 }
695 } else if (nodeType == 9) {
696 // The provided node is a document.
697 return getLanguage(node.documentElement);
698 } else if (nodeType == 11) {
699 // The provided node is a document fragment.
700 return getLanguage(node.ownerDocument.documentElement);
701 } else {
702 // The provided node may inherit a language from a parent node.
703 const { parentNode } = node;
704 if (parentNode != null) {
705 // The provided node has a parent; get the language from there.
706 return getLanguage(parentNode);
707 } else {
708 // The provided node has no parent and consequently no language.
709 return null;
710 }
711 }
712 };
713
714 /**
715 * Returns whether the provided node has the provided namespace and
716 * local name.
717 */
718 const hasExpandedName = (node, namespace, localName) =>
719 node.namespaceURI == namespace && node.localName == localName;
720
721 /**
722 * Processes an RDF document and returns an object of Atom metadata.
723 *
724 * See `context` for the metadata properties supported.
725 */
726 const metadataFromDocument = (
727 { documentElement: root, lastModified },
728 ) => {
729 const contextEntries = [...Object.entries(context)];
730 const documentType = hasExpandedName(root, AWOL, "Feed")
731 ? "feed"
732 : "entry";
733 const result = Object.assign(Object.create(null), {
734 id: root.getAttributeNS(RDF, "about"),
735 updated: documentType == "feed" || lastModified == null
736 ? new Date().toISOString()
737 : lastModified.toISOString(),
738 title: null,
739 author: [],
740 contributor: [],
741 rights: null,
742 ...(documentType == "feed"
743 ? { // additional feed properties
744 subtitle: null,
745 logo: null,
746 icon: null,
747 }
748 : { // additional entry properties
749 published: null,
750 summary: null,
751 content: null,
752 }),
753 });
754 for (
755 const node of [
756 ...Array.from(root.attributes),
757 ...Array.from(root.childNodes),
758 ]
759 ) {
760 // Iterate over all child nodes and attributes, finding ones which
761 // correspond to Atom properties and assigning the appropriate
762 // metadata.
763 const [name, { type }] = contextEntries.find(
764 ([_, value]) =>
765 hasExpandedName(node, value.namespace, value.localName),
766 ) ?? [, {}];
767 if (name != null && name in result) {
768 // The current node corresponds with an Atom property.
769 const { [name]: existing } = result;
770 const content = (() => {
771 switch (type) {
772 case "person": {
773 // The node describes a person.
774 const base =
775 node.getAttributeNS?.(RDF, "parseType") == "Resource"
776 ? node
777 : Array.from(node.childNodes).find(($) =>
778 $.nodeType == 1
779 );
780 const person = {
781 name: null,
782 uri: base.getAttributeNS?.(RDF, "about") || null,
783 };
784 for (
785 const subnode of [
786 ...Array.from(base.attributes),
787 ...Array.from(base.childNodes),
788 ]
789 ) {
790 // Process child nodes and attributes for the current
791 // person, looking for name metadata.
792 if (hasExpandedName(subnode, FOAF, "name")) {
793 // This is a name node.
794 if (person.name == null) {
795 // No name has been set yet.
796 person.name = subnode.textContent;
797 } else {
798 // A name has already been set.
799 throw new TypeError(
800 `Duplicate name found for person${
801 person.id != null ? ` <${person.id}>` : ""
802 } while processing <${result.id}>.`,
803 );
804 }
805 } else {
806 // This is not a name node
807 /* do nothing */
808 }
809 }
810 return person;
811 }
812 case "text": {
813 // The node describes (potentially rich) textual content.
814 //
815 // ☡ Don’t return an Array here or it will look like a list
816 // of multiple values. Return the NodeList of child nodes
817 // directly.
818 const parseType = node.getAttributeNS?.(RDF, "parseType");
819 if (parseType == "Markdown") {
820 // This is an element with Markdown content (which
821 // hopefully can be converted into X·M·L).
822 return parser.parseFromString(
823 `<福 xmlns="${XHTML}" lang="${
824 getLanguage(node) ?? ""
825 }">${
826 markdownTokensToHTML(
827 markdownTokens(node.textContent),
828 )
829 }</福>`,
830 "application/xml",
831 ).documentElement.childNodes;
832 } else if (parseType == "Literal") {
833 // This is an element with literal X·M·L contents.
834 return node.childNodes;
835 } else {
836 // This is an element without literal X·M·L contents.
837 /* do nothing */
838 }
839 } // falls through
840 default: {
841 // The node describes something in plaintext.
842 const text = new String(node.textContent);
843 const lang = getLanguage(node);
844 if (lang) {
845 text.lang = lang;
846 } else {
847 /* do nothing */
848 }
849 return text;
850 }
851 }
852 })();
853 if (existing == null) {
854 // The property takes at most one value, but none has been set.
855 result[name] = content;
856 } else if (Array.isArray(existing)) {
857 // The property takes multiple values.
858 existing.push(content);
859 } else {
860 // The property takes at most one value, and one has already
861 // been set.
862 throw new TypeError(
863 `Duplicate content found for ${name} while processing <${result.id}>.`,
864 );
865 }
866 } else {
867 // The current node does not correspond with an Atom property.
868 /* do nothing */
869 }
870 }
871 globalThis.bjørnTransformMetadata?.(result, documentType);
872 return validateMetadata(result, documentType);
873 };
874
875 /** The DOMParser used by this script. */
876 const parser = new DOMParser();
877
878 /** The XMLSerializer used by this script. */
879 const serializer = new XMLSerializer();
880
881 /**
882 * Sets the @xml:lang attribute of the provided element, and if it is
883 * an H·T·M·L element also sets the @lang.
884 */
885 const setLanguage = (element, lang) => {
886 element.setAttributeNS(XML, "xml:lang", lang ?? "");
887 if (element.namespaceURI == XHTML) {
888 element.setAttribute("lang", lang ?? "");
889 } else {
890 /* do nothing */
891 }
892 };
893
894 /**
895 * Throws if the provided metadata does not conform to expectations for
896 * the provided type, and otherwise returns it.
897 */
898 const validateMetadata = (metadata, type) => {
899 if (metadata.id == null) {
900 throw new TypeError("Missing id.");
901 } else if (metadata.title == null) {
902 throw new TypeError(`Missing title for item <${metadata.id}>.`);
903 } else if (type == "feed" && metadata.author == null) {
904 throw new TypeError(`Missing author for feed <${metadata.id}>.`);
905 } else if (type == "entry" && metadata.content == null) {
906 throw new TypeError(`Missing content for entry <${metadata.id}>.`);
907 } else {
908 return metadata;
909 }
910 };
911
912 { // Set up global variables for use in hooks.
913 //
914 // Bjørn is principally built to be run from the command line (as a
915 // shell script) rather than conforming to typical Ecmascript module
916 // patterns. However, it recognizes hooks through various
917 // specially‐named properties on `globalThis`. After defining these
918 // hooks, a script can use a *dynamic* `import("./path/to/build.js")`
919 // to run the Bjørn build steps.
920 //
921 // To make writing scripts which make use of these hooks easier,
922 // infrastructural dependencies and useful functions are provided on
923 // `globalThis` so that wrapping scripts don’t have to attempt to
924 // manage the dependencies themselves.
925 //
926 // Note that the `Lemon/window` polyfill will already have
927 // established some D·O·M‐related global properties by the time this
928 // runs, so they don’t need to be redeclared here.
929 globalThis.Lemon = Lemon;
930 globalThis.Bjørn = {
931 addContent,
932 getLanguage,
933 setLanguage,
934 };
935 }
936
937 await (async () => { // this is the run script
938 const writes = [];
939
940 // Set up the feed metadata and Atom feed document.
941 const feedDocument = parser.parseFromString(
942 await Deno.readTextFile(`${basePath}/#feed.rdf`),
943 "application/xml",
944 );
945 const feedMetadata = metadataFromDocument(feedDocument);
946 const feedURI = new URL(feedMetadata.id);
947 const document = parser.parseFromString(
948 `<?xml version="1.0" encoding="utf-8"?>
949 <feed xmlns="http://www.w3.org/2005/Atom"><generator>🧸📔 Bjørn</generator><link rel="self" type="application/atom+xml" href="${new URL(
950 "./feed.atom",
951 feedURI,
952 )}"/></feed>`,
953 "application/xml",
954 );
955 const { documentElement: feed } = document;
956 const feedLanguage = getLanguage(feedDocument);
957 if (feedLanguage) {
958 // The feed element has a language.
959 setLanguage(feed, feedLanguage);
960 } else {
961 // There is no language for the feed.
962 /* do nothing */
963 }
964 applyMetadata(feed, feedMetadata);
965
966 // Set up the index page.
967 const feedTemplate = await documentFromTemplate("feed");
968 const { documentElement: feedTemplateRoot } = feedTemplate;
969 if (feedLanguage && !getLanguage(feedTemplateRoot)) {
970 // The root element of the template does not have an
971 // assigned language, but the feed does.
972 setLanguage(feedTemplateRoot, feedLanguage);
973 } else {
974 // Either the template root already has a language, or the
975 // entry doesn’t either.
976 /* do nothing */
977 }
978 const feedEntries = feedTemplate.createDocumentFragment();
979
980 // Process entries and save the resulting index files.
981 for await (
982 const { name: date, isDirectory } of Deno.readDir(
983 `${basePath}/`,
984 )
985 ) {
986 // Iterate over each directory and process the ones which are
987 // dates.
988 if (!isDirectory || !/[0-9]{4}-[0-9]{2}-[0-9]{2}/u.test(date)) {
989 // This isn’t a dated directory.
990 continue;
991 } else {
992 // This is a dated directory.
993 for (
994 const { name: entryName, isDirectory } of Array.from(
995 Deno.readDirSync(`${basePath}/${date}/`),
996 ).sort(({ name: a }, { name: b }) =>
997 a < b ? -1 : a > b ? 1 : 0
998 )
999 ) {
1000 // Iterate over each directory and process the ones which look
1001 // like entries.
1002 if (
1003 !isDirectory ||
1004 //deno-lint-ignore no-control-regex
1005 /[\x00-\x20\x22#%/<>?\\^\x60{|}\x7F]/u.test(entryName)
1006 ) {
1007 // This isn’t an entry directory.
1008 continue;
1009 } else {
1010 // Process the entry.
1011 const entry = document.createElement("entry");
1012 const entryPath =
1013 `${basePath}/${date}/${entryName}/#entry.rdf`;
1014 const entryDocument = parser.parseFromString(
1015 await Deno.readTextFile(entryPath),
1016 "application/xml",
1017 );
1018 const { documentElement: entryRoot } = entryDocument;
1019 entryDocument.lastModified =
1020 (await Deno.lstat(entryPath)).mtime;
1021 if (!entryRoot.hasAttributeNS(RDF, "about")) {
1022 // The entry doesn’t have an identifier; let’s give it one.
1023 entryRoot.setAttributeNS(
1024 RDF,
1025 "about",
1026 new URL(`./${date}/${entryName}/`, feedURI),
1027 );
1028 } else {
1029 // The entry already has an identifier.
1030 /* do nothing */
1031 }
1032 const entryMetadata = metadataFromDocument(entryDocument);
1033 if (entryMetadata.author.length == 0) {
1034 // The entry metadata did not supply an author.
1035 entryMetadata.author = feedMetadata.author;
1036 } else {
1037 // The entry metadata supplied its own author.
1038 /* do nothing */
1039 }
1040 const entryTemplate = await documentFromTemplate("entry");
1041 const { documentElement: templateRoot } = entryTemplate;
1042 const lang = getLanguage(entryRoot);
1043 if (lang && !getLanguage(templateRoot)) {
1044 // The root element of the template does not have an
1045 // assigned language, but the entry does.
1046 setLanguage(templateRoot, lang);
1047 } else {
1048 // Either the template root already has a language, or the
1049 // entry doesn’t either.
1050 /* do nothing */
1051 }
1052 writes.push(
1053 Deno.writeTextFile(
1054 `${basePath}/${date}/${entryName}/index.xhtml`,
1055 serializer.serializeToString(
1056 applyMetadata(entryTemplate, entryMetadata),
1057 ) + "\n",
1058 ),
1059 );
1060 applyMetadata(entry, entryMetadata);
1061 applyMetadata(feedEntries, entryMetadata);
1062 feed.appendChild(entry);
1063 }
1064 }
1065 }
1066 }
1067
1068 // Apply the feed metadata to the feed template and save the
1069 // resulting index file.
1070 if (hasExpandedName(feedTemplateRoot, XHTML, "html")) {
1071 // This is an XHTML template.
1072 const LMN = Lemon.bind({ document: feedTemplate });
1073 const {
1074 id,
1075 title,
1076 subtitle,
1077 rights,
1078 updated,
1079 } = feedMetadata;
1080 fillOutHead(feedTemplate, feedMetadata, "feed");
1081 const contentPlaceholder = feedTemplate.getElementsByTagNameNS(
1082 XHTML,
1083 "bjørn-content",
1084 ).item(0);
1085 if (contentPlaceholder != null) {
1086 // There is a content placeholder.
1087 const { parentNode: contentParent } = contentPlaceholder;
1088 const contentElement = contentParent.insertBefore(
1089 LMN.nav.about(`${id}`)`${"\n"}`,
1090 contentPlaceholder,
1091 );
1092 const contentHeader = contentElement.appendChild(
1093 LMN.header`${"\n\t"}`,
1094 );
1095 addContent(
1096 contentHeader.appendChild(LMN.h1.property(`${DC11}title`)``),
1097 title,
1098 );
1099 addContent(contentHeader, "\n");
1100 if (subtitle) {
1101 // The feed has a subtitle.
1102 addContent(
1103 contentHeader.appendChild(LMN.p.property(`${RDFS}label`)``),
1104 subtitle,
1105 );
1106 addContent(contentHeader, "\n");
1107 } else {
1108 // The feed has no subtitle.
1109 /* do nothing */
1110 }
1111 addContent(contentElement, "\n");
1112 const entriesElement = contentElement.appendChild(
1113 LMN.ul.rel(`${AWOL}entry`)`${"\n"}`,
1114 );
1115 entriesElement.appendChild(feedEntries);
1116 addContent(contentElement, "\n");
1117 const contentFooter = contentElement.appendChild(
1118 LMN.footer`${"\n\t"}`,
1119 );
1120 if (rights) {
1121 // The feed has a rights statement.
1122 addContent(
1123 contentFooter.appendChild(
1124 LMN.div.property(`${DC11}rights`)``,
1125 ),
1126 rights,
1127 );
1128 addContent(contentFooter, "\n\t");
1129 } else {
1130 // The feed has no rights statement.
1131 /* do nothing */
1132 }
1133 contentFooter.appendChild(
1134 LMN.p.id("entry.updated")`Last updated: ${LMN.time.property(
1135 `${AWOL}updated`,
1136 )`${updated}`}.`,
1137 );
1138 addContent(contentFooter, "\n");
1139 addContent(contentElement, "\n");
1140 contentParent.removeChild(contentPlaceholder);
1141 } else {
1142 /* do nothing */
1143 }
1144 }
1145 globalThis.bjørnTransformFeedHTML?.(feedTemplate, feedMetadata);
1146 writes.push(
1147 Deno.writeTextFile(
1148 "index.xhtml",
1149 serializer.serializeToString(feedTemplate) + "\n",
1150 ),
1151 );
1152
1153 // Save the feed Atom file.
1154 globalThis.bjørnTransformFeedAtom?.(document, feedMetadata);
1155 writes.push(
1156 Deno.writeTextFile(
1157 "feed.atom",
1158 serializer.serializeToString(document) + "\n",
1159 ),
1160 );
1161
1162 // Await all writes.
1163 await Promise.all(writes);
1164 })();
This page took 0.16666 seconds and 5 git commands to generate.