mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
test: cover 5.3 changes the mutation audit found untested
- SlugRedirects emitter (emit/partialEmit, gating, live set, relative targets) - loadQuartzConfig with extends: default (merged configuration, plugins, layout; before/after against built-ins; JSON configs) - fetchRemoteConfig: offline cache, http redirect, 1 MB limit (bytes), memoisation counted, retry after a failure; non-object base; cycle chain - resolveTarget refuses http URLs that contain https:// - orderPlugins with several before/after targets - plugin entry keys before/after accepted by the CLI validator - Head on the 404 page and tag pages - isolateComponentCss warning; componentStylesheet extracted from ComponentResources so the test uses the emitter's own wrapping - dateIsFromFrontmatter, pluginMatchKey without name/subdir - todo: stripDiacritics link paths decode a percent-encoded % twice
This commit is contained in:
11 files changed
+634
-34
No files matched your search
@@ -198,6 +198,36 @@ describe("validatePluginEntry", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("accepts before, after and every layout key", () => {
|
||||
assert.deepStrictEqual(
|
||||
validatePluginEntry({
|
||||
source: "@quartz-community/description",
|
||||
enabled: true,
|
||||
order: 60,
|
||||
before: "Links",
|
||||
after: ["obsidian-flavored-markdown"],
|
||||
layout: {
|
||||
position: "right",
|
||||
priority: 5,
|
||||
display: "desktop-only",
|
||||
condition: "not-index",
|
||||
group: "toolbar",
|
||||
groupOptions: { grow: true },
|
||||
},
|
||||
}),
|
||||
[],
|
||||
)
|
||||
})
|
||||
|
||||
test("an unknown key without a close match lists the allowed keys", () => {
|
||||
assert.deepStrictEqual(
|
||||
validatePluginEntry({ source: "x/y", enabled: true, zzzzzz: 1 }).map((i) => i.message),
|
||||
[
|
||||
'unknown key "zzzzzz" is ignored (allowed: source, enabled, options, order, before, after, layout)',
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
test("catches typoed keys and a missing enabled flag", () => {
|
||||
const issues = validatePluginEntry({ source: "x/y", enable: true, option: {} })
|
||||
const messages = issues.map((i) => i.message).join("\n")
|
||||
|
||||
@@ -64,4 +64,37 @@ describe("Head", () => {
|
||||
})
|
||||
assert.strictEqual(meta(html, "article:modified_time"), undefined)
|
||||
})
|
||||
|
||||
test("the 404 page: no canonical, no article meta, og:url is the site's address", () => {
|
||||
const real = new Date("2024-05-06T00:00:00Z")
|
||||
// as the 404 page type generates it (a virtual page gets `404.md` as its relativePath)
|
||||
const html = head({
|
||||
slug: "404",
|
||||
relativePath: "404.md",
|
||||
frontmatter: { title: "Not Found", tags: [] },
|
||||
dates: { created: real, modified: real, published: real },
|
||||
})
|
||||
assert.strictEqual(meta(html, "og:type"), "website")
|
||||
assert.strictEqual(meta(html, "og:url"), "https://example.org/")
|
||||
assert.strictEqual(meta(html, "twitter:url"), "https://example.org/")
|
||||
assert.doesNotMatch(html, /rel="canonical"/)
|
||||
assert.doesNotMatch(html, /article:/)
|
||||
// a note has all three
|
||||
const note = head({
|
||||
slug: "notes/a b",
|
||||
dates: { created: real, modified: real, published: real },
|
||||
})
|
||||
assert.strictEqual(meta(note, "og:url"), "https://example.org/notes/a%20b")
|
||||
assert.match(note, /<link rel="canonical" href="https:\/\/example.org\/notes\/a%20b"\/>/)
|
||||
assert.strictEqual(meta(note, "article:modified_time"), real.toISOString())
|
||||
})
|
||||
|
||||
test("tag pages and pages without a file are not articles", () => {
|
||||
assert.strictEqual(meta(head({ slug: "tags/recipes" }), "og:type"), "website")
|
||||
assert.strictEqual(meta(head({ slug: "tags/food/recipes" }), "og:type"), "website")
|
||||
// a note in a folder named like the tag folder is still an article
|
||||
assert.strictEqual(meta(head({ slug: "notes/tags/recipes" }), "og:type"), "article")
|
||||
assert.strictEqual(meta(head({ slug: "my-tags/x" }), "og:type"), "article")
|
||||
assert.strictEqual(meta(head({ slug: "a", relativePath: undefined }), "og:type"), "website")
|
||||
})
|
||||
})
|
||||
@@ -41,8 +41,8 @@ import {
|
||||
import type { PluginJsonEntry } from "../loader/types"
|
||||
import type { BuildCtx } from "../../util/ctx"
|
||||
import type { ContentDetails } from "../types"
|
||||
import type { FullSlug, SimpleSlug } from "../../util/path"
|
||||
import { setSlugOptions } from "../../util/path"
|
||||
import type { FilePath, FullSlug, SimpleSlug } from "../../util/path"
|
||||
import { setSlugOptions, slugifyFilePath } from "../../util/path"
|
||||
import type { ProcessedContent } from "../vfile"
|
||||
|
||||
const entry = (source: string, extra: Partial<PluginJsonEntry> = {}): PluginJsonEntry => ({
|
||||
@@ -464,6 +464,31 @@ describe("links built-in", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test(
|
||||
"slugs.stripDiacritics: a percent-encoded % in a link target is decoded once",
|
||||
{
|
||||
todo: "slugOptionsOnLinkPath decodes the path and transformLink decodes it again, so %2520 becomes a space",
|
||||
},
|
||||
() => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
try {
|
||||
// `Kódování/Mezera je %20.md`, linked as Obsidian writes a Markdown link to it
|
||||
const target = slugifyFilePath("Kódování/Mezera je %20.md" as FilePath)
|
||||
assert.strictEqual(target, "kodovani/mezera-je--percent20")
|
||||
const { els } = run(
|
||||
[a("K%C3%B3dov%C3%A1n%C3%AD/Mezera%20je%20%2520.md")],
|
||||
"index",
|
||||
{ markdownLinkResolution: "shortest" },
|
||||
["index", target],
|
||||
)
|
||||
assert.strictEqual(els[0].properties.href, "./kodovani/mezera-je--percent20")
|
||||
assert.ok(!(els[0].properties.className as string[]).includes("broken"))
|
||||
} finally {
|
||||
setSlugOptions(undefined)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
test("without slugs.stripDiacritics link targets keep their diacritics", () => {
|
||||
const { els } = run([a("Příliš")], "page", { markdownLinkResolution: "shortest" }, [
|
||||
"page",
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
import { Features, transform } from "lightningcss"
|
||||
import { transform as transpile } from "esbuild"
|
||||
import { write } from "./helpers"
|
||||
import { isolateComponentCss } from "../../util/componentCss"
|
||||
import { componentStylesheet } from "../../util/componentCss"
|
||||
|
||||
/**
|
||||
* Content hash for cache-busting file names (`postscript-<hash>.js`). Not a password or security
|
||||
@@ -444,17 +444,11 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
|
||||
const cssStringToFilename = new Map<string, string>()
|
||||
const componentCss = [...componentResources.componentCssStrings]
|
||||
if (componentCss.length > 0) {
|
||||
const isolated = componentCss.map((c) =>
|
||||
isolateComponentCss(c, componentResources.cssOwners.get(c)),
|
||||
const minified = componentStylesheet(
|
||||
componentCss,
|
||||
(c) => componentResources.cssOwners.get(c),
|
||||
lightningTargets,
|
||||
)
|
||||
const wrapped = `@layer quartz-base {\n${isolated.join("\n")}\n}`
|
||||
const minified = transform({
|
||||
filename: "component.css",
|
||||
code: Buffer.from(wrapped),
|
||||
minify: true,
|
||||
targets: lightningTargets,
|
||||
include: Features.MediaQueries,
|
||||
}).code.toString()
|
||||
|
||||
const hash = hashContent(minified)
|
||||
const slug = `component-${hash}`
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test, { describe } from "node:test"
|
||||
import test, { afterEach, describe } from "node:test"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { VFile } from "vfile"
|
||||
import { Root } from "hast"
|
||||
import { ProcessedContent } from "../vfile"
|
||||
import { FilePath, FullSlug, setSlugOptions, slugifyFilePath } from "../../util/path"
|
||||
import { strippedAddressMoves } from "./slugRedirects"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import type { StaticResources } from "../../util/resources"
|
||||
import { SlugRedirects, strippedAddressMoves } from "./slugRedirects"
|
||||
|
||||
const page = (
|
||||
relativePath: string,
|
||||
@@ -50,3 +55,94 @@ describe("redirects from addresses slugs.stripDiacritics changed", () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("SlugRedirects emitter", () => {
|
||||
const tempDirs: string[] = []
|
||||
afterEach(async () => {
|
||||
setSlugOptions(undefined)
|
||||
await Promise.all(tempDirs.splice(0).map((dir) => fs.promises.rm(dir, { recursive: true })))
|
||||
})
|
||||
|
||||
/** Runs `emit` (or `partialEmit`) into a temp output dir → output path → file contents. */
|
||||
const emitAll = async (content: ProcessedContent[], partial = false) => {
|
||||
const output = await fs.promises.mkdtemp(path.join(os.tmpdir(), "quartz-slug-redirects-"))
|
||||
tempDirs.push(output)
|
||||
const ctx = { argv: { output } } as unknown as BuildCtx
|
||||
const plugin = SlugRedirects()
|
||||
assert.equal(plugin.name, "SlugRedirects")
|
||||
const emitted = partial
|
||||
? plugin.partialEmit!(ctx, content, {} as StaticResources, [])
|
||||
: plugin.emit(ctx, content, {} as StaticResources)
|
||||
const written: Record<string, string> = {}
|
||||
for await (const fp of emitted as AsyncIterable<string>) {
|
||||
written[path.relative(output, fp).split(path.sep).join("/")] = await fs.promises.readFile(
|
||||
fp,
|
||||
"utf8",
|
||||
)
|
||||
}
|
||||
return written
|
||||
}
|
||||
|
||||
const redirect = (to: string, url: string) => `<!DOCTYPE html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
<title>${to}</title>
|
||||
<link rel="canonical" href="${url}">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="refresh" content="0; url=${url}">
|
||||
</head>
|
||||
</html>
|
||||
`
|
||||
|
||||
const withAliases = (content: ProcessedContent, aliases: string[]): ProcessedContent => {
|
||||
content[1].data.aliases = aliases as FullSlug[]
|
||||
return content
|
||||
}
|
||||
|
||||
test("writes a redirect at each unstripped address to the stripped one", async () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
const content = [withAliases(page("české/Čeština.md", { aliases: ["stará"] }), ["stara"])]
|
||||
assert.equal(content[0][1].data.slug, "ceske/cestina")
|
||||
const expected = {
|
||||
"české/čeština.html": redirect("ceske/cestina", "../ceske/cestina"),
|
||||
"české/index.html": redirect("ceske/", "../ceske/"),
|
||||
"stará.html": redirect("ceske/cestina", "./ceske/cestina"),
|
||||
}
|
||||
assert.deepEqual(await emitAll(content), expected)
|
||||
assert.deepEqual(await emitAll(content, true), expected)
|
||||
})
|
||||
|
||||
test("the redirect target is relative to the nested old address", async () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
const written = await emitAll([page("Ä/b/Über.md")])
|
||||
assert.deepEqual(written, {
|
||||
"ä/b/über.html": redirect("a/b/uber", "../../a/b/uber"),
|
||||
"ä/b/index.html": redirect("a/b/", "../../a/b/"),
|
||||
"ä/index.html": redirect("a/", "../a/"),
|
||||
})
|
||||
})
|
||||
|
||||
test("an old address that is another page's alias is not overwritten", async () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
// a page (e.g. from a plugin that registers addresses) already answers at `české/index`
|
||||
const content = [page("české/Čeština.md"), withAliases(page("other.md"), ["české/index"])]
|
||||
assert.deepEqual(Object.keys(await emitAll(content)).sort(), ["české/čeština.html"])
|
||||
})
|
||||
|
||||
test("an old address that is a page without a file (a plugin's page) is not overwritten", async () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
const virtual = new VFile("")
|
||||
virtual.data = { slug: "české/index" as FullSlug, frontmatter: { title: "České" } }
|
||||
const content: ProcessedContent[] = [
|
||||
page("české/Čeština.md"),
|
||||
[{ type: "root", children: [] } as Root, virtual],
|
||||
]
|
||||
assert.deepEqual(Object.keys(await emitAll(content)), ["české/čeština.html"])
|
||||
})
|
||||
|
||||
test("nothing is emitted without slugs.stripDiacritics", async () => {
|
||||
setSlugOptions({ stripDiacritics: false })
|
||||
assert.deepEqual(await emitAll([page("české/Čeština.md", { aliases: ["stará"] })]), {})
|
||||
})
|
||||
})
|
||||
@@ -87,6 +87,7 @@ describe("pluginMatchKey for monorepo subdirectories", () => {
|
||||
)
|
||||
}
|
||||
assert.strictEqual(pluginMatchKey({ repo: "github:me/explorer", subdir: "." }), "explorer")
|
||||
assert.strictEqual(pluginMatchKey({ repo: "github:me/explorer" }), "explorer")
|
||||
})
|
||||
test("an overlay entry for one monorepo plugin leaves the other alone", () => {
|
||||
const merged = mergeQuartzConfigs(
|
||||
@@ -355,7 +356,10 @@ describe("resolveExtends", () => {
|
||||
quartzRoot: root,
|
||||
readFile,
|
||||
}),
|
||||
/cycle/,
|
||||
{
|
||||
name: "ConfigExtendsError",
|
||||
message: '"extends" cycle: quartz.config.yaml → a.yaml → b.yaml → a.yaml',
|
||||
},
|
||||
)
|
||||
await assert.rejects(
|
||||
() =>
|
||||
@@ -375,6 +379,21 @@ describe("resolveExtends", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("a base that is not a configuration object is an error", async () => {
|
||||
files[path.join(root, "list.yaml")] = "- source: explorer\n- source: graph\n"
|
||||
const file = path.join(root, "list.yaml")
|
||||
await assert.rejects(
|
||||
resolveExtends({ extends: "./list.yaml" }, path.join(root, "quartz.config.yaml"), {
|
||||
quartzRoot: root,
|
||||
readFile,
|
||||
}),
|
||||
{
|
||||
name: "ConfigExtendsError",
|
||||
message: `"extends: ./list.yaml": ${file} is not a valid config (${file} does not contain a configuration object)`,
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test("extends: default reproduces the shipped default config exactly", async () => {
|
||||
const defaultFile = path.resolve("quartz.config.default.yaml")
|
||||
const shipped = YAML.parse(fs.readFileSync(defaultFile, "utf-8"))
|
||||
@@ -448,11 +467,6 @@ describe("fetchRemoteConfig", () => {
|
||||
await fetchRemoteConfig(url, { cacheDir, fetchImpl: ok("a: 1\n"), offline: false }),
|
||||
"a: 1\n",
|
||||
)
|
||||
// memoised per process: a second call does not fetch again
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig(url, { cacheDir, fetchImpl: failing, offline: false }),
|
||||
"a: 1\n",
|
||||
)
|
||||
const warnings: string[] = []
|
||||
const other = tmp()
|
||||
fs.cpSync(cacheDir, other, { recursive: true })
|
||||
@@ -503,3 +517,159 @@ describe("fetchRemoteConfig", () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("fetchRemoteConfig limits and memoisation", () => {
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "quartz-extends-"))
|
||||
/** A fetch that answers `body` (from `finalUrl` after redirects) and counts its calls. */
|
||||
const counting = (body: string, finalUrl?: string) => {
|
||||
const calls: string[] = []
|
||||
const impl = (async (url: string) => {
|
||||
calls.push(url)
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
url: finalUrl ?? url,
|
||||
text: async () => body,
|
||||
}
|
||||
}) as unknown as typeof fetch
|
||||
return { calls, impl }
|
||||
}
|
||||
const failing = (async () => {
|
||||
throw new Error("getaddrinfo ENOTFOUND")
|
||||
}) as unknown as typeof fetch
|
||||
|
||||
test("two calls for one URL fetch once", async () => {
|
||||
const cacheDir = tmp()
|
||||
const { calls, impl } = counting("a: 1\n")
|
||||
const url = "https://cfg.example/memo.yaml"
|
||||
const warnings: string[] = []
|
||||
const opts = {
|
||||
cacheDir,
|
||||
fetchImpl: impl,
|
||||
offline: false,
|
||||
warn: (m: string) => warnings.push(m),
|
||||
}
|
||||
const [first, second] = await Promise.all([
|
||||
fetchRemoteConfig(url, opts),
|
||||
fetchRemoteConfig(url, opts),
|
||||
])
|
||||
assert.strictEqual(await fetchRemoteConfig(url, opts), "a: 1\n")
|
||||
assert.deepStrictEqual([first, second], ["a: 1\n", "a: 1\n"])
|
||||
assert.deepStrictEqual(calls, [url])
|
||||
assert.deepStrictEqual(warnings, [])
|
||||
})
|
||||
|
||||
test("a failed fetch is tried again by the next call", async () => {
|
||||
const cacheDir = tmp()
|
||||
const url = "https://cfg.example/retry.yaml"
|
||||
await assert.rejects(
|
||||
fetchRemoteConfig(url, { cacheDir, fetchImpl: failing, offline: false }),
|
||||
/could not be fetched: getaddrinfo ENOTFOUND/,
|
||||
)
|
||||
const { calls, impl } = counting("b: 2\n")
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig(url, { cacheDir, fetchImpl: impl, offline: false }),
|
||||
"b: 2\n",
|
||||
)
|
||||
assert.deepStrictEqual(calls, [url])
|
||||
})
|
||||
|
||||
test("offline, the cached copy is returned without fetching", async () => {
|
||||
const online = tmp()
|
||||
const url = "https://cfg.example/offline.yaml"
|
||||
await fetchRemoteConfig(url, { cacheDir: online, fetchImpl: counting("c: 3\n").impl })
|
||||
const offlineDir = tmp()
|
||||
fs.cpSync(online, offlineDir, { recursive: true })
|
||||
const { calls, impl } = counting("c: changed\n")
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig(url, { cacheDir: offlineDir, fetchImpl: impl, offline: true }),
|
||||
"c: 3\n",
|
||||
)
|
||||
assert.deepStrictEqual(calls, [])
|
||||
})
|
||||
|
||||
test("a redirect to http:// is an error, even with a cached copy", async () => {
|
||||
const url = "https://cfg.example/redirected.yaml"
|
||||
const cacheDir = tmp()
|
||||
await fetchRemoteConfig(url, { cacheDir, fetchImpl: counting("d: 4\n").impl })
|
||||
const other = tmp()
|
||||
fs.cpSync(cacheDir, other, { recursive: true })
|
||||
const warnings: string[] = []
|
||||
await assert.rejects(
|
||||
fetchRemoteConfig(url, {
|
||||
cacheDir: other,
|
||||
fetchImpl: counting("d: evil\n", "http://evil.example/x.yaml").impl,
|
||||
offline: false,
|
||||
warn: (m) => warnings.push(m),
|
||||
}),
|
||||
{
|
||||
name: "ConfigExtendsError",
|
||||
message: `"extends: ${url}" redirected to http://evil.example/x.yaml, which is not https`,
|
||||
},
|
||||
)
|
||||
assert.deepStrictEqual(warnings, [])
|
||||
// a redirect that stays on https is fine
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig(url, {
|
||||
cacheDir: tmp(),
|
||||
fetchImpl: counting("d: 5\n", "https://mirror.example/x.yaml").impl,
|
||||
offline: false,
|
||||
}),
|
||||
"d: 5\n",
|
||||
)
|
||||
})
|
||||
|
||||
test("a body over 1 MB is an error and is not cached", async () => {
|
||||
const limit = 1024 * 1024
|
||||
const exactly = tmp()
|
||||
const atLimit = "#".repeat(limit)
|
||||
assert.strictEqual(
|
||||
await fetchRemoteConfig("https://cfg.example/1mb.yaml", {
|
||||
cacheDir: exactly,
|
||||
fetchImpl: counting(atLimit).impl,
|
||||
offline: false,
|
||||
}),
|
||||
atLimit,
|
||||
)
|
||||
for (const [name, body] of [
|
||||
["over.yaml", "#".repeat(limit + 1)],
|
||||
// 524 289 characters, 1 048 578 bytes: the limit is in bytes
|
||||
["utf8.yaml", "é".repeat(limit / 2 + 1)],
|
||||
]) {
|
||||
const url = `https://cfg.example/${name}`
|
||||
const cacheDir = tmp()
|
||||
await assert.rejects(
|
||||
fetchRemoteConfig(url, { cacheDir, fetchImpl: counting(body).impl, offline: false }),
|
||||
{ name: "ConfigExtendsError", message: `"extends: ${url}" is larger than 1 MB` },
|
||||
)
|
||||
assert.deepStrictEqual(fs.readdirSync(cacheDir), [])
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("resolveTarget accepts only https URLs", () => {
|
||||
const from = path.resolve("/site/quartz.config.yaml")
|
||||
test("an http URL with https:// in its query is refused", () => {
|
||||
for (const target of [
|
||||
"http://evil.example/?https://cfg.example/x.yaml",
|
||||
"http://evil.example/https://cfg.example/x.yaml",
|
||||
"file:///etc/https://x.yaml",
|
||||
]) {
|
||||
assert.throws(() => resolveTarget(target, from, "/site"), {
|
||||
name: "ConfigExtendsError",
|
||||
message: `${from}: "extends: ${target}" — only https:// URLs can be extended`,
|
||||
})
|
||||
}
|
||||
assert.throws(
|
||||
() => resolveTarget("?https://x", "http://evil.example/base.yaml", "/site"),
|
||||
/only https:\/\/ URLs can be extended/,
|
||||
)
|
||||
})
|
||||
|
||||
test("a local path that contains :// is a path, not a URL", () => {
|
||||
assert.strictEqual(
|
||||
resolveTarget("mirror/https://cfg.example/x.yaml", from, "/site"),
|
||||
path.resolve("/site/mirror/https:/cfg.example/x.yaml"),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,159 @@
|
||||
import test, { after, afterEach, before, describe } from "node:test"
|
||||
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 { getSlugOptions, setSlugOptions } from "../../util/path"
|
||||
import type { QuartzComponent } from "../../components/types"
|
||||
|
||||
// loadQuartzConfig imports the built-in emitters, whose SCSS and inline browser scripts 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 { loadQuartzConfig, loadQuartzLayout } = await import("./config-loader")
|
||||
|
||||
const names = (list: { name: string }[]) => list.map((p) => p.name)
|
||||
const componentNames = (list: QuartzComponent[] | undefined) =>
|
||||
(list ?? []).map((c) => c.displayName ?? c.name)
|
||||
|
||||
describe("loadQuartzConfig with extends: default", () => {
|
||||
let dir: string
|
||||
before(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-extends-"))
|
||||
process.env.QUARTZ_CONFIG_QUIET = "1"
|
||||
})
|
||||
afterEach(() => {
|
||||
delete process.env.QUARTZ_CONFIG_PATH
|
||||
setSlugOptions(undefined)
|
||||
})
|
||||
after(() => {
|
||||
delete process.env.QUARTZ_CONFIG_QUIET
|
||||
fs.rmSync(dir, { recursive: true })
|
||||
})
|
||||
const useConfig = (name: string, content: string) => {
|
||||
const file = path.join(dir, name)
|
||||
fs.writeFileSync(file, content)
|
||||
process.env.QUARTZ_CONFIG_PATH = file
|
||||
}
|
||||
|
||||
test("merges configuration, plugins, layout and applies before/after", async () => {
|
||||
useConfig(
|
||||
"quartz.config.yaml",
|
||||
`extends: default
|
||||
configuration:
|
||||
pageTitle: Extended garden
|
||||
slugs:
|
||||
stripDiacritics: true
|
||||
plugins:
|
||||
- source: "@quartz-community/description"
|
||||
order: 60
|
||||
before: Links
|
||||
- source: "@quartz-community/favicon"
|
||||
after: [CustomOgImages, Links]
|
||||
# names that don't run among the transformers: a disabled plugin, an absorbed one, a built-in
|
||||
# emitter. They are accepted and change nothing
|
||||
- source: "@quartz-community/latex"
|
||||
after: [citations, remove-draft, Fonts]
|
||||
- source: "@quartz-community/explorer"
|
||||
layout:
|
||||
position: right
|
||||
priority: 5
|
||||
layout:
|
||||
byPageType:
|
||||
folder:
|
||||
positions:
|
||||
right: null
|
||||
`,
|
||||
)
|
||||
const cfg = await loadQuartzConfig()
|
||||
// the extending file's value, and the base's for what it leaves out
|
||||
assert.equal(cfg.configuration.pageTitle, "Extended garden")
|
||||
assert.equal(cfg.configuration.baseUrl, "quartz.jzhao.xyz")
|
||||
assert.equal(getSlugOptions().stripDiacritics, true)
|
||||
// plugins enabled only in the base are loaded; Description (order 60 here, 70 in the base)
|
||||
// runs before the built-in Links at the same order
|
||||
assert.deepEqual(names(cfg.plugins.transformers), [
|
||||
"Frontmatter",
|
||||
"NoteProperties",
|
||||
"CreatedModifiedDate",
|
||||
"SyntaxHighlighting",
|
||||
"GitHubFlavoredMarkdown",
|
||||
"ObsidianFlavoredMarkdown",
|
||||
"UnlistedPages",
|
||||
"TableOfContents",
|
||||
"BasesTransformer",
|
||||
"Description",
|
||||
"Links",
|
||||
"Latex",
|
||||
"EncryptedPages",
|
||||
])
|
||||
// `after:` names og-image by its instance name; favicon comes first in the base list
|
||||
assert.deepEqual(names(cfg.plugins.emitters), [
|
||||
"ComponentResources",
|
||||
"Assets",
|
||||
"Static",
|
||||
"SlugRedirects",
|
||||
"ContentIndex",
|
||||
"AliasRedirects",
|
||||
"CustomOgImages",
|
||||
"Favicon",
|
||||
"CNAME",
|
||||
"Fonts",
|
||||
"EncryptedContentIndex",
|
||||
"PageTypeDispatcher",
|
||||
])
|
||||
|
||||
const layout = await loadQuartzLayout()
|
||||
assert.deepEqual(componentNames(layout.defaults.right), [
|
||||
"ExplorerComponent",
|
||||
"Graph",
|
||||
"TableOfContents",
|
||||
"Backlinks",
|
||||
])
|
||||
assert.ok(!componentNames(layout.defaults.left).includes("ExplorerComponent"))
|
||||
// `right: null` removed the base's `right: []` for folder pages
|
||||
assert.deepEqual(Object.keys(layout.byPageType?.folder ?? {}), ["left"])
|
||||
assert.deepEqual(Object.keys(layout.byPageType?.tag ?? {}).sort(), ["left", "right"])
|
||||
})
|
||||
|
||||
test("after: on a built-in is checked against the order kept from the base", async () => {
|
||||
useConfig(
|
||||
"after-links.yaml",
|
||||
`extends: default
|
||||
plugins:
|
||||
- source: "@quartz-community/table-of-contents"
|
||||
after: Links
|
||||
`,
|
||||
)
|
||||
await assert.rejects(loadQuartzConfig(), {
|
||||
name: "PluginOrderError",
|
||||
message:
|
||||
'plugin "@quartz-community/table-of-contents" (order 50) must run after "Links", but "Links" has order 60, so it runs later. ' +
|
||||
'Give "@quartz-community/table-of-contents" an order above 60, or "Links" one below 50.',
|
||||
})
|
||||
})
|
||||
|
||||
test("a JSON config extends too", async () => {
|
||||
useConfig(
|
||||
"quartz.plugins.json",
|
||||
JSON.stringify({
|
||||
extends: "default",
|
||||
configuration: { pageTitle: "From JSON" },
|
||||
plugins: [{ source: "@quartz-community/latex", enabled: false }],
|
||||
}),
|
||||
)
|
||||
const cfg = await loadQuartzConfig()
|
||||
assert.equal(cfg.configuration.pageTitle, "From JSON")
|
||||
assert.equal(cfg.configuration.locale, "en-US")
|
||||
const transformers = names(cfg.plugins.transformers)
|
||||
assert.ok(!transformers.includes("Latex"))
|
||||
assert.ok(transformers.includes("Description"))
|
||||
})
|
||||
})
|
||||
@@ -26,6 +26,30 @@ describe("orderPlugins", () => {
|
||||
assert.deepStrictEqual(orderPlugins(items, known("x", "y", "z")), ["z", "y", "x"])
|
||||
})
|
||||
|
||||
test("one plugin before several others", () => {
|
||||
const items = [item("b", 50), item("c", 50), item("a", 50, { before: ["b", "c"] })]
|
||||
assert.deepStrictEqual(orderPlugins(items, known("a", "b", "c")), ["a", "b", "c"])
|
||||
})
|
||||
|
||||
test("one plugin after several others, and several targets in both directions", () => {
|
||||
const items = [item("x", 50, { after: ["z", "y"] }), item("y", 50), item("z", 50)]
|
||||
assert.deepStrictEqual(orderPlugins(items, known("x", "y", "z")), ["y", "z", "x"])
|
||||
const mixed = [
|
||||
item("p", 50),
|
||||
item("q", 50, { after: ["r", "s"], before: ["p", "t"] }),
|
||||
item("r", 50),
|
||||
item("s", 50),
|
||||
item("t", 50),
|
||||
]
|
||||
assert.deepStrictEqual(orderPlugins(mixed, known("p", "q", "r", "s", "t")), [
|
||||
"r",
|
||||
"s",
|
||||
"q",
|
||||
"p",
|
||||
"t",
|
||||
])
|
||||
})
|
||||
|
||||
test("constraints that agree with order are fine and change nothing", () => {
|
||||
const items = [item("late", 70, { after: ["early"] }), item("early", 40, { before: ["late"] })]
|
||||
assert.deepStrictEqual(orderPlugins(items, known("late", "early")), ["early", "late"])
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test, { describe } from "node:test"
|
||||
import test, { beforeEach, describe } from "node:test"
|
||||
import { Features, transform } from "lightningcss"
|
||||
import { isolateComponentCss } from "./componentCss"
|
||||
import { componentStylesheet, isolateComponentCss } from "./componentCss"
|
||||
import { getDiagnostics, resetDiagnostics } from "./diagnostics"
|
||||
|
||||
/** The component stylesheet as ComponentResources builds it. */
|
||||
const sheet = (chunks: string[]) =>
|
||||
transform({
|
||||
filename: "component.css",
|
||||
code: Buffer.from(
|
||||
`@layer quartz-base {\n${chunks.map((c) => isolateComponentCss(c, "Bad")).join("\n")}\n}`,
|
||||
),
|
||||
minify: true,
|
||||
include: Features.MediaQueries,
|
||||
}).code.toString()
|
||||
const sheet = (chunks: string[]) => componentStylesheet(chunks, () => "Bad")
|
||||
|
||||
describe("isolateComponentCss", () => {
|
||||
beforeEach(() => resetDiagnostics())
|
||||
const later = ".later{color:red}"
|
||||
for (const [what, bad] of [
|
||||
["a missing }", ".bad{color:blue"],
|
||||
@@ -24,11 +18,35 @@ describe("isolateComponentCss", () => {
|
||||
]) {
|
||||
test(`${what} in one component doesn't swallow the next one's rules`, () => {
|
||||
assert.match(sheet([bad, later]), /@layer quartz-base\{.*\.later\{color:red\}\}$/)
|
||||
// the end of the chunk closes what it left open: not an error
|
||||
assert.deepEqual(getDiagnostics(), [])
|
||||
})
|
||||
}
|
||||
|
||||
test("a stray } doesn't fail the stylesheet", () => {
|
||||
assert.match(sheet([".bad{color:blue}}", later]), /\.bad\{color:#00f\}.*\.later\{color:red\}/)
|
||||
assert.deepEqual(
|
||||
getDiagnostics().map((d) => d.message.split(" has ")[0]),
|
||||
["The CSS of component Bad"],
|
||||
)
|
||||
})
|
||||
|
||||
test("CSS that doesn't parse keeps the rules that do, with a warning naming the component", () => {
|
||||
assert.equal(
|
||||
isolateComponentCss(".bad{color:blue}}", "Explorer"),
|
||||
".bad {\n color: #00f;\n}\n",
|
||||
)
|
||||
assert.deepEqual(getDiagnostics(), [
|
||||
{
|
||||
severity: "warning",
|
||||
area: "css",
|
||||
message:
|
||||
"The CSS of component Explorer has a syntax error (Unexpected end of input at line 1, column 18); the rules that parse are kept.",
|
||||
},
|
||||
])
|
||||
resetDiagnostics()
|
||||
isolateComponentCss(".bad{color:blue}}")
|
||||
assert.match(getDiagnostics()[0].message, /^The CSS of a component has a syntax error/)
|
||||
})
|
||||
|
||||
test("balanced CSS comes out as it did before", () => {
|
||||
@@ -40,5 +58,6 @@ describe("isolateComponentCss", () => {
|
||||
include: Features.MediaQueries,
|
||||
}).code.toString()
|
||||
assert.equal(sheet([css, later]), raw)
|
||||
assert.deepEqual(getDiagnostics(), [])
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { transform } from "lightningcss"
|
||||
import { Features, Targets, transform } from "lightningcss"
|
||||
import { recordDiagnostic } from "./diagnostics"
|
||||
|
||||
/**
|
||||
@@ -31,3 +31,23 @@ export function isolateComponentCss(css: string, owner = ""): string {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* All components' CSS as ComponentResources emits it: each chunk isolated, in order, in one
|
||||
* `quartz-base` layer, minified.
|
||||
*/
|
||||
export function componentStylesheet(
|
||||
chunks: string[],
|
||||
ownerOf: (css: string) => string | undefined = () => undefined,
|
||||
targets?: Targets,
|
||||
): string {
|
||||
const isolated = chunks.map((c) => isolateComponentCss(c, ownerOf(c)))
|
||||
const wrapped = `@layer quartz-base {\n${isolated.join("\n")}\n}`
|
||||
return transform({
|
||||
filename: "component.css",
|
||||
code: Buffer.from(wrapped),
|
||||
minify: true,
|
||||
targets,
|
||||
include: Features.MediaQueries,
|
||||
}).code.toString()
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { realDate } from "./dates"
|
||||
import { dateIsFromFrontmatter, realDate } from "./dates"
|
||||
import type { QuartzPluginData } from "../plugins/vfile"
|
||||
|
||||
const data = (d: Record<string, unknown>) => d as unknown as QuartzPluginData
|
||||
@@ -43,3 +43,33 @@ describe("realDate", () => {
|
||||
assert.strictEqual(realDate(data({ dates: { modified: now } }), undefined), undefined)
|
||||
})
|
||||
})
|
||||
|
||||
describe("dateIsFromFrontmatter", () => {
|
||||
test("a date-time value is compared as written, a date-only one as local midnight", () => {
|
||||
const d = data({ frontmatter: { published: "2024-01-02T10:00:00" } })
|
||||
assert.strictEqual(dateIsFromFrontmatter(d, new Date("2024-01-02T10:00:00"), "published"), true)
|
||||
assert.strictEqual(
|
||||
dateIsFromFrontmatter(d, new Date("2024-01-02T00:00:00"), "published"),
|
||||
false,
|
||||
)
|
||||
const dateOnly = data({ frontmatter: { published: "2024-01-02" } })
|
||||
assert.strictEqual(
|
||||
dateIsFromFrontmatter(dateOnly, new Date("2024-01-02T00:00:00"), "published"),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
test("YAML dates and timestamps compare by value; other values and missing ones never match", () => {
|
||||
const when = new Date("2024-01-02T10:00:00Z")
|
||||
const of = (published: unknown) => data({ frontmatter: { published } })
|
||||
assert.strictEqual(dateIsFromFrontmatter(of(new Date(when)), when, "published"), true)
|
||||
assert.strictEqual(dateIsFromFrontmatter(of(when.getTime()), when, "published"), true)
|
||||
assert.strictEqual(dateIsFromFrontmatter(of([when.toISOString()]), when, "published"), false)
|
||||
assert.strictEqual(dateIsFromFrontmatter(of(""), new Date(0), "published"), false)
|
||||
assert.strictEqual(dateIsFromFrontmatter(of(null), new Date(0), "published"), false)
|
||||
assert.strictEqual(dateIsFromFrontmatter(of(when), new Date(NaN), "published"), false)
|
||||
// the page's default date type
|
||||
const d = data({ frontmatter: { modified: when.toISOString() }, defaultDateType: "modified" })
|
||||
assert.strictEqual(dateIsFromFrontmatter(d, when), true)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user