feat(config): experimental extends: merge quartz.config.yaml onto the default config (#2440)

This commit is contained in:
saberzero1 committed 2026-11-26 16:07:12 +01:00
1 parent 773e2c7fe1
commit df11e31ef3
7 files changed
+564 -11

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Experimental `extends` in `quartz.config.yaml`: `extends: default` (or a path) starts from `quartz.config.default.yaml` and applies only the changes in your file. `configuration` and `layout` merge key by key, plugin entries merge with the default entry of the same plugin. Configs without `extends` behave exactly as before.
+28
View File
@@ -23,6 +23,34 @@ layout:
`configuration` and `plugins` are described below; the `layout` section (component groups, `byPageType` overrides, sidebar modes) is described in [[layout]].
## Extending the default configuration
Without a `quartz.config.yaml`, Quartz uses `quartz.config.default.yaml`. A `quartz.config.yaml` normally replaces it completely. With `extends`, your file can hold just the changes you make to another configuration instead:
```yaml title="quartz.config.yaml"
extends: default # quartz.config.default.yaml
configuration:
pageTitle: "My Site"
baseUrl: example.com
plugins:
- source: "@quartz-community/graph"
enabled: false # turn off a default plugin
- source: "@quartz-community/explorer"
options:
folderDefaultState: open # only this option changes
- source: github:me/my-plugin # a plugin the defaults don't have
enabled: true
```
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), or a list of those. Later entries in the list win.
- `configuration` and `layout` merge key by key, including nested objects (`theme.colors.lightMode.secondary` changes only that colour). Any other value replaces the default: strings, numbers and lists such as `ignorePatterns` or `byPageType.<type>.exclude`. Setting a key to `null` removes it, so the built-in default applies.
- A plugin entry changes the default entry for the same plugin, matched by name (`github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the same name replaces it). `enabled`, `order` and `source` replace the default values. `options` and `layout` merge like `configuration`, and `null` drops them so the plugin's own defaults apply. A plugin that is not in the base is added, and it needs `enabled: true` just as in a full config.
- Plugins run in `order` as before. Your file can change a default plugin's `order`. Where two plugins have the same order, the base config's list order decides, and added plugins come last.
- Your updates to `quartz.config.default.yaml` (for example after `npx quartz upgrade`) reach your site without copying them over.
> [!warning] Experimental
> `npx quartz plugin` commands that edit plugin entries (`enable`, `disable`, `config`, …) only see the entries in your own file so far. Edit an extending `quartz.config.yaml` by hand.
## General Configuration
This part of the configuration concerns anything that can affect the whole site. The following is a list breaking down all the things you can configure:
@@ -0,0 +1,259 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import path from "path"
import fs from "fs"
import YAML from "yaml"
import {
ConfigExtendsError,
deepMerge,
mergeQuartzConfigs,
pluginMatchKey,
resolveExtends,
} from "./config-extends"
import type { QuartzPluginsJson } from "./types"
const base = (): QuartzPluginsJson => ({
configuration: {
pageTitle: "Quartz",
ignorePatterns: ["private", ".obsidian"],
theme: { typography: { header: "Schibsted Grotesk", body: "Source Sans Pro" } },
links: { markdownLinkResolution: "shortest" },
},
plugins: [
{ source: "@quartz-community/explorer", enabled: true, options: { a: 1, nested: { x: 1 } } },
{
source: "github:quartz-community/graph",
enabled: true,
order: 50,
layout: { position: "right", priority: 10 },
},
{ source: "@quartz-community/comments", enabled: false },
],
layout: { byPageType: { folder: { exclude: ["graph"] } } },
})
describe("deepMerge", () => {
test("objects merge, other values replace, null deletes", () => {
assert.deepStrictEqual(
deepMerge({ a: { b: 1, c: 2 }, l: [1, 2], k: 1 }, { a: { c: 3 }, l: [9], k: null }),
{
a: { b: 1, c: 3 },
l: [9],
},
)
})
test("does not modify its inputs", () => {
const b = { a: { b: 1 } }
deepMerge(b, { a: { b: 2 } })
assert.deepStrictEqual(b, { a: { b: 1 } })
})
})
describe("pluginMatchKey", () => {
test("npm, GitHub, git URL and local sources of one plugin match", () => {
for (const source of [
"@quartz-community/explorer",
"@quartz-community/explorer@^2.0.0",
"github:quartz-community/explorer",
"github:someone/explorer#v2",
"git+https://github.com/quartz-community/explorer.git",
"https://github.com/quartz-community/explorer",
"./plugins/explorer/",
"explorer",
{ repo: "github:quartz-community/plugins", subdir: "x", name: "explorer" },
]) {
assert.strictEqual(pluginMatchKey(source as never), "explorer", JSON.stringify(source))
}
})
})
describe("mergeQuartzConfigs", () => {
test("configuration deep-merges; arrays replace; null resets a key", () => {
const merged = mergeQuartzConfigs(base(), {
configuration: {
pageTitle: "My garden",
ignorePatterns: ["drafts"],
theme: { typography: { header: "Inter" } },
links: null,
},
})
assert.strictEqual(merged.configuration.pageTitle, "My garden")
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["drafts"])
assert.deepStrictEqual(merged.configuration.theme, {
typography: { header: "Inter", body: "Source Sans Pro" },
})
assert.ok(!("links" in merged.configuration))
// the base plugins are kept when the overlay lists none
assert.strictEqual(merged.plugins.length, 3)
})
test("plugins match by name; enabled/order/source replace, options/layout merge", () => {
const merged = mergeQuartzConfigs(base(), {
plugins: [
{
source: "github:quartz-community/explorer",
options: { b: 2, nested: { y: 2 } },
} as never,
{ source: "@quartz-community/graph", enabled: false, order: 10, layout: { priority: 1 } },
{ source: "@quartz-community/comments", enabled: true },
],
})
const [explorer, graph, comments] = merged.plugins
assert.strictEqual(explorer.source, "github:quartz-community/explorer")
assert.strictEqual(explorer.enabled, true)
assert.deepStrictEqual(explorer.options, { a: 1, b: 2, nested: { x: 1, y: 2 } })
assert.strictEqual(graph.enabled, false)
assert.strictEqual(graph.order, 10)
assert.deepStrictEqual(graph.layout, { position: "right", priority: 1 })
assert.strictEqual(comments.enabled, true)
assert.strictEqual(merged.plugins.length, 3)
})
test("new plugins are appended as written (no enabled → disabled, as in a full config)", () => {
const merged = mergeQuartzConfigs(base(), {
plugins: [
{ source: "github:me/my-plugin", enabled: true, order: 70 },
{ source: "github:me/other" },
],
})
assert.strictEqual(merged.plugins.length, 5)
assert.deepStrictEqual(merged.plugins[3], {
source: "github:me/my-plugin",
enabled: true,
order: 70,
})
assert.deepStrictEqual(merged.plugins[4], { source: "github:me/other" })
})
test("null removes a plugin's options, layout or order (back to the plugin's defaults)", () => {
const merged = mergeQuartzConfigs(base(), {
plugins: [
{ source: "@quartz-community/graph", layout: null, order: null } as never,
{ source: "@quartz-community/explorer", options: { nested: null } } as never,
],
})
const [explorer, graph] = merged.plugins
assert.ok(!("layout" in graph) && !("order" in graph))
assert.deepStrictEqual(explorer.options, { a: 1 })
})
test("layout merges; arrays like byPageType.*.exclude replace", () => {
const merged = mergeQuartzConfigs(base(), {
layout: { byPageType: { folder: { exclude: [] }, tag: { exclude: ["graph"] } } },
})
assert.deepStrictEqual(merged.layout, {
byPageType: { folder: { exclude: [] }, tag: { exclude: ["graph"] } },
})
})
test("does not modify the base", () => {
const b = base()
const before = JSON.stringify(b)
mergeQuartzConfigs(b, {
configuration: { pageTitle: "x" },
plugins: [{ source: "@quartz-community/explorer", options: { a: 2 } } as never],
})
assert.strictEqual(JSON.stringify(b), before)
})
test("a plugin entry without source is an error", () => {
assert.throws(
() => mergeQuartzConfigs(base(), { plugins: [{ enabled: false } as never] }),
ConfigExtendsError,
)
})
})
describe("resolveExtends", () => {
const files: Record<string, string> = {}
const root = path.resolve("/site")
const readFile = (f: string) => {
const content = files[path.resolve(f)]
if (content === undefined) throw new Error("ENOENT")
return content
}
const put = (rel: string, data: unknown) => {
files[path.join(root, rel)] = YAML.stringify(data)
}
put("quartz.config.default.yaml", base())
test("a config without extends is returned as is", () => {
const data = { configuration: { pageTitle: "x" }, plugins: [] }
assert.strictEqual(resolveExtends(data, path.join(root, "quartz.config.yaml")), data as never)
})
test("extends: default merges onto quartz.config.default.yaml", () => {
const merged = resolveExtends(
{
extends: "default",
configuration: { pageTitle: "Mine" },
plugins: [{ source: "@quartz-community/graph", enabled: false }],
},
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
)
assert.strictEqual(merged.configuration.pageTitle, "Mine")
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["private", ".obsidian"])
assert.strictEqual(
merged.plugins.find((p) => pluginMatchKey(p.source) === "graph")!.enabled,
false,
)
assert.ok(!("extends" in merged))
})
test("relative paths, chains and lists (later wins)", () => {
put("configs/team.yaml", {
extends: "default",
configuration: { pageTitle: "Team", locale: "cs-CZ" },
})
put("configs/dark.yaml", { configuration: { pageTitle: "Dark" } })
const merged = resolveExtends(
{
extends: ["./configs/team.yaml", "configs/dark.yaml"],
configuration: { baseUrl: "x.org" },
},
path.join(root, "quartz.config.yaml"),
{ quartzRoot: root, readFile },
)
assert.strictEqual(merged.configuration.pageTitle, "Dark")
assert.strictEqual(merged.configuration.locale, "cs-CZ")
assert.strictEqual(merged.configuration.baseUrl, "x.org")
assert.strictEqual(merged.plugins.length, 3) // from default, through team.yaml
})
test("cycles and missing files are reported", () => {
put("a.yaml", { extends: "./b.yaml" })
put("b.yaml", { extends: "./a.yaml" })
assert.throws(
() =>
resolveExtends({ extends: "./a.yaml" }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
/cycle/,
)
assert.throws(
() =>
resolveExtends({ extends: "./nope.yaml" }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
/not found/,
)
assert.throws(
() =>
resolveExtends({ extends: 3 }, path.join(root, "quartz.config.yaml"), {
quartzRoot: root,
readFile,
}),
ConfigExtendsError,
)
})
test("extends: default reproduces the shipped default config exactly", () => {
const defaultFile = path.resolve("quartz.config.default.yaml")
const shipped = YAML.parse(fs.readFileSync(defaultFile, "utf-8"))
const merged = resolveExtends({ extends: "default" }, path.resolve("quartz.config.yaml"))
assert.deepStrictEqual(merged, shipped)
})
})
+219
View File
@@ -0,0 +1,219 @@
import fs from "fs"
import path from "path"
import YAML from "yaml"
import type {
PluginJsonEntry,
PluginLayoutDeclaration,
PluginSource,
QuartzPluginsJson,
} from "./types"
/**
* `extends:` in quartz.config.yaml (#2440): start from another config and apply only the
* differences on top.
*
* ```yaml
* extends: default # quartz.config.default.yaml next to quartz.config.yaml's Quartz
* configuration:
* pageTitle: My garden
* plugins:
* - source: "@quartz-community/explorer"
* options: { folderDefaultState: open }
* - source: "@quartz-community/graph"
* enabled: false
* ```
*
* Merge rules (`mergeQuartzConfigs`):
* - `configuration` and `layout`: objects merge key by key, recursively; any other value
* (strings, numbers, arrays such as `ignorePatterns` or `byPageType.*.exclude`) replaces the
* base value; `null` removes the key (back to the built-in default).
* - `plugins`: an entry matches the base entry of the same plugin (by plugin name, so
* `github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the
* same name replaces the original). Of a matched entry, `source`, `enabled` and `order`
* replace the base values, and `options` and `layout` merge like `configuration`. Entries
* that match nothing are appended, as in a full config (so they need `enabled: true`). The base list keeps its order, which only matters as the
* tie-break between plugins with the same `order`.
* - A config without `extends` is used exactly as written, as before.
*/
/** The name `extends: default` stands for. */
export const DEFAULT_EXTENDS = "default"
export const DEFAULT_CONFIG_FILE = "quartz.config.default.yaml"
export class ConfigExtendsError extends Error {}
type PlainObject = Record<string, unknown>
/** A plugin entry in a config that extends another: only `source` is required. */
export interface PluginOverlayEntry {
source: PluginSource
enabled?: boolean
/** Merged into the base entry's options; `null` drops them (the plugin's defaults apply). */
options?: Record<string, unknown> | null
order?: number | null
/** Merged into the base entry's layout; `null` drops it (the plugin's default placement). */
layout?: Partial<PluginLayoutDeclaration> | null
}
/** What a config with `extends` may contain: any part of a full config. */
export interface QuartzConfigOverlay {
$schema?: string
extends?: string | string[] | null
configuration?: Record<string, unknown>
plugins?: PluginOverlayEntry[]
layout?: Record<string, unknown>
}
function isPlainObject(value: unknown): value is PlainObject {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
/** Recursive merge: objects merge, everything else replaces, `null` deletes. */
export function deepMerge(base: unknown, overlay: unknown): unknown {
if (overlay === undefined) return base
if (!isPlainObject(base) || !isPlainObject(overlay)) return overlay
const result: PlainObject = { ...base }
for (const [key, value] of Object.entries(overlay)) {
if (value === null) {
delete result[key]
} else {
result[key] = deepMerge(base[key], value)
}
}
return result
}
/**
* The name a plugin entry is matched by: the last path segment of its package or repository
* (`@quartz-community/explorer`, `github:quartz-community/explorer#v2`, `./plugins/explorer` →
* `explorer`), or the `name` of an object source.
*/
export function pluginMatchKey(source: PluginSource): string {
if (typeof source === "object" && source !== null) {
if (source.name) return source.name
return pluginMatchKey(source.repo)
}
let s = String(source).trim()
s = s.replace(/^git\+/, "").replace(/^github:/, "")
s = s.split("#")[0]
s = s.replace(/\.git$/, "").replace(/\/+$/, "")
// an npm version/range: @scope/name@1.2.3, name@^1
s = s.replace(/(.)@[^/]*$/, "$1")
return s.slice(s.lastIndexOf("/") + 1)
}
function mergePluginEntry(base: PluginJsonEntry, overlay: PluginOverlayEntry) {
const merged: PlainObject = { ...base }
for (const [key, value] of Object.entries(overlay)) {
if (value === undefined) continue
if (key === "options" || key === "layout") {
const next = value === null ? undefined : deepMerge(merged[key], value)
if (next === undefined) delete merged[key]
else merged[key] = next
} else if (value === null) {
delete merged[key]
} else {
merged[key] = value
}
}
return merged as unknown as PluginJsonEntry
}
/** `overlay` on top of `base` (see the module comment). Neither input is modified. */
export function mergeQuartzConfigs(
base: QuartzPluginsJson,
overlay: QuartzConfigOverlay,
): QuartzPluginsJson {
const { extends: _extends, plugins: overlayPlugins, ...rest } = overlay
const merged = deepMerge(
{ ...base, plugins: undefined },
{ ...rest, plugins: undefined },
) as QuartzPluginsJson
const plugins = (base.plugins ?? []).map((entry) => ({ ...entry }))
for (const entry of overlayPlugins ?? []) {
if (!entry || entry.source === undefined) {
throw new ConfigExtendsError(`a plugin entry without "source" cannot be merged`)
}
const key = pluginMatchKey(entry.source)
const index = plugins.findIndex((p) => pluginMatchKey(p.source) === key)
if (index === -1) {
// a new plugin, read like an entry of a full config (no `enabled` → disabled, with a warning)
plugins.push({ ...entry } as PluginJsonEntry)
} else {
plugins[index] = mergePluginEntry(plugins[index], entry)
}
}
merged.plugins = plugins
merged.configuration = (merged.configuration ?? {}) as QuartzPluginsJson["configuration"]
return merged
}
export interface ResolveExtendsOptions {
/** Directory holding quartz.config.default.yaml (`extends: default`). Default: cwd. */
quartzRoot?: string
/** File reader, for tests. */
readFile?: (file: string) => string
}
function parseConfigFile(file: string, raw: string): PlainObject {
const data = file.endsWith(".json") ? JSON.parse(raw) : YAML.parse(raw)
if (!isPlainObject(data)) {
throw new ConfigExtendsError(`${file} does not contain a configuration object`)
}
return data
}
function extendsTargets(value: unknown, file: string): string[] {
const list = Array.isArray(value) ? value : [value]
for (const item of list) {
if (typeof item !== "string" || item.trim() === "") {
throw new ConfigExtendsError(
`${file}: "extends" must be "${DEFAULT_EXTENDS}", a path to another config file, or a list of them`,
)
}
}
return list as string[]
}
/**
* Apply `extends` of `data` (read from `file`): load each base (recursively; later entries of
* an `extends` list win), then merge `data` on top. Returns `data` itself when it has no
* `extends`, so configs without it behave exactly as before.
*/
export function resolveExtends(
data: PlainObject,
file: string,
options: ResolveExtendsOptions = {},
seen: string[] = [],
): QuartzPluginsJson {
if (data.extends === undefined || data.extends === null) {
const { extends: _drop, ...rest } = data
return (data.extends === null ? rest : data) as unknown as QuartzPluginsJson
}
const readFile = options.readFile ?? ((f: string) => fs.readFileSync(f, "utf-8"))
const quartzRoot = options.quartzRoot ?? process.cwd()
const chain = [...seen, path.resolve(file)]
let base: QuartzPluginsJson | undefined
for (const target of extendsTargets(data.extends, file)) {
const targetFile =
target === DEFAULT_EXTENDS
? path.join(quartzRoot, DEFAULT_CONFIG_FILE)
: path.resolve(path.dirname(file), target)
if (chain.includes(path.resolve(targetFile))) {
throw new ConfigExtendsError(
`"extends" cycle: ${[...chain, targetFile].map((f) => path.basename(f)).join(" → ")}`,
)
}
let raw: string
try {
raw = readFile(targetFile)
} catch {
throw new ConfigExtendsError(`${file}: "extends: ${target}" — ${targetFile} not found`)
}
const resolved = resolveExtends(parseConfigFile(targetFile, raw), targetFile, options, chain)
base = base ? mergeQuartzConfigs(base, resolved as QuartzConfigOverlay) : resolved
}
return mergeQuartzConfigs(base!, data as QuartzConfigOverlay)
}
+7 -4
View File
@@ -61,6 +61,7 @@ import {
import { collectPluginConfigWarnings, printPluginConfigWarnings } from "./option-validation"
import { componentRegistry, RegisteredComponent } from "../../components/registry"
import { frameRegistry } from "../../components/frames/registry"
import { resolveExtends } from "./config-extends"
import { getCondition, getAllConditionNames } from "./conditions"
import {
LAYOUT_SLOTS,
@@ -98,10 +99,12 @@ function readPluginsJson(): QuartzPluginsJson | null {
return null
}
const raw = fs.readFileSync(configPath, "utf-8")
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
return YAML.parse(raw) as QuartzPluginsJson
}
return JSON.parse(raw) as QuartzPluginsJson
const data =
configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? YAML.parse(raw) : JSON.parse(raw)
// `extends:` (#2440): merge onto the base config; a config without it is used as written
return data && typeof data === "object" && "extends" in data
? resolveExtends(data, configPath)
: (data as QuartzPluginsJson)
}
function extractPluginName(source: PluginSource): string {
+6 -4
View File
@@ -5,6 +5,7 @@ import YAML from "yaml"
import { installPlugins, parsePluginSource, regeneratePluginIndex } from "./gitLoader.js"
import type { PluginSource, QuartzPluginsJson } from "./types.js"
import { absorbingBuiltin } from "../builtins/index.js"
import { resolveExtends } from "./config-extends.js"
function resolveConfigPath(): string {
if (process.env.QUARTZ_CONFIG_PATH) return path.resolve(process.env.QUARTZ_CONFIG_PATH)
@@ -24,10 +25,11 @@ function readPluginsJson(): QuartzPluginsJson | null {
const configPath = resolveConfigPath()
if (!fs.existsSync(configPath)) return null
const raw = fs.readFileSync(configPath, "utf-8")
if (configPath.endsWith(".yaml") || configPath.endsWith(".yml")) {
return YAML.parse(raw)
}
return JSON.parse(raw)
const data =
configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? YAML.parse(raw) : JSON.parse(raw)
return data && typeof data === "object" && "extends" in data
? resolveExtends(data, configPath)
: data
}
async function getExternalPluginSources(): Promise<PluginSource[]> {
+40 -3
View File
@@ -3,16 +3,54 @@
"title": "Quartz Plugins Configuration Schema",
"description": "Schema for validating quartz.config.yaml (and legacy quartz.plugins.json) configuration files",
"type": "object",
"required": ["configuration", "plugins"],
"additionalProperties": false,
"if": {
"required": ["extends"]
},
"then": {
"properties": {
"plugins": {
"items": {
"required": ["source"]
}
}
}
},
"else": {
"required": ["configuration", "plugins"],
"properties": {
"configuration": {
"required": ["pageTitle", "enableSPA", "locale", "theme"]
},
"plugins": {
"items": {
"required": ["source", "enabled"]
}
}
}
},
"properties": {
"$schema": {
"type": "string",
"description": "JSON Schema reference"
},
"extends": {
"description": "Start from another config and apply this file on top: \"default\" (quartz.config.default.yaml) or a path relative to this file, or a list of them (later ones win). Objects merge key by key, other values replace, null removes a key; plugin entries match the base entry of the same plugin by name. Without extends, this file is the whole configuration.",
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
},
"minItems": 1
}
]
},
"configuration": {
"type": "object",
"required": ["pageTitle", "enableSPA", "locale", "theme"],
"additionalProperties": false,
"properties": {
"pageTitle": {
@@ -362,7 +400,6 @@
"description": "Array of plugin configurations",
"items": {
"type": "object",
"required": ["source", "enabled"],
"additionalProperties": false,
"properties": {
"source": {