Compare commits

..
Author SHA1 Message Date
saberzero1 60c8318b34 chore: changeset names the GitHubFlavoredMarkdown release that marks Obsidian anchors (2.1.0) 2026-11-09 03:36:20 +01:00
saberzero1 2ef60c6be5 fix: header transclusion matches a heading's Obsidian-anchor alias 2026-11-08 19:28:04 +01:00
Emile Bangma 8a62b70b1d Merge pull request #2604 from jackyzha0/dev-mode/lockfile-note-properties-1.1.1
chore(deps): note-properties 1.1.1
2026-11-08 18:45:07 +01:00
saberzero1 22c18d1981 chore(deps): note-properties 1.1.1 (refuses JavaScript frontmatter) 2026-11-08 18:37:34 +01:00
Emile Bangma e5332d4491 Merge pull request #2602 from jackyzha0/dev-mode/lockfile-ofm-2.1
chore: lockfile for obsidian-flavored-markdown 2.1.0
2026-11-08 18:18:45 +01:00
Emile Bangma 9f9547eb2d Merge pull request #2603 from jackyzha0/dev-mode/no-js-frontmatter
fix: refuse JavaScript frontmatter instead of executing it
2026-11-08 18:18:27 +01:00
saberzero1 b2da325a32 fix: refuse JavaScript frontmatter instead of executing it; report invalid frontmatter as a content problem 2026-11-08 17:49:08 +01:00
saberzero1 986aa227a8 chore: lockfile for obsidian-flavored-markdown 2.1.0 (highlights keep their formatting; coloured highlights) 2026-11-08 16:47:16 +01:00
Emile Bangma ec1d0b4c06 Merge pull request #2601 from jackyzha0/dev-mode/async-generate
feat: page types may generate virtual pages asynchronously
2026-11-08 16:39:27 +01:00
saberzero1 eab5c532c7 feat: page types may generate virtual pages asynchronously (#2575) 2026-11-08 16:11:50 +01:00
Emile Bangma 6b7bc28912 Merge pull request #2597 from jackyzha0/dev-mode/improvements
Quartz 5.1: built-in processing, plugin capabilities, permalinks, release workflow and fixes
2026-11-08 15:48:42 +01:00
16 changed files with 331 additions and 88 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
A page type's `generate` can be async: it may return a promise of its virtual pages, which Quartz awaits in full and incremental builds. Page types that create pages from other files (like `.mdx`) can now run content through the site's transformers or bundle with esbuild; previously a promise crashed the build with "virtualPages is not iterable" (#2575).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Embedding a section by the anchor Obsidian writes for its heading works when that anchor differs from the heading's id: `![[note#Colon unspaced]]` now embeds `## Colon:unspaced`. It needs GitHubFlavoredMarkdown 2.1.0 or later, which marks those anchors on the heading.
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Security: frontmatter can no longer run code during a build. A note starting with `---js` or `---javascript` had its frontmatter evaluated as JavaScript (gray-matter's default engine), so building content you didn't write, such as a pull request preview, could run arbitrary code. Quartz now refuses JavaScript frontmatter with an error naming the file. Invalid frontmatter (for example broken YAML) is now reported as a problem in that file instead of as a Quartz bug.
+1 -1
View File
@@ -391,7 +391,7 @@ export interface QuartzPageTypePluginInstance {
- `priority`: Controls matching order when multiple page types could match a slug. Higher priority page types are checked first. Default: `0`.
- `fileExtensions`: Array of file extensions this page type handles (e.g. `[".canvas"]`, `[".base"]`). Content files (`.md`) are handled by the default content page type.
- `match`: A function that determines whether a given slug/file should be rendered by this page type.
- `generate`: An optional function that produces virtual pages (pages not backed by files on disk, such as folder listings or tag indices).
- `generate`: An optional function that produces virtual pages (pages not backed by files on disk, such as folder listings or tag indices). It receives `{ content, cfg, ctx }` and returns the pages, or (Quartz 5.1+) a promise of them, so it can do async work such as running content through the site's transformers or bundling with esbuild. Page types generate one after another, in priority order. A plugin with an async `generate` should declare `"quartzVersion": ">=5.1.0"`, since older versions don't wait for it.
- `layout`: The layout configuration key (e.g. `"content"`, `"folder"`, `"tag"`). This determines which `byPageType` entry in `quartz.config.yaml` provides the layout overrides for this page type.
- `frame`: The [[layout#Page Frames|page frame]] to use for this page type. Controls the overall HTML structure (e.g. `"default"`, `"full-width"`, `"minimal"`, or a custom frame provided by your plugin). If not set, defaults to `"default"`. Can be overridden per-page-type via `layout.byPageType.<name>.template` in `quartz.config.yaml`.
- `body`: The Quartz component constructor that renders the page body content.
+13 -13
View File
@@ -37,7 +37,7 @@
"@quartz-community/graph": "^1.0.0",
"@quartz-community/hard-line-breaks": "^1.0.0",
"@quartz-community/latex": "^1.0.0",
"@quartz-community/note-properties": "^1.0.0",
"@quartz-community/note-properties": "^1.1.1",
"@quartz-community/obsidian-flavored-markdown": "^2.0.0",
"@quartz-community/og-image": "^1.0.0",
"@quartz-community/ox-hugo": "^1.0.0",
@@ -2892,9 +2892,9 @@
}
},
"node_modules/@quartz-community/note-properties": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.1.0.tgz",
"integrity": "sha512-TYpEDTO9Im3zZBqKpsQHFbSABj/FPswPSBBhle9FSiNUQpIOSZk6lj6Yw3LHz2mpa01w3Cvag5MGtugYe+HYEQ==",
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.1.1.tgz",
"integrity": "sha512-kURVT2PTQZTcRZxiT7o/gerI/8n0EhVogLaMznviJXYKSSvenE+8uKlPxJtZr1nbTJOn73UNBr5iNMhQIycQtg==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -2918,9 +2918,9 @@
}
},
"node_modules/@quartz-community/obsidian-flavored-markdown": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.0.0.tgz",
"integrity": "sha512-B8Q52yWmtvuNXpmRuNRHZSTgjAcdzT2N0eQiZhYfykUC6dQwMNs/mHIzxBK8T7A8xr3KjkGrtqzEM1s49dYjgw==",
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.1.0.tgz",
"integrity": "sha512-yOLBsYrJ5IVjxhl/ppZmXQAHianKkeIGMvDT7mwNOaalsah19p9luHrPYg0eEsn1o6IkHFP8h1LaY2WT+wIABw==",
"license": "MIT",
"dependencies": {
"@quartz-community/rehype-obsidian": "^1.2.0",
@@ -3296,9 +3296,9 @@
}
},
"node_modules/@quartz-community/types": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@quartz-community/types/-/types-1.1.0.tgz",
"integrity": "sha512-FedvwWskypTuEd/ZNqV7o/HjSE+F9rQGpBxy35Ia/hUitUA92tJsoxOtX+OAOjsB0kEq679e60zCXoyoIq8QRA==",
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@quartz-community/types/-/types-1.2.0.tgz",
"integrity": "sha512-82L+hallWn9LCMw9kFUWJhAGwlTd4rT2KxxL8B7IAWTEvj/20StWsuC01Mbfk5hLhd8jAHGgj1WHb0u/cdUXEA==",
"license": "MIT",
"dependencies": {
"unified": "^11.0.5",
@@ -7604,9 +7604,9 @@
"license": "ISC"
},
"node_modules/ws": {
"version": "8.22.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz",
"integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==",
"version": "8.22.2",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz",
"integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
+1 -1
View File
@@ -67,7 +67,7 @@
"@quartz-community/graph": "^1.0.0",
"@quartz-community/hard-line-breaks": "^1.0.0",
"@quartz-community/latex": "^1.0.0",
"@quartz-community/note-properties": "^1.0.0",
"@quartz-community/note-properties": "^1.1.1",
"@quartz-community/obsidian-flavored-markdown": "^2.0.0",
"@quartz-community/og-image": "^1.0.0",
"@quartz-community/ox-hugo": "^1.0.0",
+40
View File
@@ -183,6 +183,46 @@ describe("renderTranscludes", () => {
assert.ok(!secondText.includes("Circular transclusion"), "should not show circular warning")
})
test("a header transclusion matches a heading's Obsidian-anchor alias", () => {
const root: Root = {
type: "root",
children: [makeTranscludeBlockquote("target", "#colon-unspaced")],
}
const targetHtml: Root = {
type: "root",
children: [
{
type: "element",
tagName: "h2",
properties: { id: "colonunspaced" },
children: [
{
type: "element",
tagName: "span",
properties: { id: "colon-unspaced", className: ["heading-alias"] },
children: [],
},
{ type: "text", value: "Colon:unspaced" },
],
},
{
type: "element",
tagName: "p",
properties: {},
children: [{ type: "text", value: "Section text" }],
},
],
}
renderTranscludes(
root,
cfg,
"current" as FullSlug,
makeComponentData([makePageData("target", targetHtml)]) as QuartzComponentProps,
new Set<FullSlug>(["current" as FullSlug]),
)
assert.ok(JSON.stringify((root.children[0] as Element).children).includes("Section text"))
})
test("detects actual circular transclusion (A -> B -> A)", () => {
// Page A embeds B, and B's htmlAst contains a transclusion of A
const bTranscludesA = makeTranscludeBlockquote("pageA")
+20 -1
View File
@@ -31,6 +31,25 @@ interface RenderComponents {
}
const headerRegex = new RegExp(/h[1-6]/)
/**
* Whether a heading answers to `id`: its own id, or the id of a `span.heading-alias` inside it.
* GitHubFlavoredMarkdown adds that alias when the anchor Obsidian writes for a heading (`:`, `|`,
* `^`, `#` and `\` become spaces) slugs differently, e.g. `![[note#Colon unspaced]]` for
* `## Colon:unspaced`.
*/
function headingHasId(heading: Element, id: string): boolean {
if (heading.properties?.id === id) return true
const hasAlias = (el: Element): boolean =>
el.children.some(
(child) =>
child.type === "element" &&
((child.properties?.id === id &&
([] as unknown[]).concat(child.properties?.className ?? []).includes("heading-alias")) ||
hasAlias(child)),
)
return hasAlias(heading)
}
export function pageResources(
baseDir: FullSlug | RelativeURL,
staticResources: StaticResources,
@@ -231,7 +250,7 @@ export function renderTranscludes(
const depth = Number(htmlEl.tagName.substring(1))
if (startIdx === undefined || startDepth === undefined) {
if (htmlEl.properties?.id === blockRef) {
if (headingHasId(htmlEl, blockRef)) {
startIdx = i
startDepth = depth
}
+33 -1
View File
@@ -7,8 +7,14 @@ import { VFile } from "vfile"
import { Element, Root } from "hast"
import { visit } from "unist-util-visit"
import { BUILTINS, instantiateBuiltins, officialPluginName, planBuiltins, PlanInput } from "."
import { Frontmatter, normalizeFrontmatter, extractLinksFromValue } from "./frontmatter"
import {
Frontmatter,
normalizeFrontmatter,
extractLinksFromValue,
readFrontmatterData,
} from "./frontmatter"
import { Links } from "./links"
import { isContentError } from "../../util/pluginErrors"
import { Drafts, isDraft } from "./drafts"
import {
ContentIndex,
@@ -210,6 +216,32 @@ describe("frontmatter built-in", () => {
)
})
test("refuses JavaScript frontmatter instead of executing it", async () => {
const g = globalThis as { __quartzFrontmatterRan?: boolean }
delete g.__quartzFrontmatterRan
for (const lang of ["js", "javascript"]) {
const source = `---${lang}\n{ title: "x", ran: (globalThis.__quartzFrontmatterRan = true) }\n---\nbody\n`
assert.throws(() => readFrontmatterData(source), /JavaScript frontmatter/)
await assert.rejects(parse(source), /JavaScript frontmatter/)
// also when a site sets `language: js` (the type allows only yaml/toml, a YAML config does not)
assert.throws(
() =>
readFrontmatterData(`---\n{ ran: (globalThis.__quartzFrontmatterRan = true) }\n---\n`, {
language: lang as "yaml",
}),
/JavaScript frontmatter/,
)
}
assert.strictEqual(g.__quartzFrontmatterRan, undefined)
})
test("invalid frontmatter is reported as a content error", () => {
assert.throws(
() => readFrontmatterData("---\ntitle: [unclosed\n---\nbody\n"),
(err: Error) => isContentError(err) && err.message.startsWith("Invalid frontmatter: "),
)
})
test("a permalink is the page's address, not an alias (Obsidian Publish)", () => {
const data: Record<string, unknown> = { permalink: "short", aliases: ["old-name"] }
assert.deepStrictEqual(normalizeFrontmatter(data, "x").aliases, ["old-name"])
+29 -9
View File
@@ -5,6 +5,7 @@ import toml from "toml"
import { QuartzTransformerPlugin } from "../types"
import { QuartzPluginData } from "../vfile"
import { FrontmatterConfig } from "../../cfg"
import { ContentError } from "../../util/pluginErrors"
import {
FilePath,
FullSlug,
@@ -130,20 +131,39 @@ export function normalizeFrontmatter(
return { aliases: aliasSlugs }
}
/**
* gray-matter adds custom engines to its defaults, which include a `javascript`/`js` engine that
* `eval`s the frontmatter (`---js`). Content is data, not code: refuse those languages.
*/
const refuseJavaScript = (): never => {
throw new ContentError(
"JavaScript frontmatter (---js / ---javascript) is not supported: Quartz does not execute code from content. Use YAML or TOML frontmatter.",
)
}
/** Parse a file's frontmatter with the configured delimiters and language (`{}` when it has none). */
export function readFrontmatterData(
source: Buffer | string,
options: Pick<FrontmatterConfig, "delimiters" | "language"> = {},
): Record<string, unknown> {
const { data } = matter(Buffer.isBuffer(source) ? source : Buffer.from(source), {
delimiters: options.delimiters ?? frontmatterDefaults.delimiters,
language: options.language ?? frontmatterDefaults.language,
engines: {
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
toml: (s) => toml.parse(s) as object,
},
})
return data
try {
const { data } = matter(Buffer.isBuffer(source) ? source : Buffer.from(source), {
delimiters: options.delimiters ?? frontmatterDefaults.delimiters,
language: options.language ?? frontmatterDefaults.language,
engines: {
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
toml: (s) => toml.parse(s) as object,
javascript: refuseJavaScript,
js: refuseJavaScript,
},
})
return data
} catch (err) {
if (err instanceof ContentError) throw err
throw new ContentError(`Invalid frontmatter: ${err instanceof Error ? err.message : err}`, {
cause: err,
})
}
}
export const Frontmatter: QuartzTransformerPlugin<FrontmatterConfig> = (userOpts) => {
@@ -5,6 +5,7 @@ import os from "os"
import path from "path"
import {
collectComponents,
generateVirtualPages,
pageOutputPath,
removeStalePageOutput,
resolveLayout,
@@ -12,6 +13,7 @@ import {
import { QuartzPageTypePluginInstance } from "../types"
import { QuartzComponent } from "../../components/types"
import { FilePath, FullSlug } from "../../util/path"
import { BuildCtx } from "../../util/ctx"
const StubA: QuartzComponent = (() => null) as unknown as QuartzComponent
const StubB: QuartzComponent = (() => null) as unknown as QuartzComponent
@@ -211,3 +213,67 @@ describe("incremental page deletion", () => {
assert.strictEqual(await fs.promises.readFile(outputPath, "utf8"), "current")
})
})
describe("generateVirtualPages", () => {
const makeCtx = () => ({ cfg: { configuration: {} }, virtualPages: [] }) as unknown as BuildCtx
const page = (slug: string) => ({ slug: slug as FullSlug, title: slug, data: {} })
test("accepts sync and async generate, in page type order (#2575)", async () => {
const ctx = makeCtx()
const entries = await generateVirtualPages(
[
makePageType({ name: "sync", generate: () => [page("tags/a")] }),
makePageType({
name: "async",
generate: async () => {
await new Promise((resolve) => setTimeout(resolve, 5))
return [page("mdx/b")]
},
}),
makePageType({ name: "none" }),
],
[],
ctx,
{ head: StubHead },
{},
)
assert.deepStrictEqual(
entries.map((e) => e.vpSlug),
["tags/a", "mdx/b"],
)
assert.strictEqual(entries[1].vfile.data.slug, "mdx/b")
assert.strictEqual(ctx.virtualPages.length, 2)
})
test("keeps the 404 page out of ctx.virtualPages", async () => {
const ctx = makeCtx()
const entries = await generateVirtualPages(
[makePageType({ generate: async () => [page("404")] })],
[],
ctx,
{ head: StubHead },
{},
)
assert.strictEqual(entries.length, 1)
assert.strictEqual(ctx.virtualPages.length, 0)
})
test("a failing async generate rejects instead of being skipped", async () => {
await assert.rejects(
generateVirtualPages(
[
makePageType({
generate: async () => {
throw new Error("boom")
},
}),
],
[],
makeCtx(),
{ head: StubHead },
{},
),
/boom/,
)
})
})
+59 -56
View File
@@ -138,18 +138,57 @@ export async function removeStalePageOutput(
return outputPath
}
export type VirtualEntry = {
tree: ProcessedContent[0]
vfile: ProcessedContent[1]
layout: FullPageLayout
vpSlug: FullSlug
}
/**
* Run every page type's `generate` and turn the virtual pages it returns into processed
* content. `generate` may be async (Quartz 5.1+), e.g. to run the transformer chain or
* esbuild; page types run one after another in priority order, as before. Virtual pages
* (except the 404 page) are added to `ctx.virtualPages`.
*/
export async function generateVirtualPages(
pageTypes: QuartzPageTypePluginInstance[],
content: ProcessedContent[],
ctx: BuildCtx,
defaults: Partial<FullPageLayout>,
byPageType: Record<string, Partial<FullPageLayout>>,
): Promise<VirtualEntry[]> {
const cfg = ctx.cfg.configuration
const virtualEntries: VirtualEntry[] = []
for (const pt of pageTypes) {
if (!pt.generate) continue
const virtualPages = await pt.generate({ content, cfg, ctx })
const layout = resolveLayout(pt, defaults, byPageType)
for (const vp of virtualPages) {
const vpSlug = vp.slug as FullSlug
const vpRelativePath = (vpSlug + ".md") as FilePath
const [tree, vfile] = defaultProcessedContent({
slug: vpSlug,
relativePath: vpRelativePath,
frontmatter: { title: vp.title, tags: [] },
...vp.data,
})
if (vpSlug !== "404") {
ctx.virtualPages.push([tree, vfile])
}
virtualEntries.push({ tree, vfile, layout, vpSlug })
}
}
return virtualEntries
}
/**
* Render each virtual page's Body component to HTML and parse it to a hast tree,
* populating both the ProcessedContent tree and vfile.data.htmlAst so that
* transclusion (e.g. ![[file.canvas]]) can inline the virtual page's content.
*/
function populateVirtualPageHtmlAst(
virtualEntries: Array<{
tree: ProcessedContent[0]
vfile: ProcessedContent[1]
layout: FullPageLayout
vpSlug: FullSlug
}>,
virtualEntries: VirtualEntry[],
ctx: BuildCtx,
allFiles: ProcessedContent[1]["data"][],
resources: StaticResources,
@@ -203,31 +242,13 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
// Phase 1: Generate all virtual pages first so their data is available in allFiles
// for transclude resolution in renderPage (e.g. ![[file.canvas]], ![[file.base]])
const virtualEntries: Array<{
tree: ProcessedContent[0]
vfile: ProcessedContent[1]
layout: FullPageLayout
vpSlug: FullSlug
}> = []
for (const pt of pageTypes) {
if (!pt.generate) continue
const virtualPages = pt.generate({ content, cfg, ctx })
const layout = resolveLayout(pt, defaults, byPageType)
for (const vp of virtualPages) {
const vpSlug = vp.slug as FullSlug
const vpRelativePath = (vpSlug + ".md") as FilePath
const [tree, vfile] = defaultProcessedContent({
slug: vpSlug,
relativePath: vpRelativePath,
frontmatter: { title: vp.title, tags: [] },
...vp.data,
})
if (vpSlug !== "404") {
ctx.virtualPages.push([tree, vfile])
}
virtualEntries.push({ tree, vfile, layout, vpSlug })
}
}
const virtualEntries = await generateVirtualPages(
pageTypes,
content,
ctx,
defaults,
byPageType,
)
// Merge virtual page data into allFiles before populating htmlAst so that
// Body components rendered during populateVirtualPageHtmlAst can resolve
@@ -305,31 +326,13 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
}
// Phase 1: Generate all virtual pages first so their data is available in allFiles
const virtualEntries: Array<{
tree: ProcessedContent[0]
vfile: ProcessedContent[1]
layout: FullPageLayout
vpSlug: FullSlug
}> = []
for (const pt of pageTypes) {
if (!pt.generate) continue
const virtualPages = pt.generate({ content, cfg, ctx })
const layout = resolveLayout(pt, defaults, byPageType)
for (const vp of virtualPages) {
const vpSlug = vp.slug as FullSlug
const vpRelativePath = (vpSlug + ".md") as FilePath
const [tree, vfile] = defaultProcessedContent({
slug: vpSlug,
relativePath: vpRelativePath,
frontmatter: { title: vp.title, tags: [] },
...vp.data,
})
if (vpSlug !== "404") {
ctx.virtualPages.push([tree, vfile])
}
virtualEntries.push({ tree, vfile, layout, vpSlug })
}
}
const virtualEntries = await generateVirtualPages(
pageTypes,
content,
ctx,
defaults,
byPageType,
)
const allFilesWithVirtual = [...allFiles, ...virtualEntries.map((ve) => ve.vfile.data)]
+2 -2
View File
@@ -125,7 +125,7 @@ export type PageGenerator = (args: {
cfg: GlobalConfiguration
ctx: BuildCtx
[key: string]: unknown
}) => VirtualPage[]
}) => VirtualPage[] | Promise<VirtualPage[]>
/** A function that mutates a HAST tree at render time, when allFiles is available. */
export type TreeTransform = (
@@ -163,7 +163,7 @@ export interface PageTypePluginEntry {
priority?: number
fileExtensions?: string[]
match: (...args: never[]) => boolean
generate?: (...args: never[]) => VirtualPage[]
generate?: (...args: never[]) => VirtualPage[] | Promise<VirtualPage[]>
layout: string
/** Optional page frame name (e.g. "default", "full-width", "minimal"). Defaults to "default". */
frame?: string
+20 -1
View File
@@ -3,7 +3,13 @@ import assert from "node:assert"
import { unified, type Plugin } from "unified"
import remarkParse from "remark-parse"
import { VFile } from "vfile"
import { attributePluggables, pluginErrorInfo, PluginError } from "./pluginErrors"
import {
attributePluggables,
pluginErrorInfo,
PluginError,
ContentError,
isContentError,
} from "./pluginErrors"
import {
recordDiagnostic,
resetDiagnostics,
@@ -133,6 +139,19 @@ describe("describePluginError", () => {
})
})
describe("content errors", () => {
test("are recognised through a plugin attribution", () => {
const origin = { builtin: true, displayName: "frontmatter", source: "frontmatter" }
const wrapped = new PluginError(new ContentError("Invalid frontmatter: bad"), {
origin,
stage: "markdown",
} as never)
assert.strictEqual(isContentError(wrapped), true)
assert.strictEqual(isContentError(new PluginError(new Error("x"), { origin } as never)), false)
assert.strictEqual(isContentError(undefined), false)
})
})
describe("unresolved links report", () => {
beforeEach(() => resetDiagnostics())
+22
View File
@@ -38,6 +38,28 @@ export class PluginError extends Error {
}
}
/**
* An error in a file's content (e.g. invalid frontmatter), not in Quartz or a plugin: `trace()` tells
* the user to fix the file instead of reporting a bug. `quartzContent` survives module copies.
*/
export class ContentError extends Error {
readonly quartzContent = true
constructor(message: string, options?: { cause?: unknown }) {
super(message, options)
this.name = "ContentError"
}
}
/** Whether `err` or one of its causes (e.g. inside a {@link PluginError}) is a {@link ContentError}. */
export function isContentError(err: unknown): boolean {
let e = err
for (let depth = 0; depth < 10 && e && typeof e === "object"; depth++) {
if ((e as { quartzContent?: unknown }).quartzContent === true) return true
e = (e as { cause?: unknown }).cause
}
return false
}
export function pluginErrorInfo(err: unknown): PluginErrorInfo | undefined {
const info = (err as { quartzPlugin?: PluginErrorInfo } | null)?.quartzPlugin
return info && typeof info === "object" && info.origin ? info : undefined
+10 -3
View File
@@ -1,7 +1,7 @@
import { styleText } from "util"
import process from "process"
import { isMainThread } from "workerpool"
import { pluginErrorInfo, PluginErrorInfo } from "./pluginErrors"
import { isContentError, pluginErrorInfo, PluginErrorInfo } from "./pluginErrors"
import { knownProblemsFor } from "./diagnostics"
const rootFile = /.*at file:/
@@ -96,13 +96,20 @@ export function trace(msg: string, err: Error) {
styleText("red", ` ${msg}`) +
(err.message.length > 0 ? `: ${err.message}` : ""),
)
if (info) {
const contentError = isContentError(err)
if (contentError) {
// the file needs fixing, not Quartz or a plugin: no plugin details or stack trace
lines.push("")
lines.push(
styleText("gray", " This is a problem in the file's content: fix it and build again."),
)
} else if (info) {
lines.push("")
lines.push(...describePluginError(info))
}
lines.push("")
let reachedEndOfLegibleTrace = false
let reachedEndOfLegibleTrace = contentError
for (const line of stack.split("\n").slice(1)) {
if (reachedEndOfLegibleTrace) {
break