test(config): plugin loading, option merging and dependency checks

loadQuartzConfig: CLI overrides, built-in settings exposed in the
configuration, absorbed crawl-links entries, defaultOptions under entry
options, plugin order, load failures and incompatible plugins in CI,
local plugin manifests from package.json, dependency errors. Unit tests
for source names, dependency validation and layout placement. Adds a todo
test: validateDependencies orders dependencies across pipeline stages.
This commit is contained in:
saberzero1 committed 2026-11-27 14:44:06 +01:00
1 parent bd3ac11469
commit 9909b508e7
2 files changed
+562

No files matched your search

@@ -5,6 +5,7 @@ import os from "node:os"
import path from "node:path"
import { registerHooks } from "node:module"
import { getSlugOptions, setSlugOptions } from "../../util/path"
import { getDiagnostics, resetDiagnostics } from "../../util/diagnostics"
import type { QuartzComponent } from "../../components/types"
// loadQuartzConfig imports the built-in emitters, whose SCSS and inline browser scripts esbuild
@@ -157,3 +158,271 @@ plugins:
assert.ok(transformers.includes("Description"))
})
})
describe("loadQuartzConfig: configuration, options and loading", () => {
let dir: string
before(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-config-"))
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 = (content: string) => {
const file = path.join(dir, "quartz.config.yaml")
fs.writeFileSync(file, content)
process.env.QUARTZ_CONFIG_PATH = file
}
const instance = (cfg: Awaited<ReturnType<typeof loadQuartzConfig>>, name: string) =>
cfg.plugins.transformers.find((p) => p.name === name)
test("CLI overrides win over the YAML configuration; built-ins are exposed with their settings", async () => {
useConfig(`configuration:
pageTitle: From YAML
baseUrl: yaml.example.com
links:
prettyLinks: false
plugins: []
`)
const cfg = await loadQuartzConfig({ baseUrl: "cli.example.com" })
assert.equal(cfg.configuration.baseUrl, "cli.example.com")
assert.equal(cfg.configuration.pageTitle, "From YAML")
// configuration.links: the configured options over the built-in's defaults, enabled and order
assert.deepEqual(cfg.configuration.links, {
markdownLinkResolution: "shortest",
prettyLinks: false,
openLinksInNewTab: false,
lazyLoad: false,
externalLinkIcon: true,
disableBrokenWikilinks: true,
enabled: true,
order: 60,
})
assert.deepEqual(names(cfg.plugins.transformers), ["Frontmatter", "Links"])
// the built-in emitters, then the page renderer last; the 404 page type is always there
assert.deepEqual(names(cfg.plugins.emitters), [
"ComponentResources",
"Assets",
"Static",
"SlugRedirects",
"ContentIndex",
"Fonts",
"PageTypeDispatcher",
])
assert.deepEqual(names(cfg.plugins.pageTypes ?? []), ["404"])
})
test("a former crawl-links entry configures the built-in with crawl-links' defaults and isn't loaded", async () => {
useConfig(`plugins:
- source: "@quartz-community/crawl-links"
enabled: true
options:
openLinksInNewTab: true
`)
resetDiagnostics()
const cfg = await loadQuartzConfig()
// not installed, and not tried: no load error
assert.deepEqual(
getDiagnostics().filter((d) => d.severity === "error"),
[],
)
const links = cfg.configuration.links as unknown as Record<string, unknown>
assert.equal(links.markdownLinkResolution, "absolute")
assert.equal(links.openLinksInNewTab, true)
assert.deepEqual(names(cfg.plugins.transformers), ["Frontmatter", "Links"])
})
test("an entry's options override the manifest's defaultOptions", async () => {
// Latex' defaultOptions say renderEngine: katex, whose stylesheet it adds as a resource;
// with mathjax it adds none
useConfig(`plugins:
- source: "@quartz-community/latex"
enabled: true
`)
const katex = instance(await loadQuartzConfig(), "Latex")
assert.ok(katex?.externalResources?.({} as never), "katex resources")
useConfig(`plugins:
- source: "@quartz-community/latex"
enabled: true
options:
renderEngine: mathjax
`)
const mathjax = instance(await loadQuartzConfig(), "Latex")
assert.ok(mathjax, "Latex is loaded")
assert.equal(mathjax.externalResources?.({} as never), undefined)
})
test("plugins run by entry order, then defaultOrder; disabled entries aren't loaded", async () => {
// defaultOrder: description 70, latex 80, table-of-contents 50
useConfig(`plugins:
- source: "@quartz-community/latex"
enabled: true
order: 5
- source: "@quartz-community/description"
enabled: true
- source: "@quartz-community/table-of-contents"
enabled: true
- source: "@quartz-community/hard-line-breaks"
enabled: false
`)
const cfg = await loadQuartzConfig()
assert.deepEqual(names(cfg.plugins.transformers), [
"Frontmatter",
"Latex",
"TableOfContents",
"Links",
"Description",
])
})
test("a plugin that can't be loaded is skipped locally and fails the build in CI", async () => {
useConfig(`plugins:
- source: "@quartz-community/does-not-exist"
enabled: true
- source: "@quartz-community/description"
enabled: true
`)
const cfg = await loadQuartzConfig()
assert.ok(names(cfg.plugins.transformers).includes("Description"))
const saved = { ...process.env }
try {
delete process.env.QUARTZ_CONFIG_QUIET
delete process.env.QUARTZ_ALLOW_BROKEN_PLUGINS
process.env.CI = "true"
await assert.rejects(loadQuartzConfig(), {
message:
/^1 enabled plugin could not be loaded: @quartz-community\/does-not-exist \(see above\)/,
})
process.env.QUARTZ_ALLOW_BROKEN_PLUGINS = "1"
await loadQuartzConfig()
} finally {
for (const key of ["CI", "QUARTZ_ALLOW_BROKEN_PLUGINS", "QUARTZ_CONFIG_QUIET"]) {
if (saved[key] === undefined) delete process.env[key]
else process.env[key] = saved[key]
}
}
})
})
describe("loadQuartzConfig: a local plugin's manifest (package.json → quartz)", () => {
let dir: string
const linked: string[] = []
// .quartz/plugins and .quartz, where this test creates them
const pluginsDir = path.join(process.cwd(), ".quartz", "plugins")
const created = [pluginsDir, path.dirname(pluginsDir)].filter((d) => !fs.existsSync(d))
before(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-local-plugin-"))
process.env.QUARTZ_CONFIG_QUIET = "1"
})
afterEach(() => {
delete process.env.QUARTZ_CONFIG_PATH
})
after(() => {
delete process.env.QUARTZ_CONFIG_QUIET
// the symlinks installPlugin made in .quartz/plugins
for (const link of linked)
if (fs.lstatSync(link, { throwIfNoEntry: false })) fs.unlinkSync(link)
for (const d of created) if (fs.readdirSync(d).length === 0) fs.rmdirSync(d)
fs.rmSync(dir, { recursive: true })
})
/** A transformer plugin in `dir/<name>` whose instance records the options it got. */
function localPlugin(name: string, quartz: Record<string, unknown>) {
const root = path.join(dir, name)
fs.mkdirSync(root)
fs.writeFileSync(
path.join(root, "package.json"),
JSON.stringify({ name, version: "2.3.4", type: "module", main: "index.js", quartz }),
)
fs.writeFileSync(
path.join(root, "index.js"),
`export default (opts) => ({ name: ${JSON.stringify(name)}, opts, textTransform: (_c, s) => s })\n`,
)
linked.push(path.join(process.cwd(), ".quartz", "plugins", name))
return root
}
const useConfig = (plugins: { source: string; options?: object }[]) => {
const file = path.join(dir, `config-${Math.random().toString(36).slice(2)}.yaml`)
fs.writeFileSync(
file,
`plugins:\n${plugins.map((p) => ` - source: ${JSON.stringify(p.source)}\n enabled: true\n options: ${JSON.stringify(p.options ?? {})}\n`).join("")}`,
)
process.env.QUARTZ_CONFIG_PATH = file
}
const withEnv = async (env: Record<string, string | undefined>, fn: () => Promise<void>) => {
const saved = Object.fromEntries(Object.keys(env).map((k) => [k, process.env[k]]))
for (const [k, v] of Object.entries(env)) {
if (v === undefined) delete process.env[k]
else process.env[k] = v
}
try {
await fn()
} finally {
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete process.env[k]
else process.env[k] = v
}
}
}
test("its defaultOptions are the base of the entry's options", async () => {
const root = localPlugin("audit-options", {
name: "audit-options",
category: "transformer",
defaultOptions: { greeting: "hello", size: 1 },
})
useConfig([{ source: root, options: { size: 2 } }])
const cfg = await loadQuartzConfig()
const plugin = cfg.plugins.transformers.find((p) => p.name === "audit-options") as unknown as {
opts: unknown
}
assert.deepEqual(plugin.opts, { greeting: "hello", size: 2 })
})
test("a plugin that needs a newer Quartz warns locally and fails the build in CI", async () => {
const root = localPlugin("audit-future", {
name: "audit-future",
category: "transformer",
quartzVersion: ">=99.0.0",
})
useConfig([{ source: root }])
await withEnv({ CI: undefined, QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: undefined }, async () => {
const cfg = await loadQuartzConfig()
assert.ok(names(cfg.plugins.transformers).includes("audit-future"))
})
await withEnv(
{ CI: "true", QUARTZ_CONFIG_QUIET: undefined, QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: undefined },
async () => {
await assert.rejects(loadQuartzConfig(), {
message: /^1 enabled plugin does not support Quartz [^:]+: audit-future \(see above\)/,
})
},
)
await withEnv(
{ CI: "true", QUARTZ_CONFIG_QUIET: undefined, QUARTZ_ALLOW_INCOMPATIBLE_PLUGINS: "1" },
async () => {
await loadQuartzConfig()
},
)
})
test("a missing dependency fails the build", async () => {
const root = localPlugin("audit-deps", {
name: "audit-deps",
category: "transformer",
dependencies: ["github:someone/not-configured"],
})
useConfig([{ source: root }])
await withEnv({ QUARTZ_CONFIG_QUIET: undefined }, async () => {
await assert.rejects(loadQuartzConfig(), {
message: "Plugin dependency validation failed with 1 error(s). See above for details.",
})
})
})
})
+293
View File
@@ -14,6 +14,9 @@ import type { PluginManifest } from "./types"
import { componentRegistry } from "../../components/registry"
import type { QuartzComponent, QuartzComponentConstructor } from "../../components/types"
import { PluginJsonEntry, LayoutPosition } from "./types"
import { LayoutDiagnostics } from "./layoutReport"
import { h } from "preact"
import { render } from "preact-render-to-string"
describe("resolveConfigPath", () => {
afterEach(() => {
@@ -432,3 +435,293 @@ describe("async plugin factories", () => {
assert.strictEqual(detectCategoryFromModule({ default: factory }), "transformer")
})
})
describe("dependency order between plugins", () => {
const validate = (
plugin: Partial<PluginManifest>,
dep: Partial<PluginManifest>,
order?: { plugin?: number; dep?: number },
) => {
const entries: PluginJsonEntry[] = [
{ source: "github:someone/x", enabled: true, options: {}, order: order?.plugin },
{ source: "github:someone/y", enabled: true, options: {}, order: order?.dep },
]
const manifests = new Map<string, PluginManifest>([
[
"github:someone/x",
{ name: "x", dependencies: ["github:someone/y"], ...plugin } as PluginManifest,
],
["github:someone/y", { name: "y", ...dep } as PluginManifest],
])
return validateDependencies(entries, manifests, [])
}
test("a dependency of the same stage must run first: entry order, else defaultOrder, else 50", () => {
const transformer = { category: "transformer" } as const
assert.deepStrictEqual(validate(transformer, { ...transformer, defaultOrder: 40 }).errors, [])
assert.match(
validate(transformer, { ...transformer, defaultOrder: 60 }).errors[0],
/"x" \(order: 50\) depends on "y" \(order: 60\)/,
)
// the entry's order wins over the manifest's defaultOrder, on both sides
assert.deepStrictEqual(
validate(
{ ...transformer, defaultOrder: 10 },
{ ...transformer, defaultOrder: 60 },
{
plugin: 70,
},
).errors,
[],
)
assert.match(
validate(transformer, { ...transformer, defaultOrder: 10 }, { dep: 55 }).errors[0],
/\(order: 50\) depends on "y" \(order: 55\)/,
)
// equal order: stable, the dependency is not after the plugin
assert.deepStrictEqual(validate(transformer, transformer).errors, [])
})
test("a dependency cycle fails the build", () => {
const entries: PluginJsonEntry[] = [
{ source: "github:someone/x", enabled: true, options: {} },
{ source: "github:someone/y", enabled: true, options: {} },
]
const manifests = new Map<string, PluginManifest>([
["github:someone/x", { name: "x", dependencies: ["github:someone/y"] } as PluginManifest],
["github:someone/y", { name: "y", dependencies: ["github:someone/x"] } as PluginManifest],
])
assert.deepStrictEqual(validateDependencies(entries, manifests, []).errors, [
"Circular dependency detected: x → y → x",
])
})
// Order only decides between plugins of the same stage: all transformers run before any filter or
// emitter, and a component-only plugin has no place in the pipeline. The check against a built-in
// compares categories (above); the check between plugins doesn't, so an emitter (or a
// component) depending on a transformer with a higher order fails the build with "is configured
// to run first", although the transformer always runs first.
test(
"a dependency of another stage is not ordered against the plugin",
{ todo: "bug: validateDependencies compares order across stages (config-loader.ts:225)" },
() => {
const transformer = { category: "transformer", defaultOrder: 60 } as const
assert.deepStrictEqual(validate({ category: "emitter" }, transformer).errors, [])
assert.deepStrictEqual(validate({ category: "component" }, transformer).errors, [])
},
)
})
describe("plugin names of each source form", () => {
test("github:, git+…, https:// URLs, local paths and { repo, name } objects", () => {
const cases: [Parameters<typeof isExcluded>[0], string][] = [
["github:someone/my-plugin#v2", "my-plugin"],
["git+https://github.com/someone/my-plugin.git", "my-plugin"],
["https://gitlab.com/group/my-plugin.git#main", "my-plugin"],
["https://github.com/someone/my-plugin", "my-plugin"],
["./plugins/my-plugin/", "my-plugin"],
[{ repo: "github:someone/repo", name: "my-plugin" }, "my-plugin"],
[{ repo: "github:someone/my-plugin" }, "my-plugin"],
]
for (const [source, name] of cases) {
assert.ok(isExcluded(source, [name]), JSON.stringify(source))
assert.ok(!isExcluded(source, ["someone"]), JSON.stringify(source))
}
})
})
describe("validateDependencies: which plugins are checked", () => {
const entry = (source: string, extra: Partial<PluginJsonEntry> = {}): PluginJsonEntry => ({
source,
enabled: true,
options: {},
...extra,
})
const m = (extra: Partial<PluginManifest>) => ({ name: "n", ...extra }) as PluginManifest
test("a disabled plugin's dependencies are not required", () => {
const { errors } = validateDependencies(
[entry("github:a/x", { enabled: false })],
new Map([["github:a/x", m({ dependencies: ["github:a/missing"] })]]),
)
assert.deepStrictEqual(errors, [])
})
test("messages name the plugin by its displayName", () => {
const { errors } = validateDependencies(
[entry("github:a/x")],
new Map([["github:a/x", m({ displayName: "Fancy X", dependencies: ["github:a/missing"] })]]),
)
assert.deepStrictEqual(errors, [
'Plugin "Fancy X" requires "missing". Run: npx quartz plugin add github:a/missing',
])
})
test("a disabled dependency with a higher order is only a warning", () => {
const { errors, warnings } = validateDependencies(
[entry("github:a/x"), entry("github:a/y", { enabled: false, order: 90 })],
new Map([["github:a/x", m({ dependencies: ["github:a/y"] })]]),
)
assert.deepStrictEqual(errors, [])
assert.strictEqual(warnings.length, 1)
})
test("a plugin at the same order as the built-in it depends on runs after it", () => {
const plan = planBuiltins({
configuration: {},
entries: [],
nameOf: () => "",
providesOf: () => undefined,
})
const { errors } = validateDependencies(
[entry("github:a/x", { order: 60 })],
new Map([
[
"github:a/x",
m({ category: "transformer", dependencies: ["@quartz-community/crawl-links"] }),
],
]),
plan.builtins,
)
assert.deepStrictEqual(errors, [])
})
test("cycles of any length are found once; shared dependencies are no cycle", () => {
const deps = (map: Record<string, string[]>) =>
new Map(Object.entries(map).map(([k, d]) => [k, m({ dependencies: d })]))
const sources = ["github:a/w", "github:a/x", "github:a/y", "github:a/z"]
const entries = sources.map((s) => entry(s))
// w → x → y → z, and w → y: a diamond, no cycle
assert.deepStrictEqual(
validateDependencies(
entries,
deps({
"github:a/w": ["github:a/x", "github:a/y"],
"github:a/x": ["github:a/y"],
"github:a/y": ["github:a/z"],
}),
).errors,
[],
)
// w → x → y → z → x
assert.deepStrictEqual(
validateDependencies(
entries,
deps({
"github:a/w": ["github:a/x"],
"github:a/x": ["github:a/y"],
"github:a/y": ["github:a/z"],
"github:a/z": ["github:a/x"],
}),
).errors,
["Circular dependency detected: x → y → z → x"],
)
})
})
describe("buildLayoutForEntries: components and options", () => {
const place = (layout: Record<string, unknown>, manifest?: Record<string, unknown>) => {
componentRegistry.register("p", makeComponent("P"), "test-source", manifest as never)
return buildLayoutForEntries(
[{ source: "p", enabled: true, options: {}, layout: layout as never }],
{},
)
}
test("mobile-only and desktop-only wrap the component in their class", () => {
const html = (layout: Record<string, unknown>) => {
const [C] = place({ position: "left", ...layout }).left!
return render(h(C as never, {} as never))
}
assert.strictEqual(html({ display: "mobile-only" }), '<div class="mobile-only"></div>')
assert.strictEqual(html({ display: "desktop-only" }), '<div class="desktop-only"></div>')
assert.strictEqual(html({ display: "all" }), "")
assert.strictEqual(html({ display: null }), "")
})
test("display all / null raise no warning; a non-numeric priority is 50 with a warning", () => {
const diag = new LayoutDiagnostics()
componentRegistry.register("q", makeComponent("Q"), "test-source")
componentRegistry.register("r", makeComponent("R"), "test-source")
componentRegistry.register("s", makeComponent("S"), "test-source")
const result = buildLayoutForEntries(
[
{
source: "q",
enabled: true,
options: {},
layout: { position: "left", priority: "high", display: "all" } as never,
},
{
source: "r",
enabled: true,
options: {},
layout: { position: "left", priority: 60, display: null } as never,
},
{
source: "s",
enabled: true,
options: {},
layout: { position: "left", priority: 40 } as never,
},
],
{},
diag,
)
assert.deepStrictEqual(diag.warnings, [
'plugin "q": layout priority "high" is not a number — using 50.',
])
assert.deepStrictEqual(
result.left!.map((c) => c.displayName),
["S", "Q", "R"],
)
})
test("layout.position: null falls back to the manifest's defaultPosition", () => {
const result = place({ position: null, priority: 1 }, { defaultPosition: "right" })
assert.strictEqual(result.right!.length, 1)
})
test("a component registered under the PascalCase name of a kebab-case plugin is found", () => {
componentRegistry.register("TagList", makeComponent("TagListC"), "test-source")
const result = buildLayoutForEntries(
[
{
source: "tag-list",
enabled: true,
options: {},
layout: { position: "left", priority: 1 },
},
],
{},
)
assert.deepStrictEqual(
result.left!.map((c) => c.displayName),
["TagListC"],
)
})
test("a constructor gets the entry's options with quartz.ts overrides on top, or none", () => {
const received: unknown[] = []
const ctor = ((opts?: unknown) => {
received.push(opts)
return makeComponent(`C${received.length}`)
}) as QuartzComponentConstructor
componentRegistry.register("ctor-a", ctor, "test-source")
componentRegistry.register("ctor-b", ctor, "test-source")
componentRegistry.setOptionOverrides("ctor-a", { extra: true, base: 2 })
buildLayoutForEntries(
[
{
source: "ctor-a",
enabled: true,
options: { base: 1, own: "x" },
layout: { position: "left", priority: 1 },
},
{ source: "ctor-b", enabled: true, options: {}, layout: { position: "left", priority: 2 } },
],
{},
)
assert.deepStrictEqual(received, [{ base: 2, own: "x", extra: true }, undefined])
})
})