@allons-y/course-kit 0.0.0-stage → 0.2.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 (137) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +90 -2
  3. package/assets/fonts/instrument-sans-italic-var.woff2 +0 -0
  4. package/assets/fonts/instrument-sans-var.woff2 +0 -0
  5. package/assets/fonts/pt-mono.woff2 +0 -0
  6. package/assets/scripts/copy.js +99 -0
  7. package/assets/scripts/deck.js +161 -0
  8. package/assets/scripts/email.js +19 -0
  9. package/assets/scripts/practice.js +545 -0
  10. package/assets/scripts/theme-panel.js +647 -0
  11. package/assets/scripts/theme-restore.js +17 -0
  12. package/assets/styles/base.css +2091 -0
  13. package/assets/styles/deck.css +968 -0
  14. package/assets/styles/font.css +36 -0
  15. package/assets/styles/notes.css +137 -0
  16. package/assets/styles/print.css +428 -0
  17. package/assets/styles/semantics.css +101 -0
  18. package/components/practice/check-controls.webc +50 -0
  19. package/components/practice/choice-list.webc +86 -0
  20. package/components/practice/cite-panel.webc +108 -0
  21. package/components/practice/practice-figure.webc +47 -0
  22. package/components/practice/practice-fill.webc +154 -0
  23. package/components/practice/practice-grid.webc +82 -0
  24. package/components/practice/practice-judge.webc +165 -0
  25. package/components/practice/practice-match.webc +178 -0
  26. package/components/practice/practice-question.webc +141 -0
  27. package/components/practice/practice-selfcheck.webc +40 -0
  28. package/components/practice/practice-terms.webc +95 -0
  29. package/components/practice/practice-tree.webc +91 -0
  30. package/components/practice/practice-worksheet.webc +369 -0
  31. package/components/site/copyright.webc +13 -0
  32. package/components/site/course-documents.webc +27 -0
  33. package/components/site/course-now.webc +393 -0
  34. package/components/site/course-summary.webc +136 -0
  35. package/components/site/demo-weeks.webc +91 -0
  36. package/components/site/glossary-entry.webc +31 -0
  37. package/components/site/glossary-panel.webc +1482 -0
  38. package/components/site/glossary.webc +45 -0
  39. package/components/site/grading.webc +50 -0
  40. package/components/site/instructor.webc +432 -0
  41. package/components/site/masthead.webc +147 -0
  42. package/components/site/nav-links.webc +174 -0
  43. package/components/site/policies.webc +17 -0
  44. package/components/site/practice-index.webc +31 -0
  45. package/components/site/schedule-overview.webc +145 -0
  46. package/components/site/schedule-weeks.webc +589 -0
  47. package/components/site/site-footer.webc +119 -0
  48. package/components/site/slide-timetable.webc +152 -0
  49. package/components/site/syllabus.webc +370 -0
  50. package/components/ui/arrow-link.webc +19 -0
  51. package/components/ui/assigned-list.webc +101 -0
  52. package/components/ui/callout.webc +11 -0
  53. package/components/ui/card-list.webc +124 -0
  54. package/components/ui/codepen-embed.webc +123 -0
  55. package/components/ui/download-button.webc +49 -0
  56. package/components/ui/eyebrow.webc +18 -0
  57. package/components/ui/icons/github.webc +6 -0
  58. package/components/ui/icons/google.webc +9 -0
  59. package/components/ui/link-list.webc +130 -0
  60. package/components/ui/link-section.webc +40 -0
  61. package/components/ui/meeting-card.webc +73 -0
  62. package/components/ui/meeting-decks.webc +38 -0
  63. package/components/ui/table-rubric.webc +251 -0
  64. package/components/ui/today-link.webc +43 -0
  65. package/components/ui/today-marker.webc +149 -0
  66. package/components/ui/week-block.webc +53 -0
  67. package/examples/starter/_data/course.json +20 -0
  68. package/examples/starter/_data/dates.json +16 -0
  69. package/examples/starter/_data/grading.json +6 -0
  70. package/examples/starter/_data/instructor.json +7 -0
  71. package/examples/starter/_data/policies.json +9 -0
  72. package/examples/starter/_data/scale.json +8 -0
  73. package/examples/starter/_data/schedule.json +22 -0
  74. package/examples/starter/_data/theme.json +17 -0
  75. package/examples/starter/content/index.webc +12 -0
  76. package/examples/starter/content/schedule.webc +12 -0
  77. package/examples/starter/content/slides/index.11tydata.js +5 -0
  78. package/examples/starter/content/slides/index.webc +12 -0
  79. package/examples/starter/content/slides/week-1-day-1.md +40 -0
  80. package/examples/starter/eleventy.config.js +8 -0
  81. package/glue/deck-notes.data.js +41 -0
  82. package/glue/deck-notes.webc +32 -0
  83. package/glue/lesson-day.data.js +17 -0
  84. package/glue/lesson-day.webc +0 -0
  85. package/glue/lesson-plans.data.js +13 -0
  86. package/glue/lesson-plans.webc +2 -0
  87. package/index.js +6 -0
  88. package/layouts/base.webc +79 -0
  89. package/layouts/deck.webc +46 -0
  90. package/layouts/demo.webc +16 -0
  91. package/layouts/document.webc +10 -0
  92. package/layouts/lesson-detail.webc +109 -0
  93. package/layouts/lesson.webc +71 -0
  94. package/layouts/notes.webc +23 -0
  95. package/layouts/worksheet.webc +52 -0
  96. package/lib/assets.js +42 -0
  97. package/lib/bundles.js +79 -0
  98. package/lib/check.js +110 -0
  99. package/lib/components.js +19 -0
  100. package/lib/copy.js +656 -0
  101. package/lib/data/build.js +22 -0
  102. package/lib/data/fonts.js +16 -0
  103. package/lib/data/glossary.js +304 -0
  104. package/lib/data/index.js +8 -0
  105. package/lib/data/lessons.js +173 -0
  106. package/lib/data/project.js +22 -0
  107. package/lib/data/read.js +61 -0
  108. package/lib/data/site.js +70 -0
  109. package/lib/data/term.js +80 -0
  110. package/lib/extensions.js +70 -0
  111. package/lib/files.js +14 -0
  112. package/lib/filters.js +584 -0
  113. package/lib/fit.js +106 -0
  114. package/lib/glue.js +26 -0
  115. package/lib/lesson-materials.js +66 -0
  116. package/lib/markdown.js +568 -0
  117. package/lib/minify.js +53 -0
  118. package/lib/paths.js +5 -0
  119. package/lib/pdf.js +134 -0
  120. package/lib/plugin.js +231 -0
  121. package/lib/plugins.js +34 -0
  122. package/lib/postcss.js +93 -0
  123. package/lib/theme-server.js +88 -0
  124. package/lib/theme.js +185 -0
  125. package/lib/worksheet-dialect.js +415 -0
  126. package/lib/worksheets.js +276 -0
  127. package/package.json +119 -4
  128. package/schemas/course.schema.json +161 -0
  129. package/schemas/dates.schema.json +165 -0
  130. package/schemas/grading.schema.json +59 -0
  131. package/schemas/instructor.schema.json +76 -0
  132. package/schemas/policies.schema.json +90 -0
  133. package/schemas/project.schema.json +209 -0
  134. package/schemas/scale.schema.json +68 -0
  135. package/schemas/schedule.schema.json +260 -0
  136. package/schemas/theme.schema.json +704 -0
  137. package/schemas/worksheet.schema.json +449 -0
package/lib/minify.js ADDED
@@ -0,0 +1,53 @@
1
+ import { transform } from "esbuild";
2
+
3
+ /** `<script>` types whose body is JavaScript; anything else (JSON data, `py-editor`) is left alone. */
4
+ const SCRIPT_TYPES = new Set(["", "module", "text/javascript", "application/javascript"]);
5
+
6
+ /** The value of an attribute in a tag's attribute text, or undefined. */
7
+ const attribute = (attributes, name) => new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|(\\S+))`, "i").exec(attributes)?.slice(1).find((value) => value !== undefined);
8
+
9
+ /**
10
+ * An Eleventy transform that minifies the inline JavaScript and CSS of every built page with esbuild: each `<script>` with no `src` and a JavaScript type,
11
+ * and each `<style>`. It does nothing else: names are shortened inside a script but no property or string is ever renamed, so a copy key or a
12
+ * `data-*` selector a script looks up by name survives, and a JSON data block, a `<pre>` and every attribute are left as they are.
13
+ * A script or style esbuild cannot parse fails the build and names the page, rather than shipping something broken.
14
+ * The kit does not register this; a course opts in (docs/configuration.md).
15
+ *
16
+ * @param {{ production?: boolean }} [options] `production: false` runs it in every build; by default only when `ELEVENTY_ENV` is `production`
17
+ * @returns {(content: string, outputPath?: string) => Promise<string>}
18
+ */
19
+ export function minifyInline({ production = true } = {}) {
20
+ return async function minifyInlineTransform(content, outputPath) {
21
+ if (production && process.env.ELEVENTY_ENV !== "production") return content;
22
+ const page = outputPath ?? this?.page?.outputPath;
23
+ if (typeof page !== "string" || !page.endsWith(".html")) return content;
24
+ const jobs = [];
25
+ const queue = (pattern, kind) => {
26
+ content.replace(pattern, (whole, attributes, body, offset) => {
27
+ if (!body.trim()) return whole;
28
+ if (kind === "js" && (/\ssrc\s*=/i.test(attributes) || !SCRIPT_TYPES.has((attribute(attributes, "type") ?? "").toLowerCase()))) return whole;
29
+ jobs.push({ kind, body, module: (attribute(attributes, "type") ?? "").toLowerCase() === "module", offset: offset + whole.indexOf(">") + 1, length: body.length });
30
+ return whole;
31
+ });
32
+ };
33
+ queue(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi, "js");
34
+ queue(/<style\b([^>]*)>([\s\S]*?)<\/style>/gi, "css");
35
+ if (!jobs.length) return content;
36
+ const done = await Promise.all(
37
+ jobs.map(async (job) => {
38
+ try {
39
+ // A module's top-level names are its own, so esbuild may shorten them; a classic script's are globals, which it leaves.
40
+ const options = job.kind === "js" ? { loader: "js", format: job.module ? "esm" : undefined } : { loader: "css" };
41
+ const { code } = await transform(job.body, { ...options, minify: true, legalComments: "none" });
42
+ return { ...job, code: code.trim() };
43
+ } catch (error) {
44
+ throw new Error(`minifyInline: could not minify an inline ${job.kind === "js" ? "script" : "style"} in ${page}: ${error.message}`, { cause: error });
45
+ }
46
+ }),
47
+ );
48
+ // Splice from the end, so earlier offsets stay true.
49
+ let result = content;
50
+ for (const job of done.sort((a, b) => b.offset - a.offset)) result = result.slice(0, job.offset) + job.code + result.slice(job.offset + job.length);
51
+ return result;
52
+ };
53
+ }
package/lib/paths.js ADDED
@@ -0,0 +1,5 @@
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ /** Absolute path to the package root. */
5
+ export const packageRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
package/lib/pdf.js ADDED
@@ -0,0 +1,134 @@
1
+ /*
2
+ * The syllabus PDF: the built landing page, printed with headless Chromium
3
+ * straight after the site build (`eleventy.after`), to `public/resources/
4
+ * syllabus.pdf`. Puppeteer is imported lazily, inside the handler, so a
5
+ * dev/watch build never pays the Chromium launch — only a production build,
6
+ * or a dev build with BUILD_PDF=1 set by hand, actually runs this.
7
+ */
8
+ import { createServer } from "node:http";
9
+ import { existsSync } from "node:fs";
10
+ import { mkdir, readFile } from "node:fs/promises";
11
+ import { extname, join, resolve, sep } from "node:path";
12
+
13
+ import { fill, resolveCopy } from "./copy.js";
14
+ import { readCourseData } from "./data/read.js";
15
+ import { resolveTerm } from "./data/term.js";
16
+
17
+ /**
18
+ * @param {{ course?: object, term?: object, dataDir: string }} options
19
+ * @returns {{ course: object, term: object }} the options, else resolved from the course's data files
20
+ */
21
+ const loadFooterData = ({ course, term, dataDir }) => {
22
+ const data = course && term ? null : readCourseData(dataDir);
23
+ return { course: course ?? data.course, term: term ?? resolveTerm(data) };
24
+ };
25
+
26
+ const MIME = {
27
+ ".css": "text/css",
28
+ ".html": "text/html; charset=utf-8",
29
+ ".ico": "image/x-icon",
30
+ ".jpg": "image/jpeg",
31
+ ".js": "text/javascript",
32
+ ".png": "image/png",
33
+ ".svg": "image/svg+xml",
34
+ ".txt": "text/plain",
35
+ ".woff2": "font/woff2",
36
+ ".xml": "application/xml",
37
+ };
38
+
39
+ /**
40
+ * Serve `root` over loopback HTTP so Chromium resolves root-relative assets.
41
+ * Strips a leading PATH_PREFIX segment. Shared with fit.js.
42
+ */
43
+ export function servePublic(root, pathPrefix) {
44
+ return createServer(async (request, response) => {
45
+ try {
46
+ const url = new URL(request.url, "http://localhost");
47
+ let pathname = url.pathname;
48
+ if (pathPrefix && pathPrefix !== "/" && pathname.startsWith(pathPrefix)) {
49
+ pathname = pathname.slice(pathPrefix.length - 1) || "/";
50
+ }
51
+ let path = join(root, pathname);
52
+ if (path !== root && !path.startsWith(root + sep)) throw new Error("traversal");
53
+ if (!extname(path)) path = join(path, "index.html");
54
+ const body = await readFile(path);
55
+ response.writeHead(200, { "content-type": MIME[extname(path)] ?? "application/octet-stream" });
56
+ response.end(body);
57
+ } catch {
58
+ response.writeHead(404);
59
+ response.end("not found");
60
+ }
61
+ });
62
+ }
63
+
64
+ /**
65
+ * Register the `eleventy.after` handler that generates the syllabus PDF.
66
+ * `outputDir` is passed in because Eleventy reports its default on `eleventy.after` (docs/internals.md).
67
+ * @param {import('@11ty/eleventy').TemplateConfig} config
68
+ * @param {{ isProduction: boolean, timezone: string, outputDir?: string, dataDir?: string, course?: object, term?: object }} options
69
+ */
70
+ export default function registerSyllabusPdf(config, { isProduction, timezone, outputDir: output = "public", dataDir = "_data", course, term }) {
71
+ config.on("eleventy.after", async ({ runMode, results }) => {
72
+ if (runMode !== "build") return;
73
+ if (!(isProduction || process.env.BUILD_PDF === "1")) return;
74
+ if (!results?.length) return;
75
+
76
+ const root = resolve(output);
77
+ if (!existsSync(join(root, "index.html"))) {
78
+ process.stderr.write("[syllabus-pdf] public/index.html is missing — skipping.\n");
79
+ return;
80
+ }
81
+
82
+ const pathPrefix = config.pathPrefix ?? "/";
83
+ let puppeteer;
84
+ try {
85
+ ({ default: puppeteer } = await import("puppeteer"));
86
+ } catch {
87
+ throw new Error(
88
+ "A production build writes the syllabus as a PDF with headless Chrome, and the `puppeteer` package is not installed. " +
89
+ "Install it (yarn add puppeteer), or turn the PDF off by passing `pdf: false` to courseKit.",
90
+ );
91
+ }
92
+
93
+ const server = servePublic(root, pathPrefix);
94
+ await new Promise((done) => server.listen(0, "127.0.0.1", done));
95
+ const { port } = server.address();
96
+
97
+ const generated = new Date().toLocaleDateString("en-CA", { timeZone: timezone });
98
+ const version = (process.env.GITHUB_SHA ?? process.env.COMMIT_REF ?? "local").slice(0, 7);
99
+ const outputDir = join(root, "resources");
100
+ const outputPath = join(outputDir, "syllabus.pdf");
101
+ const footerData = loadFooterData({ course, term, dataDir });
102
+
103
+ const browser = await puppeteer.launch({
104
+ args: process.env.CI ? ["--no-sandbox", "--disable-setuid-sandbox"] : [],
105
+ });
106
+
107
+ try {
108
+ await mkdir(outputDir, { recursive: true });
109
+ const page = await browser.newPage();
110
+ await page.emulateMediaFeatures([{ name: "prefers-color-scheme", value: "light" }]);
111
+ await page.goto(`http://127.0.0.1:${port}${pathPrefix === "/" ? "/" : pathPrefix}`, { waitUntil: "networkidle0" });
112
+ await page.$$eval("details", (elements) => {
113
+ for (const details of elements) details.open = true;
114
+ });
115
+ await page.evaluateHandle("document.fonts.ready");
116
+ await page.pdf({
117
+ path: outputPath,
118
+ format: "letter",
119
+ // No `scale` — Chromium bleeds the margins when one is set.
120
+ tagged: true, // Accessible PDF structure for screen readers.
121
+ printBackground: true,
122
+ displayHeaderFooter: true,
123
+ headerTemplate: "<span></span>",
124
+ footerTemplate: `<div style="width: 100%; font-size: 7px; text-align: center; color: #666;">${fill(resolveCopy({ dataDir }).pdf.footer, { course: footerData.course.code, name: footerData.course.name, term: footerData.term.label, generated, version, page: '<span class="pageNumber"></span>', pages: '<span class="totalPages"></span>' })}</div>`,
125
+ margin: { top: "0.4in", bottom: "0.45in", left: "0.5in", right: "0.5in" },
126
+ });
127
+ await page.close();
128
+ process.stdout.write(`[syllabus-pdf] wrote ${outputPath.replace(root, "")}\n`);
129
+ } finally {
130
+ await browser.close();
131
+ server.close();
132
+ }
133
+ });
134
+ }
package/lib/plugin.js ADDED
@@ -0,0 +1,231 @@
1
+ import path from "node:path";
2
+ import { createRequire } from "node:module";
3
+
4
+ import dotenv from "dotenv";
5
+ import dashly from "@allons-y/dashly";
6
+
7
+ import { registerAssets } from "./assets.js";
8
+ import registerBundles from "./bundles.js";
9
+ import { checkOptions, courseWarnings } from "./check.js";
10
+ import { buildGlossary, buildLessons, courseDefines, inlineFontFaces, readCourseData, readPackage, resolveAudience, resolvePdf, resolveSite, resolveTerm, withoutSchema } from "./data/index.js";
11
+ import { copyJson, copyReader, fill, plural, resolveCopy } from "./copy.js";
12
+ import registerExtensions from "./extensions.js";
13
+ import registerFilters from "./filters.js";
14
+ import registerSlideFitCheck from "./fit.js";
15
+ import { registerGlue } from "./glue.js";
16
+ import { markdown } from "./markdown.js";
17
+ import { setWorksheetDefaults } from "./worksheets.js";
18
+ import { packageRoot } from "./paths.js";
19
+ import { resolveTheme } from "./theme.js";
20
+ import { themeMiddleware } from "./theme-server.js";
21
+ import registerSyllabusPdf from "./pdf.js";
22
+ import registerPlugins from "./plugins.js";
23
+
24
+ const PRISM = {
25
+ theme: {
26
+ light: "prism-coldark-cold",
27
+ dark: "prism-coldark-dark",
28
+ },
29
+ plugins: ["toolbar", "copy-to-clipboard", "treeview", "command-line"],
30
+ };
31
+
32
+ /** Keep html-minifier-terser's defaults; add py-editor blocks, whose first-line indent PyScript needs. */
33
+ const PYSCRIPT_MINIFIER = {
34
+ ignoreCustomFragments: [/<%[\s\S]*?%>/, /<\?[\s\S]*?\?>/, /<script type="py-editor"[\s\S]*?<\/script>/],
35
+ };
36
+
37
+ /**
38
+ * The course-kit Eleventy plugin: directories, layouts, components, bundles,
39
+ * filters, the PDF and fit hooks, the markdown dialect and every shared asset.
40
+ * @param {import('@11ty/eleventy').UserConfig} config
41
+ * @param {object} [options]
42
+ * @param {string} [options.inputDir] the course's content directory
43
+ * @param {string} [options.outputDir] where the site is written
44
+ * @param {string} [options.dataDir] the course's authored data files
45
+ * @param {{ name?: string, timezone?: string }} [options.institution] the college's name, and the time zone "today" is judged in (default `"UTC"`)
46
+ * @param {{ description?: string, keywords?: string, language?: string }} [options.site] site metadata, derived from the course when omitted
47
+ * @param {{ segments?: object[], defaultDays?: string[] }} [options.lessons] the lesson outline and the meeting days used when the schedule names none
48
+ * @param {{ checkMode?: "question" | "end" }} [options.worksheets] site-wide worksheet defaults: `checkMode` is `"end"` (only See results at the end, the default) or `"question"` (also a Check answer button on each question); a worksheet's own `checkMode` wins
49
+ * @param {string[]} [options.components] extra WebC component globs
50
+ * @param {{ runtime?: "none" | "codepen" | "pyscript", dir?: string }} [options.demos] how runnable demos are served
51
+ * @param {{ decks?: string }} [options.slides] where the deck markdown lives, under the repo root
52
+ * @param {false | { course?: object, term?: object, dataDir?: string }} [options.pdf] `false` skips the syllabus PDF; otherwise its footer data (read from the course's `_data` when omitted)
53
+ * @param {{ theme: { light: string, dark: string }, plugins: string[] }} [options.prism] vendored Prism theme and plugin files to publish
54
+ * @param {object} [options.theme] color overrides in the shape of `_data/theme.json`, which wins over them
55
+ */
56
+ export default function courseKit(config, options = {}) {
57
+ checkOptions(options);
58
+ const { inputDir = "content", outputDir = "public", dataDir = "_data", components = [], demos = {}, slides = {}, pdf = {}, prism = PRISM, theme, copy: courseCopy, clientCopy = [], institution = {}, site = {}, lessons = {}, worksheets = {} } = options;
59
+ resolveTheme({ dataDir, theme }); // fail at startup on a bad theme
60
+ resolveCopy({ dataDir, extra: courseCopy }); // and on a bad `strings.json`
61
+ setWorksheetDefaults(worksheets);
62
+ const { runtime = "none", dir: demosDir = `${inputDir}/demo` } = demos;
63
+ const { decks: decksDir = `${inputDir}/slides` } = slides;
64
+
65
+ dotenv.config({ path: ".env" });
66
+
67
+ const env = process.env.ELEVENTY_ENV || "development";
68
+ const isProduction = env === "production";
69
+ const audience = resolveAudience().value;
70
+
71
+ // Drafts stay out of the student build.
72
+ config.addPreprocessor("drafts", "*", (data) => {
73
+ if (data.draft && audience === "student") return false;
74
+ });
75
+
76
+ // So does instructor-only material.
77
+ config.addPreprocessor("instructorOnly", "*", (data) => {
78
+ if (data.instructorOnly && audience === "student") return false;
79
+ });
80
+
81
+ config.setDataFileBaseName("index");
82
+ config.ignores.add("README.md");
83
+ config.ignores.add("**/AGENTS.md");
84
+ if (runtime === "codepen") {
85
+ // Demo fragments are published by the course's demo data, not as pages.
86
+ config.ignores.add(`${demosDir}/*.html`);
87
+ }
88
+
89
+ config.setInputDirectory(inputDir);
90
+ config.setOutputDirectory(outputDir);
91
+
92
+ // Student builds skip the lessons directory; glue pages use instructorOnly (docs/internals.md).
93
+ if (audience === "student") {
94
+ config.ignores.add(`${inputDir}/lessons/**`);
95
+ }
96
+
97
+ // these are relative to input directory...
98
+ config.setIncludesDirectory("../_includes");
99
+ config.setLayoutsDirectory(path.relative(inputDir, path.join(packageRoot, "layouts")));
100
+ config.setDataDirectory("../_data");
101
+
102
+ config.directoryAssignments.css = "styles";
103
+ config.directoryAssignments.js = "js";
104
+ config.directoryAssignments.images = "images";
105
+ config.directoryAssignments.fonts = "fonts";
106
+
107
+ config.addLayoutAlias("base", "base.webc");
108
+ config.addLayoutAlias("document", "document.webc");
109
+ config.addLayoutAlias("lesson", "lesson.webc");
110
+ config.addLayoutAlias("lesson-detail", "lesson-detail.webc");
111
+ config.addLayoutAlias("deck", "deck.webc");
112
+ config.addLayoutAlias("notes", "notes.webc");
113
+ config.addLayoutAlias("worksheet", "worksheet.webc");
114
+
115
+ // A data file's `$schema` is for the editor; a template that loops over `scale` or `policies` must not see it.
116
+ config.addDataExtension("json", { parser: (text) => withoutSchema(JSON.parse(text)) });
117
+
118
+ registerPlugins(config, { components });
119
+ registerBundles(config, { inputDir });
120
+ registerFilters(config);
121
+ config.addFilter("copyJson", (data) => copyJson(data, clientCopy));
122
+ config.addFilter("copyReader", copyReader);
123
+ /** The word a callout of a type opens with, from the copy layer (`copy.callout`); "" for no type or an unknown one. */
124
+ config.addFilter("calloutLabel", (type) => resolveCopy({ dataDir, extra: courseCopy }).callout[{ success: "success", warn: "warning", error: "error" }[type]] ?? "");
125
+ config.addFilter("fill", fill);
126
+ config.addFilter("plural", plural);
127
+ registerAssets(config, {
128
+ inputDir,
129
+ exclude: [...(runtime === "none" || runtime === "pyscript" ? ["styles/semantics.css"] : []), ...(isProduction ? ["scripts/theme-panel.js"] : [])],
130
+ });
131
+ registerGlue(config, { inputDir, pages: { "lesson-day": "lessons/lesson-day.webc", "deck-notes": "lessons/deck-notes.webc", "lesson-plans": "lessons/lesson-plans.webc" } });
132
+ if (pdf !== false) registerSyllabusPdf(config, { isProduction, outputDir, dataDir, timezone: institution.timezone || "UTC", ...pdf });
133
+ registerSlideFitCheck(config, { outputDir, decksDir });
134
+
135
+ // Derived data. Config global data outranks `_data` files, so a global is skipped when the course has its own.
136
+ const globalData = (name, value) => {
137
+ if (!courseDefines(name, dataDir)) config.addGlobalData(name, value);
138
+ };
139
+ globalData("audience", () => resolveAudience());
140
+ globalData("pdf", () => (pdf === false ? { available: false } : resolvePdf()));
141
+ globalData("term", () => resolveTerm(readCourseData(dataDir)));
142
+ globalData("lessons", () => {
143
+ const data = readCourseData(dataDir);
144
+ return buildLessons({ ...data, term: resolveTerm(data), ...lessons });
145
+ });
146
+ globalData("glossary", () => {
147
+ const data = readCourseData(dataDir);
148
+ return buildGlossary({ ...data, lessons: buildLessons({ ...data, term: resolveTerm(data), ...lessons }), slidesDir: decksDir, copy: resolveCopy({ dataDir, extra: courseCopy }) });
149
+ });
150
+ globalData("copy", () => resolveCopy({ dataDir, extra: courseCopy }));
151
+ globalData("site", () => resolveSite({ course: readCourseData(dataDir).course, pkg: readPackage(), institution, site }));
152
+ globalData("fontFaces", () => inlineFontFaces(inputDir));
153
+
154
+ // Say so, once per build, when the data would give a wrong page.
155
+ config.on("eleventy.before", () => {
156
+ for (const warning of courseWarnings(readCourseData(dataDir))) console.warn(`[course-kit] ${warning}`);
157
+ });
158
+
159
+ // The theme panel: development builds only, saving through the dev server (docs/theme-panel.md).
160
+ config.addGlobalData("themePanel", !isProduction);
161
+ if (!isProduction) config.setServerOptions({ middleware: [themeMiddleware({ dataDir })] });
162
+
163
+ // 11tydata files belong to the data cascade, not the `js` template format.
164
+ config.ignores.add(`${inputDir}/**/*.11tydata.js`);
165
+ /* Worksheet content: a data source for its page, never a page itself. */
166
+ config.ignores.add(`${inputDir}/practice/*.worksheet.md`);
167
+ config.addWatchTarget(`${inputDir}/practice/*.worksheet.md`);
168
+
169
+ registerExtensions(config, { isProduction, inputDir, theme: () => resolveTheme({ dataDir, theme }) });
170
+
171
+ config.setLibrary("md", markdown);
172
+
173
+ dashly(config, {
174
+ tagsExclude: [],
175
+ ...(runtime === "pyscript" ? { transforms: { htmlmin: { minifier: PYSCRIPT_MINIFIER } } } : {}),
176
+ });
177
+
178
+ config.addFilter("length", (array) => {
179
+ if (!array || !Array.isArray(array)) return 0;
180
+ return array.length;
181
+ });
182
+
183
+ /** Passthrough record for a resolved vendor file (docs/internals.md). */
184
+ const requireResolve = createRequire(import.meta.url).resolve;
185
+ function addVendorFile(spec, outputPath) {
186
+ try {
187
+ return { [requireResolve(spec)]: outputPath };
188
+ } catch {
189
+ return {};
190
+ }
191
+ }
192
+
193
+ // Handouts and starter code.
194
+ config.addPassthroughCopy(`${inputDir}/resources/*`);
195
+
196
+ config.addPassthroughCopy({
197
+ ...addVendorFile(`prism-themes/themes/${prism.theme.light}${isProduction ? ".min" : ""}.css`, `${config.directoryAssignments.css}/prism-light.css`),
198
+ ...addVendorFile(`prism-themes/themes/${prism.theme.dark}${isProduction ? ".min" : ""}.css`, `${config.directoryAssignments.css}/prism-dark.css`),
199
+ ...prism.plugins.reduce((vendor, plugin) => {
200
+ for (const ext of ["js", "css"]) {
201
+ const spec = `prismjs/plugins/${plugin}/prism-${plugin}${isProduction ? ".min" : ""}.${ext}`;
202
+ const outputPath = `${config.directoryAssignments[ext]}/prism-${plugin}.${ext}`;
203
+ vendor = { ...vendor, ...addVendorFile(spec, outputPath) };
204
+ }
205
+ return vendor;
206
+ }, {}),
207
+ [`${config.directoryAssignments.input}/assets/favicon*`]: "/",
208
+ [`${config.directoryAssignments.input}/assets/images/*`]: `/${config.directoryAssignments.images}/`,
209
+ // Course-owned fonts.
210
+ [`${config.directoryAssignments.input}/fonts/*`]: `/${config.directoryAssignments.fonts}/`,
211
+ });
212
+
213
+ if (runtime === "pyscript") {
214
+ // Only the .py files, not the listing template; `_answer.py` solutions never publish.
215
+ config.addPassthroughCopy(`${demosDir}/**/!(*_answer).py`);
216
+
217
+ // Self-hosted so the demo pages need no CDN. Both packages belong to the course, so they resolve from it, not from here.
218
+ const fromCourse = createRequire(path.resolve("package.json")).resolve;
219
+ const packageDir = (name) => {
220
+ try {
221
+ return path.dirname(fromCourse(`${name}/package.json`));
222
+ } catch {
223
+ throw new Error(`demos.runtime "pyscript" needs the \`${name}\` package in your course. Install it: yarn add @pyscript/core pyodide`);
224
+ }
225
+ };
226
+ config.addPassthroughCopy({
227
+ [`${packageDir("@pyscript/core")}/dist/!(*.map)`]: "/pyscript/",
228
+ [`${packageDir("pyodide")}/{pyodide.mjs,pyodide.asm.mjs,pyodide.asm.wasm,python_stdlib.zip,pyodide-lock.json}`]: "/pyodide/",
229
+ });
230
+ }
231
+ }
package/lib/plugins.js ADDED
@@ -0,0 +1,34 @@
1
+ import { createRequire } from "node:module";
2
+
3
+ import { HtmlBasePlugin, InputPathToUrlTransformPlugin, RenderPlugin } from "@11ty/eleventy";
4
+ import pluginWebc from "@11ty/eleventy-plugin-webc";
5
+ import pluginTOC from "eleventy-plugin-toc";
6
+ import navigation from "@11ty/eleventy-navigation";
7
+
8
+ import { componentFiles } from "./components.js";
9
+
10
+ // createRequire, not import: the CJS Prism loader needs a real `require.cache`.
11
+ const syntaxHighlight = createRequire(import.meta.url)("@11ty/eleventy-plugin-syntaxhighlight");
12
+
13
+ /**
14
+ * Register the third-party Eleventy plugins the sites are built on.
15
+ * @param {import('@11ty/eleventy').UserConfig} config
16
+ * @param {{ components?: string[], includesDir?: string }} [options] extra component globs; the course's component directory
17
+ */
18
+ export default function registerPlugins(config, { components = [], includesDir = "_includes" } = {}) {
19
+ config.addPlugin(InputPathToUrlTransformPlugin);
20
+ // Rewrites root-relative URLs under a path prefix (GitHub Pages project sites).
21
+ config.addPlugin(HtmlBasePlugin);
22
+ config.addPlugin(syntaxHighlight, {
23
+ alwaysWrapLineHighlights: true,
24
+ preAttributes: { tabindex: 0 },
25
+ });
26
+ config.addPlugin(pluginTOC, { ul: false });
27
+ config.addPlugin(navigation);
28
+ config.addPlugin(RenderPlugin, {
29
+ accessGlobalData: true,
30
+ });
31
+ config.addPlugin(pluginWebc, {
32
+ components: [...componentFiles(includesDir), ...components],
33
+ });
34
+ }
package/lib/postcss.js ADDED
@@ -0,0 +1,93 @@
1
+ import path from "node:path";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+
4
+ import postcss from "postcss";
5
+
6
+ /**
7
+ * The PostCSS pipeline: partial imports (`_`-prefixed only), polyfills, and
8
+ * minification in production. Plugin object form, as a `postcss.config.js`
9
+ * would export it.
10
+ * @param {{ env?: string, inputDir?: string }} [options]
11
+ * @returns {{ env: string, map: boolean, plugins: Record<string, object> }}
12
+ */
13
+ export default function postcssConfig({ env = process.env.ELEVENTY_ENV ?? "development", inputDir = "content" } = {}) {
14
+ const isProduction = env === "production";
15
+ return {
16
+ env,
17
+ map: !isProduction,
18
+ plugins: {
19
+ "postcss-import": {
20
+ filter: (url) => url.startsWith("_") && url.endsWith(".css"),
21
+ path: path.resolve(inputDir, "styles"),
22
+ },
23
+ /* stage 3; stage 4 === stable. https://preset-env.cssdb.org/features/#stage-3 */
24
+ "postcss-preset-env": {
25
+ stage: 3,
26
+ },
27
+ cssnano: {
28
+ preset: [
29
+ "advanced",
30
+ {
31
+ reduceIdents: false,
32
+ // Font families live in custom properties discardUnused cannot see.
33
+ discardUnused: { fontFace: false },
34
+ normalizeWhitespace: true,
35
+ discardComments: { removeAll: true },
36
+ },
37
+ ],
38
+ },
39
+ },
40
+ };
41
+ }
42
+
43
+ /**
44
+ * Instantiate plugin-object form the way postcss-load-config does.
45
+ * @param {Record<string, object>} plugins
46
+ * @returns {Promise<import("postcss").AcceptedPlugin[]>}
47
+ */
48
+ const instantiate = (plugins) =>
49
+ Promise.all(
50
+ Object.entries(plugins).map(async ([name, options]) => {
51
+ const { default: plugin } = await import(name);
52
+ return plugin(options);
53
+ }),
54
+ );
55
+
56
+ /** @type {Map<string, Promise<import("postcss").AcceptedPlugin[]>>} */
57
+ const cache = new Map();
58
+
59
+ /**
60
+ * Process CSS through the pipeline above.
61
+ * @param {string} content
62
+ * @param {import('@11ty/eleventy').TemplateContext} ctx
63
+ * @param {{ inputDir?: string }} [options]
64
+ * @returns {Promise<string>}
65
+ */
66
+ export async function processCSS(content, ctx, { inputDir = "content" } = {}) {
67
+ const inputPath = ctx.page?.inputPath;
68
+ const outputPath = ctx.page?.outputPath;
69
+ const { plugins, env, map } = postcssConfig({ inputDir });
70
+ if (!cache.has(env + inputDir)) cache.set(env + inputDir, instantiate(plugins));
71
+
72
+ try {
73
+ const result = await postcss(await cache.get(env + inputDir)).process(content, { map, from: inputPath, to: outputPath });
74
+
75
+ // Dev only: write the source map beside the stylesheet.
76
+ if (result.map && outputPath) {
77
+ await mkdir(path.dirname(outputPath), { recursive: true });
78
+ await writeFile(`${outputPath}.map`, result.map.toString());
79
+ }
80
+
81
+ // Rebuild on --watch when an imported partial changes.
82
+ const dependencies = (result.messages ?? [])
83
+ .filter((message) => message.type === "dependency")
84
+ .map((message) => message.file);
85
+ if (dependencies.length > 0 && typeof ctx.addDependency === "function") {
86
+ ctx.addDependency(inputPath, dependencies);
87
+ }
88
+
89
+ return result.css;
90
+ } catch (err) {
91
+ throw new Error(`\n[processCSS] ${inputPath}: ${err.message}`, { cause: err });
92
+ }
93
+ }
@@ -0,0 +1,88 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+
4
+ import { GRADIENT, TOKENS, validateTheme } from "./theme.js";
5
+
6
+ export const ENDPOINT = "/.course-kit/theme";
7
+ const MAX_BODY = 64 * 1024;
8
+
9
+ /**
10
+ * @param {import("node:http").ServerResponse} res
11
+ * @param {number} status
12
+ * @param {object} body
13
+ */
14
+ const send = (res, status, body) => {
15
+ res.statusCode = status;
16
+ res.setHeader("content-type", "application/json; charset=utf-8");
17
+ res.setHeader("cache-control", "no-store");
18
+ res.end(JSON.stringify(body));
19
+ };
20
+
21
+ /**
22
+ * @param {import("node:http").IncomingMessage} req
23
+ * @returns {Promise<string>}
24
+ */
25
+ const readBody = (req) =>
26
+ new Promise((resolve, reject) => {
27
+ let size = 0;
28
+ const chunks = [];
29
+ req.on("data", (chunk) => {
30
+ size += chunk.length;
31
+ if (size > MAX_BODY) reject(new Error("theme: request is too large"));
32
+ else chunks.push(chunk);
33
+ });
34
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
35
+ req.on("error", reject);
36
+ });
37
+
38
+ /** @param {import("node:http").IncomingMessage} req */
39
+ const sameOrigin = (req) => {
40
+ const origin = req.headers.origin;
41
+ if (!origin) return true;
42
+ try {
43
+ return new URL(origin).host === req.headers.host;
44
+ } catch {
45
+ return false;
46
+ }
47
+ };
48
+
49
+ /**
50
+ * Dev-server middleware for the theme panel: GET returns the token table and
51
+ * `_data/theme.json`; POST validates and writes it.
52
+ * @param {{ dataDir?: string }} [options]
53
+ * @returns {(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse, next: () => unknown) => Promise<unknown>}
54
+ */
55
+ export function themeMiddleware({ dataDir = "_data" } = {}) {
56
+ const file = join(dataDir, "theme.json");
57
+ return async (req, res, next) => {
58
+ if (new URL(req.url, "http://localhost").pathname !== ENDPOINT) return next();
59
+ if (!sameOrigin(req)) return send(res, 403, { error: "theme: cross-origin request refused" });
60
+
61
+ if (req.method === "GET") {
62
+ let theme = {};
63
+ try {
64
+ theme = JSON.parse(await readFile(file, "utf8"));
65
+ } catch (error) {
66
+ if (error.code !== "ENOENT") return send(res, 500, { error: `theme: ${file} is not valid JSON` });
67
+ }
68
+ const tokens = TOKENS.map(({ key, role, site, deck }) => ({ key, role, site: site !== undefined, deck: deck !== undefined }));
69
+ return send(res, 200, { file, tokens, gradient: GRADIENT, theme });
70
+ }
71
+
72
+ if (req.method === "POST") {
73
+ if (!String(req.headers["content-type"]).startsWith("application/json")) return send(res, 415, { error: "theme: send JSON" });
74
+ try {
75
+ const theme = JSON.parse(await readBody(req));
76
+ validateTheme(theme);
77
+ const { $schema, ...rest } = theme;
78
+ const ordered = { $schema: $schema ?? "../node_modules/@allons-y/course-kit/schemas/theme.schema.json", ...rest };
79
+ await writeFile(file, `${JSON.stringify(ordered, null, "\t")}\n`);
80
+ return send(res, 200, { file });
81
+ } catch (error) {
82
+ return send(res, 400, { error: error.message });
83
+ }
84
+ }
85
+
86
+ return send(res, 405, { error: "theme: use GET or POST" });
87
+ };
88
+ }