mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
test(dispatcher, emitters, parse): page emission, resource bundling and parsing
PageTypeDispatcher emit/partialEmit (page type priority, virtual and 404 pages, processed file-backed pages, link marks, stale output, what bodies see), ComponentResources (hashed names, script order, component CSS, inline resource extraction, serve mode, analytics scripts) and the single-threaded Markdown pipeline.
This commit is contained in:
4 files changed
+868
-1
No files matched your search
@@ -0,0 +1,430 @@
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { registerHooks } from "node:module"
|
||||
import test, { after, describe } from "node:test"
|
||||
import { createContext, runInContext } from "node:vm"
|
||||
import type { BuildCtx } from "../../util/ctx"
|
||||
import type { QuartzComponent } from "../../components/types"
|
||||
import type { StaticResources } from "../../util/resources"
|
||||
import type { GlobalConfiguration } from "../../cfg"
|
||||
|
||||
// The emitter imports SCSS and inline browser scripts that esbuild bundles in a real build. Under
|
||||
// tsx each one is replaced by a marker: `.stub-<name>{--stub:<name>}` for SCSS, `window.__stub_<name>`
|
||||
// for scripts, so the tests can tell where each one ends up.
|
||||
registerHooks({
|
||||
load(url, context, next) {
|
||||
const name = path.basename(new URL(url).pathname).replace(/\.(inline\.ts|scss)$/, "")
|
||||
if (url.endsWith(".scss")) {
|
||||
const css = `.stub-${name.replace(/\W/g, "_")}{--stub:${name.replace(/\W/g, "_")}}`
|
||||
return {
|
||||
format: "module",
|
||||
source: `export default ${JSON.stringify(css)}`,
|
||||
shortCircuit: true,
|
||||
}
|
||||
}
|
||||
if (/\.inline\.ts$/.test(url)) {
|
||||
const js = `window.__stub_${name} = 1`
|
||||
return {
|
||||
format: "module",
|
||||
source: `export default ${JSON.stringify(js)}`,
|
||||
shortCircuit: true,
|
||||
}
|
||||
}
|
||||
return next(url, context)
|
||||
},
|
||||
})
|
||||
const { ComponentResources } = await import("./componentResources")
|
||||
|
||||
const theme = {
|
||||
fontOrigin: "local",
|
||||
cdnCaching: true,
|
||||
typography: { header: "Header Font", body: "Body Font", code: "Code Font" },
|
||||
colors: {
|
||||
lightMode: {
|
||||
light: "#fff",
|
||||
lightgray: "#eee",
|
||||
gray: "#999",
|
||||
darkgray: "#444",
|
||||
dark: "#222",
|
||||
secondary: "#00f",
|
||||
tertiary: "#0f0",
|
||||
highlight: "#ff0",
|
||||
textHighlight: "#ff08",
|
||||
},
|
||||
darkMode: {
|
||||
light: "#000",
|
||||
lightgray: "#111",
|
||||
gray: "#666",
|
||||
darkgray: "#bbb",
|
||||
dark: "#ddd",
|
||||
secondary: "#88f",
|
||||
tertiary: "#8f8",
|
||||
highlight: "#880",
|
||||
textHighlight: "#8808",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const Widget: QuartzComponent = Object.assign(() => null, {
|
||||
css: ".widget{color:blue}",
|
||||
beforeDOMLoaded: "window.__widgetBefore = 1",
|
||||
afterDOMLoaded: "window.__widgetAfter = 1",
|
||||
})
|
||||
const Other: QuartzComponent = Object.assign(() => null, {
|
||||
css: [".other{color:green}"],
|
||||
afterDOMLoaded: ["window.__otherAfter = 1"],
|
||||
})
|
||||
|
||||
const dirs: string[] = []
|
||||
after(() => {
|
||||
for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
async function emit(
|
||||
configuration: Partial<GlobalConfiguration>,
|
||||
{
|
||||
serve = false,
|
||||
resources = { css: [], js: [], additionalHead: [] } as StaticResources,
|
||||
// the same component from two emitters is collected once; an emitter may have none
|
||||
emitters = [
|
||||
{ getQuartzComponents: () => [Widget, Other] },
|
||||
{ getQuartzComponents: () => [Widget] },
|
||||
{},
|
||||
] as unknown[],
|
||||
} = {},
|
||||
) {
|
||||
const output = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-component-resources-"))
|
||||
dirs.push(output)
|
||||
const ctx = {
|
||||
argv: { output, serve },
|
||||
cfg: {
|
||||
configuration: { enableSPA: true, enablePopovers: true, theme, ...configuration },
|
||||
plugins: { emitters },
|
||||
},
|
||||
} as unknown as BuildCtx
|
||||
const written: string[] = []
|
||||
for await (const fp of ComponentResources().emit(ctx, [], resources) as AsyncIterable<string>) {
|
||||
written.push(path.relative(output, fp))
|
||||
}
|
||||
const read = (name: string) => fs.readFileSync(path.join(output, name), "utf8")
|
||||
return { ctx, written, read }
|
||||
}
|
||||
|
||||
/** The script files postscript.js imports, in its order, with whether each is awaited alone. */
|
||||
function importedScripts(postscript: string) {
|
||||
return [...postscript.matchAll(/import\("\.\/([^"]+)"\)/g)].map((m) => m[1])
|
||||
}
|
||||
|
||||
describe("ComponentResources emitter", () => {
|
||||
test("production: content-hashed index.css / prescript / postscript, named in ctx.hashedResourceNames", async () => {
|
||||
const { ctx, written, read } = await emit({})
|
||||
const names = ctx.hashedResourceNames!
|
||||
assert.match(names["index.css"], /^index-[0-9a-f]{8}\.css$/)
|
||||
assert.match(names["prescript.js"], /^prescript-[0-9a-f]{8}\.js$/)
|
||||
assert.match(names["postscript.js"], /^postscript-[0-9a-f]{8}\.js$/)
|
||||
for (const file of Object.values(names)) assert.ok(written.includes(file), file)
|
||||
|
||||
// components' beforeDOMLoaded scripts go in the prescript (once, though listed twice)
|
||||
const prescript = read(names["prescript.js"])
|
||||
assert.equal(prescript.split("__widgetBefore").length, 2)
|
||||
})
|
||||
|
||||
test("production: postscript loads component scripts in parallel and the SPA router last", async () => {
|
||||
const { ctx, written, read } = await emit({ prefetch: "hover" })
|
||||
const postscript = read(ctx.hashedResourceNames!["postscript.js"])
|
||||
const scripts = importedScripts(postscript)
|
||||
for (const s of scripts) {
|
||||
assert.match(s, /^static\/scripts\/script-\d+-[0-9a-f]{8}\.js$/)
|
||||
assert.ok(written.includes(s), s)
|
||||
}
|
||||
const contents = scripts.map(read)
|
||||
// component scripts, then the global ones: popover, prefetch (with its settings), router
|
||||
assert.deepEqual(
|
||||
contents.map((c) =>
|
||||
c.includes("__widgetAfter")
|
||||
? "widget"
|
||||
: c.includes("__otherAfter")
|
||||
? "other"
|
||||
: c.includes("__stub_popover")
|
||||
? "popover"
|
||||
: c.includes("__stub_prefetch")
|
||||
? "prefetch"
|
||||
: c.includes("__stub_spa")
|
||||
? "spa"
|
||||
: c,
|
||||
),
|
||||
["widget", "other", "popover", "prefetch", "spa"],
|
||||
)
|
||||
assert.match(
|
||||
contents[3],
|
||||
/window\.__quartzPrefetchMode = "hover";\nwindow\.__quartzSpa = true;/,
|
||||
)
|
||||
// all but the router are imported together; the router (which dispatches the first `nav`)
|
||||
// only after they all registered their listeners
|
||||
const last = scripts[scripts.length - 1]
|
||||
const [parallel, rest] = postscript.split(`await import("./${last}")`)
|
||||
assert.ok(parallel.startsWith("await Promise.all(["), postscript)
|
||||
assert.ok(!parallel.includes("__stub_spa") && !parallel.includes(last), postscript)
|
||||
for (const s of scripts.slice(0, -1)) assert.ok(parallel.includes(`import("./${s}")`), s)
|
||||
assert.equal(rest.trim(), ";")
|
||||
})
|
||||
|
||||
test("prefetching defaults to viewport mode", async () => {
|
||||
const { ctx, read } = await emit({ prefetch: undefined })
|
||||
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
|
||||
const prefetch = scripts.find((s) => s.includes("__stub_prefetch"))!
|
||||
assert.match(prefetch, /^window\.__quartzPrefetchMode = "viewport";/)
|
||||
})
|
||||
|
||||
test("without SPA routing the last script dispatches the first nav itself; prefetch: false loads no prefetcher", async () => {
|
||||
const { ctx, read } = await emit({
|
||||
enableSPA: false,
|
||||
enablePopovers: false,
|
||||
prefetch: false as never,
|
||||
})
|
||||
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
|
||||
assert.ok(!scripts.some((s) => s.includes("__stub_spa")))
|
||||
assert.ok(!scripts.some((s) => s.includes("__stub_prefetch") || s.includes("__stub_popover")))
|
||||
assert.match(scripts[scripts.length - 1], /new CustomEvent\("nav"/)
|
||||
assert.ok(!read(ctx.hashedResourceNames!["index.css"]).includes("stub-popover"))
|
||||
})
|
||||
|
||||
test("component CSS goes into one component stylesheet; index.css has theme, global and base styles", async () => {
|
||||
const { ctx, written, read } = await emit({})
|
||||
const componentFile = written.find((f) => /^component-[0-9a-f]{8}\.css$/.test(f))
|
||||
assert.ok(componentFile, written.join(", "))
|
||||
const componentCss = read(componentFile)
|
||||
assert.match(componentCss, /\.widget\{color:#00f\}/)
|
||||
assert.match(componentCss, /\.other\{color:green\}/)
|
||||
assert.equal(ctx.componentCssMap!.get(".widget{color:blue}"), componentFile)
|
||||
assert.equal(ctx.componentCssMap!.get(".other{color:green}"), componentFile)
|
||||
|
||||
const index = read(ctx.hashedResourceNames!["index.css"])
|
||||
assert.ok(!index.includes(".widget"), "component CSS is not duplicated into index.css")
|
||||
// the popover's CSS (added globally) and base styles in the quartz-base layer, then custom.scss
|
||||
assert.match(
|
||||
index,
|
||||
/^@layer quartz-base\{.*\.stub-popover\{.*\.stub-base\{.*\}\.stub-custom\{/s,
|
||||
)
|
||||
assert.match(index, /--secondary:#00f/)
|
||||
assert.match(index, /--titleFont:"Header Font"/)
|
||||
})
|
||||
|
||||
test("inline plugin CSS/JS resources are moved to files named in ctx.extractedInlineResources", async () => {
|
||||
const resources = {
|
||||
css: [
|
||||
{ content: ".plugin-inline { color: red; }", inline: true },
|
||||
{ content: "https://example.com/external.css" },
|
||||
],
|
||||
js: [
|
||||
{ script: "window.__early = 1", loadTime: "beforeDOMReady", contentType: "inline" },
|
||||
{ script: "window.__late = 1", loadTime: "afterDOMReady", contentType: "inline" },
|
||||
{ src: "https://example.com/x.js", loadTime: "afterDOMReady", contentType: "external" },
|
||||
],
|
||||
additionalHead: [],
|
||||
} as unknown as StaticResources
|
||||
const { ctx, written, read } = await emit({}, { resources })
|
||||
const map = ctx.extractedInlineResources!
|
||||
assert.equal(map.size, 3)
|
||||
const css = map.get(".plugin-inline { color: red; }")!
|
||||
assert.match(css, /^static\/resource-style-[0-9a-f]{8}\.css$/)
|
||||
assert.equal(read(css), ".plugin-inline{color:red}")
|
||||
const early = map.get("window.__early = 1")!
|
||||
const late = map.get("window.__late = 1")!
|
||||
assert.match(early, /^static\/resource-before-[0-9a-f]{8}\.js$/)
|
||||
assert.match(late, /^static\/resource-after-[0-9a-f]{8}\.js$/)
|
||||
assert.match(read(late), /window\.__late=1/)
|
||||
for (const f of [css, early, late]) assert.ok(written.includes(f), f)
|
||||
// the resources themselves are left as they are (partial rebuilds reuse them)
|
||||
assert.equal(resources.css.length, 2)
|
||||
})
|
||||
|
||||
test("CSS a plugin marks inline that lightningcss can't parse is written as it is", async () => {
|
||||
const broken = ".a { color: red"
|
||||
const resources = {
|
||||
css: [
|
||||
{ content: "@media (", inline: true },
|
||||
{ content: broken, inline: true },
|
||||
],
|
||||
js: [],
|
||||
additionalHead: [],
|
||||
} as unknown as StaticResources
|
||||
const { ctx, read } = await emit({}, { resources })
|
||||
assert.equal(read(ctx.extractedInlineResources!.get("@media (")!), "@media (")
|
||||
})
|
||||
|
||||
test("serve mode: unhashed names and one minified postscript bundle in order", async () => {
|
||||
const { ctx, written, read } = await emit({}, { serve: true })
|
||||
assert.deepEqual(ctx.hashedResourceNames, {
|
||||
"index.css": "index.css",
|
||||
"prescript.js": "prescript.js",
|
||||
"postscript.js": "postscript.js",
|
||||
})
|
||||
assert.ok(!written.some((f) => f.startsWith("static/scripts/")))
|
||||
const postscript = read("postscript.js")
|
||||
const order = [
|
||||
"__widgetAfter",
|
||||
"__otherAfter",
|
||||
"__stub_popover",
|
||||
"__stub_prefetch",
|
||||
"__stub_spa",
|
||||
].map((marker) => postscript.indexOf(marker))
|
||||
assert.ok(order.every((at) => at >= 0))
|
||||
assert.deepEqual(
|
||||
[...order].sort((a, b) => a - b),
|
||||
order,
|
||||
)
|
||||
// minified by esbuild
|
||||
assert.ok(!postscript.includes("window.__widgetAfter = 1"), postscript)
|
||||
})
|
||||
|
||||
test("postscript.js is a valid module: the parallel imports are comma-separated", async () => {
|
||||
const { ctx, read } = await emit({})
|
||||
const postscript = read(ctx.hashedResourceNames!["postscript.js"])
|
||||
const AsyncFunction = (async () => {}).constructor as new (code: string) => unknown
|
||||
assert.doesNotThrow(() => new AsyncFunction(postscript), postscript)
|
||||
assert.equal(importedScripts(postscript).length, 5)
|
||||
})
|
||||
|
||||
test("without component CSS no component stylesheet is emitted", async () => {
|
||||
const { ctx, written } = await emit({}, { emitters: [] })
|
||||
assert.ok(!written.some((f) => f.startsWith("component-")), written.join(", "))
|
||||
assert.equal(ctx.componentCssMap!.size, 0)
|
||||
})
|
||||
})
|
||||
|
||||
describe("analytics scripts", () => {
|
||||
/** Run the site's analytics script in a fake page; returns the URLs of the scripts it loads. */
|
||||
async function loadedScripts(analytics: Record<string, unknown>) {
|
||||
const { ctx, read } = await emit(
|
||||
{
|
||||
analytics: analytics as GlobalConfiguration["analytics"],
|
||||
enablePopovers: false,
|
||||
prefetch: false as never,
|
||||
},
|
||||
{ emitters: [] },
|
||||
)
|
||||
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
|
||||
// the analytics script(s), before the router
|
||||
const ours = scripts.slice(0, -1)
|
||||
const loaded: { src: string; attributes: Record<string, string> }[] = []
|
||||
const element = () => ({
|
||||
attributes: {} as Record<string, string>,
|
||||
setAttribute(name: string, value: string) {
|
||||
this.attributes[name] = value
|
||||
},
|
||||
})
|
||||
const firstScript = { parentNode: { insertBefore: (s: never) => loaded.push(s) } }
|
||||
const document = Object.assign(new EventTarget(), {
|
||||
title: "Page",
|
||||
createElement: element,
|
||||
head: { appendChild: (s: never) => loaded.push(s) },
|
||||
getElementsByTagName: () => [firstScript],
|
||||
})
|
||||
const context = createContext({
|
||||
document,
|
||||
location: { hostname: "garden.example", pathname: "/", href: "https://garden.example/" },
|
||||
})
|
||||
context.window = context
|
||||
for (const script of ours) runInContext(script, context)
|
||||
return { loaded: loaded.map((s) => ({ src: s.src, attributes: s.attributes })), context, ours }
|
||||
}
|
||||
|
||||
const cases: [Record<string, unknown>, string, Record<string, string>?][] = [
|
||||
[{ provider: "google", tagId: "G-1" }, "https://www.googletagmanager.com/gtag/js?id=G-1"],
|
||||
[
|
||||
{ provider: "plausible" },
|
||||
"https://plausible.io/js/script.manual.js",
|
||||
{ "data-domain": "garden.example" },
|
||||
],
|
||||
[{ provider: "plausible", host: "https://p.example" }, "https://p.example/js/script.manual.js"],
|
||||
[
|
||||
{ provider: "umami", websiteId: "w1" },
|
||||
"https://analytics.umami.is/script.js",
|
||||
{ "data-website-id": "w1" },
|
||||
],
|
||||
[
|
||||
{ provider: "umami", websiteId: "w1", host: "https://u.example", script: "u.js" },
|
||||
"https://u.example/u.js",
|
||||
],
|
||||
[{ provider: "goatcounter", websiteId: "g1" }, "https://gc.zgo.at/count.js"],
|
||||
[{ provider: "posthog", apiKey: "k" }, "https://app.posthog.com/static/array.js"],
|
||||
[
|
||||
{ provider: "posthog", apiKey: "k", host: "https://ph.example" },
|
||||
"https://ph.example/static/array.js",
|
||||
],
|
||||
[
|
||||
{ provider: "posthog", apiKey: "k", host: "https://h", apiHost: "https://api.h" },
|
||||
"https://api.h/static/array.js",
|
||||
],
|
||||
[{ provider: "tinylytics", siteId: "t 1" }, "https://tinylytics.app/embed/t%201.js?spa"],
|
||||
[{ provider: "cabin" }, "https://scripts.withcabin.com/hello.js"],
|
||||
[{ provider: "cabin", host: "https://c.example" }, "https://c.example/hello.js"],
|
||||
[{ provider: "clarity", projectId: "c1" }, "https://www.clarity.ms/tag/c1"],
|
||||
[{ provider: "matomo", host: "m.example", siteId: "3" }, "//m.example/matomo.js"],
|
||||
[{ provider: "vercel" }, "/_vercel/insights/script.js"],
|
||||
[
|
||||
{ provider: "rybbit", siteId: "r1" },
|
||||
"https://app.rybbit.io/api/script.js",
|
||||
{ "data-site-id": "r1" },
|
||||
],
|
||||
[
|
||||
{ provider: "rybbit", siteId: "r1", host: "https://r.example" },
|
||||
"https://r.example/api/script.js",
|
||||
],
|
||||
]
|
||||
for (const [analytics, src, attributes] of cases) {
|
||||
test(`${JSON.stringify(analytics)} loads ${src}`, async () => {
|
||||
const { loaded } = await loadedScripts(analytics)
|
||||
assert.deepEqual(
|
||||
loaded.map((s) => s.src),
|
||||
[src],
|
||||
)
|
||||
for (const [name, value] of Object.entries(attributes ?? {})) {
|
||||
assert.equal(loaded[0].attributes[name], value, name)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
test("goatcounter counts at the site's endpoint; posthog gets its options", async () => {
|
||||
const gc = await loadedScripts({ provider: "goatcounter", websiteId: "g1", host: "gc.example" })
|
||||
assert.ok(gc.ours.join("\n").includes('"https://" + "g1" + "." + "gc.example" + "/count"'))
|
||||
const ph = await loadedScripts({
|
||||
provider: "posthog",
|
||||
apiKey: "k",
|
||||
uiHost: "https://ui.example",
|
||||
personProfiles: "identified_only",
|
||||
})
|
||||
const init = (ph.context.posthog as { _i: [string, Record<string, unknown>][] })._i[0]
|
||||
assert.deepEqual(init[0], "k")
|
||||
assert.deepEqual(
|
||||
{ ...init[1] },
|
||||
{
|
||||
api_host: "https://app.posthog.com",
|
||||
ui_host: "https://ui.example",
|
||||
person_profiles: "identified_only",
|
||||
capture_pageview: false,
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test("vercel's queue stub is defined in the prescript, before any script runs", async () => {
|
||||
const { ctx, read } = await emit({ analytics: { provider: "vercel" } }, { emitters: [] })
|
||||
const context = createContext({})
|
||||
context.window = context
|
||||
runInContext(read(ctx.hashedResourceNames!["prescript.js"]), context)
|
||||
assert.equal(typeof context.va, "function")
|
||||
context.va("event", "x")
|
||||
assert.deepEqual(
|
||||
[...(context.vaq as unknown[][])].map((args) => [...args]),
|
||||
[["event", "x"]],
|
||||
)
|
||||
})
|
||||
|
||||
test("no analytics, no analytics script", async () => {
|
||||
const { ours } = await loadedScripts({})
|
||||
assert.deepEqual(ours, [])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,309 @@
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { registerHooks } from "node:module"
|
||||
import test, { after, describe } from "node:test"
|
||||
import { h } from "preact"
|
||||
import type { BuildCtx } from "../../util/ctx"
|
||||
import type { QuartzComponent, QuartzComponentProps } from "../../components/types"
|
||||
import type { QuartzPageTypePluginInstance } from "../types"
|
||||
import type { FilePath, FullSlug } from "../../util/path"
|
||||
import type { StaticResources } from "../../util/resources"
|
||||
import type { ChangeEvent } from "../types"
|
||||
import type { Element, Root } from "hast"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
|
||||
// Rendering a page imports components with SCSS and inline browser scripts, which esbuild bundles
|
||||
// in a real build; under tsx they are stubbed out.
|
||||
registerHooks({
|
||||
load(url, context, next) {
|
||||
if (url.endsWith(".scss") || /\.inline\.ts$/.test(url)) {
|
||||
return { format: "module", source: "export default ''", shortCircuit: true }
|
||||
}
|
||||
return next(url, context)
|
||||
},
|
||||
})
|
||||
const { PageTypeDispatcher } = await import("./dispatcher")
|
||||
const { defaultProcessedContent } = await import("../vfile")
|
||||
|
||||
const Head: QuartzComponent = ({ fileData }: QuartzComponentProps) =>
|
||||
h("head", null, h("title", null, String(fileData.frontmatter?.title ?? "")))
|
||||
|
||||
/** A page type whose body names it, so the emitted HTML tells which page type rendered a page. */
|
||||
function pageType(
|
||||
name: string,
|
||||
overrides: Partial<QuartzPageTypePluginInstance> = {},
|
||||
): QuartzPageTypePluginInstance {
|
||||
const Body: QuartzComponent = ({ fileData }: QuartzComponentProps) =>
|
||||
h("article", { "data-type": name }, `${name}:${fileData.slug}`)
|
||||
return {
|
||||
name,
|
||||
layout: name,
|
||||
match: () => true,
|
||||
body: () => Body,
|
||||
...overrides,
|
||||
} as QuartzPageTypePluginInstance
|
||||
}
|
||||
|
||||
const dirs: string[] = []
|
||||
after(() => {
|
||||
for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function setup(
|
||||
pageTypes: QuartzPageTypePluginInstance[],
|
||||
removedPages?: Map<string, string>,
|
||||
transformers: unknown[] = [],
|
||||
) {
|
||||
const output = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-dispatcher-"))
|
||||
dirs.push(output)
|
||||
const ctx = {
|
||||
argv: { output, serve: false, directory: "content" },
|
||||
cfg: {
|
||||
configuration: { baseUrl: "example.com/sub", locale: "en-US" },
|
||||
plugins: { pageTypes, transformers },
|
||||
},
|
||||
allSlugs: [],
|
||||
virtualPages: [],
|
||||
removedPages,
|
||||
} as unknown as BuildCtx
|
||||
const read = (slug: string) => fs.readFileSync(path.join(output, `${slug}.html`), "utf8")
|
||||
return { ctx, output, read }
|
||||
}
|
||||
|
||||
const resources: StaticResources = { css: [], js: [], additionalHead: [] }
|
||||
const dispatcher = () => PageTypeDispatcher({ defaults: { head: Head } })
|
||||
|
||||
function page(slug: string, html = "", links: string[] = []) {
|
||||
return defaultProcessedContent({
|
||||
slug: slug as FullSlug,
|
||||
relativePath: `${slug}.md` as FilePath,
|
||||
filePath: `content/${slug}.md` as FilePath,
|
||||
frontmatter: { title: slug, tags: [] },
|
||||
links: links as never,
|
||||
htmlAst: { type: "root", children: [] },
|
||||
}).map((x, i) =>
|
||||
i === 0 && html
|
||||
? {
|
||||
type: "root",
|
||||
children: [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: `./${html}`, "data-slug": html, className: ["internal"] },
|
||||
children: [{ type: "text", value: html }],
|
||||
},
|
||||
],
|
||||
}
|
||||
: x,
|
||||
) as ReturnType<typeof defaultProcessedContent>
|
||||
}
|
||||
|
||||
const linkOf = ([tree]: ReturnType<typeof page>) => (tree as Root).children[0] as Element
|
||||
|
||||
async function collect(gen: AsyncGenerator<FilePath> | AsyncIterable<FilePath>, output: string) {
|
||||
const out: string[] = []
|
||||
for await (const fp of gen) out.push(path.relative(output, fp))
|
||||
return out.sort()
|
||||
}
|
||||
|
||||
describe("PageTypeDispatcher.emit", () => {
|
||||
test("each page is rendered by the first matching page type in priority order", async () => {
|
||||
const types = [
|
||||
pageType("low", { priority: 1 }),
|
||||
pageType("high", { priority: 10, match: ({ slug }) => slug.startsWith("special/") }),
|
||||
pageType("none", { match: () => false, priority: 100 }),
|
||||
]
|
||||
const { ctx, output, read } = setup(types)
|
||||
const content = [page("index"), page("special/a")]
|
||||
const files = await collect(dispatcher().emit(ctx, content, resources) as never, output)
|
||||
assert.deepEqual(files, ["index.html", "special/a.html"])
|
||||
assert.match(read("index"), /<article data-type="low">low:index<\/article>/)
|
||||
assert.match(read("special/a"), /<article data-type="high">high:special\/a<\/article>/)
|
||||
assert.match(read("special/a"), /<title>special\/a<\/title>/)
|
||||
})
|
||||
|
||||
test("virtual pages are emitted with their page type's body; the 404 page uses the site's base path", async () => {
|
||||
const generated = pageType("tags", {
|
||||
match: () => false,
|
||||
generate: () => [
|
||||
{ slug: "tags/x" as FullSlug, title: "Tag x", data: {} },
|
||||
{ slug: "404" as FullSlug, title: "Not found", data: {} },
|
||||
],
|
||||
})
|
||||
const { ctx, output, read } = setup([pageType("content"), generated])
|
||||
const files = await collect(dispatcher().emit(ctx, [page("a/b")], resources) as never, output)
|
||||
assert.deepEqual(files, ["404.html", "a/b.html", "tags/x.html"])
|
||||
assert.match(read("tags/x"), /tags:tags\/x/)
|
||||
assert.match(read("tags/x"), /<title>Tag x<\/title>/)
|
||||
// the 404 page is served from any depth: its assets are under the absolute base path
|
||||
assert.match(read("404"), /<script src="\/sub\/postscript\.js"/)
|
||||
assert.match(read("a/b"), /<script src="\.\.\/postscript\.js"/)
|
||||
assert.deepEqual(
|
||||
ctx.virtualPages.map(([, f]) => f.data.slug),
|
||||
["tags/x"],
|
||||
)
|
||||
})
|
||||
|
||||
test("links to a draft are marked broken in the emitted page", async () => {
|
||||
const removed = new Map([["draft", "Drafts"]])
|
||||
const { ctx, output } = setup([pageType("content")], removed)
|
||||
const a = page("a", "draft")
|
||||
await collect(dispatcher().emit(ctx, [a], resources) as never, output)
|
||||
assert.deepEqual(linkOf(a).properties, {
|
||||
href: "./draft",
|
||||
"data-slug": "draft",
|
||||
className: ["internal", "broken"],
|
||||
"data-filtered": "Drafts",
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("PageTypeDispatcher: pages that stand for files", () => {
|
||||
test("virtualPageHtmlPlugins' result is what the page shows; a page whose body fails isn't emitted", async () => {
|
||||
const Board: QuartzComponent = ({ fileData }: QuartzComponentProps) => {
|
||||
if (fileData.slug === "broken.canvas") throw new Error("cannot render")
|
||||
return h("p", null, `board ${fileData.slug}`)
|
||||
}
|
||||
const canvas = pageType("canvas", {
|
||||
match: () => false,
|
||||
fileExtensions: [".canvas"],
|
||||
body: () => Board,
|
||||
generate: () =>
|
||||
["a.canvas", "secret.canvas", "broken.canvas"].map((slug) => ({
|
||||
slug: slug as FullSlug,
|
||||
title: slug,
|
||||
data: {},
|
||||
})),
|
||||
})
|
||||
const encrypt = {
|
||||
name: "Encrypt",
|
||||
virtualPageHtmlPlugins: () => [
|
||||
() => (tree: Root, file: { data: { slug?: string } }) => {
|
||||
if (file.data.slug === "secret.canvas") {
|
||||
tree.children = [
|
||||
{
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: {},
|
||||
children: [{ type: "text", value: "ciphertext" }],
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
],
|
||||
}
|
||||
// transformers without virtualPageHtmlPlugins are skipped
|
||||
const { ctx, output, read } = setup([pageType("content"), canvas], undefined, [
|
||||
{ name: "Plain" },
|
||||
encrypt,
|
||||
])
|
||||
const files = await collect(dispatcher().emit(ctx, [page("index")], resources) as never, output)
|
||||
assert.deepEqual(files, ["a.canvas.html", "index.html", "secret.canvas.html"])
|
||||
assert.match(read("a.canvas"), /<p>board a\.canvas<\/p>/)
|
||||
assert.match(read("secret.canvas"), /<div>ciphertext<\/div>/)
|
||||
assert.doesNotMatch(read("secret.canvas"), /board/)
|
||||
// later emitters read the processed tree from ctx.virtualPages; the failed page is gone
|
||||
const trees = Object.fromEntries(
|
||||
ctx.virtualPages.map(([tree, f]) => [f.data.slug, toHtml(tree as Root)]),
|
||||
)
|
||||
assert.deepEqual(Object.keys(trees), ["a.canvas", "secret.canvas"])
|
||||
assert.equal(trees["secret.canvas"], "<div>ciphertext</div>")
|
||||
assert.equal(trees["a.canvas"], "")
|
||||
})
|
||||
})
|
||||
|
||||
describe("PageTypeDispatcher: what page bodies see", () => {
|
||||
// a body listing the pages it can embed (allFiles) and the files of folder "f" (ctx.trie)
|
||||
const Lister: QuartzComponent = ({ allFiles, ctx }: QuartzComponentProps) =>
|
||||
h(
|
||||
"article",
|
||||
null,
|
||||
`files:${allFiles.map((f) => f.slug).join(",")};` +
|
||||
`f:${(ctx.trie?.findNode(["f"])?.children ?? []).map((c) => c.slug).join(",")}`,
|
||||
)
|
||||
const types = () => [
|
||||
pageType("content", { body: () => Lister }),
|
||||
pageType("canvas", {
|
||||
match: () => false,
|
||||
fileExtensions: [".canvas"],
|
||||
generate: () => [{ slug: "f/board.canvas" as FullSlug, title: "Board", data: {} }],
|
||||
}),
|
||||
pageType("tags", {
|
||||
match: () => false,
|
||||
generate: () => [{ slug: "tags/t" as FullSlug, title: "t", data: {} }],
|
||||
}),
|
||||
]
|
||||
const expected = "files:f/note,f/board.canvas,tags/t;f:f/note,f/board.canvas"
|
||||
|
||||
test("emit: virtual pages are in allFiles; the folder trie holds the pages that stand for files", async () => {
|
||||
const { ctx, output, read } = setup(types())
|
||||
await collect(dispatcher().emit(ctx, [page("f/note")], resources) as never, output)
|
||||
assert.match(read("f/note"), new RegExp(`<article>${expected}</article>`))
|
||||
})
|
||||
|
||||
test("partialEmit: the same, for the pages it re-emits", async () => {
|
||||
const { ctx, output, read } = setup(types())
|
||||
const note = page("f/note")
|
||||
const events = [
|
||||
{ type: "change", path: "f/note.md", file: note[1] },
|
||||
] as unknown as ChangeEvent[]
|
||||
await collect(dispatcher().partialEmit!(ctx, [note], resources, events) as never, output)
|
||||
assert.match(read("f/note"), new RegExp(`<article>${expected}</article>`))
|
||||
})
|
||||
|
||||
test("partialEmit renders a changed page with the first matching page type by priority", async () => {
|
||||
const { ctx, output, read } = setup([
|
||||
pageType("low", { priority: 1 }),
|
||||
pageType("high", { priority: 10, match: ({ slug }) => slug === "special" }),
|
||||
])
|
||||
const [a, b] = [page("special"), page("plain")]
|
||||
const events = [
|
||||
{ type: "change", path: "special.md", file: a[1] },
|
||||
{ type: "change", path: "plain.md", file: b[1] },
|
||||
] as unknown as ChangeEvent[]
|
||||
await collect(dispatcher().partialEmit!(ctx, [a, b], resources, events) as never, output)
|
||||
assert.match(read("special"), /data-type="high"/)
|
||||
assert.match(read("plain"), /data-type="low"/)
|
||||
})
|
||||
})
|
||||
|
||||
describe("PageTypeDispatcher.partialEmit", () => {
|
||||
test("re-emits changed Markdown pages and all virtual pages, removes deleted pages' output", async () => {
|
||||
const generated = pageType("folder", {
|
||||
match: () => false,
|
||||
generate: () => [{ slug: "f/index" as FullSlug, title: "F", data: {} }],
|
||||
})
|
||||
const { ctx, output } = setup([pageType("content"), generated])
|
||||
const [a, b] = [page("a"), page("b")]
|
||||
await collect(dispatcher().emit(ctx, [a, b], resources) as never, output)
|
||||
fs.writeFileSync(path.join(output, "gone.html"), "stale")
|
||||
|
||||
const events = [
|
||||
{ type: "change", path: "a.md", file: a[1] },
|
||||
{ type: "delete", path: "gone.md" },
|
||||
// not Markdown: no page of its own
|
||||
{ type: "change", path: "image.png" },
|
||||
] as unknown as ChangeEvent[]
|
||||
ctx.virtualPages = []
|
||||
const files = await collect(
|
||||
dispatcher().partialEmit!(ctx, [a, b], resources, events) as never,
|
||||
output,
|
||||
)
|
||||
assert.deepEqual(files, ["a.html", "f/index.html"])
|
||||
assert.ok(!fs.existsSync(path.join(output, "gone.html")))
|
||||
})
|
||||
|
||||
test("a page whose link to a removed page changed is re-emitted although its source didn't", async () => {
|
||||
const removed = new Map([["draft", "Drafts"]])
|
||||
const { ctx, output } = setup([pageType("content")], removed)
|
||||
const linking = page("linking", "draft")
|
||||
const files = await collect(
|
||||
dispatcher().partialEmit!(ctx, [linking, page("other")], resources, []) as never,
|
||||
output,
|
||||
)
|
||||
assert.deepEqual(files, ["linking.html"])
|
||||
assert.equal(linkOf(linking).properties["data-filtered"], "Drafts")
|
||||
})
|
||||
})
|
||||
@@ -635,3 +635,38 @@ describe("links to unpublished pages, after the page types ran (crawl-links#7)",
|
||||
assert.ok(marks(home).every((m) => m === "ok"))
|
||||
})
|
||||
})
|
||||
|
||||
describe("resolveLayout: every slot", () => {
|
||||
test("a page type's override replaces each default slot; the page type's body is the page body", () => {
|
||||
const Body = (() => null) as unknown as QuartzComponent
|
||||
const pt = makePageType({ body: () => Body })
|
||||
const slots = ["header", "beforeBody", "afterBody", "left", "right", "footer"] as const
|
||||
const defaults = Object.fromEntries(slots.map((s) => [s, [StubA]]))
|
||||
const overrides = Object.fromEntries(slots.map((s) => [s, [StubB]]))
|
||||
const OtherHead = (() => null) as unknown as QuartzComponent
|
||||
const layout = resolveLayout(
|
||||
pt,
|
||||
{ head: StubHead, ...defaults },
|
||||
{ [pt.layout]: { head: OtherHead, ...overrides } },
|
||||
)
|
||||
for (const slot of slots) assert.deepStrictEqual(layout[slot], [StubB], slot)
|
||||
assert.strictEqual(layout.head, OtherHead)
|
||||
assert.strictEqual(layout.pageBody, Body)
|
||||
// without an override, the defaults
|
||||
const plain = resolveLayout(pt, { head: StubHead, ...defaults }, {})
|
||||
for (const slot of slots) assert.deepStrictEqual(plain[slot], [StubA], slot)
|
||||
})
|
||||
|
||||
test("collectComponents leaves out a missing head", () => {
|
||||
const components = collectComponents([makePageType()], { left: [StubA] }, {})
|
||||
assert.ok(!components.includes(undefined as never))
|
||||
assert.strictEqual(components.length, 2)
|
||||
})
|
||||
|
||||
test("collectTreeTransforms: page types without treeTransforms add none", () => {
|
||||
const t = (() => {}) as never
|
||||
const ctx = { cfg: { plugins: { transformers: [] } } } as unknown as BuildCtx
|
||||
const result = collectTreeTransforms(ctx, [{}, { treeTransforms: () => [t] }])
|
||||
assert.deepStrictEqual(result, { before: [], treeTransforms: [t], after: [] })
|
||||
})
|
||||
})
|
||||
@@ -3,7 +3,12 @@ import assert from "node:assert"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { readContentFile } from "./parse"
|
||||
import { createHtmlProcessor, createMdProcessor, parseMarkdown, readContentFile } from "./parse"
|
||||
import type { Root as MdRoot } from "mdast"
|
||||
import type { Root as HtmlRoot } from "hast"
|
||||
import type { VFile } from "vfile"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
import type { BuildCtx } from "../util/ctx"
|
||||
import { isContentError } from "../util/pluginErrors"
|
||||
import type { FilePath } from "../util/path"
|
||||
|
||||
@@ -39,3 +44,91 @@ describe("readContentFile", () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("parseMarkdown (one thread)", () => {
|
||||
// a transformer that records which of its hooks ran, in which order
|
||||
const recorder = (name: string, log: string[]) => ({
|
||||
name,
|
||||
textTransform: (_ctx: unknown, src: string) => {
|
||||
log.push(`${name}:text`)
|
||||
return `${src}\n\n${name}`
|
||||
},
|
||||
markdownPlugins: () => [
|
||||
() => (tree: MdRoot) => {
|
||||
log.push(`${name}:md`)
|
||||
tree.children.push({ type: "paragraph", children: [{ type: "text", value: `md-${name}` }] })
|
||||
},
|
||||
],
|
||||
htmlPlugins: () => [
|
||||
() => (tree: HtmlRoot, file: VFile) => {
|
||||
log.push(`${name}:html`)
|
||||
file.data[`html-${name}` as "slug"] = toHtml(tree) as never
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
test("runs text, Markdown and HTML transforms in plugin order and sets the file's paths", async () => {
|
||||
const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "quartz-parse-"))
|
||||
try {
|
||||
await fs.promises.mkdir(path.join(dir, "Sub Folder"))
|
||||
const a = path.join(dir, "Sub Folder", "My Note.md")
|
||||
const b = path.join(dir, "other.md")
|
||||
await fs.promises.writeFile(a, "\n\n # Title \n\n")
|
||||
await fs.promises.writeFile(b, "text")
|
||||
const log: string[] = []
|
||||
const ctx = {
|
||||
argv: { directory: dir, verbose: false, concurrency: 1 },
|
||||
// a transformer may implement any subset of the hooks
|
||||
cfg: {
|
||||
plugins: { transformers: [recorder("one", log), { name: "bare" }, recorder("two", log)] },
|
||||
},
|
||||
// a frontmatter permalink is the page's address
|
||||
permalinks: { "other.md": "elsewhere/page" },
|
||||
} as unknown as BuildCtx
|
||||
const res = await parseMarkdown(ctx, [a, b] as FilePath[])
|
||||
|
||||
assert.deepStrictEqual(
|
||||
res.map(([, file]) => [file.data.relativePath, file.data.slug, file.data.filePath]),
|
||||
[
|
||||
["Sub Folder/My Note.md", "sub-folder/my-note", a],
|
||||
["other.md", "elsewhere/page", b],
|
||||
],
|
||||
)
|
||||
// the text is trimmed before the first textTransform, which sees what the one before returned
|
||||
assert.strictEqual(String(res[0][1].value), "# Title\n\none\n\ntwo")
|
||||
// per file: all text transforms, then Markdown plugins, then (after all files) HTML plugins
|
||||
assert.deepStrictEqual(log, [
|
||||
"one:text",
|
||||
"two:text",
|
||||
"one:md",
|
||||
"two:md",
|
||||
"one:text",
|
||||
"two:text",
|
||||
"one:md",
|
||||
"two:md",
|
||||
"one:html",
|
||||
"two:html",
|
||||
"one:html",
|
||||
"two:html",
|
||||
])
|
||||
const data = res[0][1].data as Record<string, string>
|
||||
// Markdown plugins ran in order, and remark-rehype turned the Markdown AST into HTML
|
||||
assert.strictEqual(
|
||||
data["html-one"],
|
||||
"<h1>Title</h1>\n<p>one</p>\n<p>two</p>\n<p>md-one</p>\n<p>md-two</p>",
|
||||
)
|
||||
assert.strictEqual(res[0][0].type, "root")
|
||||
assert.strictEqual(toHtml(res[0][0] as HtmlRoot), data["html-two"])
|
||||
} finally {
|
||||
await fs.promises.rm(dir, { recursive: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("raw HTML in Markdown is kept (allowDangerousHtml)", async () => {
|
||||
const ctx = { cfg: { plugins: { transformers: [] } } } as unknown as BuildCtx
|
||||
const md = createMdProcessor(ctx)
|
||||
const ast = md.parse('<div class="x">hi</div>')
|
||||
const html = await createHtmlProcessor(ctx).run(await md.run(ast))
|
||||
assert.strictEqual(toHtml(html, { allowDangerousHtml: true }), '<div class="x">hi</div>')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user