Compare commits

...
Author SHA1 Message Date
Emile Bangma 2e69d52f76 Merge pull request #2728 from jackyzha0/changeset-release/v5
chore: release Quartz
2026-11-30 12:03:53 +01:00
github-actions[bot] 8c81436188 chore: release Quartz 2026-11-30 10:40:15 +00:00
Emile Bangma fe47fb1239 Merge pull request #2733 from jackyzha0/dev-mode/lockfile-next-to-config
feat(plugins): quartz.lock.json next to the config; --config on plugin commands
2026-11-30 11:39:54 +01:00
Emile Bangma fb4dbab487 Merge pull request #2732 from jackyzha0/dev-mode/npm-plugin-pins
feat(plugins): pin npm plugins outside package.json in quartz.lock.json
2026-11-30 11:37:45 +01:00
Emile Bangma 9ca6f4ee69 Merge pull request #2731 from jackyzha0/dev-mode/extends-stable
feat(config): extends is stable for default and local paths; reserve $ keys
2026-11-30 11:37:30 +01:00
saberzero1 cc8d104cc7 feat(plugins): quartz.lock.json next to the config; --config on plugin commands
The lockfile is read and written next to the config file in use, and
every plugin command takes --config/-C like build. A config elsewhere
keeps using an existing lockfile in Quartz's folder until its own
folder has one. Plugin commands also edit the config chosen with
QUARTZ_CONFIG_PATH instead of ./quartz.config.yaml.
2026-11-30 02:51:45 +01:00
saberzero1 b86276f52b feat(plugins): pin npm plugins outside package.json in quartz.lock.json
npm plugins that Quartz's package.json does not list are pinned in
quartz.lock.json (version, integrity) and installed into
.quartz/plugins/@scope/name, like Git plugins, instead of being written
into Quartz's package.json. npm plugins in package.json are versioned
there as before; when a plugin is in both, package.json wins.
2026-11-30 02:47:09 +01:00
saberzero1 9ebfc67c1b feat(config): extends is stable for default and local paths; reserve $ keys
Keys starting with $ are an error in every file of an extends chain (the
top-level $schema aside), so merge operators can be added later without
changing existing configs. https:// URLs stay experimental.

A ConfigExtendsError from a command now prints just its message instead of
the CLI usage text.
2026-11-30 01:49:44 +01:00
Emile Bangma ffc6bfd3ed Merge pull request #2726 from jackyzha0/dev-mode/og-image-1-2-0
chore(deps): og-image 1.2.0 (social images from the content folder)
2026-11-28 17:23:38 +01:00
saberzero1 ea4b07518c chore(deps): og-image 1.2.0 (social images from the content folder) 2026-11-28 13:12:04 +01:00
Emile Bangma afebc38b3b Merge pull request #2723 from jackyzha0/dev-mode/remove-legacy-tag-job
ci: remove the legacy publish-tag job, which made every release tag unverified
2026-11-28 00:58:29 +01:00
saberzero1 c7131c909f ci: remove the legacy publish-tag job, which made every release tag unverified 2026-11-28 00:52:51 +01:00
Emile Bangma 5a740b3ae0 Merge pull request #2717 from jackyzha0/changeset-release/v5
chore: release Quartz
2026-11-28 00:47:01 +01:00
github-actions[bot] 6f67702b3e chore: release Quartz 2026-11-27 22:58:40 +00:00
Emile Bangma 685a5c3461 Merge pull request #2721 from jackyzha0/dev-mode/release-notes-5-3-1
docs: changes you may notice in 5.3.1
2026-11-27 23:58:13 +01:00
Emile Bangma 114923ac6a Merge pull request #2720 from jackyzha0/dev-mode/locale-fallback
fix(i18n): a locale without a translation falls back instead of crashing the build
2026-11-27 23:58:07 +01:00
Emile Bangma a7d7389f57 Merge pull request #2719 from jackyzha0/dev-mode/update-disabled-plugin-failure
fix(cli): a disabled plugin that can't be updated warns instead of failing the update
2026-11-27 23:58:01 +01:00
Emile Bangma 699c668cba Merge pull request #2722 from jackyzha0/dev-mode/deps-5-3-1-fixes
chore(deps): plugin fixes for 5.3.1
2026-11-27 23:57:54 +01:00
saberzero1 9889d3fb04 chore(deps): folder-page 1.1.5, canvas-page 1.1.7, search 1.1.5, graph 1.0.10, stacked-pages 1.0.5, remark-obsidian 2.2.6 2026-11-27 23:47:25 +01:00
saberzero1 c68a4945ab docs: changes you may notice in 5.3.1 2026-11-27 23:23:44 +01:00
saberzero1 ce108c8c95 fix(i18n): a locale without a translation falls back instead of crashing the build 2026-11-27 23:22:20 +01:00
saberzero1 57b3b5d0af fix(cli): a disabled plugin that can't be updated warns instead of failing the update 2026-11-27 23:20:59 +01:00
Emile Bangma c317915450 Merge pull request #2718 from jackyzha0/dev-mode/utils-1.3.4
chore(deps): utils 1.3.4 (tag links under a base path)
2026-11-27 23:12:02 +01:00
saberzero1 1e1a3561b3 chore(deps): utils 1.3.4 (tag links under a base path) 2026-11-27 23:10:00 +01:00
Emile Bangma ce1b5d4d89 Merge pull request #2716 from jackyzha0/dev-mode/deps-audit-fixes
chore(deps): plugin fixes from the test audit
2026-11-27 21:30:42 +01:00
saberzero1 e02d690957 chore(deps): plugins with the audit fixes (utils 1.3.3, bases-page 1.5.6, encrypted-pages 1.3.1, explorer 1.2.5, …) 2026-11-27 21:12:20 +01:00
saberzero1 5d94a93a03 Merge branch 'v5' of https://github.com/jackyzha0/quartz into dev-mode/deps-audit-fixes 2026-11-27 21:09:48 +01:00
Emile Bangma 9a4beb1747 Merge pull request #2715 from jackyzha0/dev-mode/audit-full
test + fix: audit of whole-repo coverage and mutation survivors, and the bugs it found
2026-11-27 20:37:58 +01:00
saberzero1 c03c643a7c test: compare emitted paths with / and give the parser POSIX paths, so the new tests pass on Windows 2026-11-27 16:32:34 +01:00
saberzero1 74d06afca0 docs(dispatcher): a plugin throwing in virtualPageHtmlPlugins fails the build 2026-11-27 16:10:11 +01:00
saberzero1 f285e12ff9 fix(plugins): compare dependency order only within a pipeline stage 2026-11-27 16:10:11 +01:00
saberzero1 6729a1e7bb fix(spa): keep the query string when rebasing relative URLs 2026-11-27 16:10:11 +01:00
saberzero1 37a61cfc08 chore(deps): explorer 1.2.4, search 1.1.3, canvas-page 1.1.5, latex 1.1.3, ox-hugo 1.0.4 2026-11-27 16:04:04 +01:00
saberzero1 45ed91c90c test(dispatcher, emitters, parse): page emission, resource bundling and parsing
PageTypeDispatcher emit/partialEmit (page type priority, virtual and 404
pages, processed file-backed pages, link marks, stale output, what bodies
see), ComponentResources (hashed names, script order, component CSS,
inline resource extraction, serve mode, analytics scripts) and the
single-threaded Markdown pipeline.
2026-11-27 14:44:06 +01:00
saberzero1 9909b508e7 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.
2026-11-27 14:44:06 +01:00
saberzero1 bd3ac11469 test(links): link options, resources, removed-page marks and SPA URL rebasing
Covers the Links built-in's defaults and options (pretty links, new tab,
external icon, lazy loading), src/data resolution of media, object and
source elements, folder/home page existence, permalink anchors,
frontmatter fragment links, re-marking when a filter changes, and
normalizeRelativeURLs. Adds a todo test: normalizeRelativeURLs drops the
query string of relative URLs.
2026-11-27 14:44:06 +01:00
Emile Bangma 92fa358ef1 Merge pull request #2682 from jackyzha0/changeset-release/v5
chore: release Quartz
2026-11-27 13:23:03 +01:00
github-actions[bot] ae8049d0fa chore: release Quartz 2026-11-27 12:21:03 +00:00
Emile Bangma e42cdf469d Merge pull request #2714 from jackyzha0/dev-mode/audit-tests-core
test: cover 5.3 changes the mutation audit found untested; fix double-decoded link targets under stripDiacritics
2026-11-27 13:20:39 +01:00
Emile Bangma 747d10ce3a Merge pull request #2713 from jackyzha0/dev-mode/prerelease-link-tests
test: broken-link marking for published folder notes and after page generation
2026-11-27 13:19:43 +01:00
saberzero1 2635c6080a fix(links): don't decode link targets twice under slugs.stripDiacritics
slugOptionsOnLinkPath decoded and stripped the target's path before transformLink, which
decodes it again and (utils 1.3) strips diacritics itself. It changed nothing for any link
except one with a percent-encoded % (`%2520`), which it turned into a space, so the link
pointed at the wrong slug and was marked broken. Removed; the stripDiacritics link tests
still pass without it.
2026-11-27 04:45:48 +01:00
saberzero1 149c82f1da 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
2026-11-27 04:44:46 +01:00
saberzero1 f47668e024 test: broken-link marking for published folder notes and after page generation
markUnpublishedLinks never marks a link to a published page (a folder note that no page
type generates, an alias) once the page types ran, and a draft folder note leaves the link
to the generated folder page or marks it missing. markLinksToUnpublishedPages (exported for
the test) builds the generated set from the virtual pages, marks drafts with their filter
and folders no page type generated as missing, reports changed pages once, and marks
nothing when the Links transformer doesn't mark broken links.
2026-11-27 04:24:38 +01:00
Emile Bangma 29be20f41c Merge pull request #2712 from jackyzha0/dev-mode/block-id-caret
fix: block anchors are #^id, separate from headings (as in Obsidian)
2026-11-27 00:44:05 +01:00
saberzero1 f7b41e7bbf chore(deps): block anchors #^id (utils 1.3.2, rehype-obsidian 1.6.0 via OFM 2.5.3, GFM 2.2.2, canvas-page 1.1.4, note-properties 1.2.3, bases-page 1.5.5) 2026-11-27 00:42:31 +01:00
saberzero1 7c24cc66e1 Merge remote-tracking branch 'origin/v5' into dev-mode/block-id-caret 2026-11-27 00:41:24 +01:00
saberzero1 3df0062b6f fix(transclude): find blocks by their lowercased name; docs for #^id block anchors 2026-11-27 00:22:34 +01:00
Emile Bangma beca3bc26d Merge pull request #2711 from jackyzha0/dev-mode/investigate-c
fix: broken marks for missing folder/tag pages, watch-mode re-emit, per-component CSS isolation, SPA scroll, stripDiacritics redirects, popover selector
2026-11-27 00:21:42 +01:00
saberzero1 0e16919455 docs(slugs): old addresses redirect when stripDiacritics is on; fold the redirect changeset into the option's 2026-11-27 00:20:07 +01:00
saberzero1 81b358224b fix(popover): escape the target id in the popover's scroll-to selector (ids like ^block-id are not CSS identifiers) 2026-11-26 23:30:54 +01:00
saberzero1 0346dc6149 feat(slugs): redirect from addresses that slugs.stripDiacritics changed 2026-11-26 23:25:25 +01:00
saberzero1 e0f1e03913 fix(spa): keep a scroll position still pending when Back/Forward leaves the entry 2026-11-26 23:23:03 +01:00
saberzero1 c79adab53b fix(css): parse each component's CSS on its own before joining the component stylesheet 2026-11-26 23:20:33 +01:00
saberzero1 af36801547 fix(links): mark links to folder/tag pages that aren't generated; re-emit pages whose link marks change in watch mode 2026-11-26 23:18:49 +01:00
Emile Bangma b1fc7acd8e Merge pull request #2707 from jackyzha0/docs/5-3-release-notes
docs: 5.2 and 5.3 release notes, upgrade steps and new plugin options
2026-11-26 23:13:24 +01:00
saberzero1 011c101cd3 docs: final stripDiacritics rule and stacking extends in what's new; canvas text-node embeds and tags; changeset no longer promises redirects from old addresses 2026-11-26 23:12:03 +01:00
saberzero1 690f7a0325 Merge remote-tracking branch 'origin/v5' into docs/5-3-release-notes 2026-11-26 23:11:21 +01:00
Emile Bangma abfda7b85e Merge pull request #2710 from jackyzha0/deps/5-3-audit-plugins
chore(deps): plugin releases from the pre-5.3 audit
2026-11-26 23:11:01 +01:00
saberzero1 f646ffe97d chore(deps): plugin releases from the pre-5.3 audit 2026-11-26 23:09:32 +01:00
Emile Bangma 61b06fa295 Merge pull request #2709 from jackyzha0/dev-mode/5-3-core-fixes
fix: pre-5.3 audit fixes (broken-link marks, stand-in dates, extends, CLI, order, conditions, head, frontmatter links, release workflow)
2026-11-26 22:47:29 +01:00
saberzero1 57cd6631d3 docs: 5.2 and 5.3 release notes and upgrade steps; explorer sort/rootFolder, GFM singleTilde/replacements, OFM math/markdownEmbeds, canvas options, Pele default 2026-11-26 20:55:56 +01:00
103 changed files with 5036 additions and 574 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
Links: `disableBrokenWikilinks` is on by default. Internal links to pages that don't exist get the `broken` class, as Obsidian marks unresolved links (`is-unresolved`), so Quartz's and Obsidian themes' unresolved-link styles apply. Tag and folder pages, which are generated later, count as existing. Set `links.disableBrokenWikilinks: false` for the old behaviour.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Links: links to files Quartz emits, such as `[feed](/index.xml)`, `/sitemap.xml`, `/static/icon.png` or `/404.html`, are no longer marked `broken`. A link is only marked when its target is known to be missing: a page that doesn't exist, or a vault file (image, audio, video, PDF, canvas, base) the content doesn't have. Other files may come from an emitter, so they are left unmarked.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Links to pages removed by a filter (drafts, ExplicitPublish) are now marked `broken` (with `data-filtered="<filter>"`), like links to pages that don't exist — they 404 on the site.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
Quartz now requires Node.js 22.22 or later (was 22), for chokidar 6, which watches content in `--serve` mode. chokidar 6 confirms each change against the file system before rebuilding and fixes missed and duplicate change events.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
`extends` (experimental): `npx quartz plugin list`, `status`, `doctor`, `install`, `prune` and `npx quartz info` read the merged configuration, as the build does. Before, they saw only the entries in your own file, so `list` showed a handful of plugins and `doctor` warned that overlay entries without `enabled` are disabled. `enable`, `disable` and `config` now work on plugins from a base by adding or changing your own entry for them (only that change is written; the merged configuration never is), `config --unset` resets an option a base sets with `null`, and `remove` refuses a plugin that comes from a base. `npx quartz build --serve` also rebuilds when a local base file changes.
-7
View File
@@ -1,7 +0,0 @@
---
"@jackyzha0/quartz": patch
---
`extends` (experimental): presets in a list now stack. With `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, everything `a.yaml` changed was lost, because `b.yaml` was merged on top with all of `default` again. Each file of the `extends` chain is now applied once, after the bases it extends, so the order is `default` → `a.yaml` → `b.yaml` → your file, and later entries win only where they change the same thing.
Also: a plugin source with a `subdir` and no `name` is matched by repository and folder, so an entry for one plugin of a monorepo no longer changes another; `extends: []` extends nothing; an empty base file is an empty config; `HTTPS://` URLs are accepted; and `plugins:` that isn't a list gets a clear error.
-5
View File
@@ -1,5 +0,0 @@
---
"@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.
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
`contentIndex.json` entries have `dateFromFrontmatter: true` when their `date` is the one set in the page's frontmatter for the configured date type (not from git or the file system), so client-side components can tell explicit dates apart, e.g. for folder dates in the explorer.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
`contentIndex.json` entries now include the page's `date` (the one `defaultDateType` selects) as an ISO 8601 string, so client-side components such as the explorer can sort by date. Pages without a date have no `date` field.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Layout conditions: `is-folder-index` is false on tag pages. The all-tags page (`tags/index`) matched it, so components meant for folder pages showed there; nothing under `tags/` counts as a folder index now.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Footnote references and back-links keep the `internal` class but no longer get `internal-link`: Obsidian doesn't treat them as note links, and Obsidian themes' link styles (underline, colour) overrode their footnote styles.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Markdown links in frontmatter with an angle-bracket destination, which Obsidian writes for paths with spaces (`[Exec Briefing](<./Exec Briefing.md>)`), resolve to the note instead of a missing `….md` page, so the note gets the backlink and graph edge.
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Markdown links in frontmatter are read as CommonMark reads them: angle-bracket destinations with parentheses (`[b](<Note (2024).md>)`), balanced parentheses in plain destinations (`[d](Note_(2024).md)`), titles in `"…"`, `'…'` or `(…)` (`[c](<My Note.md> "t")`), and backslash escapes. They pointed at `note-(2024` and `my-note.md-t`, so the linked note got no backlink or graph edge.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
@quartz-community/graph 1.0.5: the graph scales to large sites. On 3,000 notes and 33,000 links, the global graph opens in 0.5 s instead of 2.5 s, and it stops using the CPU once its layout settles. It also loads d3 and PixiJS as pinned, integrity-checked versions, with PixiJS's minified build (200 KB instead of 2.5 MB on every page).
-6
View File
@@ -1,6 +0,0 @@
---
"@jackyzha0/quartz": patch
---
- `@quartz-community/graph` 1.0.7: the local graph on folder index pages shows the folder's connections instead of a single node.
- `@quartz-community/utils` 1.2.1: `unescapeHTML` decodes each entity once, so a page description that mentions `&lt;br&gt;` keeps it in the page's meta tags instead of turning it into `<br>`.
-7
View File
@@ -1,7 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Pages get a canonical link (`<link rel="canonical">`, the page's URL as the sitemap lists it), and `og:url` uses the same URL: `folder/` instead of `folder/index`, and the site root for the home page. `og:site_name` is a `property` (it was a `name`, which Open Graph readers ignore). Notes are `og:type: article`, with `article:modified_time` and, when the frontmatter has a date, `article:published_time`. The home page and folder and tag pages stay `website`.
The `fonts.gstatic.com` preconnect is a CORS connection, which the font files can reuse, and the unused `cdnjs.cloudflare.com` preconnect is gone.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
Layout conditions: add `is-index` (only on the home page) and `is-folder-index` (only on folder index pages), and let `not-<condition>` negate any condition, built-in or registered (`not-has-tags`, `not-has-backlinks`, …).
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Frontmatter is read with js-yaml 5, using YAML 1.2's core schema (the values Quartz read before are unchanged). Frontmatter with only comments now has no properties, as in Obsidian, instead of being reported as invalid frontmatter.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
The page frames mark their regions for assistive technology: the centre column is a `<main>` (it was a `div.center`; the classes are unchanged) and the default frame's sidebars are `<aside>` elements. Screen readers can jump to the page's content, and the page looks the same.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Heading transclusions and their footnotes look through Obsidian's per-block wrappers (`div.el-h2 > h2`), which `@quartz-community/rehype-obsidian` now renders around each of a note's top-level blocks. `blockOf()` (in `components/transcludeScope.ts`) returns the block inside a wrapper, for other code that walks a page's top-level blocks.
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Obsidian's fold arrows in headings and list items (`.heading-collapse-indicator`, `.list-collapse-indicator`, rendered by rehype-obsidian for Obsidian themes) are hidden unless obsidian-flavored-markdown's `foldHeadings` / `foldLists` turn folding on.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
Transclusions use Obsidian's embed markup: a `div.markdown-embed-title` (the note's title, for a whole-note embed; it was an `h1`), then the content in `div.markdown-embed-content > div.markdown-preview-view.markdown-rendered`, then the link to the original. Obsidian themes' embed styles apply (embed titles, padding, maximum height). The title looks as before without a theme. Obsidian's icon link to the note (`a.markdown-embed-link`, Lucide's maximize-2) follows; Quartz hides it, and Obsidian themes, through @quartz-themes/core, show it in the embed's corner.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
@quartz-community/obsidian-flavored-markdown 2.4.0 (Obsidian's block wrappers, heading and list folding, missing-attachment embeds, Pele diagrams) and @quartz-community/og-image 1.1.2 (no build failure on emoji variants such as the footnote back-link `↩︎`).
-14
View File
@@ -1,14 +0,0 @@
---
"@jackyzha0/quartz": patch
---
@quartz-themes/core 3.2.0 (Obsidian's block wrappers styled natively, property inputs, fold arrows) and the plugin releases that carry Obsidian's markup:
- latex 1.1.0: maths in Obsidian's math elements;
- note-properties 1.2.0: Obsidian's properties markup;
- search 1.1.0: the quick switcher's classes, excerpts as written;
- explorer 1.1.2: Obsidian's folder rows;
- table-of-contents 1.0.4: the collapsed table of contents no longer clips its header;
- graph 1.0.4: colours follow Obsidian themes;
- syntax-highlighting 1.0.4: the copy button's stylesheet in the base layer;
- canvas-page 1.0.4: heading embeds look through the block wrappers.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
The `obsidian` template folds headings and lists (obsidian-flavored-markdown's `foldHeadings` and `foldLists`), as Obsidian does by default.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
A note whose name ends in "index" (`reindex.md`) is an `og:type: article` again. The home page and folder index pages were told apart by the slug ending in `index`, not by its last segment, so such notes were `website` and had no article dates.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Plugin order: `before:` / `after:` naming a plugin that is built into Quartz now (`crawl-links`, `remove-draft`, `content-index`) passed validation but was ignored. They now mean the built-in that replaced them (`links`, `drafts`, `contentIndex`), so `before: crawl-links` orders the plugin before link processing, and is checked against its `order` like `before: links`.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
`PageList` entries are `h2` headings under the page's `h1` (they were `h3`, which skipped a level for screen readers), at the `h3`'s size, as in `@quartz-community/folder-page` and `@quartz-community/tag-page`.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
Plugin entries can declare `before:` / `after:` (plugin names). They are checked against `order`: between plugins with the same order they decide, and a contradiction, a cycle or an unknown name stops the build with a clear error. `extends:` also accepts an `https://` URL, fetched with a timeout and cached in `.quartz-cache/extends/` for offline builds (`QUARTZ_EXTENDS_OFFLINE=1`).
-13
View File
@@ -1,13 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Plugin updates:
- `@quartz-community/explorer` 1.2.0: `sort` option (rules applied in sequence, e.g. folders first, then newest) and `rootFolder` option, so several explorers on one page work side by side; the `order` option is applied; scroll fixes (the bottom fade, the scroll position across SPA navigation with `layout.sidebars.left: scroll`, and opening a page no longer scrolls the page itself).
- `@quartz-community/obsidian-flavored-markdown` 2.5.0: notes, canvases and bases embedded with a Markdown link (`![](note.md#Section)`) are transcluded, as in Obsidian; `math` option (`false` leaves dollar signs as text). With `@quartz-community/rehype-obsidian` 1.5.1: same-page block links (`[[#^id]]`) reach their block, and only images on YouTube become YouTube embeds.
- `@quartz-community/github-flavored-markdown` 2.2.0: `singleTilde` option (`false` strikes only `~~text~~`, as Obsidian does) and `replacements` option (for example Quartz 4's arrows), empty by default.
- `@quartz-community/canvas-page` 1.1.0: the mouse wheel and trackpad pan the canvas, as in Obsidian (`wheelBehavior`); text nodes are rendered with the site's Markdown plugins, so Mermaid diagrams, callouts and math work in them (`textNodeMarkdown`).
- `@quartz-community/utils` 1.3.0: the `stripDiacritics` slug option reaches plugins too; links in embedded folder notes point at the right directory.
- `@quartz-community/created-modified-date` 1.0.4: git dates resolve when `content/` is a symlink to a vault in another git repository.
- `@quartz-community/ox-hugo` 1.0.2: the Markdown rewrites leave code alone and no longer match across unrelated text.
-12
View File
@@ -1,12 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Plugin updates for accessibility and page speed:
- Text in the table of contents, footer, folder and tag listings, search button and Bases group headings meets WCAG AA contrast in light and dark mode. Under an Obsidian theme from quartz-themes (`@quartz-themes/core` 3.2.1), the search button and Bases group headings keep the theme's faint text colour.
- Page listings in folder and tag pages use `<h2>` titles (at the previous size), so headings no longer skip a level.
- Valid ARIA and unique ids in the table of contents, explorer, backlinks, heading anchors and Bases views.
- The graph loads d3 and PixiJS only when it scrolls into view (or when the global graph opens), instead of on every page.
- KaTeX's stylesheet no longer blocks rendering on pages without math.
- `@quartz-community/remark-obsidian` 2.2.3: the `legacy` parser no longer uses memory that grows with the square of the note's length on notes with many tables, lists or other blocks.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Release tags are verified on GitHub: the release workflow creates each `vX.Y.Z` tag as a lightweight tag on the merged release commit (which GitHub signs) instead of letting the release create an unsigned annotated tag. It also starts the Docker build for the tag, so versioned images (`5.3.0`, `5.3`) are published for each release (none were built for 5.1.0–5.2.2).
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Component styles are one stylesheet (`component-<hash>.css`, in the `quartz-base` layer as before) instead of one per component. Pages load about 20 fewer render-blocking stylesheets (29 to 11 on the docs site), and the styles they compute are unchanged.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
With SPA navigation, Back and Forward return to where the reader was on each page. The router keeps each history entry's scroll position and restores it after swapping the page in. The browser restored the position while the previous page was still on screen, so it came out wrong: Back after a table-of-contents link stayed at the heading, and Back to a page landed at its top or bottom. Back and Forward between headings of the same page now only scroll, instead of reloading the page, and a reload keeps the position.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Build-time stand-in dates are no longer written as real dates. A page whose date no source gives (for example `defaultDateType: published` and no `published:`, or an invalid one) gets the build time from the date plugin; `contentIndex.json` now leaves its `date` out, and `article:published_time` / `article:modified_time` are only set for real dates (an invalid `published:` gave the build time). RSS and the sitemap keep the build time. created-modified-date 1.0.5 lists its stand-ins in `file.data.fallbackDates`; with older versions a `published` date only counts when the frontmatter sets it.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
`slugs.stripDiacritics` reaches plugins and the browser: bases-page 1.5.3, breadcrumbs 1.0.4, canvas-page 1.1.1, explorer 1.2.1, folder-page 1.1.2, note-properties 1.2.1 and obsidian-flavored-markdown 2.5.1 bundle `@quartz-community/utils` 1.3, so their links, tag pages from inline tags, canvas file nodes and base views use the stripped addresses. Quartz also passes the option to scripts in the browser, so the explorer places folders and pages with accents where the build put them.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
New opt-in `configuration.slugs.stripDiacritics`: strips accents and other diacritics from generated slugs (`české/čeština.md` → `/ceske/cestina`). Links, embeds, aliases, permalinks, tags and folder pages resolve to the stripped addresses, and the old addresses redirect to them; heading anchors keep their diacritics. Only Latin letters change: they lose their accents and fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`); other scripts (Korean, Japanese, Chinese, Greek, Cyrillic, Indic, Hebrew, Arabic, …) are left as written. Plugins that make slugs follow the option when they bundle `@quartz-community/utils` 1.3 or later, as the plugins updated in this release do (1.3.1 for the ASCII folding).
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
The templates' colours meet WCAG AA contrast (4.5:1) on their backgrounds. Light `gray` goes from #b8b8b8 to #727272 (was 1.9:1), dark `gray` from #646464 to #7f7f7f (was 3.1:1), and light `tertiary`, the link hover colour, from #84a59d to #587971 (was 2.5:1). Text selection mixes 40% of `tertiary` instead of 60%, so text stays readable on it in both modes. Existing sites keep the colours in their own `quartz.config.yaml`.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
Type checking (`npm run check`) uses TypeScript 7. `tsconfig.json` switches `moduleResolution` from `node` (removed in TypeScript 7) to `bundler`, which reads packages' `exports`: custom code that imports a package's internal files may need to import from the package itself.
-24
View File
@@ -64,27 +64,3 @@ jobs:
run: |
npx changeset status --since=origin/v5 >/dev/null 2>&1 \
|| echo "::warning::No changeset in this PR. If it changes how Quartz behaves, run 'npx changeset' (see .changeset/README.md)."
publish-tag:
if: ${{ github.repository == 'jackyzha0/quartz' && github.ref == 'refs/heads/v5' }}
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: 24
- name: Get package version
run: node -p -e '`PACKAGE_VERSION=${require("./package.json").version}`' >> $GITHUB_ENV
- name: Create release tag
uses: pkgdeps/git-tag-action@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
github_repo: ${{ github.repository }}
version: ${{ env.PACKAGE_VERSION }}
git_commit_sha: ${{ github.sha }}
git_tag_prefix: "v"
+2
View File
@@ -85,6 +85,8 @@ jobs:
# Letting `gh release create` make the tag instead gives an unsigned annotated tag
# object (tagger: whoever merged the release PR), which GitHub marks "Unverified"
# (jackyzha0/quartz#2455). `git describe --tags` reads lightweight tags as well.
# This is the only place that tags a release: ci.yaml's old `publish-tag` job (an annotated
# tag through pkgdeps/git-tag-action) ran first and kept every release tag unverified.
if [ -z "$EXISTING" ]; then
gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$TAG" -f sha="$GITHUB_SHA" >/dev/null
else
+137
View File
@@ -1,5 +1,142 @@
# @jackyzha0/quartz
## 5.4.0
### Minor Changes
- 9ebfc67: `extends` in `quartz.config.yaml` is stable for `default` and local paths: its merge rules won't change in a minor release. `https://` URLs stay experimental. Keys starting with `$` are now reserved in every file of an `extends` chain (the top-level `$schema` aside), so merge operators such as appending to a list can be added later without changing existing configs; a config that uses one stops with an error naming the key. Configs without `extends` are not affected.
- cc8d104: `quartz.lock.json` is read and written next to the config file Quartz uses, and every `npx quartz plugin` command takes `--config` / `-C` like `build`. A site's repository can hold its content, `quartz.config.yaml` and `quartz.lock.json` while Quartz is checked out elsewhere (as the GitHub Action will). With the config in Quartz's folder nothing changes, and a config elsewhere keeps using an existing lockfile in Quartz's folder until its own folder has one. Plugin commands with a config chosen by `QUARTZ_CONFIG_PATH` now also edit that file; they used to write their changes to `./quartz.config.yaml`.
- b86276f: npm plugins that Quartz's `package.json` doesn't list are pinned in `quartz.lock.json` (version and integrity) and installed into `.quartz/plugins/@scope/name`, like Git plugins. `plugin add`, and `plugin install --from-config` (e.g. for the `obsidian` and `ttrpg` templates' Excalidraw plugin), no longer write them into Quartz's `package.json`, so `npx quartz upgrade` doesn't conflict with your plugins, and `npm install` / `npm ci` can't remove them. `plugin install`, `--latest`, `restore`, `remove`, `prune`, `list`, `doctor` and `npx quartz plugin` handle them alongside Git plugins, and a build installs a missing one at its pinned version. npm plugins in `package.json` (the default plugins, and any you `npm install` yourself) are versioned there and load from `node_modules`, as before: when a plugin is in both, `package.json` wins.
### Patch Changes
- ea4b075: Plugin update: og-image 1.2.0. A page's social image (`socialImage`, or Obsidian's `image` / `cover` property) can be an image in the content folder, written as a wikilink (`[[cover.png]]`), a path from the content folder, a path relative to the note, or a bare file name. Before, every value that was not a URL was read as a path in `quartz/static/`.
## 5.3.1
### Patch Changes
- f285e12: A plugin that depends on a plugin of another pipeline stage (an emitter or component on a transformer) no longer fails the build because of their `order`: order is checked only between plugins of the same stage.
- ce108c8: A `locale` that Quartz has no translation for (such as `sv-SE`, `da-DK` or `es-MX`) no longer crashes the build. Quartz uses a translation of the same language (`es-MX` uses `es-ES`), else English, and prints one warning; dates still use the configured locale.
- 9889d3f: Plugin updates: folder-page 1.1.5 (a folder's unlisted `index.md` is no longer replaced by a generated folder page), canvas-page 1.1.7 (edges drawn as in Obsidian), search 1.1.5 (Escape with tag suggestions open closes only the suggestions), graph 1.0.10 (the local graph is drawn once per page), stacked-pages 1.0.5 (unused template exports removed) and remark-obsidian 2.2.6.
- 37a61cf: Plugin updates with the fixes from a test audit:
- note-properties: an empty `tags:` or `aliases:` no longer fails the build.
- bases-page: sorting, filters, formulas and group headings work as in Obsidian.
- encrypted-pages: a numeric `password` encrypts the page, and a custom `outputPath` works.
- darkmode, reader-mode, syntax-highlighting and comments: no double handlers after a page is unlocked.
- stacked-pages: links work under a base path.
- breadcrumbs: `resolveFrontmatterTitle` is honoured.
- canvas-page: a `#View` link selects that view.
- search: fields left out of `fieldPriority` are searched, and excerpts keep their last word.
- explorer: a note next to a folder of the same name stays listed, and folder options apply.
- folder-page, og-image, description, table-of-contents, graph, obsidian-flavored-markdown and utils: smaller fixes.
- latex: `customMacros` work with MathJax. ox-hugo: figure parameters in backticks.
- 6729a1e: Relative links and embeds keep their query string after SPA navigation and in popovers (`./viewer.html?file=a.pdf` no longer loses `?file=a.pdf`).
- c68a494: Some fixes in this release change how existing pages look, mostly to match Obsidian: Bases sorting (natural text order, empty values last, mixed types), Bases `not:` filters and `== null`, Bases group headings, canvas edges, and folders with an unlisted `index.md`. See [Upgrading from 5.3.0 to 5.3.1](https://quartz.jzhao.xyz/getting-started/upgrading#upgrading-from-530-to-531).
- 57b3b5d: `npx quartz plugin install --latest` (and `plugin update`) no longer fails because a disabled plugin can't be updated, for example an old `quartz-themes` entry whose repository moved its plugin. The build doesn't load disabled plugins, so this is now a warning that says how to remove the entry. A failing enabled plugin still fails the command.
- 1e1a356: utils 1.3.4: inline `#tag` links from notes two or more folders deep stay under the site's base path. They went to `/tags/…` instead of `/<base>/tags/…`, a 404 on sites served under a sub-path such as GitHub Pages project sites.
## 5.3.0
### Minor Changes
- 55311cb: Links: `disableBrokenWikilinks` is on by default. Internal links to pages that don't exist get the `broken` class, as Obsidian marks unresolved links (`is-unresolved`), so Quartz's and Obsidian themes' unresolved-link styles apply. Tag and folder pages, which are generated later, count as existing. Set `links.disableBrokenWikilinks: false` for the old behaviour.
- 857de3b: Quartz now requires Node.js 22.22 or later (was 22), for chokidar 6, which watches content in `--serve` mode. chokidar 6 confirms each change against the file system before rebuilding and fixes missed and duplicate change events.
- df11e31: 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.
- 09a6b03: `contentIndex.json` entries have `dateFromFrontmatter: true` when their `date` is the one set in the page's frontmatter for the configured date type (not from git or the file system), so client-side components can tell explicit dates apart, e.g. for folder dates in the explorer.
- d5dad62: `contentIndex.json` entries now include the page's `date` (the one `defaultDateType` selects) as an ISO 8601 string, so client-side components such as the explorer can sort by date. Pages without a date have no `date` field.
- 2209ee6: Layout conditions: add `is-index` (only on the home page) and `is-folder-index` (only on folder index pages), and let `not-<condition>` negate any condition, built-in or registered (`not-has-tags`, `not-has-backlinks`, …).
- c770681: Transclusions use Obsidian's embed markup: a `div.markdown-embed-title` (the note's title, for a whole-note embed; it was an `h1`), then the content in `div.markdown-embed-content > div.markdown-preview-view.markdown-rendered`, then the link to the original. Obsidian themes' embed styles apply (embed titles, padding, maximum height). The title looks as before without a theme. Obsidian's icon link to the note (`a.markdown-embed-link`, Lucide's maximize-2) follows; Quartz hides it, and Obsidian themes, through @quartz-themes/core, show it in the embed's corner.
- c229350: Plugin entries can declare `before:` / `after:` (plugin names). They are checked against `order`: between plugins with the same order they decide, and a contradiction, a cycle or an unknown name stops the build with a clear error. `extends:` also accepts an `https://` URL, fetched with a timeout and cached in `.quartz-cache/extends/` for offline builds (`QUARTZ_EXTENDS_OFFLINE=1`).
- b25eba0: New opt-in `configuration.slugs.stripDiacritics`: strips accents and other diacritics from generated slugs (`české/čeština.md` → `/ceske/cestina`). Links, embeds, aliases, permalinks, tags and folder pages resolve to the stripped addresses; heading anchors keep their diacritics. Turning it on changes the URLs of existing pages; their old addresses redirect to the new ones. Only Latin letters change: they lose their accents and fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`); other scripts (Korean, Japanese, Chinese, Greek, Cyrillic, Indic, Hebrew, Arabic, …) are left as written. Plugins that make slugs follow the option when they bundle `@quartz-community/utils` 1.3 or later, as the plugins updated in this release do (1.3.1 for the ASCII folding).
### Patch Changes
- f7b41e7: Block anchors are `#^id`, as in Obsidian: `@quartz-community/utils` 1.3.2 and `@quartz-community/rehype-obsidian` 1.6.0, bundled by obsidian-flavored-markdown 2.5.3, github-flavored-markdown 2.2.2, canvas-page 1.1.4, note-properties 1.2.3 and bases-page 1.5.5, give blocks `id="^id"` and link to them as `#^id`. A block and a heading with the same name (`^para-1`, `## Para 1`) no longer share an id, so `[[#^para-1]]` and `[[#Para 1]]` each reach their own target. canvas-page also scopes the ids of text nodes rendered with `textNodeMarkdown: basic`.
- 3df0062: Block anchors are `#^id`: with @quartz-community/utils 1.3.2 and rehype-obsidian 1.6.0, blocks get the id `^id` and links to them `#^id` (was `#id`), as in Obsidian, so block `^para-1` and heading `## Para 1` no longer share an id. A block transclusion finds its block whatever the case of its `^id` (`![[note#^Para-1]]`), and the popover scrolls to a block it links to.
- 2b061ab: Links: links to files Quartz emits, such as `[feed](/index.xml)`, `/sitemap.xml`, `/static/icon.png` or `/404.html`, are no longer marked `broken`. A link is only marked when its target is known to be missing: a page that doesn't exist, or a vault file (image, audio, video, PDF, canvas, base) the content doesn't have. Other files may come from an emitter, so they are left unmarked.
- 734e1b8: Links to pages removed by a filter (drafts, ExplicitPublish) are now marked `broken` (with `data-filtered="<filter>"`), like links to pages that don't exist — they 404 on the site.
- 9de19e3: `extends` (experimental): `npx quartz plugin list`, `status`, `doctor`, `install`, `prune` and `npx quartz info` read the merged configuration, as the build does. Before, they saw only the entries in your own file, so `list` showed a handful of plugins and `doctor` warned that overlay entries without `enabled` are disabled. `enable`, `disable` and `config` now work on plugins from a base by adding or changing your own entry for them (only that change is written; the merged configuration never is), `config --unset` resets an option a base sets with `null`, and `remove` refuses a plugin that comes from a base. `npx quartz build --serve` also rebuilds when a local base file changes.
- a51b7df: `extends` (experimental): presets in a list now stack. With `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, everything `a.yaml` changed was lost, because `b.yaml` was merged on top with all of `default` again. Each file of the `extends` chain is now applied once, after the bases it extends, so the order is `default` → `a.yaml` → `b.yaml` → your file, and later entries win only where they change the same thing.
Also: a plugin source with a `subdir` and no `name` is matched by repository and folder, so an entry for one plugin of a monorepo no longer changes another; `extends: []` extends nothing; an empty base file is an empty config; `HTTPS://` URLs are accepted; and `plugins:` that isn't a list gets a clear error.
- b2241c3: Layout conditions: `is-folder-index` is false on tag pages. The all-tags page (`tags/index`) matched it, so components meant for folder pages showed there; nothing under `tags/` counts as a folder index now.
- cc253be: Footnote references and back-links keep the `internal` class but no longer get `internal-link`: Obsidian doesn't treat them as note links, and Obsidian themes' link styles (underline, colour) overrode their footnote styles.
- 71454c7: Markdown links in frontmatter with an angle-bracket destination, which Obsidian writes for paths with spaces (`[Exec Briefing](<./Exec Briefing.md>)`), resolve to the note instead of a missing `….md` page, so the note gets the backlink and graph edge.
- 8be4d8e: Markdown links in frontmatter are read as CommonMark reads them: angle-bracket destinations with parentheses (`[b](<Note (2024).md>)`), balanced parentheses in plain destinations (`[d](Note_(2024).md)`), titles in `"…"`, `'…'` or `(…)` (`[c](<My Note.md> "t")`), and backslash escapes. They pointed at `note-(2024` and `my-note.md-t`, so the linked note got no backlink or graph edge.
- c33b6cf: @quartz-community/graph 1.0.5: the graph scales to large sites. On 3,000 notes and 33,000 links, the global graph opens in 0.5 s instead of 2.5 s, and it stops using the CPU once its layout settles. It also loads d3 and PixiJS as pinned, integrity-checked versions, with PixiJS's minified build (200 KB instead of 2.5 MB on every page).
- 6ce31a4: - `@quartz-community/graph` 1.0.7: the local graph on folder index pages shows the folder's connections instead of a single node.
- `@quartz-community/utils` 1.2.1: `unescapeHTML` decodes each entity once, so a page description that mentions `&lt;br&gt;` keeps it in the page's meta tags instead of turning it into `<br>`.
- 9d6cdba: Pages get a canonical link (`<link rel="canonical">`, the page's URL as the sitemap lists it), and `og:url` uses the same URL: `folder/` instead of `folder/index`, and the site root for the home page. `og:site_name` is a `property` (it was a `name`, which Open Graph readers ignore). Notes are `og:type: article`, with `article:modified_time` and, when the frontmatter has a date, `article:published_time`. The home page and folder and tag pages stay `website`.
The `fonts.gstatic.com` preconnect is a CORS connection, which the font files can reuse, and the unused `cdnjs.cloudflare.com` preconnect is gone.
- c79adab: Each component's CSS is parsed on its own before the component stylesheet is put together, so a missing `}` or an unclosed comment in one plugin's CSS no longer swallows the rules of every component after it, and a stray `}` no longer fails the build; a syntax error is reported with the component's name.
- 3b78d16: Frontmatter is read with js-yaml 5, using YAML 1.2's core schema (the values Quartz read before are unchanged). Frontmatter with only comments now has no properties, as in Obsidian, instead of being reported as invalid frontmatter.
- a55f25f: The page frames mark their regions for assistive technology: the centre column is a `<main>` (it was a `div.center`; the classes are unchanged) and the default frame's sidebars are `<aside>` elements. Screen readers can jump to the page's content, and the page looks the same.
- 7714325: Heading transclusions and their footnotes look through Obsidian's per-block wrappers (`div.el-h2 > h2`), which `@quartz-community/rehype-obsidian` now renders around each of a note's top-level blocks. `blockOf()` (in `components/transcludeScope.ts`) returns the block inside a wrapper, for other code that walks a page's top-level blocks.
- b4d7358: Obsidian's fold arrows in headings and list items (`.heading-collapse-indicator`, `.list-collapse-indicator`, rendered by rehype-obsidian for Obsidian themes) are hidden unless obsidian-flavored-markdown's `foldHeadings` / `foldLists` turn folding on.
- 0bab8ea: @quartz-community/obsidian-flavored-markdown 2.4.0 (Obsidian's block wrappers, heading and list folding, missing-attachment embeds, Pele diagrams) and @quartz-community/og-image 1.1.2 (no build failure on emoji variants such as the footnote back-link `↩︎`).
- db7484e: @quartz-themes/core 3.2.0 (Obsidian's block wrappers styled natively, property inputs, fold arrows) and the plugin releases that carry Obsidian's markup:
- latex 1.1.0: maths in Obsidian's math elements;
- note-properties 1.2.0: Obsidian's properties markup;
- search 1.1.0: the quick switcher's classes, excerpts as written;
- explorer 1.1.2: Obsidian's folder rows;
- table-of-contents 1.0.4: the collapsed table of contents no longer clips its header;
- graph 1.0.4: colours follow Obsidian themes;
- syntax-highlighting 1.0.4: the copy button's stylesheet in the base layer;
- canvas-page 1.0.4: heading embeds look through the block wrappers.
- fd744c0: The `obsidian` template folds headings and lists (obsidian-flavored-markdown's `foldHeadings` and `foldLists`), as Obsidian does by default.
- 7b4da1c: A note whose name ends in "index" (`reindex.md`) is an `og:type: article` again. The home page and folder index pages were told apart by the slug ending in `index`, not by its last segment, so such notes were `website` and had no article dates.
- bc0e393: Plugin order: `before:` / `after:` naming a plugin that is built into Quartz now (`crawl-links`, `remove-draft`, `content-index`) passed validation but was ignored. They now mean the built-in that replaced them (`links`, `drafts`, `contentIndex`), so `before: crawl-links` orders the plugin before link processing, and is checked against its `order` like `before: links`.
- 52af9f1: `PageList` entries are `h2` headings under the page's `h1` (they were `h3`, which skipped a level for screen readers), at the `h3`'s size, as in `@quartz-community/folder-page` and `@quartz-community/tag-page`.
- f646ffe: Plugin fixes from the pre-release audit:
- `@quartz-community/latex` 1.1.2: KaTeX's stylesheet applies on pages whose maths comes from a transclusion or a popover, and after SPA navigation (it stayed print-only).
- `@quartz-community/obsidian-flavored-markdown` 2.5.2: bundles rehype-obsidian 1.5.1 and remark-obsidian 2.2.4, so same-page block links (`[[#^id]]`) work, only real YouTube hosts become embeds, large notes use less memory, and under `preset: strict` other plugins' text rewrites survive in notes with callouts; `math: false` works under `strict` with the LaTeX plugin; Markdown-link embeds with a query or in reference style are transcluded.
- `@quartz-community/github-flavored-markdown` 2.2.1: `replacements` leaves autolink text alone, applies to wikilink aliases, and honours backslash escapes; `data-heading` keeps the heading as written.
- `@quartz-community/canvas-page` 1.1.2 and `@quartz-community/tag-page` 1.0.7: file nodes find headings as Obsidian writes them (`#Sub Section`), embeds in text nodes are filled in, text-node tags get tag pages, and ids are unique per node; the tag index lists pages as `h3` under each tag.
- `@quartz-community/search` 1.1.2: Enter on a result navigates without a full reload, `#tags` match with `slugs.stripDiacritics`, and searches ignore accents (`creme` finds "Crème").
- `@quartz-community/explorer` 1.2.2: keeps the current page open after a `render` event without details (encrypted pages), and each explorer's phone button is named after its title.
- `@quartz-community/bases-page` 1.5.4: view tabs follow the WAI-ARIA tabs pattern (arrow keys, unique ids).
- `@quartz-community/graph` 1.0.8: no animation loop while the graph is idle, closed or removed.
- `@quartz-community/created-modified-date` 1.0.5: stand-in dates are marked, so they stay out of `contentIndex.json`, and git dates work for a symlinked vault in a content folder outside git.
- `@quartz-community/og-image` 1.1.3, `@quartz-community/ox-hugo` 1.0.3, `@quartz-community/breadcrumbs` 1.0.5, `@quartz-community/folder-page` 1.1.3, `@quartz-community/note-properties` 1.2.2: descriptions decoded once and keycap/flag emoji in social images; captioned figures and indented code in ox-hugo; utils 1.3.1 (Latin-only `stripDiacritics`).
- 8c61245: Plugin updates:
- `@quartz-community/explorer` 1.2.0: `sort` option (rules applied in sequence, e.g. folders first, then newest) and `rootFolder` option, so several explorers on one page work side by side; the `order` option is applied; scroll fixes (the bottom fade, the scroll position across SPA navigation with `layout.sidebars.left: scroll`, and opening a page no longer scrolls the page itself).
- `@quartz-community/obsidian-flavored-markdown` 2.5.0: notes, canvases and bases embedded with a Markdown link (`![](note.md#Section)`) are transcluded, as in Obsidian; `math` option (`false` leaves dollar signs as text). With `@quartz-community/rehype-obsidian` 1.5.1: same-page block links (`[[#^id]]`) reach their block, and only images on YouTube become YouTube embeds.
- `@quartz-community/github-flavored-markdown` 2.2.0: `singleTilde` option (`false` strikes only `~~text~~`, as Obsidian does) and `replacements` option (for example Quartz 4's arrows), empty by default.
- `@quartz-community/canvas-page` 1.1.0: the mouse wheel and trackpad pan the canvas, as in Obsidian (`wheelBehavior`); text nodes are rendered with the site's Markdown plugins, so Mermaid diagrams, callouts and math work in them (`textNodeMarkdown`).
- `@quartz-community/utils` 1.3.0: the `stripDiacritics` slug option reaches plugins too; links in embedded folder notes point at the right directory.
- `@quartz-community/created-modified-date` 1.0.4: git dates resolve when `content/` is a symlink to a vault in another git repository.
- `@quartz-community/ox-hugo` 1.0.2: the Markdown rewrites leave code alone and no longer match across unrelated text.
- 96fc9c1: Plugin updates for accessibility and page speed:
- Text in the table of contents, footer, folder and tag listings, search button and Bases group headings meets WCAG AA contrast in light and dark mode. Under an Obsidian theme from quartz-themes (`@quartz-themes/core` 3.2.1), the search button and Bases group headings keep the theme's faint text colour.
- Page listings in folder and tag pages use `<h2>` titles (at the previous size), so headings no longer skip a level.
- Valid ARIA and unique ids in the table of contents, explorer, backlinks, heading anchors and Bases views.
- The graph loads d3 and PixiJS only when it scrolls into view (or when the global graph opens), instead of on every page.
- KaTeX's stylesheet no longer blocks rendering on pages without math.
- `@quartz-community/remark-obsidian` 2.2.3: the `legacy` parser no longer uses memory that grows with the square of the note's length on notes with many tables, lists or other blocks.
- 661b56a: Release tags are verified on GitHub: the release workflow creates each `vX.Y.Z` tag as a lightweight tag on the merged release commit (which GitHub signs) instead of letting the release create an unsigned annotated tag. It also starts the Docker build for the tag, so versioned images (`5.3.0`, `5.3`) are published for each release (none were built for 5.1.0–5.2.2).
- 799b8e3: Component styles are one stylesheet (`component-<hash>.css`, in the `quartz-base` layer as before) instead of one per component. Pages load about 20 fewer render-blocking stylesheets (29 to 11 on the docs site), and the styles they compute are unchanged.
- e0f1e03: A scroll made just before Back (less than 150 ms) is no longer lost: Forward returns to where the reader scrolled.
- 3ab4503: With SPA navigation, Back and Forward return to where the reader was on each page. The router keeps each history entry's scroll position and restores it after swapping the page in. The browser restored the position while the previous page was still on screen, so it came out wrong: Back after a table-of-contents link stayed at the heading, and Back to a page landed at its top or bottom. Back and Forward between headings of the same page now only scroll, instead of reloading the page, and a reload keeps the position.
- 0d05ef7: Build-time stand-in dates are no longer written as real dates. A page whose date no source gives (for example `defaultDateType: published` and no `published:`, or an invalid one) gets the build time from the date plugin; `contentIndex.json` now leaves its `date` out, and `article:published_time` / `article:modified_time` are only set for real dates (an invalid `published:` gave the build time). RSS and the sitemap keep the build time. created-modified-date 1.0.5 lists its stand-ins in `file.data.fallbackDates`; with older versions a `published` date only counts when the frontmatter sets it.
- dd667ee: `slugs.stripDiacritics` reaches plugins and the browser: bases-page 1.5.3, breadcrumbs 1.0.4, canvas-page 1.1.1, explorer 1.2.1, folder-page 1.1.2, note-properties 1.2.1 and obsidian-flavored-markdown 2.5.1 bundle `@quartz-community/utils` 1.3, so their links, tag pages from inline tags, canvas file nodes and base views use the stripped addresses. Quartz also passes the option to scripts in the browser, so the explorer places folders and pages with accents where the build put them.
- 093d233: The templates' colours meet WCAG AA contrast (4.5:1) on their backgrounds. Light `gray` goes from #b8b8b8 to #727272 (was 1.9:1), dark `gray` from #646464 to #7f7f7f (was 3.1:1), and light `tertiary`, the link hover colour, from #84a59d to #587971 (was 2.5:1). Text selection mixes 40% of `tertiary` instead of 60%, so text stays readable on it in both modes. Existing sites keep the colours in their own `quartz.config.yaml`.
- 7c3df89: Type checking (`npm run check`) uses TypeScript 7. `tsconfig.json` switches `moduleResolution` from `node` (removed in TypeScript 7) to `bundler`, which reads packages' `exports`: custom code that imports a package's internal files may need to import from the package itself.
- af36801: Links to a folder or tag page that isn't generated (a folder whose notes are all drafts or that holds only images, a tag no published page uses) are marked broken, and in watch mode a page whose links to a page that was published or filtered out change is re-emitted, so its marks don't go stale.
## 5.2.2
### Patch Changes
+2 -1
View File
@@ -65,5 +65,6 @@ Heading ids follow the GitHub rule (`github-slugger`, as `rehype-slug` and the t
- `slugHeading(text)`: the id of a heading with this text;
- `HeadingSlugger`: slugs all headings of one page in order and numbers repeats (`foo`, `foo-1`, …) — create one per page;
- `obsidianHeadingAnchor(text)`: the anchor Obsidian writes for a heading (it replaces `:`, `|`, `^`, `#` and `\` with spaces); slug it with `slugHeading` and add it as an extra id when it differs;
- `resolveAnchorHref(href, ids)`: points a same-page `#anchor` at an id that exists on the page (an id as written, a block reference `#^name`, or a heading's text);
- `resolveAnchorHref(href, ids)`: points a same-page `#anchor` at an id that exists on the page (an id as written, or a heading's text); a block reference `#^name` always points at the block (`#^name`), never at a heading;
- `blockAnchor(name)`: the anchor of the block `^name`, `#^name` (lowercased). Blocks have the id `^name`, so they never share an id with a heading;
- `slugTag(tag)`: the slug of a tag, as used for tag pages.
+7
View File
@@ -65,6 +65,13 @@ By default Quartz loads `quartz.config.yaml` from the current working directory.
npx quartz build --config ../my-vault/quartz.config.yaml
```
`quartz.lock.json` is read from the same folder as the config, so a site's repository can hold its content, `quartz.config.yaml` and `quartz.lock.json` together while Quartz is checked out elsewhere. Plugins are still installed into Quartz's `.quartz/plugins/`. Use the same `--config` with the [[cli/plugin|plugin]] commands, which pin plugins in that lockfile. (A config in a folder without a lockfile keeps using an existing `quartz.lock.json` in Quartz's folder.)
```shell
npx quartz plugin install --config ../my-vault/quartz.config.yaml
npx quartz build --config ../my-vault/quartz.config.yaml -d ../my-vault/content
```
> [!note]
> The shorthand for `--config` is an uppercase `-C`. A lowercase `-c` is the shorthand for `--concurrency`, so the two are distinct.
+11 -7
View File
@@ -6,18 +6,20 @@ The `plugin` command is the heart of the Quartz v5 plugin management system. it
Quartz plugins come from two kinds of sources:
- **npm packages** (`@quartz-community/explorer`) — the default plugins. They are installed into `node_modules/` by `npm install` / `npm ci` and versioned by `package.json` and `package-lock.json`.
- **npm packages** (`@quartz-community/explorer`). Those in Quartz's `package.json` — the default plugins, and any you install with `npm install` yourself — are installed into `node_modules/` by `npm install` / `npm ci` and versioned by `package.json` and `package-lock.json`. Other npm plugins are pinned in `quartz.lock.json` (version and integrity) and installed into `.quartz/plugins/@scope/name`, like Git plugins: `plugin add` doesn't change Quartz's `package.json`, so `npx quartz upgrade` doesn't conflict with your plugins, and `npm install` / `npm ci` can't remove them. When a plugin is in both, `package.json` wins.
- **Git repositories and local directories** (`github:owner/repo`, `./my-plugin`) — cloned or symlinked into `.quartz/plugins/`. Their exact commits are pinned in `quartz.lock.json`.
Wherever a command takes a plugin name you can use the full name (`@quartz-community/explorer`), the source as written in `quartz.config.yaml`, or the short name (`explorer`). Misspelled names get a "did you mean" suggestion.
Every subcommand takes `--config` / `-C`, like [[cli/build#Custom config file|build]]: it reads and edits that config file, and the `quartz.lock.json` next to it, instead of `./quartz.config.yaml` and `./quartz.lock.json`.
Every subcommand exits with a non-zero status when something fails (a clone, a build, an unknown plugin name), so `npx quartz plugin install && npx quartz build` stops in CI instead of building a site with missing plugins.
## Subcommands
### list
List all configured plugins: Git/local plugins with their pinned commit, npm plugins with their installed version, and any plugins that are in `quartz.config.yaml` but not installed yet.
List all configured plugins: plugins pinned in `quartz.lock.json` (Git/local plugins with their commit, npm plugins with their version), npm plugins from `package.json` with their installed version, and any plugins that are in `quartz.config.yaml` but not installed yet.
```shell
npx quartz plugin list
@@ -25,7 +27,7 @@ npx quartz plugin list
### add
Add a new plugin from npm or a Git repository. The plugin is installed (Git plugins are pinned in `quartz.lock.json`, npm packages recorded in `package.json`), and added to `quartz.config.yaml` with its default options — enabled unless the plugin is disabled by default.
Add a new plugin from npm or a Git repository. The plugin is installed and pinned in `quartz.lock.json` (Git plugins by commit, npm packages by version; an npm package already in `package.json` stays versioned there), and added to `quartz.config.yaml` with its default options — enabled unless the plugin is disabled by default.
```shell
npx quartz plugin add @quartz-community/graph # an npm package, as the default config uses
@@ -67,7 +69,7 @@ npx quartz plugin remove plugin-name
npx quartz plugin remove explorer # short name of @quartz-community/explorer
```
For npm plugins the package stays in `node_modules/` (most of them ship with Quartz). If another configured plugin declares a dependency on the one you removed, a warning tells you so.
A pinned npm plugin is removed from `.quartz/plugins/` and `quartz.lock.json`; an npm plugin from `package.json` stays in `node_modules/` (most of them ship with Quartz). If another configured plugin declares a dependency on the one you removed, a warning tells you so.
### install
@@ -77,7 +79,9 @@ Install plugins for your Quartz project. By default, this installs all plugins l
npx quartz plugin install
```
If there is no `quartz.lock.json` yet, `install` falls back to installing the Git/local plugins from `quartz.config.yaml` and writes the lockfile — commit it to pin those versions. If only npm plugins are configured there is nothing to do and the command says so. When `quartz.config.yaml` lists Git plugins that are missing from the lockfile, `install` prints them with a hint to run `install --from-config`.
If there is no `quartz.lock.json` yet, `install` falls back to installing the plugins from `quartz.config.yaml` and writes the lockfile — commit it to pin those versions. If only npm plugins from `package.json` are configured there is nothing to do and the command says so. When `quartz.config.yaml` lists plugins that are missing from the lockfile, `install` prints them with a hint to run `install --from-config`.
`npx quartz build` also installs a pinned npm plugin that is missing from `.quartz/plugins/`, at the version the lockfile pins.
> [!note]
> `npx quartz build` also installs any configured Git plugin that is missing from `.quartz/plugins/`, and checks out the commit pinned in `quartz.lock.json` when there is one. Running `plugin install` first is still recommended in CI, because it fails loudly when a plugin cannot be installed.
@@ -85,7 +89,7 @@ If there is no `quartz.lock.json` yet, `install` falls back to installing the Gi
#### Flags
- `--from-config`: Synchronize plugins with `quartz.config.yaml` instead of the lockfile. This will install missing plugins and prune orphaned ones.
- `--latest`: Fetch the latest version of plugins from their remote sources instead of using the version in the lockfile.
- `--latest`: Fetch the latest version of plugins from their remote sources instead of using the version in the lockfile (for a pinned npm plugin, the version npm's `latest` tag points at).
- `--clean`: Only restore plugins whose directory is missing; existing directories are left untouched.
- `--dry-run`: Preview the changes without actually installing or removing any files.
- `--concurrency`, `-c`: Maximum number of plugins to clone, fetch, and build in parallel. Defaults to the number of CPU cores. Lower this (e.g. `-c 1` or `-c 2`) on memory- or CPU-constrained machines where the default parallelism causes failures, OOMs, or hangs. See [[#Installing on low-end hardware]] below.
@@ -348,4 +352,4 @@ Running the plugin command without any subcommand shows a status dashboard of al
npx quartz plugin
```
This displays each plugin with its source, commit (or npm version), enabled/disabled status, and checks Git plugins for available updates in parallel. npm plugins are updated together with Quartz (`npx quartz upgrade`). A misspelled subcommand (e.g. `npx quartz plugin lst`) is reported as an error with a suggestion instead of falling back to this dashboard. For the full interactive management interface, use [[tui|npx quartz tui]] instead.
This displays each plugin with its source, commit (or npm version), enabled/disabled status, and checks pinned plugins for available updates in parallel (Git plugins against their repository, npm plugins against npm). npm plugins in `package.json` are updated together with Quartz (`npx quartz upgrade`). A misspelled subcommand (e.g. `npx quartz plugin lst`) is reported as an error with a suggestion instead of falling back to this dashboard. For the full interactive management interface, use [[tui|npx quartz tui]] instead.
+7 -4
View File
@@ -44,17 +44,20 @@ plugins:
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), an `https://` URL, or a list of those. An empty file (or one with only comments) is an empty config, and `extends: []` extends nothing.
- A list stacks presets: each file in it adds its own changes. Quartz puts every file of the `extends` chain in one line and applies each once, its bases before it: the list's entries in order, each after the bases it extends, and your file last. A base that several entries share (usually `default`) is applied once, at its first appearance. So with `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, the order is `default` → `a.yaml` → `b.yaml` → your file: what `a.yaml` changes stays unless `b.yaml` changes the same thing (later entries win), and your file wins over both. An entry that doesn't extend the shared base is applied before it if it comes first, so the base's settings win over it; make such a preset extend `default` too, or list it after the others.
- A URL is fetched when the config is loaded (10 s timeout, at most 1 MB) and kept in `.quartz-cache/extends/`. If a later fetch fails (offline, timeout, HTTP error), Quartz uses the cached copy and warns; without one, the build stops. `QUARTZ_EXTENDS_OFFLINE=1` uses only the cached copy. Relative `extends` inside a fetched file are resolved against its URL; `default` always means your local `quartz.config.default.yaml`. Only `https://` URLs are allowed, and only extend configs you trust: they choose which plugins your build runs.
- **Experimental:** `https://` URLs. How they are fetched, cached and trusted may still change. A URL is fetched when the config is loaded (10 s timeout, at most 1 MB) and kept in `.quartz-cache/extends/`. If a later fetch fails (offline, timeout, HTTP error), Quartz uses the cached copy and warns; without one, the build stops. `QUARTZ_EXTENDS_OFFLINE=1` uses only the cached copy. Relative `extends` inside a fetched file are resolved against its URL; `default` always means your local `quartz.config.default.yaml`. Only `https://` URLs are allowed, and only extend configs you trust: they choose which plugins your build runs.
- `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). A source with a `name` matches by that name; a source with a `subdir` and no `name` matches by repository and folder, so two plugins of one repository stay separate. `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.
- Keys starting with `$` are reserved in every file of an `extends` chain, at any depth (the top-level `$schema` aside): they are kept free for merge operators, such as adding to a list instead of replacing it. A config that uses one stops with an error naming the key. Values may contain `$` freely.
- 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.
- `npx quartz build --serve` also rebuilds when a local file your config extends changes.
- `npx quartz plugin` commands and `npx quartz info` read the merged configuration, as the build does: `plugin list`, `status`, `doctor`, `install` and `prune` see the plugins your bases configure. Commands that change plugins only ever write your own file, never the merged result: `enable`, `disable` and `config --set` add or change your entry for the plugin (`- source: …` with just that change), `config --unset` removes your value and, when a base sets the option, sets it to `null` so the plugin's default applies, and `add` appends a full entry. `remove` refuses a plugin that a base configures (it can't be removed from your file); disable it instead.
> [!warning] Experimental
> `extends` is experimental: the merge rules may still change.
> [!note] Stability
> `extends` with `default` and local paths is stable: the merge rules above don't change in a minor release. `https://` URLs are experimental.
>
> A Quartz upgrade can change the defaults your site extends. A changed default applies to your site unless your file sets that value itself.
## General Configuration
@@ -91,7 +94,7 @@ This part of the configuration concerns anything that can affect the whole site.
- `stripDiacritics`: `true` strips accents and other diacritics from page, folder and file URLs, e.g. `české/čeština.md` is published at `/ceske/cestina` instead of `/české/čeština` (which browsers show as `%C4%8Desk%C3%A9/...` when copied). Off by default.
- Links keep working as written in your notes: `[[čeština]]`, `[[české/čeština#Nadpis]]` and embeds like `![[obrázek.png]]` resolve to the stripped addresses. Aliases and `permalink`s are stripped the same way. Heading anchors (`#Nadpis`) keep their diacritics. Tag pages and the pages plugins generate from files (canvas, bases, …) are stripped too with `@quartz-community/utils` 1.3 or newer; with older versions they keep their diacritics.
- Only Latin letters change: they lose their accents (`á č é ů …`), and Latin letters without a decomposition fold to ASCII (`ł` → `l`, `ø` → `o`, `ß` → `ss`, `æ` → `ae`). Other scripts (Chinese, Japanese, Korean, Greek, Cyrillic, Arabic, Hebrew, Devanagari, …) are left as written, marks included.
- Turning it on changes the URLs of existing pages; links shared elsewhere to the old addresses will 404 unless you add the old addresses as `aliases`.
- Turning it on changes the URLs of existing pages. Quartz writes a redirect from each page's, folder's and alias's old address (the slug with its diacritics) to the new one, so links shared elsewhere keep working. Old `permalink` addresses are not redirected; add them as `aliases` if they need to keep working.
- `ignorePatterns`: a list of [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) patterns that Quartz should ignore and not search through when looking for files inside the `content` folder. See [[private pages]] for more details.
- `theme`: configure how the site looks.
- `fontOrigin`: where to load fonts from.
+2 -2
View File
@@ -6,7 +6,7 @@ tags:
Quartz supports [Mermaid](https://mermaid.js.org) for diagrams and charts in your notes (flow charts, sequence diagrams, timelines, and so on). This is part of [[Obsidian compatibility]] and can be turned on or off on that plugin.
Default renderer is Mermaid.js. Set `diagramRenderer: pele` on [[ObsidianFlavoredMarkdown]] to use [Pele](https://pele.run) instead. Mermaid.js is deprecated; Pele will become the default later.
Diagrams are drawn with [Pele](https://pele.run), as in Obsidian 1.15 (since [[ObsidianFlavoredMarkdown]] 2.4 / Quartz 5.3), inside a `<div class="mermaid">`. Set `diagramRenderer: mermaid` on ObsidianFlavoredMarkdown to use the deprecated Mermaid.js instead.
> [!note]
> In the default config [[ObsidianFlavoredMarkdown]] (`order: 40`) runs after [[SyntaxHighlighting]] (`order: 20`). If Mermaid diagrams don't show up and you changed either `order`, restore that sequence.
@@ -16,7 +16,7 @@ plugins:
- source: "@quartz-community/obsidian-flavored-markdown"
options:
mermaid: true
diagramRenderer: pele # default: mermaid
diagramRenderer: pele # or mermaid (deprecated)
```
Both renderers only load on pages that contain a Mermaid diagram. Pele is served from your own site (Quartz 5.1+) and only downloads the code for the diagram types on the page; on older Quartz versions it is loaded from jsDelivr. Mermaid.js is always loaded from a CDN.
+78 -9
View File
@@ -59,7 +59,70 @@ plugins:
priority: 50
```
For advanced options like custom sort, filter, and map functions, use the TS override in `quartz.ts`:
### Sorting
`sort` is a list of rules. Each folder's entries are sorted by the first rule; entries it considers equal are sorted by the next one, and so on. A rule is `{ by: <key>, direction: asc | desc }` (`direction` defaults to `asc`), or just the key. As in [[Bases]] views, `direction` may also be written `ASC` / `DESC`, and `by` as `property`.
| `by` | Sorts by |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `folder` | Folders before files (`desc`: files before folders) |
| `title` | The displayed name (the page title), in natural order: `Note 2` before `Note 10`, case-insensitive |
| `name` | The file or folder name, whatever the title or `mapFn` (e.g. numbered names: `10 Research`) |
| `date` | The page's date, as `defaultDateType` picks it (created, modified or published). A folder's date is its index page's date when that page sets one in its frontmatter, else the date of its newest page |
| `tag` | The page's tags in the order they are written: first tags compared, then second tags when those are equal, and so on. With `firstTagOnly: true`, only the first tags |
Entries without a date or tags come after the others, in either direction. The default is `[folder, title]`. Newest first, folders still on top:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
options:
sort:
- folder
- { by: date, direction: desc }
- title
```
Grouped by first tag, newest first within a tag:
```yaml
sort:
- by: tag
firstTagOnly: true
- by: date
direction: desc
```
A `sortFn` set in `quartz.ts` replaces `sort`. Sorting runs at the `sort` step of `order`, so with the default order it sees the names `mapFn` set. `order: [filter, sort, map]` sorts by the original names, for example to strip [Johnny.Decimal](https://johnnydecimal.com/) prefixes in `mapFn` while keeping the numbered order.
### Several explorers
List the plugin once per explorer, each entry with its own options and layout. `rootFolder` shows only one folder's contents (a folder path as in your vault, or its slug):
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
layout:
position: left
priority: 50
- source: "@quartz-community/explorer"
enabled: true
options:
title: Notes
rootFolder: Notes/Daily Notes
layout:
position: left
priority: 55
display: desktop-only # one menu button on phones
```
Opened folders are remembered per folder, so a folder shown in both explorers is open or closed in both; scroll positions are kept per explorer. Options set in a TypeScript override apply to every entry.
### Custom functions
For custom sort, filter, and map functions, use the TS override in `quartz.ts`:
```ts title="quartz.ts"
import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
@@ -100,7 +163,8 @@ Want to customize it even more?
- Removing explorer: remove the `explorer` entry from `quartz.config.yaml` or set `enabled: false`
- (optional): After removing the explorer component, you can move the [[table of contents | Table of Contents]] component back to the `left` part of the layout
- Changing `sort`, `filter` and `map` behavior: explained in [[#Advanced customization]]
- Changing the sort order: [[#Sorting]]
- Custom `sort`, `filter` and `map` functions: explained in [[#Advanced customization]]
## Advanced customization
@@ -122,9 +186,13 @@ export type ContentDetails = {
links: SimpleSlug[]
tags: string[]
content: string
date?: string // ISO 8601, the date `defaultDateType` picks (Quartz 5.3+)
dateFromFrontmatter?: true // the date is set in the page's frontmatter (Quartz 5.3+)
}
```
To sort by date, use `sort: [{ by: date, direction: desc }]` (see [[#Sorting]]), or compare `a.data?.date` in a `sortFn`.
Every function you can pass is optional. By default, only a `sort` function will be used:
```ts title="Default sort function"
@@ -167,24 +235,25 @@ These examples show the basic usage of `sort`, `map` and `filter`.
### Use `sort` to put files first
Using this example, the explorer will alphabetically sort everything.
Files before folders, everything by title:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/explorer"
enabled: true
options:
# Simple options go in YAML
title: Explorer
folderDefaultState: collapsed
sort:
- { by: folder, direction: desc }
- title
```
Custom sort functions require the TS override:
The same with a sort function in the TS override:
```ts title="quartz.ts (override)"
ExternalPlugin.Explorer({
sortFn: (a, b) => {
return a.displayName.localeCompare(b.displayName)
if (a.isFolder === b.isFolder) return a.displayName.localeCompare(b.displayName)
return a.isFolder ? 1 : -1
},
})
```
@@ -203,7 +272,7 @@ ExternalPlugin.Explorer({
```
> [!note]
> The `mapFn`, `filterFn`, and `sortFn` options require JavaScript callback functions and cannot be expressed in YAML. Use the TS override for these.
> The `mapFn`, `filterFn`, and `sortFn` options require JavaScript callback functions and cannot be expressed in YAML. Use the TS override for these. Sorting by folder, title, name, date or tag needs no code: see [[#Sorting]].
### Remove list of elements (`filter`)
+89
View File
@@ -28,6 +28,95 @@ npx quartz plugin install --latest
See the [[upgrade|CLI reference for upgrade]] for more details on available flags.
## Upgrading from 5.3.0 to 5.3.1
5.3.1 is a patch release: fixes from a test audit of Quartz and its plugins, many checked against Obsidian. Upgrade as usual:
```bash
npx quartz upgrade
npx quartz plugin install --latest
```
### Changes you may notice
Most of these make a page look the way Obsidian shows it, so an existing site can look different after the upgrade.
- **[[Bases]] sorting**: text sorts naturally ("Chapter 2" before "Chapter 10") and ignores case, also for the default order by file name. Empty values come last in both directions, including descending sorts. A column that mixes types sorts numbers, dates and durations by value and everything else as text. Group order follows the same rules.
- **[[Bases]] filters and formulas**, as in Obsidian:
- `not:` leaves out a note that matches _any_ of its conditions (it left out only notes matching all of them).
- `status == null` matches notes without `status`, and `status != null` no longer keeps them.
- `"5" == 5` and `1 == true` are true, two strings compare as text (`"10" > "9"` is false), and an empty list counts as false.
- A formula can use a formula defined after it. `x / 0` shows ∞. `sum()`, `mean()`, `min()` and `max()` skip text and booleans, and are empty without numbers. `number("abc")` is an error.
- **[[Bases]] group headings** show their value as a cell does: dates in the local format (not an ISO timestamp, sometimes of the previous day), durations as "4 days", links as the note's name, booleans as a checkbox.
- **[[CanvasPage|Canvas]] edges** leave and enter each card through the side they name, with Obsidian's curve, and the arrow points into that side. An edge without sides joins the sides that face each other (it joined the cards' centres).
- **Folder pages**: a folder whose own `index.md` is unlisted shows that note, with the folder listing below it. A generated folder page used to replace it.
- **Tag links under a base path**: inline `#tag` links from notes two or more folders deep stay on the site. On a site served under a sub-path, such as a GitHub Pages project site, they went to `/tags/…` and returned 404.
- **Locales without a translation** (such as `sv-SE`) no longer crash the build: Quartz uses a translation of the same language, else English, and prints a warning. Dates still use your locale.
- **`npx quartz plugin install --latest`** no longer fails because a _disabled_ plugin can't be updated (for example an old `quartz-themes` entry). It prints a warning with the command to remove the entry.
## Upgrading from 5.2 to 5.3
Quartz 5.3 needs **Node.js 22.22 or later**. Then upgrade as usual:
```bash
npx quartz upgrade
npx quartz plugin install --latest
```
### Changes you may notice
- **Block anchors**: a block's id is now `^id` and links to it are `#^id` (`[[note#^para-1]]` → `note#^para-1`, was `note#para-1`), as in Obsidian, where blocks and headings are separate namespaces: block `^para-1` and heading `## Para 1` no longer share an id, so `[[#^para-1]]` and `[[#Para 1]]` each land on their own target. Links inside the site are regenerated; old `#id` URLs of blocks from outside the site now go to the top of the page (or to a heading of that name). CSS or scripts that select a block by id need `#\^para-1` (or `getElementById`).
- **Unresolved links**: `configuration.links.disableBrokenWikilinks` is now on by default. Links to pages that don't exist get the `broken` class and are styled as unresolved, as in Obsidian. Links to pages a filter removes (drafts, unpublished notes) are marked the same way, with `data-filtered="<filter>"`. Set `links.disableBrokenWikilinks: false` to style them as before.
- **Mermaid diagrams** render with [Pele](https://pele.run) by default, as in Obsidian, inside a `<div class="mermaid">` rather than a code block. Set `diagramRenderer: mermaid` on [[ObsidianFlavoredMarkdown]] to keep Mermaid.js. See [[Mermaid diagrams]].
- **Block wrappers**: each top-level block of a note is wrapped in the `div` Obsidian puts it in (`div.el-p > p`, `div.el-h2 > h2`). Custom CSS that selects a page's blocks as direct children (`article > p`) no longer matches. Select them without `>`, or set `blockWrappers: false` on ObsidianFlavoredMarkdown.
- **Transclusions** use Obsidian's embed markup: the title of a whole-note embed is a `div.markdown-embed-title` (it was an `h1`), and the content is in `div.markdown-embed-content`. It looks the same without a theme. Custom CSS for transclusions may need new selectors.
- **Page structure**: the centre column is a `<main>` (it was a `div`; the `center` class is unchanged) and the default frame's sidebars are `<aside>` elements. Page listings use `h2` titles (they were `h3`) at the same size. Footnote links keep the `internal` class but no longer have `internal-link`.
- **Colours**: the templates' `gray` and `tertiary` colours meet WCAG AA contrast. Your site keeps the colours in its own `quartz.config.yaml`. To adopt the new ones, set them under `configuration.theme.colors`:
```yaml title="quartz.config.yaml"
configuration:
theme:
colors:
lightMode:
gray: "#727272" # was #b8b8b8
tertiary: "#587971" # was #84a59d
darkMode:
gray: "#7f7f7f" # was #646464
```
- **Folding**: the `obsidian` template folds headings and lists. Other sites can turn it on with `foldHeadings` and `foldLists` on ObsidianFlavoredMarkdown.
- **Stylesheets**: component styles are one `component-<hash>.css` file instead of one per component. The styles are unchanged.
- **Frontmatter** is read as YAML 1.2. Frontmatter with only comments has no properties, as in Obsidian, instead of being reported as invalid.
- **Custom TypeScript**: type checking (`npm run check`) uses TypeScript 7 with `moduleResolution: bundler`. Code that imports a package's internal files may need to import from the package itself.
### New options
- `extends` (experimental) and `before`/`after` on plugin entries. See [[configuration#Extending the default configuration]].
- `configuration.slugs.stripDiacritics`. See [[configuration#General Configuration]].
- The layout conditions `is-index`, `is-folder-index` and `not-<condition>`. See [[layout#Conditional Rendering]].
- [[plugins/Explorer|Explorer]]: `sort`, `rootFolder`, and `order` in YAML. [[GitHubFlavoredMarkdown]]: `singleTilde`, `replacements`. [[ObsidianFlavoredMarkdown]]: `math`, `markdownEmbeds`, `blockWrappers`, `foldHeadings`, `foldLists`. [[CanvasPage]]: `wheelBehavior`, `textNodeMarkdown`.
See [[whats-new#New in 5.3|What's new in 5.3]] for everything else.
## Upgrading from 5.1 to 5.2
```bash
npx quartz upgrade
npx quartz plugin doctor --fix
```
`--fix` moves the Fonts plugin's entry (`@quartz-community/quartz-fonts`) into `configuration.fonts`, now that font loading is built in. Until you run it, the entry keeps working and is applied automatically.
### Changes you may notice
- **Themes**: [[ThemesCore]] 3 converts Obsidian themes at build time, so the `@quartz-themes/<theme>` packages are no longer needed. Theme ids from 2.x (`tokyo-night`) keep working. The `aspects`, `include`, `calloutStyle` and `fonts` options were removed.
- **Callouts and transclusions** render as `<div>` elements, as in Obsidian (callouts were `<blockquote>`). Callout titles are in `.callout-title-inner` without a `<p>`. Custom CSS for either may need new selectors.
- **Bases** columns are labelled with the property's name (`priority`, `file name`) instead of title case (`Priority`, `Name`). Set `propertyLabels: title` on [[BasesPage]] for the old labels.
- **Permalinks** with `.` or `..` segments are ignored with a warning.
- **Fonts**: configured `body`, `code` and `interface` fonts now apply under an Obsidian theme, and the interface and heading fonts are loaded from Google Fonts like the others.
See [[whats-new#New in 5.2|What's new in 5.2]] for everything else.
## Upgrading from 5.0 to 5.1
Run the upgrade, then let `plugin doctor` update your config:
+30
View File
@@ -7,6 +7,36 @@ aliases:
Quartz 5 is a ground-up rearchitecture of Quartz focused on extensibility, performance, and Obsidian compatibility. If you're coming from v4, see [[migrating|Migrating to Quartz 5]] for the upgrade path.
## New in 5.3
Upgrading from 5.2? See [[upgrading#Upgrading from 5.2 to 5.3|Upgrading from 5.2 to 5.3]] for the changes you may notice.
- **Accessibility** — the templates' colours meet WCAG AA contrast, and so does text in the table of contents, footer, folder and tag listings, search button and Bases group headings. The centre column is a `<main>` and the sidebars are `<aside>` elements, page listings no longer skip heading levels, and ARIA attributes and ids are valid in the table of contents, explorer, backlinks, heading anchors and Bases views.
- **Faster pages** — component styles are one stylesheet (about 20 fewer render-blocking requests per page), the [[graph view]] loads d3 and PixiJS only when it is shown and opens five times faster on large sites, and KaTeX's stylesheet no longer blocks pages without math.
- **Back and Forward** — with [[SPA Routing]], Back and Forward return to where you were on each page, and moving between headings of the same page only scrolls.
- **Markup as in Obsidian** — [[ObsidianFlavoredMarkdown]] wraps each top-level block in Obsidian's `div.el-*` wrappers, renders [[Mermaid diagrams]] with Pele by default, and can fold headings and lists (`foldHeadings`, `foldLists`; on in the `obsidian` template). Transclusions use Obsidian's embed markup, a missing attachment reads "could not be found", and notes embedded with a Markdown link (`![](note.md#Section)`) are transcluded. Obsidian themes ([[ThemesCore]] 3.2) style all of these.
- **Unresolved links** — links to pages that don't exist, or that a filter removed (drafts, [[ExplicitPublish]]), get the `broken` class, as Obsidian marks unresolved links (`links.disableBrokenWikilinks` is on by default). See [[CrawlLinks]].
- **Extending a configuration** (experimental) — `extends: default` in `quartz.config.yaml` keeps only your changes to the default configuration; it also takes a path or an `https://` URL. Several presets can be listed and stack. Plugin entries can declare `before:` / `after:` other plugins. See [[configuration#Extending the default configuration]].
- **Slugs without accents** — `configuration.slugs.stripDiacritics` publishes `české/čeština.md` at `/ceske/cestina` and `Łódź.md` at `/lodz`, so URLs in Latin-script languages need no percent-encoding; other scripts are left as written. See [[configuration#General Configuration]].
- **Layout conditions** — `is-index` (home page), `is-folder-index`, and `not-<condition>` for any condition (`not-has-tags`). See [[layout#Conditional Rendering]].
- **Explorer** 1.2 — sort from YAML with rules applied in sequence (`sort: [folder, { by: date, direction: desc }]`), several explorers on a page (`rootFolder`), and `order` in YAML. See [[plugins/Explorer|Explorer]].
- **Plugin options** — [[GitHubFlavoredMarkdown]]: `singleTilde` and `replacements` (for example Quartz 4's arrows); [[ObsidianFlavoredMarkdown]]: `math`; [[CanvasPage]]: the wheel and trackpad pan the canvas as in Obsidian, and text nodes render with the site's Markdown plugins (Mermaid, callouts, math).
- **Link previews and search engines** — each page has a canonical link, and `og:url`, `og:type` and the article times are set as Open Graph readers expect.
- **Content index** — `contentIndex.json` entries carry the page's `date`, for client-side components such as the explorer.
- **Releases** — release tags are verified on GitHub, and each release publishes a versioned Docker image.
## New in 5.2
Upgrading from 5.1? See [[upgrading#Upgrading from 5.1 to 5.2|Upgrading from 5.1 to 5.2]].
- **Obsidian themes** — [[ThemesCore]] 3.1 converts any Obsidian community theme at build time: name it as Obsidian lists it (`Minimal`, `AnuPpuccin`), or give a GitHub repository, a URL or a local `theme.css`. Style Settings exports and CSS snippets apply as in Obsidian.
- **Fonts built in** — font loading is part of Quartz as `configuration.fonts` (formerly the Fonts plugin), including the interface font and per-heading fonts. See [[configuration#Fonts]].
- **`quartz build --config <path>`** — read the configuration from another file, so it can live with your content and one Quartz install can build several sites.
- **Bases** closer to Obsidian ([[BasesPage]] 1.5) — custom summaries, `html()`, `image()`, `icon()`, regular expressions and `file.backlinks` in formulas, `kanban` views, `groupOrder`, grouped lists and cards, and columns labelled with the property's name. Bases inside a transcluded note render, and links in bases follow `configuration.links`.
- **Transclusions** — headings and footnotes inside a transclusion get ids unique on the page, and a heading transclusion holds only the footnotes it references.
- **Permalinks on large sites** — notes with a `permalink` are published at it on sites of any size.
- **Plugins** can be async and declare `renderTransforms`, so encrypted notes show their bases and transclusions once unlocked ([[EncryptedPages]]).
## New in 5.1
Upgrading from 5.0? See [[upgrading#Upgrading from 5.0 to 5.1|Upgrading from 5.0 to 5.1]] for the steps and the changes you may notice.
+3 -1
View File
@@ -21,6 +21,8 @@ This plugin accepts the following configuration options:
- `initialZoom`: The initial zoom level when the canvas is first displayed. Default: `1{:ts}`.
- `minZoom`: The minimum zoom level allowed when zooming out. Default: `0.1{:ts}`.
- `maxZoom`: The maximum zoom level allowed when zooming in. Default: `5{:ts}`.
- `wheelBehavior`: What the mouse wheel and two-finger trackpad scroll do. `"pan"` (default) moves the canvas, as in Obsidian (Shift + wheel: sideways); Ctrl/Cmd + wheel and pinching zoom. `"zoom"`: the wheel always zooms.
- `textNodeMarkdown`: How text nodes are rendered. `"site"` (default): with the site's own Markdown plugins, like a note. `"basic"`: plain CommonMark + GFM, with wikilinks and links to notes still resolved.
### Canvas Frame
@@ -43,7 +45,7 @@ layout:
### Features
- **Text nodes**: Render Markdown content including headings, bold, italic, strikethrough, lists, links, and code blocks via [GFM](https://github.github.com/gfm/) support.
- **Text nodes**: Rendered with the site's own Markdown plugins, like a note, as in Obsidian: wikilinks, callouts, [[Mermaid diagrams]], math, syntax highlighting and embedded notes (`![[Note#Section]]`). Tags in text nodes count as the canvas's tags, so they get tag pages.
- **File nodes**: Link to other pages in your vault. Supports popover previews on hover.
- **Link nodes**: Reference external URLs.
- **Group nodes**: Visual grouping containers with optional labels and background colors.
+5 -3
View File
@@ -26,15 +26,17 @@ This plugin accepts the following configuration options:
- `folderClickBehavior`: The behavior when a folder is clicked. Can be `"link"` to navigate or `"collapse"` to toggle. Defaults to `link`.
- `folderDefaultState`: The default state of folders. Can be `"collapsed"` or `"open"`. Defaults to `collapsed`.
- `useSavedState`: Whether to use local storage to save the state of the explorer. Defaults to `true`.
- `sort`: Sort rules, applied in sequence: entries the first rule considers equal are sorted by the next one. Defaults to `[folder, title]` (folders first, then by title). See [[features/explorer#Sorting]].
- `rootFolder`: Show only this folder's contents, e.g. `Notes` or `Notes/Daily Notes`. Defaults to everything. See [[features/explorer#Several explorers]].
- `order`: The order in which `filterFn`, `mapFn` and `sortFn` run. Defaults to `[filter, map, sort]`.
**TS override options** (in `quartz.ts`, for callback functions that can't be expressed in YAML):
- `sortFn`: Custom sort function for ordering files and folders.
- `sortFn`: Custom sort function for ordering files and folders. Replaces `sort`.
- `filterFn`: Custom filter function to exclude specific nodes.
- `mapFn`: Custom map function to transform node properties (e.g. display names).
- `order`: Array controlling the order of operations. Defaults to `["filter", "map", "sort"]`.
By default the explorer hides the `tags` folder (`filterFn`) and sorts folders before files, then alphabetically with numeric ordering (`sortFn`).
By default the explorer hides the `tags` folder (`filterFn`) and sorts folders before files, then by title in natural order (`Note 2` before `Note 10`).
### Default options
+25
View File
@@ -20,6 +20,8 @@ This plugin accepts the following configuration options:
- `enableSmartyPants`: When true, enables typographic enhancements. Default is true.
- `linkHeadings`: When true, gives headings their `id`s and adds a link to each heading. Default is true. Setting it to `false` also turns off heading ids, so links to headings (`[[page#Heading]]`) and section embeds no longer reach them (on pages with a [[table of contents]], TableOfContents still gives headings ids).
- `singleTilde`: When true (default), text between single tildes (`~text~`) is struck through, as on GitHub. `false` strikes only `~~text~~`, as Obsidian does, so a `~` meaning "about" (`~20 W and (~€120)`) stays as written. Under [[ObsidianFlavoredMarkdown]]'s default `legacy` preset, which parses as Obsidian, single tildes never strike.
- `replacements`: Text to replace as written, outside code and math, before SmartyPants; the longest match wins. Empty by default: neither GitHub nor Obsidian replaces anything. See [[#Arrows]].
### Default options
@@ -29,11 +31,34 @@ This plugin accepts the following configuration options:
options:
enableSmartyPants: true
linkHeadings: true
singleTilde: true
replacements: {}
order: 30
```
This plugin must run before [[ObsidianFlavoredMarkdown]] (order `30` and `40` in the default config). If you set `order` on either plugin, keep this one first.
## Arrows
Quartz 4 turned typed arrows into arrow characters (`parseArrows`). Obsidian doesn't, so Quartz 5 leaves them as typed. To render them as Quartz 4 did:
```yaml title="quartz.config.yaml"
plugins:
- source: "@quartz-community/github-flavored-markdown"
options:
replacements:
"->": "→"
"-->": "⇒"
"=>": "⇒"
"==>": "⇒"
"<-": "←"
"<--": "⇐"
"<=": "⇐"
"<==": "⇐"
```
Text in code, inline code and math is left alone. Note that `<=` then also replaces a "less than or equal" written in prose.
## Heading ids
Heading ids are made from the heading as written, with the same slug function that links and the [[table of contents]] use, and match GitHub's:
+3 -1
View File
@@ -22,10 +22,11 @@ This plugin accepts the following configuration options:
- `strictLineBreaks`: Obsidian's "Strict line breaks" setting. `false` (the default under `preset: "legacy"`) renders a single line break inside a paragraph as a `<br>`, as in Obsidian's default reading view. `true` (the default under `preset: "strict"`) renders it as a space, as CommonMark does. This replaces the deprecated [[HardLineBreaks]] plugin.
- `comments`: If `true` (default), enables parsing of `%%` style Obsidian comment blocks.
- `highlight`: If `true` (default), enables parsing of `==` style highlights within content. A highlight that starts with a colour emoji (🔴 🟠 🟡 🟢 🔵 🟣, or the matching squares) is coloured as in Obsidian 1.14, e.g. `==🔴 urgent==`.
- `math`: If `true` (default), parses `$inline$` and `$$display$$` math. With `false`, dollar signs stay text (`cost of $2-$3`), for sites without math.
- `wikilinks`: If `true` (default), turns [[wikilinks]] into regular links.
- `callouts`: If `true` (default), adds support for [[callouts|callout]] blocks for emphasizing content.
- `mermaid`: If `true` (default), enables [[Mermaid diagrams|Mermaid diagram]] parsing within Markdown files.
- `diagramRenderer`: `"mermaid"` (default) or `"pele"`. Which engine draws Mermaid fences. [Pele](https://pele.run) is opt-in; Mermaid.js is deprecated.
- `diagramRenderer`: `"pele"` (default) or `"mermaid"`. Which engine draws Mermaid fences: [Pele](https://pele.run), as in Obsidian, or the deprecated Mermaid.js.
- `parseTags`: If `true` (default), parses and links tags within the content.
- `parseBlockReferences`: If `true` (default), handles block references, linking to specific content blocks.
- `enableInHtmlEmbed`: If `true`, allows embedding of content directly within HTML. Defaults to `false`.
@@ -34,6 +35,7 @@ This plugin accepts the following configuration options:
- `enableVideoEmbed`: If `true` (default), enables the embedding of video files.
- `enableCheckbox`: If `true`, adds support for interactive checkboxes in content, including custom task characters (e.g. `- [?]`, `- [!]`, `- [/]`). Defaults to `false`; the default `quartz.config.yaml` turns it on.
- `enableObsidianUri`: If `true` (default), marks `obsidian://` protocol links with a CSS class and data attribute for custom styling.
- `markdownEmbeds`: If `true` (default), a note, canvas or base embedded with a Markdown link (`![](note.md#Section)`, `![](note)`, `![alt](board.canvas)`, `![](projects.base)`) is transcluded like `![[note#Section]]`, as in Obsidian (which writes embeds this way when its `Use [[Wikilinks]]` setting is off), instead of shown as a broken image. The link resolves like any Markdown link, by `configuration.links.markdownLinkResolution`.
- `blockWrappers`: If `true` (default), wraps each top-level block in the `div` Obsidian puts it in (`div.el-p > p`), which Obsidian themes space blocks with. No visible change without a theme.
- `foldHeadings`: If `true`, headings fold as in Obsidian's reading view ("Fold heading"): an arrow before each heading, shown on hover, hides everything up to the next heading of the same or a higher level. Defaults to `false`.
- `foldLists`: If `true`, list items with a sublist fold as in Obsidian's reading view ("Fold indent"): an arrow before the item, shown on hover, hides its sublist. Defaults to `false`.
+116 -116
View File
@@ -1,12 +1,12 @@
{
"name": "@jackyzha0/quartz",
"version": "5.2.2",
"version": "5.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@jackyzha0/quartz",
"version": "5.2.2",
"version": "5.4.0",
"license": "MIT",
"dependencies": {
"@clack/prompts": "^1.8.0",
@@ -16,42 +16,42 @@
"@quartz-community/alias-redirects": "^1.0.3",
"@quartz-community/article-title": "^1.0.2",
"@quartz-community/backlinks": "^1.0.4",
"@quartz-community/bases-page": "^1.5.3",
"@quartz-community/breadcrumbs": "^1.0.4",
"@quartz-community/canvas-page": "^1.1.1",
"@quartz-community/bases-page": "^1.5.6",
"@quartz-community/breadcrumbs": "^1.0.6",
"@quartz-community/canvas-page": "^1.1.7",
"@quartz-community/citations": "^1.0.1",
"@quartz-community/cname": "^1.0.1",
"@quartz-community/comments": "^1.0.2",
"@quartz-community/comments": "^1.0.3",
"@quartz-community/content-meta": "^1.0.2",
"@quartz-community/content-page": "^1.0.3",
"@quartz-community/created-modified-date": "^1.0.4",
"@quartz-community/darkmode": "^1.0.2",
"@quartz-community/description": "^1.0.2",
"@quartz-community/encrypted-pages": "^1.2.0",
"@quartz-community/created-modified-date": "^1.0.5",
"@quartz-community/darkmode": "^1.0.3",
"@quartz-community/description": "^1.0.3",
"@quartz-community/encrypted-pages": "^1.3.1",
"@quartz-community/explicit-publish": "^1.2.0",
"@quartz-community/explorer": "^1.2.1",
"@quartz-community/explorer": "^1.2.5",
"@quartz-community/favicon": "^1.0.1",
"@quartz-community/folder-page": "^1.1.2",
"@quartz-community/folder-page": "^1.1.5",
"@quartz-community/footer": "^1.1.2",
"@quartz-community/github-flavored-markdown": "^2.2.0",
"@quartz-community/graph": "^1.0.7",
"@quartz-community/github-flavored-markdown": "^2.2.2",
"@quartz-community/graph": "^1.0.10",
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.1.1",
"@quartz-community/note-properties": "^1.2.1",
"@quartz-community/obsidian-flavored-markdown": "^2.5.1",
"@quartz-community/og-image": "^1.1.2",
"@quartz-community/ox-hugo": "^1.0.2",
"@quartz-community/latex": "^1.1.3",
"@quartz-community/note-properties": "^1.2.4",
"@quartz-community/obsidian-flavored-markdown": "^2.5.4",
"@quartz-community/og-image": "^1.2.0",
"@quartz-community/ox-hugo": "^1.0.4",
"@quartz-community/page-title": "^1.0.2",
"@quartz-community/reader-mode": "^1.0.2",
"@quartz-community/reader-mode": "^1.0.3",
"@quartz-community/recent-notes": "^1.0.3",
"@quartz-community/roam": "^1.1.0",
"@quartz-community/search": "^1.1.1",
"@quartz-community/search": "^1.1.5",
"@quartz-community/spacer": "^1.0.2",
"@quartz-community/stacked-pages": "^1.0.3",
"@quartz-community/syntax-highlighting": "^1.0.4",
"@quartz-community/table-of-contents": "^1.0.5",
"@quartz-community/stacked-pages": "^1.0.5",
"@quartz-community/syntax-highlighting": "^1.0.5",
"@quartz-community/table-of-contents": "^1.0.6",
"@quartz-community/tag-list": "^1.0.3",
"@quartz-community/tag-page": "^1.0.6",
"@quartz-community/tag-page": "^1.0.7",
"@quartz-community/unlisted-pages": "^1.2.0",
"@quartz-themes/core": "^3.2.1",
"ansi-truncate": "^1.4.0",
@@ -97,7 +97,7 @@
"devDependencies": {
"@changesets/cli": "^3.0.3",
"@quartz-community/types": "^1.3.1",
"@quartz-community/utils": "^1.3.1",
"@quartz-community/utils": "^1.3.4",
"@types/hast": "^3.0.4",
"@types/node": "^26.5.1",
"@types/pretty-time": "^1.1.5",
@@ -2330,14 +2330,14 @@
}
},
"node_modules/@quartz-community/bases-page": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/@quartz-community/bases-page/-/bases-page-1.5.3.tgz",
"integrity": "sha512-MfaehkZ4iBnan43HPTVHUARbUsnJqr3H/bxeJYRqSv+rOE+QBI48XGz+AkaXodaVYihlE9dTSo6TS9lGK0opEA==",
"version": "1.5.6",
"resolved": "https://registry.npmjs.org/@quartz-community/bases-page/-/bases-page-1.5.6.tgz",
"integrity": "sha512-ohlqctMKbxneePgYKMOImCHhmo798OCyD3WuNw7QyXyIY6t3HhodvTVrtpxinlWmI6ug/kELsTyEbgrgtzAZVA==",
"license": "MIT",
"dependencies": {
"@lucide/icons": "^1.70.0",
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.0"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2361,13 +2361,13 @@
}
},
"node_modules/@quartz-community/breadcrumbs": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@quartz-community/breadcrumbs/-/breadcrumbs-1.0.4.tgz",
"integrity": "sha512-nVmGBLRQ8jibp8ednTmzh+TwSLVYNYi/Fwn42AH7HVx5Df78piqRl0eiSkSPyIECR6NSXGnh4Yd7spR15DU1TA==",
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@quartz-community/breadcrumbs/-/breadcrumbs-1.0.6.tgz",
"integrity": "sha512-YkEdGAtoeO4NupgwbTLBh2ownp4ALjGCMAlDkPocY3v8k2E+VDRXKRlnuqALv/wvR++nAz64U3zBGoD686sW5g==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.0"
"@quartz-community/utils": "^1.3.1"
},
"engines": {
"node": ">=22",
@@ -2383,13 +2383,13 @@
}
},
"node_modules/@quartz-community/canvas-page": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@quartz-community/canvas-page/-/canvas-page-1.1.1.tgz",
"integrity": "sha512-iBeqAmcWGGe1dV87YJWNxvi8LYmEDeLMxT146JiW+n6e+kx3IuSLKKn0uL58fE7SGXUEQN0IwS59RAjWw2ttmA==",
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@quartz-community/canvas-page/-/canvas-page-1.1.7.tgz",
"integrity": "sha512-I2I5JqqJ6PGnnwq57KI27Z643o/yUrxl654uwV8m+hFPmaN1iG8OQD7597JDHYXrwWCKWnNi23Wy3HXFu0yPUg==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.0"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2443,9 +2443,9 @@
}
},
"node_modules/@quartz-community/comments": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@quartz-community/comments/-/comments-1.0.2.tgz",
"integrity": "sha512-cHFjN7yn7rxgDzEOboM5viYOk1ex4Y/gIfDqN/BLNlqhPaZIkl2dq7RcYmkeVAz9kAJqNSj+WPQdVpB/2PGIGw==",
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@quartz-community/comments/-/comments-1.0.3.tgz",
"integrity": "sha512-p4NMrXIBXuFXRd7OIVTkIE8Q8Zta7fjdESR4ozrAtWISiYp3JIIQGOZXxfaKho7PpkE6/9PFkeTA9ze6HSvuOA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -2513,9 +2513,9 @@
}
},
"node_modules/@quartz-community/created-modified-date": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@quartz-community/created-modified-date/-/created-modified-date-1.0.4.tgz",
"integrity": "sha512-NSl3p+yUQEhHAD67NDdVvs68U7gBv+DkVNMnMEvF6uwOojOXMY2vCHj7IKMwerKz9phD8+pzxB74Z13o3GYhyQ==",
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@quartz-community/created-modified-date/-/created-modified-date-1.0.5.tgz",
"integrity": "sha512-fey7GLifzrjf29D1mY0XVIPZRJoLH2ktkFXckhP9OmtWPlHn73vPeBdxmGtZUgH2txGpoZYY0/XvpmzREsWxCQ==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0"
@@ -2538,9 +2538,9 @@
}
},
"node_modules/@quartz-community/darkmode": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@quartz-community/darkmode/-/darkmode-1.0.2.tgz",
"integrity": "sha512-FCfR8bdg248Y1NJhN6TWVBENwFiJak3gwqmpof/GMeTXr6e76FPe2ggTTz66a+s9UQ/ZC3JKU9xpHQi0zcGhyQ==",
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@quartz-community/darkmode/-/darkmode-1.0.3.tgz",
"integrity": "sha512-KbhU+TInNMAr+eV8x/yR56piDWQbRjhX6YhWxx0BgFBcvS84LGLsgz+5EHpB34ybsTJvUjjoj9rPTGVlFIR/ww==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -2560,9 +2560,9 @@
}
},
"node_modules/@quartz-community/description": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@quartz-community/description/-/description-1.0.2.tgz",
"integrity": "sha512-Mb0VqNOqiY9UQLK0y7p2/LVJAUqH8ra3Pek0Gz8q35FxJXkv2RDyjNb49qMUM0dpIaLVUkv9GBuKxeoxbwt4Yg==",
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@quartz-community/description/-/description-1.0.3.tgz",
"integrity": "sha512-xfVkexOUFnGVMOyXZYins32KEAkKKn1Qt6ywUwRwXiibE1xz0sXU3Z4EE0vKfeR6RxGnLiM+EfgX6DTWLmKEpA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -2582,9 +2582,9 @@
}
},
"node_modules/@quartz-community/encrypted-pages": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@quartz-community/encrypted-pages/-/encrypted-pages-1.3.0.tgz",
"integrity": "sha512-V04420LqG90y+LsZ7e9cOhRdHg/uVKKq0trWxjACnBQaHD9pAw/ODBh2FuXvjvj8ZuzzelRD6sIVeS9vq2isLg==",
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@quartz-community/encrypted-pages/-/encrypted-pages-1.3.1.tgz",
"integrity": "sha512-BWgChS+Ni+VdGAENhTu7EDWoDRrj3/k/hMynEdIf5YpCE0cB0RvkNtYskys73BxMfO+TwmT9vpMBbpHenXa4iw==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -2621,13 +2621,13 @@
}
},
"node_modules/@quartz-community/explorer": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@quartz-community/explorer/-/explorer-1.2.1.tgz",
"integrity": "sha512-xw9gN+YB4J+GnUBIxNrwR/DulSgg4uN7Ya9dWS6SD6lLCHzegaZn0wbmrkDIJa0kjSzxWgcSVPkUSELB50T3RA==",
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/@quartz-community/explorer/-/explorer-1.2.5.tgz",
"integrity": "sha512-VXKEx1IcOmdiLThHBkL8kOr6K+ofzweedGd6GVQXi8FmCemo7OUzBAkdUVkhqSEBogS3pT/znGM0K7sEF+mHyg==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.0"
"@quartz-community/utils": "^1.3.1"
},
"engines": {
"node": ">=22",
@@ -2664,13 +2664,13 @@
}
},
"node_modules/@quartz-community/folder-page": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@quartz-community/folder-page/-/folder-page-1.1.2.tgz",
"integrity": "sha512-n/1ICi+8rDv9DPxNqSO/ncCWSrbH/kWV9pxaaXw7V4Z8MAGvmQWDaOCBfMsZacX1nw8tb0JY33KibWej+U66hA==",
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@quartz-community/folder-page/-/folder-page-1.1.5.tgz",
"integrity": "sha512-Uxlno9jMCDzlKbF5HkrvUDzg0zxqabUhIfANsfC1RlfSq6cNmuXUYwe45vhkEp/KDOM8bBcfuHKARO3OqABzGA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.0"
"@quartz-community/utils": "^1.3.1"
},
"engines": {
"node": ">=22",
@@ -2712,13 +2712,13 @@
}
},
"node_modules/@quartz-community/github-flavored-markdown": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@quartz-community/github-flavored-markdown/-/github-flavored-markdown-2.2.0.tgz",
"integrity": "sha512-0DIh1zIQtJNltl00W9eVbSBnIyRfRqfnKO8p3grp7sI5B9FSdpPPH5l8WC0LrlRKlVF7iYc6DaoS7A4m1OOTTg==",
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/@quartz-community/github-flavored-markdown/-/github-flavored-markdown-2.2.2.tgz",
"integrity": "sha512-JsSeydLs05VZj2jc2KT/5vse+zNGCDH92Ih8/yp5s6EUY+wwOmzSTPxT65Ey0LK/X/nclfkMu4S4Domd2RkwmA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.1.1"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2734,9 +2734,9 @@
}
},
"node_modules/@quartz-community/graph": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@quartz-community/graph/-/graph-1.0.7.tgz",
"integrity": "sha512-UEYxW5exKlAU5/P0Ixbf08iFxIoBzKRsFCJ4wCAcywGSNvW3uFnmhuSYin9ZQA1M3PUBnXxnMJR9JuP8x7F5yg==",
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/@quartz-community/graph/-/graph-1.0.10.tgz",
"integrity": "sha512-UkqWEI48wmxLQPS+HNW4Pm0GnuUpcn7IfZ3ufcg1S4/lVqrdrofj7SioXDm7djuwr/wsLPDsdC1YBCwct/Eu5w==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -2777,9 +2777,9 @@
}
},
"node_modules/@quartz-community/latex": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@quartz-community/latex/-/latex-1.1.1.tgz",
"integrity": "sha512-OzfgfgUCe7EQi5rxLMAaO8KINUf5TBLo19eE/0KZiPR0OYUgYTkPpqdzNhY2r++dqV7CvAN0lNG+V0TULncG4g==",
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@quartz-community/latex/-/latex-1.1.3.tgz",
"integrity": "sha512-7692k+HBHmWwYhONTA5BMZOOCsVxubuirsBTk9ySh+0SgTcUxpYX9lXaaX32wO6Kxs0NX4XBsHdVLPdYjHt2Mw==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0"
@@ -2802,13 +2802,13 @@
}
},
"node_modules/@quartz-community/note-properties": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.2.1.tgz",
"integrity": "sha512-xwJoztzc6G1pUHXBfNwBIu548bi5XjbKYOM+zqn1DkonFNY9SiuS+Tz5BI+G75ndBtcmZ7aXuuiaTob5RNQUpw==",
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.2.4.tgz",
"integrity": "sha512-ZFShM1V+zwoHI6q3OHkgwfTLtoQGRiWkCLYjQZQFyxKMMKZJt/YAacwA+fSk75Uc0jnn0oQTJjWNeewvez4fHw==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.3.0"
"@quartz-community/utils": "^1.3.2"
},
"engines": {
"node": ">=22",
@@ -2828,15 +2828,15 @@
}
},
"node_modules/@quartz-community/obsidian-flavored-markdown": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.5.1.tgz",
"integrity": "sha512-VYsj6876bhH3ufqXQ+/4hlgUkFaV76IjVRH9SJHyOqDE4iq4TELHL7TrYpzg9m1lVyq8GQE1hyIG5q0GshDjPg==",
"version": "2.5.4",
"resolved": "https://registry.npmjs.org/@quartz-community/obsidian-flavored-markdown/-/obsidian-flavored-markdown-2.5.4.tgz",
"integrity": "sha512-TxSDvn3FTGa0FvEEoIA+CVQmqCrLhAWxQmhkBevjUEaAYPaW8xUU8lLm36Cb14Baoze6JnbDJ9csMHr6k/D5Vw==",
"license": "MIT",
"dependencies": {
"@quartz-community/rehype-obsidian": "^1.5.0",
"@quartz-community/remark-obsidian": "^2.2.1",
"@quartz-community/rehype-obsidian": "^1.6.0",
"@quartz-community/remark-obsidian": "^2.2.4",
"@quartz-community/types": "^1.1.0",
"@quartz-community/utils": "^1.3.0",
"@quartz-community/utils": "^1.3.2",
"pele": "^1.13.0"
},
"engines": {
@@ -2853,13 +2853,13 @@
}
},
"node_modules/@quartz-community/og-image": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@quartz-community/og-image/-/og-image-1.1.2.tgz",
"integrity": "sha512-cPIK5zrUJn6mCcesuQ0M6zklxbm4sIZnV9fSiGHuTStT7rcBvlPBUpIhGfa2ZYqjjQptqC+hKw6CUBrwdCeAsw==",
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@quartz-community/og-image/-/og-image-1.2.0.tgz",
"integrity": "sha512-fVvrOwog7QTGf7X0iNPFAmM5nRvK4Mdh9XQqpE8PDQ3X9fbHcnCq++H1H+a0xXjiB1BADKuT2146pjNmOkPEaw==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.1.0"
"@quartz-community/utils": "^1.3.1"
},
"engines": {
"node": ">=22",
@@ -2883,9 +2883,9 @@
}
},
"node_modules/@quartz-community/ox-hugo": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@quartz-community/ox-hugo/-/ox-hugo-1.0.2.tgz",
"integrity": "sha512-3e2bUZqUquxrOuHTn7w5gFK1Lm1TB7lcnTYWmjvntVGWZ360yRSC/ksfYu65FHeSoAgWZAySFG/DXVpzyB4aLg==",
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@quartz-community/ox-hugo/-/ox-hugo-1.0.4.tgz",
"integrity": "sha512-ptVP2qxdW4/BdVl20S+kfsRT1SyjcYGfICNqNJ4GLbVkE9gXWhS2QR8KZ7vXmwQ60XV5B23oYEnqH0zkz5ViFg==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0"
@@ -2926,9 +2926,9 @@
}
},
"node_modules/@quartz-community/reader-mode": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@quartz-community/reader-mode/-/reader-mode-1.0.2.tgz",
"integrity": "sha512-Mm7llTF6erRk9ASrkcfYIKApfFf/yrBiYsPs+P8vx8qXaVziem/4e2G6wnT2EQQFUuYSSKklZ328V7rfN6fRRg==",
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@quartz-community/reader-mode/-/reader-mode-1.0.3.tgz",
"integrity": "sha512-rlLFcmyIp6iYLIMajQtO11OpkRj7RofrQD3DBLRn2rNzl3ySe8pfU0WpvoyRRK/clD2/lGtwrTNJa76WG6K0Vg==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -2970,18 +2970,18 @@
}
},
"node_modules/@quartz-community/rehype-obsidian": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/@quartz-community/rehype-obsidian/-/rehype-obsidian-1.5.1.tgz",
"integrity": "sha512-PvU1JCyAndgbkjPeFaPs1r/FnijtTFTDetn9F8mUBRGB9zEDEGIHqpo+/LZvQQUP46eCbRUXkz2RVc72g0V/UQ==",
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/@quartz-community/rehype-obsidian/-/rehype-obsidian-1.6.1.tgz",
"integrity": "sha512-+YlDMPBjCUbuIvbxrDvipXXTuRjrFaL9QYrwkxRgong7HsAzTqu0XSl43ih3/GgxR8xKNECThVxJiMlmdvUXUw==",
"license": "MIT",
"engines": {
"node": ">=22"
}
},
"node_modules/@quartz-community/remark-obsidian": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/@quartz-community/remark-obsidian/-/remark-obsidian-2.2.3.tgz",
"integrity": "sha512-+EOhBhczcQF4tRDhiOaomsASYm+3lTC1hOf7K3KwZ6MEabvnlQIyGS47Ej2ulkV3C5eDkJ2eow3QqYg6o/BqAQ==",
"version": "2.2.6",
"resolved": "https://registry.npmjs.org/@quartz-community/remark-obsidian/-/remark-obsidian-2.2.6.tgz",
"integrity": "sha512-hDxyFiA5SYIcsO1i3vnlMQEryoev2RtFy9UZ9MGNfANxiWypxCG/uWUjA+uiISMJgHSRk/CpWcn7lTGGvMVT3A==",
"license": "MIT",
"dependencies": {
"@types/mdast": "^4.0.0",
@@ -3019,13 +3019,13 @@
}
},
"node_modules/@quartz-community/search": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@quartz-community/search/-/search-1.1.1.tgz",
"integrity": "sha512-e+U6Vby15h2pbXuh8qXE1uGIeQIbE1QvqHEdOIm/Gp9E4HDdNZE2Ih/ifotmEVxGe3Q5XuQ1yQLa1mjwJ4zmcg==",
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@quartz-community/search/-/search-1.1.5.tgz",
"integrity": "sha512-9qgJsfOlqBPP41ICDOmmHOYiJbjlIMYm6EduvjS4t32YWglRJpO5l0Dle6A8VYmt7PW6qrAkh2EU7TvwCUU2Aw==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
"@quartz-community/utils": "^1.1.0"
"@quartz-community/utils": "^1.3.1"
},
"engines": {
"node": ">=22",
@@ -3062,9 +3062,9 @@
}
},
"node_modules/@quartz-community/stacked-pages": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@quartz-community/stacked-pages/-/stacked-pages-1.0.3.tgz",
"integrity": "sha512-wdILZkQpYL9k490iXzNRkWtrDyRBxCfs+rqz3JUWPyMAq3ztlyH0UtDoyB+zDUN9XryPqmTf0b3rtiKlQLiJFg==",
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@quartz-community/stacked-pages/-/stacked-pages-1.0.5.tgz",
"integrity": "sha512-sUDlcgREgWyttDg4A6Xp6i3s0jjLzO0g/pvP2a5KSYfNtsN9djbvwaPaewV9e/dn92VyTWrKsXd7K05yTCcFQw==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -3088,9 +3088,9 @@
}
},
"node_modules/@quartz-community/syntax-highlighting": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@quartz-community/syntax-highlighting/-/syntax-highlighting-1.0.4.tgz",
"integrity": "sha512-4qCnsPGyEImFPPgyH9J4w5Y8NCG9gV8ra1UV6/mQJHXLN6m0i1KewwpV9hyEqNlgPJ0TyDJh04XVGcY1t3Ts6A==",
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@quartz-community/syntax-highlighting/-/syntax-highlighting-1.0.5.tgz",
"integrity": "sha512-u9yzkNK5NefFaFMp+tOOEaVs/NxmfR2HLXbmkXt4HHwztfGPue1gi8ZUixeY6NSjGWBFx/i+RofpCcrhDycFjg==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0"
@@ -3113,9 +3113,9 @@
}
},
"node_modules/@quartz-community/table-of-contents": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@quartz-community/table-of-contents/-/table-of-contents-1.0.5.tgz",
"integrity": "sha512-sz7SqYgn+bCAp6evvPSXLNGmC93XZZB+Dt7TUZEHN6Kgnct0QCo32NFsjm7B3Bah0JuMyJ/oCrX47zvO6q99wg==",
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@quartz-community/table-of-contents/-/table-of-contents-1.0.6.tgz",
"integrity": "sha512-8pc8lpOY4Awqiso16cSqqIrXy9kXy+n56uajFbtm7IHzZvXNsdh5JnXsowVUaJBONMnAu20ASFDGwVub5PUQGQ==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -3157,9 +3157,9 @@
}
},
"node_modules/@quartz-community/tag-page": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@quartz-community/tag-page/-/tag-page-1.0.6.tgz",
"integrity": "sha512-tgs7i/og667hBuHJbcE4xLGEgIpi7pAaoVrrQMFLmXBApeqsBPP5Btn90KspBfFlw/GKV4IKnxJaf4ILROyMlQ==",
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@quartz-community/tag-page/-/tag-page-1.0.7.tgz",
"integrity": "sha512-dx3+gETz5AIGWWMbzOqy34XRPNANeKw0p5u7Igj0DCwBaGyKLucjzlz+giTNn+HbincdnFwH71cb3nar/wTzNA==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -3230,9 +3230,9 @@
}
},
"node_modules/@quartz-community/utils": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.1.tgz",
"integrity": "sha512-HGlcmwzt+nzu77sVfERtGFgw9CqO0/sApDX4RBM4pJZOxBDFKOL+5aKOw3TlHUW+57GJeDO1QM464foXbp+VWQ==",
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.4.tgz",
"integrity": "sha512-S1zlszf1jcHXcWXnlow/VxW3kKlTEWWNGQmWP07b8vAOB8lAIkeYRR5KoUA0TdjZPgN5dRaFHaAhv6sC2g/4Gw==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0"
+25 -25
View File
@@ -2,7 +2,7 @@
"name": "@jackyzha0/quartz",
"description": "🌱 publish your digital garden and notes as a website",
"private": true,
"version": "5.2.2",
"version": "5.4.0",
"type": "module",
"author": "jackyzha0 <j.zhao2k19@gmail.com>",
"license": "MIT",
@@ -46,42 +46,42 @@
"@quartz-community/alias-redirects": "^1.0.3",
"@quartz-community/article-title": "^1.0.2",
"@quartz-community/backlinks": "^1.0.4",
"@quartz-community/bases-page": "^1.5.3",
"@quartz-community/breadcrumbs": "^1.0.4",
"@quartz-community/canvas-page": "^1.1.1",
"@quartz-community/bases-page": "^1.5.6",
"@quartz-community/breadcrumbs": "^1.0.6",
"@quartz-community/canvas-page": "^1.1.7",
"@quartz-community/citations": "^1.0.1",
"@quartz-community/cname": "^1.0.1",
"@quartz-community/comments": "^1.0.2",
"@quartz-community/comments": "^1.0.3",
"@quartz-community/content-meta": "^1.0.2",
"@quartz-community/content-page": "^1.0.3",
"@quartz-community/created-modified-date": "^1.0.4",
"@quartz-community/darkmode": "^1.0.2",
"@quartz-community/description": "^1.0.2",
"@quartz-community/encrypted-pages": "^1.2.0",
"@quartz-community/created-modified-date": "^1.0.5",
"@quartz-community/darkmode": "^1.0.3",
"@quartz-community/description": "^1.0.3",
"@quartz-community/encrypted-pages": "^1.3.1",
"@quartz-community/explicit-publish": "^1.2.0",
"@quartz-community/explorer": "^1.2.1",
"@quartz-community/explorer": "^1.2.5",
"@quartz-community/favicon": "^1.0.1",
"@quartz-community/folder-page": "^1.1.2",
"@quartz-community/folder-page": "^1.1.5",
"@quartz-community/footer": "^1.1.2",
"@quartz-community/github-flavored-markdown": "^2.2.0",
"@quartz-community/graph": "^1.0.7",
"@quartz-community/github-flavored-markdown": "^2.2.2",
"@quartz-community/graph": "^1.0.10",
"@quartz-community/hard-line-breaks": "^1.1.0",
"@quartz-community/latex": "^1.1.1",
"@quartz-community/note-properties": "^1.2.1",
"@quartz-community/obsidian-flavored-markdown": "^2.5.1",
"@quartz-community/og-image": "^1.1.2",
"@quartz-community/ox-hugo": "^1.0.2",
"@quartz-community/latex": "^1.1.3",
"@quartz-community/note-properties": "^1.2.4",
"@quartz-community/obsidian-flavored-markdown": "^2.5.4",
"@quartz-community/og-image": "^1.2.0",
"@quartz-community/ox-hugo": "^1.0.4",
"@quartz-community/page-title": "^1.0.2",
"@quartz-community/reader-mode": "^1.0.2",
"@quartz-community/reader-mode": "^1.0.3",
"@quartz-community/recent-notes": "^1.0.3",
"@quartz-community/roam": "^1.1.0",
"@quartz-community/search": "^1.1.1",
"@quartz-community/search": "^1.1.5",
"@quartz-community/spacer": "^1.0.2",
"@quartz-community/stacked-pages": "^1.0.3",
"@quartz-community/syntax-highlighting": "^1.0.4",
"@quartz-community/table-of-contents": "^1.0.5",
"@quartz-community/stacked-pages": "^1.0.5",
"@quartz-community/syntax-highlighting": "^1.0.5",
"@quartz-community/table-of-contents": "^1.0.6",
"@quartz-community/tag-list": "^1.0.3",
"@quartz-community/tag-page": "^1.0.6",
"@quartz-community/tag-page": "^1.0.7",
"@quartz-community/unlisted-pages": "^1.2.0",
"@quartz-themes/core": "^3.2.1",
"ansi-truncate": "^1.4.0",
@@ -124,7 +124,7 @@
"devDependencies": {
"@changesets/cli": "^3.0.3",
"@quartz-community/types": "^1.3.1",
"@quartz-community/utils": "^1.3.1",
"@quartz-community/utils": "^1.3.4",
"@types/hast": "^3.0.4",
"@types/node": "^26.5.1",
"@types/pretty-time": "^1.1.5",
+31
View File
@@ -7,6 +7,8 @@ if (major < 22 || (major === 22 && minor < 22)) {
)
process.exit(1)
}
import { existsSync } from "fs"
import { resolve } from "path"
import yargs from "yargs"
import { hideBin } from "yargs/helpers"
import {
@@ -121,6 +123,24 @@ yargs(hideBin(process.argv))
(yargs) => {
return (
yargs
// like `build --config`: plugin commands read and write that config, and the
// quartz.lock.json next to it (cli/lockfile-path.js)
.option("config", {
string: true,
alias: ["C"],
global: true,
describe:
"path to the config file (default: ./quartz.config.yaml); quartz.lock.json is next to it",
})
.middleware((argv) => {
if (!argv.config) return
const resolved = resolve(argv.config)
if (!existsSync(resolved)) {
console.error(`Config file not found: ${resolved}`)
process.exit(1)
}
process.env.QUARTZ_CONFIG_PATH = resolved
})
.command(
"install [names..]",
"Install plugins from lockfile or config",
@@ -335,6 +355,17 @@ yargs(hideBin(process.argv))
},
)
.showHelpOnFail(true)
.fail((msg, err, y) => {
// A mistake in quartz.config.yaml (an `extends` error names the file and the key): the
// message says what to fix, so print it without the usage text, which is about arguments.
if (err?.name === "ConfigExtendsError") {
console.error(`✗ ${err.message}`)
process.exit(1)
}
y.showHelp()
console.error(err ?? msg)
process.exit(1)
})
.help()
.strict()
.demandCommand().argv
+6 -3
View File
@@ -27,7 +27,7 @@ import { formatLayoutReport, getLayoutReport } from "./plugins/loader/layoutRepo
import { getBuiltinPlan } from "./plugins/loader/config-loader"
import { prepareContentIndex } from "./plugins/builtins/contentIndex"
import { filteredBy, printDiagnosticsSummary, warn } from "./util/diagnostics"
import { LinksInstance, markLinksToRemovedPages } from "./plugins/builtins/links"
import { LinksInstance, removedPages } from "./plugins/builtins/links"
import { collectPermalinks } from "./util/permalinks"
import { readFrontmatterData } from "./plugins/builtins/frontmatter"
import { ChangeRecord, clearChangeRecord } from "./util/incremental"
@@ -67,7 +67,10 @@ function updateSlugs(ctx: BuildCtx, allFiles: string[]): void {
ctx.allSlugs = [...new Set([...pathSlugs, ...Object.values(ctx.permalinks)])]
}
/** Mark links to pages the filters removed as broken (built-in links, crawl-links#7). */
/**
* Record the pages the filters removed, so PageTypeDispatcher marks links to them as broken
* (built-in links, crawl-links#7) once it knows which folder and tag pages are generated.
*/
function markRemovedLinks(
ctx: BuildCtx,
all: ProcessedContent[],
@@ -76,7 +79,7 @@ function markRemovedLinks(
const links = ctx.cfg.plugins.transformers.find((t) => t.name === "Links") as
LinksInstance | undefined
// also when nothing was removed: in watch mode, marks from the last build may need undoing
if (links?.marksBrokenLinks) markLinksToRemovedPages(all, published, filteredBy)
ctx.removedPages = links?.marksBrokenLinks ? removedPages(all, published, filteredBy) : undefined
}
function reportSlugCollisions(content: ProcessedContent[]): void {
+3
View File
@@ -0,0 +1,3 @@
export const LOCKFILE_NAME: string
export function resolveLockfilePath(configPath: string, cwd?: string): string
export function currentLockfilePath(cwd?: string): string
+29
View File
@@ -0,0 +1,29 @@
import fs from "fs"
import path from "path"
export const LOCKFILE_NAME = "quartz.lock.json"
/**
* Where quartz.lock.json is: next to the config file Quartz uses (`--config` / `-C`, or
* QUARTZ_CONFIG_PATH), so a repository that holds only a site's content, config and lockfile
* (such as one the GitHub Action builds) keeps its pins with its config.
*
* With the config in Quartz's own folder (the usual setup) that is Quartz's folder, as before.
* A config elsewhere whose folder has no lockfile yet keeps using an existing one in Quartz's
* folder (`cwd`), so setups from before this change still find their pins.
*/
export function resolveLockfilePath(configPath, cwd = process.cwd()) {
const besideConfig = path.join(path.dirname(path.resolve(configPath)), LOCKFILE_NAME)
const inQuartz = path.join(cwd, LOCKFILE_NAME)
if (besideConfig !== inQuartz && !fs.existsSync(besideConfig) && fs.existsSync(inQuartz)) {
return inQuartz
}
return besideConfig
}
/** The lockfile for the config this process uses: QUARTZ_CONFIG_PATH's, else Quartz's folder. */
export function currentLockfilePath(cwd = process.cwd()) {
return process.env.QUARTZ_CONFIG_PATH
? resolveLockfilePath(process.env.QUARTZ_CONFIG_PATH, cwd)
: path.join(cwd, LOCKFILE_NAME)
}
+50
View File
@@ -0,0 +1,50 @@
import test, { describe, afterEach } from "node:test"
import assert from "node:assert"
import fs from "fs"
import os from "os"
import path from "path"
import { currentLockfilePath, resolveLockfilePath } from "./lockfile-path.js"
describe("resolveLockfilePath", () => {
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "quartz-lockfile-path-"))
test("the lockfile is next to the config", () => {
const quartz = tmp()
const site = tmp()
assert.strictEqual(
resolveLockfilePath(path.join(site, "quartz.config.yaml"), quartz),
path.join(site, "quartz.lock.json"),
)
// the usual setup: the config in Quartz's folder
assert.strictEqual(
resolveLockfilePath(path.join(quartz, "quartz.config.yaml"), quartz),
path.join(quartz, "quartz.lock.json"),
)
})
test("an existing lockfile in Quartz's folder is kept until the config's folder has one", () => {
const quartz = tmp()
const site = tmp()
fs.writeFileSync(path.join(quartz, "quartz.lock.json"), "{}")
const config = path.join(site, "quartz.config.yaml")
assert.strictEqual(resolveLockfilePath(config, quartz), path.join(quartz, "quartz.lock.json"))
fs.writeFileSync(path.join(site, "quartz.lock.json"), "{}")
assert.strictEqual(resolveLockfilePath(config, quartz), path.join(site, "quartz.lock.json"))
})
})
describe("currentLockfilePath", () => {
const saved = process.env.QUARTZ_CONFIG_PATH
afterEach(() => {
if (saved === undefined) delete process.env.QUARTZ_CONFIG_PATH
else process.env.QUARTZ_CONFIG_PATH = saved
})
test("follows QUARTZ_CONFIG_PATH, else Quartz's folder", () => {
const site = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-lockfile-current-"))
delete process.env.QUARTZ_CONFIG_PATH
assert.strictEqual(currentLockfilePath("/q"), path.join("/q", "quartz.lock.json"))
process.env.QUARTZ_CONFIG_PATH = path.join(site, "quartz.config.yaml")
assert.strictEqual(currentLockfilePath("/q"), path.join(site, "quartz.lock.json"))
})
})
+45
View File
@@ -0,0 +1,45 @@
/** A quartz.lock.json entry pinning an npm plugin (see npm-plugins.js). */
export interface NpmLockEntry {
source: unknown
version: string
integrity?: string
resolved?: string
installedAt?: string
}
/** What installing an npm plugin returns: the fields its lock entry pins. */
export interface NpmInstallResult {
version: string
integrity?: string
resolved?: string
}
export function npmPackageName(spec: string): string
export function isNpmLockEntry(entry: unknown): entry is NpmLockEntry
export function readNpmLockEntry(name: string, lockfilePath: string): NpmLockEntry | undefined
export function isHostDependency(name: string, root?: string): boolean
export function npmPluginDir(name: string, pluginsDir?: string): string
export function installedNpmPluginVersion(name: string, pluginsDir: string): string | null
export function isPinnedNpmPluginInstalled(name: string, pluginsDir: string, root?: string): boolean
export function latestNpmVersion(name: string): string
export function latestNpmVersionAsync(name: string): Promise<string>
export function listPluginDirNames(pluginsDir: string): string[]
export function installNpmPlugin(
name: string,
options: {
version?: string
integrity?: string
pluginsDir: string
verbose?: boolean
/** Runs npm (tests pass a fake). */
run?: (args: string[], options: { cwd: string; stdio?: string; timeout?: number }) => unknown
},
): NpmInstallResult
export function removeNpmPlugin(name: string, pluginsDir: string): void
export function ensureNpmPlugin(
name: string,
options: {
lockEntry?: NpmLockEntry
fallbackVersion?: string
pluginsDir: string
verbose?: boolean
},
): NpmInstallResult | null
+272
View File
@@ -0,0 +1,272 @@
import fs from "fs"
import path from "path"
import { assertNpmSpec, npm, npmAsync } from "./subprocess.js"
/**
* npm plugins that Quartz's package.json doesn't list are pinned in quartz.lock.json and
* installed into .quartz/plugins/<@scope>/<name>, like Git plugins, instead of node_modules:
*
* - `npm install` / `npm ci` remove packages package.json doesn't list, so a plugin installed
* into node_modules without saving would disappear; saving it to Quartz's package.json made
* `npx quartz upgrade` conflict on the user's additions.
* - A site whose repository holds only its content, config and lockfile (the GitHub Action)
* pins its npm plugins in a file it owns.
*
* A plugin in package.json (Quartz's own default plugins, or one the user `npm install`ed) is
* versioned there and loaded from node_modules, as before: package.json wins.
*
* Lock entry: `{ source, version, integrity, resolved, installedAt }` (no `commit`, which every
* Git or local entry has).
*/
const NPM_INSTALL_TIMEOUT_MS = 300_000
const NPM_VIEW_TIMEOUT_MS = 60_000
/** `@scope/name` of an npm plugin source (a version suffix, `@scope/name@1.2`, is dropped). */
export function npmPackageName(spec) {
const at = spec.lastIndexOf("@")
return at > 0 ? spec.slice(0, at) : spec
}
/** Whether a lock entry pins an npm plugin. */
export function isNpmLockEntry(entry) {
return (
!!entry &&
typeof entry === "object" &&
entry.commit === undefined &&
typeof entry.version === "string"
)
}
/** The npm lock entry for `name` in the lockfile at `lockfilePath`, if there is one. */
export function readNpmLockEntry(name, lockfilePath) {
try {
const entry = JSON.parse(fs.readFileSync(lockfilePath, "utf-8"))?.plugins?.[name]
return isNpmLockEntry(entry) ? entry : undefined
} catch {
return undefined
}
}
/** Whether `name` is a dependency in package.json at `root` (Quartz's directory). */
export function isHostDependency(name, root = process.cwd()) {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf-8"))
return [
pkg.dependencies,
pkg.devDependencies,
pkg.optionalDependencies,
pkg.peerDependencies,
].some((deps) => deps && Object.hasOwn(deps, name))
} catch {
return false
}
}
/** Where a pinned npm plugin is installed: `<pluginsDir>/@scope/name`. */
export function npmPluginDir(name, pluginsDir = path.join(process.cwd(), ".quartz", "plugins")) {
return path.join(pluginsDir, ...name.split("/"))
}
/** The version of the pinned npm plugin installed in `pluginsDir`, or null. */
export function installedNpmPluginVersion(name, pluginsDir) {
try {
const pkg = JSON.parse(
fs.readFileSync(path.join(npmPluginDir(name, pluginsDir), "package.json"), "utf-8"),
)
return pkg.name === name && typeof pkg.version === "string" ? pkg.version : null
} catch {
return null
}
}
/**
* Whether the npm plugin `name` is pinned in quartz.lock.json and loaded from
* `<pluginsDir>/@scope/name` (rather than from node_modules): it is not in package.json, and it
* is installed there.
*/
export function isPinnedNpmPluginInstalled(name, pluginsDir, root = process.cwd()) {
return !isHostDependency(name, root) && installedNpmPluginVersion(name, pluginsDir) !== null
}
/** The version npm's `latest` tag points at. */
export function latestNpmVersion(name) {
const out = npm(["view", assertNpmSpec(name), "version", "--json"], {
timeout: NPM_VIEW_TIMEOUT_MS,
})
const version = JSON.parse(out)
if (typeof version !== "string") throw new Error(`npm view ${name} returned no version`)
return version
}
/** The version npm's `latest` tag points at, without blocking (for status checks in parallel). */
export async function latestNpmVersionAsync(name) {
const { stdout } = await npmAsync(["view", assertNpmSpec(name), "version", "--json"], {
timeout: NPM_VIEW_TIMEOUT_MS,
})
const version = JSON.parse(stdout)
if (typeof version !== "string") throw new Error(`npm view ${name} returned no version`)
return version
}
/**
* The directories `pluginsDir` holds plugins in: `name` for Git and local plugins,
* `@scope/name` for pinned npm plugins.
*/
export function listPluginDirNames(pluginsDir) {
if (!fs.existsSync(pluginsDir)) return []
const isDir = (p) => {
try {
return fs.statSync(p).isDirectory()
} catch {
return false
}
}
const names = []
for (const entry of fs.readdirSync(pluginsDir)) {
const full = path.join(pluginsDir, entry)
if (!isDir(full)) continue
if (entry.startsWith("@")) {
for (const child of fs.readdirSync(full)) {
if (isDir(path.join(full, child))) names.push(`${entry}/${child}`)
}
} else if (!entry.startsWith(".")) {
names.push(entry)
}
}
return names
}
// Packages plugins share with Quartz (gitLoader's getSharedExternals): one copy at runtime.
const SINGLETONS = ["preact", "@jackyzha0/quartz", "vfile", "unified"]
const SHARED_SCOPES = ["@quartz-community/", "@quartz-themes/"]
/**
* Whether a dependency of a pinned plugin should come from Quartz's node_modules rather than
* the plugin's own: a shared package (singletons, @quartz-community/*, Quartz's dependencies)
* that Quartz has installed. Git plugins with a pre-built dist/ install no dependencies at
* all, and resolve these from Quartz the same way.
*/
function sharedWithHost(dep, hostRoot) {
let quartzDeps = []
try {
const pkg = JSON.parse(fs.readFileSync(path.join(hostRoot, "package.json"), "utf-8"))
quartzDeps = Object.keys(pkg.dependencies ?? {})
} catch {}
const shared =
SINGLETONS.includes(dep) ||
SHARED_SCOPES.some((scope) => dep.startsWith(scope)) ||
quartzDeps.includes(dep)
return shared && fs.existsSync(path.join(hostRoot, "node_modules", ...dep.split("/")))
}
function moveInto(from, to) {
fs.mkdirSync(path.dirname(to), { recursive: true })
fs.rmSync(to, { recursive: true, force: true })
fs.renameSync(from, to)
}
/**
* Install `name` at `version` (exact, a range or a tag; default `latest`) into
* `<pluginsDir>/@scope/name`, with its production dependencies in its own node_modules and
* without its peer dependencies (they resolve to Quartz's copies). With `integrity`, the
* package npm downloads must match it. Returns the lock entry fields.
*/
export function installNpmPlugin(
name,
{ version = "latest", integrity, pluginsDir, verbose = false, run = npm } = {},
) {
const spec = assertNpmSpec(`${name}@${version}`)
const quartzDir = path.dirname(pluginsDir)
fs.mkdirSync(quartzDir, { recursive: true })
const tmp = fs.mkdtempSync(path.join(quartzDir, ".npm-install-"))
try {
fs.writeFileSync(
path.join(tmp, "package.json"),
JSON.stringify({ name: "quartz-npm-plugin-install", private: true }) + "\n",
)
run(
[
"install",
spec,
"--save-exact",
"--omit=dev",
"--ignore-scripts",
"--legacy-peer-deps",
"--no-audit",
"--no-fund",
],
{ cwd: tmp, stdio: verbose ? "inherit" : "pipe", timeout: NPM_INSTALL_TIMEOUT_MS },
)
const lock = JSON.parse(fs.readFileSync(path.join(tmp, "package-lock.json"), "utf-8"))
const locked = lock.packages?.[`node_modules/${name}`]
if (!locked?.version) throw new Error(`npm did not install ${name}`)
if (integrity && locked.integrity && locked.integrity !== integrity) {
throw new Error(
`${name}@${locked.version} from the registry does not match the integrity in quartz.lock.json ` +
`(${locked.integrity} instead of ${integrity})`,
)
}
const modules = path.join(tmp, "node_modules")
const target = npmPluginDir(name, pluginsDir)
moveInto(path.join(modules, ...name.split("/")), target)
// what's left in node_modules are the plugin's dependencies: they go into its own
// node_modules, except the ones it shares with Quartz (see sharedWithHost)
const hostRoot = path.dirname(quartzDir)
const deps = path.join(target, "node_modules")
const keep = (dep, from, to) => {
if (!sharedWithHost(dep, hostRoot)) moveInto(from, to)
}
for (const entry of fs.readdirSync(modules)) {
if (entry === ".bin" || entry.startsWith(".") || entry === "@types") continue
const from = path.join(modules, entry)
if (entry.startsWith("@")) {
for (const child of fs.readdirSync(from)) {
keep(`${entry}/${child}`, path.join(from, child), path.join(deps, entry, child))
}
} else {
keep(entry, from, path.join(deps, entry))
}
}
return {
version: locked.version,
...(locked.integrity && { integrity: locked.integrity }),
...(locked.resolved && { resolved: locked.resolved }),
}
} finally {
fs.rmSync(tmp, { recursive: true, force: true })
}
}
/** Remove a pinned npm plugin's directory (and its `@scope` directory when that is empty). */
export function removeNpmPlugin(name, pluginsDir) {
const dir = npmPluginDir(name, pluginsDir)
fs.rmSync(dir, { recursive: true, force: true })
const scope = path.dirname(dir)
if (scope !== pluginsDir) {
try {
if (fs.readdirSync(scope).length === 0) fs.rmdirSync(scope)
} catch {}
}
}
/**
* Make sure the pinned npm plugin `name` is installed as `lockEntry` pins it (installed at the
* locked version, else at `fallbackVersion`). Returns the lock entry fields when it installed
* something, null when the right version was already there.
*/
export function ensureNpmPlugin(name, { lockEntry, fallbackVersion, pluginsDir, verbose } = {}) {
const wanted = lockEntry?.version ?? fallbackVersion
const installed = installedNpmPluginVersion(name, pluginsDir)
if (installed && (!wanted || wanted === "latest" || installed === wanted)) return null
return installNpmPlugin(name, {
version: wanted ?? "latest",
integrity: lockEntry?.version === wanted ? lockEntry?.integrity : undefined,
pluginsDir,
verbose,
})
}
+243
View File
@@ -0,0 +1,243 @@
import test, { describe, beforeEach } from "node:test"
import assert from "node:assert"
import fs from "fs"
import os from "os"
import path from "path"
import {
ensureNpmPlugin,
installedNpmPluginVersion,
installNpmPlugin,
isHostDependency,
isNpmLockEntry,
isPinnedNpmPluginInstalled,
listPluginDirNames,
npmPackageName,
npmPluginDir,
readNpmLockEntry,
removeNpmPlugin,
} from "./npm-plugins.js"
const write = (file, content) => {
fs.mkdirSync(path.dirname(file), { recursive: true })
fs.writeFileSync(file, typeof content === "string" ? content : JSON.stringify(content))
}
let root
let pluginsDir
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-npm-plugins-"))
pluginsDir = path.join(root, ".quartz", "plugins")
write(path.join(root, "package.json"), {
name: "@jackyzha0/quartz",
dependencies: { "@quartz-community/explorer": "^1", unified: "^11", "shared-dep": "^1" },
devDependencies: { "@quartz-community/dev-only": "^1" },
})
// what Quartz has installed
for (const dep of ["unified", "shared-dep", "@quartz-community/utils"]) {
write(path.join(root, "node_modules", ...dep.split("/"), "package.json"), { name: dep })
}
})
describe("names and lock entries", () => {
test("npmPackageName drops a version", () => {
assert.strictEqual(npmPackageName("@me/plugin"), "@me/plugin")
assert.strictEqual(npmPackageName("@me/plugin@1.2.3"), "@me/plugin")
assert.strictEqual(npmPackageName("@me/plugin@^1"), "@me/plugin")
})
test("an npm lock entry has a version and no commit", () => {
assert.ok(isNpmLockEntry({ source: "@me/p", version: "1.0.0" }))
assert.ok(!isNpmLockEntry({ source: "github:me/p", commit: "abc", version: "1.0.0" }))
assert.ok(!isNpmLockEntry({ source: "./p", commit: "local" }))
assert.ok(!isNpmLockEntry(undefined))
})
test("readNpmLockEntry returns npm entries only", () => {
const lockfile = path.join(root, "quartz.lock.json")
write(lockfile, {
version: "1.0.0",
plugins: {
"@me/p": { source: "@me/p", version: "2.0.0" },
graph: { source: "github:me/graph", commit: "abc" },
},
})
assert.strictEqual(readNpmLockEntry("@me/p", lockfile)?.version, "2.0.0")
assert.strictEqual(readNpmLockEntry("graph", lockfile), undefined)
assert.strictEqual(readNpmLockEntry("@me/p", path.join(root, "missing.json")), undefined)
})
test("isHostDependency reads Quartz's package.json", () => {
assert.ok(isHostDependency("@quartz-community/explorer", root))
assert.ok(isHostDependency("@quartz-community/dev-only", root))
assert.ok(!isHostDependency("@me/plugin", root))
assert.ok(!isHostDependency("@me/plugin", path.join(root, "nowhere")))
})
})
describe("plugin directories", () => {
test("pinned npm plugins live in @scope/name; listings include them", () => {
write(path.join(pluginsDir, "graph", "package.json"), { name: "graph" })
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
name: "@me/plugin",
version: "1.4.2",
})
fs.mkdirSync(path.join(pluginsDir, ".npm-install-x"), { recursive: true })
write(path.join(pluginsDir, "index.ts"), "")
assert.deepStrictEqual(listPluginDirNames(pluginsDir).sort(), ["@me/plugin", "graph"])
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), "1.4.2")
assert.strictEqual(installedNpmPluginVersion("@me/other", pluginsDir), null)
})
test("a package with another name in the directory is not the plugin", () => {
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
name: "@someone/else",
version: "1.0.0",
})
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), null)
})
test("package.json wins over a pinned copy", () => {
write(path.join(npmPluginDir("@quartz-community/explorer", pluginsDir), "package.json"), {
name: "@quartz-community/explorer",
version: "1.0.0",
})
assert.ok(!isPinnedNpmPluginInstalled("@quartz-community/explorer", pluginsDir, root))
})
test("removeNpmPlugin removes the scope directory once it is empty", () => {
for (const name of ["@me/a", "@me/b"]) {
write(path.join(npmPluginDir(name, pluginsDir), "package.json"), { name, version: "1.0.0" })
}
removeNpmPlugin("@me/a", pluginsDir)
assert.ok(fs.existsSync(path.join(pluginsDir, "@me")))
removeNpmPlugin("@me/b", pluginsDir)
assert.ok(!fs.existsSync(path.join(pluginsDir, "@me")))
removeNpmPlugin("@me/never-installed", pluginsDir)
})
})
/**
* A stand-in for `npm install <spec>` in the temporary project: writes node_modules and
* package-lock.json as npm would for @me/plugin with two dependencies, one of which Quartz has.
*/
function fakeNpm({ version = "1.4.2", integrity = "sha512-good" } = {}) {
const calls = []
const run = (args, { cwd }) => {
calls.push({ args, cwd })
const modules = path.join(cwd, "node_modules")
write(path.join(modules, "@me", "plugin", "package.json"), { name: "@me/plugin", version })
write(path.join(modules, "@me", "plugin", "dist", "index.js"), "export {}")
write(path.join(modules, "own-dep", "package.json"), { name: "own-dep" })
write(path.join(modules, "shared-dep", "package.json"), { name: "shared-dep" })
write(path.join(modules, "@quartz-community", "utils", "package.json"), {
name: "@quartz-community/utils",
})
write(path.join(modules, "@types", "node", "package.json"), { name: "@types/node" })
write(path.join(modules, ".bin", "tool"), "")
write(path.join(cwd, "package-lock.json"), {
packages: {
"node_modules/@me/plugin": {
version,
integrity,
resolved: `https://registry.npmjs.org/@me/plugin/-/plugin-${version}.tgz`,
},
},
})
}
return { run, calls }
}
describe("installNpmPlugin", () => {
test("installs into .quartz/plugins/@scope/name with its own dependencies", () => {
const npm = fakeNpm()
const result = installNpmPlugin("@me/plugin", { version: "1.4.2", pluginsDir, run: npm.run })
assert.deepStrictEqual(result, {
version: "1.4.2",
integrity: "sha512-good",
resolved: "https://registry.npmjs.org/@me/plugin/-/plugin-1.4.2.tgz",
})
const dir = npmPluginDir("@me/plugin", pluginsDir)
assert.ok(fs.existsSync(path.join(dir, "dist", "index.js")))
assert.ok(fs.existsSync(path.join(dir, "node_modules", "own-dep", "package.json")))
// shared with Quartz: resolved from Quartz's node_modules, not a second copy
assert.ok(!fs.existsSync(path.join(dir, "node_modules", "shared-dep")))
assert.ok(!fs.existsSync(path.join(dir, "node_modules", "@quartz-community", "utils")))
assert.ok(!fs.existsSync(path.join(dir, "node_modules", "@types")))
assert.ok(!fs.existsSync(path.join(dir, "node_modules", ".bin")))
// the temporary project is gone, and nothing touched Quartz's package.json
assert.deepStrictEqual(
fs.readdirSync(path.join(root, ".quartz")).filter((n) => n.startsWith(".npm-install-")),
[],
)
assert.ok(
!JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf-8")).dependencies[
"@me/plugin"
],
)
const [{ args }] = npm.calls
assert.strictEqual(args[0], "install")
assert.strictEqual(args[1], "@me/plugin@1.4.2")
for (const flag of ["--omit=dev", "--ignore-scripts", "--legacy-peer-deps", "--save-exact"]) {
assert.ok(args.includes(flag), flag)
}
})
test("a package that doesn't match the pinned integrity is refused and not installed", () => {
const npm = fakeNpm({ integrity: "sha512-other" })
assert.throws(
() =>
installNpmPlugin("@me/plugin", {
version: "1.4.2",
integrity: "sha512-good",
pluginsDir,
run: npm.run,
}),
/does not match the integrity in quartz\.lock\.json/,
)
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), null)
})
test("reinstalling replaces the previous version", () => {
installNpmPlugin("@me/plugin", { version: "1.4.2", pluginsDir, run: fakeNpm().run })
installNpmPlugin("@me/plugin", {
version: "2.0.0",
pluginsDir,
run: fakeNpm({ version: "2.0.0" }).run,
})
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), "2.0.0")
})
test("an invalid name or version never reaches npm", () => {
const npm = fakeNpm()
assert.throws(() =>
installNpmPlugin("@me/plugin", { version: "1$(id)", pluginsDir, run: npm.run }),
)
assert.throws(() => installNpmPlugin("--global", { pluginsDir, run: npm.run }))
assert.strictEqual(npm.calls.length, 0)
})
})
describe("ensureNpmPlugin", () => {
test("does nothing when the pinned version is installed", () => {
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
name: "@me/plugin",
version: "1.4.2",
})
assert.strictEqual(
ensureNpmPlugin("@me/plugin", {
lockEntry: { source: "@me/plugin", version: "1.4.2" },
pluginsDir,
}),
null,
)
})
test("an installed plugin without a pin is left as it is", () => {
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
name: "@me/plugin",
version: "1.0.0",
})
assert.strictEqual(ensureNpmPlugin("@me/plugin", { pluginsDir }), null)
})
})
+23 -8
View File
@@ -1,8 +1,11 @@
import { isHostDependency, npmPackageName, npmPluginDir } from "./npm-plugins.js"
import { resolveLockfilePath } from "./lockfile-path.js"
import fs from "fs"
import path from "path"
import { execSync } from "child_process"
import YAML, { isMap, isNode, isScalar, isSeq } from "yaml"
// Quartz's own folder; `quartz upgrade` merges this one. Plugin commands use getLockfilePath().
const LOCKFILE_PATH = path.join(process.cwd(), "quartz.lock.json")
const PLUGINS_DIR = path.join(process.cwd(), ".quartz", "plugins")
const CONFIG_YAML_PATH = path.join(process.cwd(), "quartz.config.yaml")
@@ -250,12 +253,16 @@ export function writePluginsJson(data) {
// Edit the user's file in place; when it does not exist yet, start from the
// file we read the config from (e.g. quartz.config.default.yaml) so its
// comments carry over.
// A config chosen with QUARTZ_CONFIG_PATH (`--config`) is the user's file: edited where it is
// (it used to be read from there and written to ./quartz.config.yaml).
const chosen = process.env.QUARTZ_CONFIG_PATH ? resolveConfigPath() : null
const target = chosen && /\.ya?ml$/.test(chosen) ? chosen : CONFIG_YAML_PATH
let baseRaw
const basePath = fs.existsSync(CONFIG_YAML_PATH) ? CONFIG_YAML_PATH : resolveConfigPath()
const basePath = fs.existsSync(target) ? target : resolveConfigPath()
if (fs.existsSync(basePath) && (basePath.endsWith(".yaml") || basePath.endsWith(".yml"))) {
baseRaw = fs.readFileSync(basePath, "utf-8")
}
writeDataToFile(CONFIG_YAML_PATH, rest, baseRaw)
writeDataToFile(target, rest, baseRaw)
}
function readDefaultPluginsJson() {
@@ -263,10 +270,16 @@ function readDefaultPluginsJson() {
return readFileAsData(defaultPath)
}
/** quartz.lock.json of the config in use: next to it (see lockfile-path.js). */
export function getLockfilePath() {
return resolveLockfilePath(resolveConfigPath())
}
export function readLockfile() {
if (!fs.existsSync(LOCKFILE_PATH)) return null
const lockfilePath = getLockfilePath()
if (!fs.existsSync(lockfilePath)) return null
try {
return JSON.parse(fs.readFileSync(LOCKFILE_PATH, "utf-8"))
return JSON.parse(fs.readFileSync(lockfilePath, "utf-8"))
} catch {
return null
}
@@ -280,7 +293,7 @@ export function writeLockfile(lockfile) {
}
lockfile = { ...lockfile, plugins: sorted }
}
fs.writeFileSync(LOCKFILE_PATH, JSON.stringify(lockfile, null, 2) + "\n")
fs.writeFileSync(getLockfilePath(), JSON.stringify(lockfile, null, 2) + "\n")
}
/**
@@ -374,8 +387,9 @@ export const SOURCE_FORMATS_HELP = [
]
/**
* Directory a configured plugin lives in: node_modules for npm packages,
* .quartz/plugins/<name> for everything else. Returns null when unparseable.
* Directory a configured plugin lives in: node_modules for npm packages package.json lists,
* .quartz/plugins/@scope/<name> for other npm packages (pinned in quartz.lock.json, see
* npm-plugins.js), .quartz/plugins/<name> for everything else. Returns null when unparseable.
*/
export function resolvePluginDir(source) {
let parsed
@@ -385,7 +399,8 @@ export function resolvePluginDir(source) {
return null
}
if (parsed.npmPackage) {
const pkgName = getSourceUrl(source)
const pkgName = npmPackageName(getSourceUrl(source))
if (!isHostDependency(pkgName)) return npmPluginDir(pkgName, PLUGINS_DIR)
return path.join(process.cwd(), "node_modules", ...pkgName.split("/"))
}
return path.join(PLUGINS_DIR, parsed.name)
+399 -44
View File
@@ -17,7 +17,7 @@ import {
parseGitSource,
getGitCommit,
PLUGINS_DIR,
LOCKFILE_PATH,
getLockfilePath,
isLocalSource,
getSourceUrl,
formatSource,
@@ -56,6 +56,18 @@ import {
npmAsync,
} from "./subprocess.js"
import { writePluginIndex } from "./plugin-index.js"
import {
installedNpmPluginVersion,
installNpmPlugin,
isHostDependency,
isNpmLockEntry,
latestNpmVersion,
latestNpmVersionAsync,
listPluginDirNames,
npmPackageName,
npmPluginDir,
removeNpmPlugin,
} from "./npm-plugins.js"
import {
builtinKeyFor,
builtinMessage,
@@ -386,7 +398,12 @@ export function linkPeerPlugins(pluginDir) {
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"))
const peers = pkg.peerDependencies ?? {}
const quartzRoot = path.resolve(pluginDir, "..", "..", "..")
// .quartz/plugins/<name>, or .quartz/plugins/@scope/<name> for a pinned npm plugin
const scoped = path.basename(path.dirname(pluginDir)).startsWith("@")
const quartzRoot = path.resolve(
pluginDir,
...(scoped ? ["..", "..", "..", ".."] : ["..", "..", ".."]),
)
const hostNodeModules = path.join(quartzRoot, "node_modules")
// a local plugin is a symlink; relative links made through it would dangle
const realDir = fs.realpathSync(pluginDir)
@@ -471,12 +488,8 @@ function canonicalSource(source) {
function findPluginByPackageName(packageName) {
if (!fs.existsSync(PLUGINS_DIR)) return null
const plugins = fs.readdirSync(PLUGINS_DIR).filter((entry) => {
const entryPath = path.join(PLUGINS_DIR, entry)
return fs.statSync(entryPath).isDirectory()
})
for (const pluginDirName of plugins) {
// `name` for Git and local plugins, `@scope/name` for pinned npm plugins
for (const pluginDirName of listPluginDirNames(PLUGINS_DIR)) {
const pkgPath = path.join(PLUGINS_DIR, pluginDirName, "package.json")
if (!fs.existsSync(pkgPath)) continue
try {
@@ -497,12 +510,154 @@ async function regeneratePluginIndex() {
if (builtinMessage(entry.source)) continue
try {
const parsed = parseGitSource(entry.source)
if (parsed.npmPackage) npmPackages.push(parsed.name)
// pinned npm plugins are directories in .quartz/plugins, which the index reads anyway
if (parsed.npmPackage && isHostDependency(npmPackageName(parsed.name)))
npmPackages.push(parsed.name)
} catch {}
}
writePluginIndex({ pluginsDir: PLUGINS_DIR, npmPackages, verbose: true })
}
/**
* The npm plugins `plugin install` takes care of: those package.json doesn't list are pinned in
* quartz.lock.json and installed into .quartz/plugins/@scope/name (see npm-plugins.js); those it
* lists stay with npm. Runs before the Git plugins and writes their lock entries itself; the Git
* steps after it leave npm entries alone.
*
* - default: install each pinned plugin at its locked version (configured but unpinned ones get
* a hint to run `install --from-config`)
* - `fromConfig`: also pin and install configured ones without an entry (at the latest version),
* and remove entries the config no longer has
* - `latest`: move every pin to the version npm's `latest` tag points at
*/
async function syncNpmPlugins({ pluginsJson, names, fromConfig, latest, dryRun }) {
const lockfile = readLockfile() ?? { version: "1.0.0", plugins: {} }
lockfile.plugins ??= {}
const configured = new Map()
for (const entry of pluginsJson?.plugins ?? []) {
try {
if (!parseGitSource(entry.source).npmPackage) continue
const pkg = npmPackageName(getSourceUrl(entry.source))
if (NPM_NAME_PATTERN.test(pkg)) configured.set(pkg, entry)
} catch {}
}
const lockedNames = Object.entries(lockfile.plugins)
.filter(([, entry]) => isNpmLockEntry(entry))
.map(([name]) => name)
const wanted = (pkg) =>
!names?.length || names.some((n) => n === pkg || n === shortPluginName(pkg))
const all = [...new Set([...configured.keys(), ...lockedNames])].filter(wanted)
let changed = false
let installedAny = false
// package.json wins: an entry left from when the plugin was pinned goes
for (const pkg of all.filter((p) => isHostDependency(p))) {
if (!isNpmLockEntry(lockfile.plugins[pkg])) continue
console.log(styleText("gray", `${pkg} is in package.json, which versions it: removing its pin`))
if (dryRun) continue
delete lockfile.plugins[pkg]
removeNpmPlugin(pkg, PLUGINS_DIR)
changed = true
}
const unpinned = []
const rows = []
for (const pkg of all.filter((p) => !isHostDependency(p))) {
const entry = configured.get(pkg)
const lockEntry = isNpmLockEntry(lockfile.plugins[pkg]) ? lockfile.plugins[pkg] : undefined
if (!entry) {
// pinned, but no longer configured
if (!fromConfig) continue
console.log(styleText("yellow", `${pkg} — pinned but not in the config: removing it`))
if (dryRun) continue
delete lockfile.plugins[pkg]
removeNpmPlugin(pkg, PLUGINS_DIR)
changed = true
installedAny = true
continue
}
// like Git plugins: a disabled plugin isn't installed until it is pinned
if (!lockEntry && !entry.enabled) continue
if (!lockEntry && !fromConfig && !latest) {
unpinned.push(pkg)
continue
}
const installedVersion = installedNpmPluginVersion(pkg, PLUGINS_DIR)
let version = lockEntry?.version
if (latest || !version) {
try {
version = latestNpmVersion(pkg)
} catch (err) {
console.log(styleText("red", `✗ ${pkg}: could not look up its latest version on npm`))
console.log(styleText("gray", ` ${describeCommandError(err)}`))
markFailed()
continue
}
}
if (dryRun) {
rows.push({ pkg, installed: installedVersion ?? "—", target: version })
continue
}
// `restore` (clean) also leaves a plugin that is installed at its pinned version alone
if (installedVersion === version && lockEntry?.version === version) continue
try {
console.log(styleText("cyan", `→ Installing ${pkg}@${version} from npm...`))
const result = installNpmPlugin(pkg, {
version,
integrity: lockEntry?.version === version ? lockEntry.integrity : undefined,
pluginsDir: PLUGINS_DIR,
})
linkPeerPlugins(npmPluginDir(pkg, PLUGINS_DIR))
lockfile.plugins[pkg] = {
source: entry.source,
...result,
installedAt: new Date().toISOString(),
}
changed = true
installedAny = true
console.log(styleText("green", `✓ Installed ${pkg}@${result.version}`))
} catch (err) {
console.log(styleText("red", `✗ Failed to install ${pkg} from npm`))
console.log(styleText("gray", ` ${describeCommandError(err)}`))
markFailed()
}
}
if (rows.length > 0) {
console.log(styleText("bold", latest ? "npm plugins (latest):" : "npm plugins to install:"))
const width = Math.max(...rows.map((row) => row.pkg.length)) + 2
for (const { pkg, installed, target } of rows) {
const status =
installed === target
? styleText("green", "up to date")
: styleText("yellow", `${installed} → ${target}`)
console.log(` ${pkg.padEnd(width)}${status}`)
}
console.log()
}
if (unpinned.length > 0) {
console.log(
styleText(
"yellow",
`⚠ ${unpinned.length} npm plugin(s) in the config are not pinned in quartz.lock.json: ${unpinned.join(", ")}`,
),
)
console.log(
styleText("gray", " Run 'npx quartz plugin install --from-config' to install and pin them."),
)
}
if (changed && !dryRun) writeLockfile(lockfile)
if (installedAny && !dryRun) await regeneratePluginIndex()
return { installedAny }
}
export async function handlePluginInstallUnified({
names,
fromConfig = false,
@@ -528,14 +683,34 @@ export async function handlePluginInstallUnified({
...rawPluginsJson,
plugins: (rawPluginsJson.plugins ?? []).filter((entry) => !builtinMessage(entry.source)),
}
// npm plugins package.json doesn't list are pinned and installed first; without a lockfile
// they are pinned from the config, as Git plugins are below
const hadLockfile = readLockfile() !== null
await syncNpmPlugins({
pluginsJson,
names,
fromConfig: fromConfig || !hadLockfile,
latest,
dryRun,
})
// the steps below handle Git and local plugins; npm entries are written back as they are
let lockfile = readLockfile()
const npmLockEntries = Object.fromEntries(
Object.entries(lockfile?.plugins ?? {}).filter(([, entry]) => isNpmLockEntry(entry)),
)
const withNpmEntries = (lf) => ({ ...lf, plugins: { ...npmLockEntries, ...lf.plugins } })
if (lockfile) {
lockfile = {
...lockfile,
plugins: Object.fromEntries(
Object.entries(lockfile.plugins ?? {}).filter(([name]) => !builtinMessage(name)),
Object.entries(lockfile.plugins ?? {}).filter(
([name, entry]) => !builtinMessage(name) && !isNpmLockEntry(entry),
),
),
}
// a lockfile the npm step just created holds no Git pins: install those from the config
if (!hadLockfile && Object.keys(lockfile.plugins).length === 0) lockfile = null
}
if (!fromConfig && !lockfile) {
@@ -547,12 +722,7 @@ export async function handlePluginInstallUnified({
}
})
if (gitEntries.length === 0 && findMissingNpmPlugins(pluginsJson).length === 0) {
console.log(
styleText(
"green",
"✓ No Git or local plugins to install (plugins from npm are installed by 'npm install' / 'npm ci')",
),
)
console.log(styleText("green", "✓ No Git or local plugins to install"))
return
}
if (dryRun && latest) {
@@ -992,7 +1162,7 @@ export async function handlePluginInstallUnified({
}
if (lockfileChanged) {
writeLockfile(lockfile)
writeLockfile(withNpmEntries(lockfile))
console.log()
if (failed === 0) {
console.log(styleText("green", `✓ Resolved ${installed.length} plugin(s)`))
@@ -1160,6 +1330,13 @@ export async function handlePluginInstallUnified({
const pluginsToUpdate = nameFilter ? Array.from(nameFilter) : Object.keys(lockfile.plugins)
const updatedPlugins = []
let lockfileChanged = false
// Disabled in the config: the build never loads them, so failing to update one is a warning,
// not a failed update (an old entry whose repository changed layout failed every update).
const disabledNames = new Set(
(pluginsJson?.plugins ?? [])
.filter((entry) => entry.enabled === false)
.map((entry) => extractPluginName(entry.source)),
)
// Phase 1: Validate and categorize plugins (fast, sequential)
const validPlugins = []
@@ -1244,6 +1421,16 @@ export async function handlePluginInstallUnified({
}
}
} catch (error) {
if (disabledNames.has(name)) {
console.log(
styleText(
"yellow",
`⚠ Could not update ${name} (disabled, so the build does not load it): ${describeCommandError(error)}\n` +
` Remove it with \`npx quartz plugin remove ${name}\` or fix its source.`,
),
)
return
}
console.log(
styleText("red", `✗ Failed to update ${name}: ${describeCommandError(error)}`),
)
@@ -1271,7 +1458,7 @@ export async function handlePluginInstallUnified({
}
if (lockfileChanged) {
writeLockfile(lockfile)
writeLockfile(withNpmEntries(lockfile))
console.log()
console.log(styleText("gray", "Updated quartz.lock.json"))
}
@@ -1483,7 +1670,11 @@ export async function handlePluginInstallUnified({
const NPM_NAME_PATTERN = /^@[a-z0-9-~][a-z0-9-._~]*\/[a-z0-9-~][a-z0-9-._~]*$/
/** Enabled npm-sourced plugins whose package is not present in node_modules. */
/**
* Enabled npm-sourced plugins in package.json whose package is not present in node_modules
* (`npm install` installs them). Plugins package.json doesn't list are pinned in
* quartz.lock.json instead, see syncNpmPlugins.
*/
function findMissingNpmPlugins(pluginsJson) {
const missing = []
for (const entry of pluginsJson?.plugins ?? []) {
@@ -1492,6 +1683,7 @@ function findMissingNpmPlugins(pluginsJson) {
if (!parseGitSource(entry.source).npmPackage) continue
const pkg = getSourceUrl(entry.source)
if (!NPM_NAME_PATTERN.test(pkg)) continue
if (!isHostDependency(npmPackageName(pkg))) continue
const dir = resolvePluginDir(entry.source)
if (dir && !fs.existsSync(path.join(dir, "package.json"))) missing.push(pkg)
} catch {}
@@ -1587,11 +1779,46 @@ export async function handlePluginAdd(
)
continue
}
console.log(styleText("cyan", `→ Installing ${name} from npm...`))
npm(["install", assertNpmSpec(parsed.name)], { cwd: process.cwd(), stdio: "inherit" })
const configSource = nameOverride ? { repo: parsed.name, name: nameOverride } : parsed.name
const pluginDir = path.join(process.cwd(), "node_modules", ...parsed.name.split("/"))
addedPlugins.push({ name, pluginDir, source: parsed.name, configSource, npm: true })
const pkg = npmPackageName(parsed.name)
if (isHostDependency(pkg)) {
// in package.json already (a default plugin, or one installed with npm): npm's
console.log(styleText("cyan", `→ Installing ${name} from npm (package.json)...`))
npm(["install", assertNpmSpec(parsed.name)], { cwd: process.cwd(), stdio: "inherit" })
const pluginDir = path.join(process.cwd(), "node_modules", ...pkg.split("/"))
addedPlugins.push({ name, pluginDir, source: parsed.name, configSource, npm: true })
continue
}
// pinned in quartz.lock.json and installed into .quartz/plugins/@scope/name, so Quartz's
// package.json stays as Quartz ships it (see npm-plugins.js)
console.log(styleText("cyan", `→ Installing ${name} from npm...`))
const requested = parsed.name.slice(pkg.length + 1) || "latest"
let result
try {
result = installNpmPlugin(pkg, { version: requested, pluginsDir: PLUGINS_DIR })
} catch (err) {
console.log(styleText("red", `✗ Failed to install ${pkg} from npm`))
console.log(styleText("gray", ` ${describeCommandError(err)}`))
hadFailure = true
continue
}
const pluginDir = npmPluginDir(pkg, PLUGINS_DIR)
linkPeerPlugins(pluginDir)
lockfile.plugins[pkg] = {
source: configSource,
...result,
installedAt: new Date().toISOString(),
}
lockfileChanged = true
console.log(styleText("green", `✓ Installed ${pkg}@${result.version}`))
addedPlugins.push({
name,
pluginDir,
source: parsed.name,
configSource,
npm: true,
skipBuild: true,
})
continue
}
const name = nameOverride ?? parsed.name
@@ -1895,11 +2122,17 @@ export async function handlePluginRemove(names) {
try {
const parsed = parseGitSource(configEntry.source)
isNpm = Boolean(parsed.npmPackage)
if (!isNpm && !lockfile.plugins[lockKey]) lockKey = parsed.name
if (isNpm) lockKey = npmPackageName(getSourceUrl(configEntry.source))
else if (!lockfile.plugins[lockKey]) lockKey = parsed.name
} catch {}
} else if (isNpmLockEntry(lockfile.plugins[lockKey])) {
isNpm = true
}
const pluginDir = path.join(PLUGINS_DIR, lockKey)
const installed = !isNpm && (Boolean(lockfile.plugins[lockKey]) || fs.existsSync(pluginDir))
// an npm plugin package.json doesn't list is pinned and installed like a Git plugin
const pinnedNpm = isNpm && !isHostDependency(lockKey)
const pluginDir = path.join(PLUGINS_DIR, ...lockKey.split("/"))
const installed =
(!isNpm || pinnedNpm) && (Boolean(lockfile.plugins[lockKey]) || fs.existsSync(pluginDir))
if (!configEntry && !installed) {
const candidates = [
@@ -1925,7 +2158,10 @@ export async function handlePluginRemove(names) {
console.log(styleText("cyan", `→ Removing ${displayName}...`))
if (installed) {
if (fs.existsSync(pluginDir) || fs.lstatSync(pluginDir, { throwIfNoEntry: false })) {
if (pinnedNpm) {
removeNpmPlugin(lockKey, PLUGINS_DIR)
removedFiles = true
} else if (fs.existsSync(pluginDir) || fs.lstatSync(pluginDir, { throwIfNoEntry: false })) {
fs.rmSync(pluginDir, { recursive: true, force: true })
removedFiles = true
}
@@ -1940,7 +2176,7 @@ export async function handlePluginRemove(names) {
removedSources.push(configEntry.source)
}
console.log(styleText("green", `✓ Removed ${displayName}`))
if (isNpm) {
if (isNpm && !pinnedNpm && configEntry) {
console.log(
styleText(
"gray",
@@ -2212,6 +2448,18 @@ function collectUntrackedEntries(pluginsJson, lockfile) {
continue
}
if (parsed.npmPackage) {
const pkgName = npmPackageName(getSourceUrl(entry.source))
if (!isHostDependency(pkgName)) {
// pinned in quartz.lock.json like Git plugins; missing when it has no entry yet
if (!isNpmLockEntry(lockfile?.plugins?.[pkgName])) {
missing.push({
name: extractPluginName(entry.source),
source: formatSource(entry.source),
enabled: Boolean(entry.enabled),
})
}
continue
}
const pkg = readEntryPackageJson(entry.source)
npm.push({
name: extractPluginName(entry.source),
@@ -2260,18 +2508,43 @@ export async function handlePluginList() {
: styleText("gray", "disabled")
if (lockEntries.length > 0) {
console.log(styleText("bold", "Git / local plugins (quartz.lock.json):"))
console.log(styleText("bold", "Pinned plugins (quartz.lock.json):"))
console.log()
}
for (const [name, entry] of lockEntries) {
const pluginDir = path.join(PLUGINS_DIR, name)
const pluginDir = path.join(PLUGINS_DIR, ...name.split("/"))
const exists = fs.existsSync(pluginDir)
const overriddenName = nameOverrides.get(name)
const displayLabel = overriddenName
? `${overriddenName} ${styleText("gray", `(dir: ${name})`)}`
: name
if (isNpmLockEntry(entry)) {
const installedVersion = installedNpmPluginVersion(name, PLUGINS_DIR)
const status = !installedVersion
? styleText("red", "✗")
: installedVersion === entry.version
? styleText("green", "✓")
: styleText("yellow", "⚡")
console.log(
` ${status} ${styleText("bold", displayLabel)} ${enabledLabel(overriddenName ?? name)}`,
)
console.log(` Source: ${formatSource(entry.source)} (npm)`)
console.log(` Version: ${entry.version}`)
if (installedVersion && installedVersion !== entry.version) {
console.log(
` Current: ${installedVersion} (differs from lockfile — run 'npx quartz plugin install ${name}')`,
)
}
if (!installedVersion) console.log(` Not on disk — run 'npx quartz plugin install'`)
if (entry.installedAt) {
console.log(` Installed: ${new Date(entry.installedAt).toLocaleDateString()}`)
}
console.log()
continue
}
if (entry.commit === "local") {
const isLinked = exists && fs.lstatSync(pluginDir).isSymbolicLink()
const status = isLinked ? styleText("green", "✓") : styleText("red", "✗")
@@ -2371,6 +2644,19 @@ export async function handlePluginStatus() {
)
const rows = Object.entries(lockfile.plugins).map(([name, entry]) => {
if (isNpmLockEntry(entry)) {
const installedVersion = installedNpmPluginVersion(name, PLUGINS_DIR)
return {
name,
entry,
npmPinned: true,
exists: installedVersion !== null,
displayName: nameOverrides.get(name) ?? name,
sourceLabel: `${formatSource(entry.source)} (npm)`,
commitLabel: `v${entry.version}`,
enabled: enabledByName.get(extractPluginName(entry.source)) ?? false,
}
}
const pluginDir = path.join(PLUGINS_DIR, name)
const exists = fs.existsSync(pluginDir)
const displayName = nameOverrides.get(name) ?? name
@@ -2465,6 +2751,21 @@ export async function handlePluginStatus() {
})
}
if (row.npmPinned) {
return latestNpmVersionAsync(row.name)
.then((latestVersion) => {
const status = latestVersion === row.entry.version ? "up_to_date" : "update_available"
const display = updateDisplay(status)
updateLine(index, display.label, display.text)
return { index, status, name: row.displayName }
})
.catch(() => {
const display = updateDisplay("failed")
updateLine(index, display.label, display.text)
return { index, status: "failed", name: row.displayName }
})
}
return lsRemote(row.entry)
.then(({ stdout }) => {
const latestCommit = stdout.split("\t")[0].trim()
@@ -2502,13 +2803,13 @@ export async function handlePluginStatus() {
console.log(
styleText(
"gray",
"\nnpm plugins are versioned by package.json — update them with 'npx quartz upgrade' or 'npm update'.",
"\nnpm plugins in package.json are versioned there — update them with 'npx quartz upgrade' or 'npm update'.",
),
)
}
if (updatesAvailable.length === 0 && failedChecks.length === 0) {
console.log(styleText("green", "\n✓ All Git plugins up to date"))
console.log(styleText("green", "\n✓ All pinned plugins up to date"))
return
}
@@ -2643,7 +2944,7 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
const plugins = effective.plugins.filter((entry) => !absorbed.has(entry))
const lockfile = readLockfile()
if (fs.existsSync(LOCKFILE_PATH) && !lockfile) {
if (fs.existsSync(getLockfilePath()) && !lockfile) {
report(
"error",
"quartz.lock.json",
@@ -2717,14 +3018,55 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
const pluginDir = resolvePluginDir(entry.source)
if (parsed.npmPackage) {
if (!fs.existsSync(path.join(pluginDir, "package.json"))) {
report(
enabled ? "error" : "info",
label,
"npm package is not installed",
`Run 'npm install' (or 'npm install ${parsed.name}' if it is not in package.json).`,
)
return
const pkgName = npmPackageName(getSourceUrl(entry.source))
const pin = lockfile?.plugins?.[pkgName]
if (isHostDependency(pkgName)) {
if (isNpmLockEntry(pin)) {
report(
"warning",
label,
"is in package.json and also pinned in quartz.lock.json; package.json versions it",
`Run 'npx quartz plugin install ${pkgName}' to remove the unused pin.`,
)
}
if (!fs.existsSync(path.join(pluginDir, "package.json"))) {
report(
enabled ? "error" : "info",
label,
"npm package is not installed",
"Run 'npm install'.",
)
return
}
} else {
// pinned in quartz.lock.json, installed into .quartz/plugins/@scope/name
const installedVersion = installedNpmPluginVersion(pkgName, PLUGINS_DIR)
if (!isNpmLockEntry(pin)) {
if (enabled) {
report(
"warning",
label,
"not pinned in quartz.lock.json — the build installs the latest version",
"Run 'npx quartz plugin install --from-config' and commit quartz.lock.json.",
)
}
if (!installedVersion) return
} else if (!installedVersion) {
report(
enabled ? "error" : "info",
label,
`npm package is not installed (quartz.lock.json pins ${pin.version})`,
"Run 'npx quartz plugin install'.",
)
return
} else if (installedVersion !== pin.version) {
report(
"warning",
label,
`${installedVersion} is installed but quartz.lock.json pins ${pin.version}`,
`Run 'npx quartz plugin install ${pkgName}' to install the pinned version.`,
)
}
}
} else {
gitPluginCount++
@@ -2790,7 +3132,7 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
enabled ? "error" : "info",
label,
"has no built entry point (dist/ missing)",
parsed.npmPackage
parsed.npmPackage && isHostDependency(npmPackageName(getSourceUrl(entry.source)))
? "Reinstall it with 'npm install'."
: `Run 'npx quartz plugin install ${parsed.name}' to build it.`,
)
@@ -2868,7 +3210,11 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
const configured = new Set(
plugins.flatMap((e) => {
try {
return [parseGitSource(e.source).name]
const parsed = parseGitSource(e.source)
// npm pins are keyed by package name, also when the config renames the plugin
return parsed.npmPackage
? [parsed.name, npmPackageName(getSourceUrl(e.source))]
: [parsed.name]
} catch {
return []
}
@@ -2932,6 +3278,13 @@ export async function handlePluginPrune({ dryRun = false } = {}) {
const configuredNames = new Set(
(pluginsJson?.plugins ?? []).map((entry) => extractPluginName(entry.source)),
)
// npm pins are keyed by package name, also when the config gives the plugin another name
for (const entry of pluginsJson?.plugins ?? []) {
try {
if (parseGitSource(entry.source).npmPackage)
configuredNames.add(npmPackageName(getSourceUrl(entry.source)))
} catch {}
}
const orphans = Object.keys(lockfile.plugins).filter((name) => !configuredNames.has(name))
@@ -2957,7 +3310,9 @@ export async function handlePluginPrune({ dryRun = false } = {}) {
console.log(styleText("cyan", `→ Removing ${name}...`))
if (fs.existsSync(pluginDir)) {
if (isNpmLockEntry(lockfile.plugins[name])) {
removeNpmPlugin(name, PLUGINS_DIR)
} else if (fs.existsSync(pluginDir)) {
fs.rmSync(pluginDir, { recursive: true })
}
+128 -1
View File
@@ -229,7 +229,15 @@ describe("plugin commands with an extending config", () => {
const site = () => {
const dir = path.join(root, "site")
fs.mkdirSync(dir, { recursive: true })
fs.writeFileSync(path.join(dir, "package.json"), `{ "name": "site", "version": "5.3.0" }`)
// the default plugins are Quartz's dependencies, as in Quartz's own package.json
fs.writeFileSync(
path.join(dir, "package.json"),
JSON.stringify({
name: "site",
version: "5.3.0",
dependencies: { "@quartz-community/graph": "^1", "@quartz-community/comments": "^1" },
}),
)
fs.writeFileSync(
path.join(dir, "quartz.config.default.yaml"),
[
@@ -294,3 +302,122 @@ describe("plugin commands with an extending config", () => {
assert.doesNotMatch(read(dir), /comments/)
})
})
describe("plugin install --latest with a plugin that can't be updated", () => {
const cli = path.resolve(import.meta.dirname, "..", "bootstrap-cli.mjs")
// A Git plugin whose repository no longer has the configured subdirectory (an old
// quartz-themes entry: the repository moved its plugin out of `plugin/`).
const site = (enabled) => {
const repo = path.join(root, "repo")
fs.mkdirSync(repo, { recursive: true })
fs.writeFileSync(path.join(repo, "README.md"), "no plugin/ here\n")
const git = (args) => execSync(`git ${args}`, { cwd: repo, stdio: "ignore", timeout: 30_000 })
git("init -q -b main")
git("-c user.name=t -c user.email=t@t add .")
git("-c user.name=t -c user.email=t@t commit -q -m init")
const url = pathToFileURL(repo).href
const dir = path.join(root, "site")
fs.mkdirSync(path.join(dir, ".quartz", "plugins", "old-theme"), { recursive: true })
fs.writeFileSync(path.join(dir, "package.json"), `{ "name": "site", "version": "5.3.1" }`)
fs.writeFileSync(
path.join(dir, "quartz.config.yaml"),
YAML.stringify({
configuration: { pageTitle: "t" },
plugins: [{ source: { name: "old-theme", repo: url, subdir: "plugin" }, enabled }],
}),
)
fs.writeFileSync(
path.join(dir, "quartz.lock.json"),
JSON.stringify({
version: "1.0.0",
plugins: {
"old-theme": {
source: url,
resolved: url,
subdir: "plugin",
commit: "0000000000000000000000000000000000000000",
installedAt: "2026-01-01T00:00:00.000Z",
},
},
}),
)
return dir
}
const run = (dir) => {
const result = spawnSync(process.execPath, [cli, "plugin", "install", "--latest"], {
cwd: dir,
encoding: "utf-8",
timeout: 60_000,
env: { ...process.env, QUARTZ_CONFIG_PATH: "" },
})
return { output: result.stdout + result.stderr, status: result.status }
}
test("a disabled plugin only warns: the build doesn't load it", () => {
const { output, status } = run(site(false))
assert.match(output, /Could not update old-theme \(disabled/)
assert.match(output, /npx quartz plugin remove old-theme/)
assert.strictEqual(status, 0)
})
test("an enabled plugin fails the update", () => {
const { output, status } = run(site(true))
assert.match(output, /Failed to update old-theme/)
assert.strictEqual(status, 1)
})
})
describe("plugin commands with --config elsewhere", () => {
const cli = path.resolve(import.meta.dirname, "..", "bootstrap-cli.mjs")
const run = (cwd, args) =>
spawnSync(process.execPath, [cli, ...args], {
cwd,
encoding: "utf-8",
timeout: 60_000,
env: { ...process.env, QUARTZ_CONFIG_PATH: "" },
})
test("-C reads and writes that config and the quartz.lock.json next to it", () => {
const quartz = path.join(root, "quartz")
fs.mkdirSync(quartz, { recursive: true })
fs.writeFileSync(path.join(quartz, "package.json"), `{ "name": "q", "version": "5.3.0" }`)
fs.writeFileSync(path.join(quartz, "quartz.config.default.yaml"), "plugins: []\n")
// a site repository outside Quartz: content, config and lockfile only
const site = path.join(root, "site")
fs.mkdirSync(site, { recursive: true })
fs.writeFileSync(path.join(site, "quartz.config.yaml"), "extends: default\n")
const plugin = path.join(root, "my-plugin")
fs.mkdirSync(plugin, { recursive: true })
fs.writeFileSync(
path.join(plugin, "package.json"),
`{ "name": "my-plugin", "version": "1.0.0" }`,
)
// pre-built, so `add` doesn't build it
fs.mkdirSync(path.join(plugin, "dist"))
fs.writeFileSync(path.join(plugin, "dist", "index.js"), "export {}\n")
fs.writeFileSync(path.join(plugin, "dist", "index.d.ts"), "export {}\n")
const result = run(quartz, [
"plugin",
"add",
plugin,
"-C",
path.join(site, "quartz.config.yaml"),
])
assert.strictEqual(result.status, 0, result.stdout + result.stderr)
const lock = JSON.parse(fs.readFileSync(path.join(site, "quartz.lock.json"), "utf-8"))
assert.strictEqual(lock.plugins["my-plugin"]?.commit, "local")
assert.ok(!fs.existsSync(path.join(quartz, "quartz.lock.json")))
assert.match(fs.readFileSync(path.join(site, "quartz.config.yaml"), "utf-8"), /my-plugin/)
assert.ok(!fs.existsSync(path.join(quartz, "quartz.config.yaml")))
// installed into Quartz's .quartz/plugins, where the build loads it
assert.ok(fs.existsSync(path.join(quartz, ".quartz", "plugins", "my-plugin")))
const list = run(quartz, ["plugin", "list", "--config", path.join(site, "quartz.config.yaml")])
assert.match(list.stdout, /my-plugin/)
const missing = run(quartz, ["plugin", "list", "-C", path.join(site, "nope.yaml")])
assert.strictEqual(missing.status, 1)
assert.match(missing.stderr, /Config file not found/)
})
})
+10 -6
View File
@@ -10,6 +10,7 @@
* Overrides are registered under the key the config loader looks them up by: the npm package name
* for npm plugins, the directory name for Git/local plugins (#2565).
*/
import { listPluginDirNames } from "./npm-plugins.js"
import fs from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"
@@ -120,20 +121,23 @@ export function collectPluginExports({ pluginsDir, npmPackages = [], verbose = f
if (overridable.length > 0 || passthrough.length > 0 || types.length > 0) entries.set(key, info)
}
const dirs = fs.existsSync(pluginsDir)
? fs.readdirSync(pluginsDir).filter((n) => fs.statSync(path.join(pluginsDir, n)).isDirectory())
: []
for (const name of dirs) {
const distIndex = path.join(pluginsDir, name, "dist", "index.d.ts")
// `name` for Git and local plugins, `@scope/name` for npm plugins pinned in quartz.lock.json
const fromDirs = new Set()
for (const name of listPluginDirNames(pluginsDir)) {
const distIndex = path.join(pluginsDir, ...name.split("/"), "dist", "index.d.ts")
if (!fs.existsSync(distIndex)) {
if (verbose)
console.log(styleText("yellow", `⚠`), `Skipping ${name}: no dist/index.d.ts found`)
continue
}
add(name, { ...classify(distIndex), importPath: `./${name}`, registryKey: name })
fromDirs.add(name)
// a pinned npm plugin keeps its package name as the registry key, as from node_modules
const key = name.startsWith("@") ? name.replace(/^@/, "").replace(/\//g, "__") : name
add(key, { ...classify(distIndex), importPath: `./${name}`, registryKey: name })
}
for (const pkg of npmPackages) {
if (fromDirs.has(pkg)) continue
let distIndex
try {
const pkgJson = fileURLToPath(import.meta.resolve(`${pkg}/package.json`))
+18
View File
@@ -105,6 +105,24 @@ describe("plugin index", () => {
fs.rmSync(root, { recursive: true, force: true })
})
test("npm plugins pinned in quartz.lock.json are read from .quartz/plugins/@scope/name", () => {
const pluginsDir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-plugin-index-pinned-"))
const dist = path.join(pluginsDir, "@me", "widget", "dist")
fs.mkdirSync(dist, { recursive: true })
fs.writeFileSync(
path.join(dist, "index.d.ts"),
`import { QuartzComponent } from '@quartz-community/types';\ndeclare const Widget: () => QuartzComponent;\nexport { Widget };\n`,
)
// also listed by the config as an npm package: read once, from the directory
const entries = collectPluginExports({ pluginsDir, npmPackages: ["@me/widget"] })
assert.deepStrictEqual([...entries.keys()], ["me__widget"])
const entry = entries.get("me__widget")!
assert.strictEqual(entry.importPath, "./@me/widget")
assert.strictEqual(entry.registryKey, "@me/widget")
assert.ok(entry.overridable.includes("Widget"))
fs.rmSync(pluginsDir, { recursive: true, force: true })
})
test("npm plugins register under their package name", () => {
const source = renderPluginIndex(
new Map([
+30
View File
@@ -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")
+33
View File
@@ -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")
})
})
+42
View File
@@ -120,6 +120,48 @@ describe("renderTranscludes", () => {
assert.ok(texts.includes("Target content"), "transcluded content should be inlined")
})
test("a block transclusion finds the block by its name and scopes its ^id", () => {
const block: Element = {
type: "element",
tagName: "p",
properties: { id: "^para-1" },
children: [
{ type: "text", value: "Block text " },
{
type: "element",
tagName: "a",
properties: { href: "#^para-1" },
children: [{ type: "text", value: "self" }],
},
],
}
const heading: Element = {
type: "element",
tagName: "h2",
properties: { id: "para-1" },
children: [{ type: "text", value: "Para 1" }],
}
const targetHtml: Root = { type: "root", children: [heading, block] }
const allFiles = [makePageData("target", targetHtml, { blocks: { "para-1": block } })]
const root: Root = {
type: "root",
children: [makeTranscludeBlockquote("target", "#^Para-1")],
}
renderTranscludes(
root,
cfg,
"current" as FullSlug,
makeComponentData(allFiles) as QuartzComponentProps,
new Set<FullSlug>(["current" as FullSlug]),
)
const html = toHtml(root)
assert.ok(html.includes("Block text"), html)
assert.ok(!html.includes("Para 1"), "the heading of the same name isn't transcluded")
const id = /<p id="([^"]+)"/.exec(html)?.[1]
assert.ok(id?.endsWith("^para-1") && id !== "^para-1", `scoped block id, got ${id}`)
assert.ok(html.includes(`href="#${id}"`), "the link inside points at the scoped id")
})
test("allows the same page to be embedded twice as siblings", () => {
const root: Root = {
type: "root",
+3 -2
View File
@@ -308,8 +308,9 @@ export function renderTranscludes(
let blockRef = el.properties.dataBlock as string | undefined
if (blockRef?.startsWith("#^")) {
// block transclude
blockRef = blockRef.slice("#^".length)
// block transclude: `data.blocks` is keyed by the block's name, lowercased (`para-1`); the
// block element's id is `^para-1` (rehype-obsidian), its anchor `#^para-1`
blockRef = blockRef.slice("#^".length).toLowerCase()
let blockNode = page.blocks?.[blockRef]
if (blockNode) {
if (blockNode.tagName === "li") {
+2 -1
View File
@@ -32,7 +32,8 @@ async function mouseEnterHandler(
if (hash !== "") {
const inner = popoverElement.querySelector(".popover-inner") as HTMLElement | null
if (inner) {
const targetAnchor = `#popover-internal-${hash.slice(1)}`
// ids are not CSS identifiers: block ids start with `^`, headings may start with a digit
const targetAnchor = `#${CSS.escape(`popover-internal-${hash.slice(1)}`)}`
const heading = inner.querySelector(targetAnchor) as HTMLElement | null
if (heading) {
// leave ~12px of buffer when scrolling to a heading
+40 -4
View File
@@ -70,13 +70,43 @@ history.scrollRestoration = "manual"
let renderedPath = window.location.pathname
let saveTimer: ReturnType<typeof setTimeout> | undefined
// Each entry the router creates gets a key, so a position that was still waiting to be saved
// when Back or Forward left its entry (history.state is the new entry's by then) is kept here
// and written to the entry when it is shown again.
type EntryState = { key?: string; scrollY?: unknown } | null
const newKey = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
const unsavedScroll = new Map<string, number>()
let shownKey: string | undefined
function entryKey(): string {
let key = (history.state as EntryState)?.key
if (typeof key !== "string") {
key = newKey()
history.replaceState({ ...(history.state ?? {}), key }, "")
}
return key
}
function pushEntry(url: URL) {
history.pushState({ key: newKey() }, "", url)
shownKey = entryKey()
}
function saveScroll() {
clearTimeout(saveTimer)
saveTimer = undefined
history.replaceState({ ...(history.state ?? {}), scrollY: window.scrollY }, "")
}
function savedScroll(): number | undefined {
const y = (history.state as { scrollY?: unknown } | null)?.scrollY
const key = entryKey()
const unsaved = unsavedScroll.get(key)
if (unsaved !== undefined) {
unsavedScroll.delete(key)
history.replaceState({ ...(history.state ?? {}), scrollY: unsaved }, "")
return unsaved
}
const y = (history.state as EntryState)?.scrollY
return typeof y === "number" ? y : undefined
}
@@ -185,7 +215,7 @@ async function _navigate(url: URL, isBack: boolean = false) {
// delay setting the url until now
// at this point everything is loaded so changing the url should resolve to the correct addresses
if (!isBack) {
history.pushState({}, "", finalUrl)
pushEntry(finalUrl)
}
renderedPath = window.location.pathname
@@ -220,7 +250,7 @@ function createRouter() {
if (isSamePage(url) && url.hash) {
// Save where the reader was, then add the entry, then jump: Back returns here.
saveScroll()
history.pushState({}, "", url)
pushEntry(url)
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
el?.scrollIntoView()
return
@@ -230,8 +260,13 @@ function createRouter() {
})
window.addEventListener("popstate", () => {
// Whatever is pending belongs to the entry just left.
// Whatever is pending belongs to the entry just left: keep it for when it's shown again.
if (saveTimer !== undefined && shownKey !== undefined) {
unsavedScroll.set(shownKey, window.scrollY)
}
clearTimeout(saveTimer)
saveTimer = undefined
shownKey = entryKey()
// Back or Forward between headings of the page on screen: only scroll.
if (window.location.pathname === renderedPath) {
restoreScroll()
@@ -257,6 +292,7 @@ function createRouter() {
window.addEventListener("pagehide", () => {
if (!isNavigating) saveScroll()
})
shownKey = entryKey()
if (savedScroll() !== undefined) restoreScroll()
}
+28
View File
@@ -0,0 +1,28 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import { i18n, resolveTranslationLocale } from "./index"
describe("i18n locale fallback", () => {
test("a locale with a translation uses it, whatever its case", (t) => {
t.mock.method(console, "warn", () => {})
assert.strictEqual(resolveTranslationLocale("de-DE"), "de-DE")
assert.strictEqual(resolveTranslationLocale("de-de"), "de-DE")
assert.strictEqual(resolveTranslationLocale(undefined), "en-US")
})
test("a locale without one uses the same language, else English, and warns once", (t) => {
const warn = t.mock.method(console, "warn", () => {})
assert.strictEqual(resolveTranslationLocale("es-MX"), "es-ES")
assert.strictEqual(resolveTranslationLocale("es-MX"), "es-ES")
assert.strictEqual(resolveTranslationLocale("sv-SE"), "en-US")
assert.strictEqual(resolveTranslationLocale("nb"), "nb-NO")
assert.strictEqual(warn.mock.callCount(), 3)
assert.match(String(warn.mock.calls[0]!.arguments[0]), /no translation for locale "es-MX"/)
})
// used to throw: TRANSLATIONS["sv-SE"] was undefined
test("i18n() of a locale without a translation returns one", (t) => {
t.mock.method(console, "warn", () => {})
assert.strictEqual(i18n("da-DK").pages.error.title, i18n("en-US").pages.error.title)
})
})
+28 -1
View File
@@ -85,6 +85,33 @@ export const TRANSLATIONS = {
} as const
export const defaultTranslation = "en-US"
export const i18n = (locale: ValidLocale): Translation => TRANSLATIONS[locale ?? defaultTranslation]
const warnedLocales = new Set<string>()
/**
* The translation to use for `locale`: its own, else one of the same language (`es-MX` uses
* `es-ES`), else English. A locale without a translation used to crash the build
* (`TRANSLATIONS[locale]` is undefined); dates and numbers still use the configured locale.
*/
export function resolveTranslationLocale(locale: string | undefined): ValidLocale {
if (!locale) return defaultTranslation
const keys = Object.keys(TRANSLATIONS) as ValidLocale[]
const exact = keys.find((key) => key.toLowerCase() === locale.toLowerCase())
if (exact) return exact
const language = locale.split("-")[0]!.toLowerCase()
const chosen =
keys.find((key) => key.split("-")[0]!.toLowerCase() === language) ?? defaultTranslation
if (!warnedLocales.has(locale)) {
warnedLocales.add(locale)
console.warn(
`Quartz has no translation for locale "${locale}"; its text uses ${chosen}. ` +
`Dates still use ${locale}. Translations: https://quartz.jzhao.xyz/features/i18n`,
)
}
return chosen
}
export const i18n = (locale: ValidLocale | string | undefined): Translation =>
TRANSLATIONS[resolveTranslationLocale(locale)]
export type ValidLocale = keyof typeof TRANSLATIONS
export type ValidCallout = keyof CalloutTranslation
+360 -3
View File
@@ -14,7 +14,13 @@ import {
extractLinksFromValue,
readFrontmatterData,
} from "./frontmatter"
import { Links, LinksInstance, markLinksToRemovedPages } from "./links"
import {
Links,
LinksInstance,
markLinksToRemovedPages,
markUnpublishedLinks,
removedPages,
} from "./links"
import {
buildLayeredCSS,
buildUnlayeredCSS,
@@ -35,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 => ({
@@ -458,6 +464,25 @@ describe("links built-in", () => {
}
})
test("slugs.stripDiacritics: a percent-encoded % in a link target is decoded once", () => {
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",
@@ -1054,6 +1079,88 @@ describe("links to pages removed by filters (crawl-links#7)", () => {
assert.ok((anchors(home)[0].properties.className as string[]).includes("broken"))
})
test("marks links to folder and tag pages no page type generated", () => {
const home = page("index", [
link("drafts/index"),
link("notes/index"),
link("tags/unused"),
link("tags/used"),
link("tags/parent"),
link("index"),
])
const generated = new Set(["notes/index", "tags/used", "tags/parent/index", "tags/index"])
const changed = new Set<FullSlug>()
const marked = markUnpublishedLinks([home], new Map(), generated, changed)
const broken = anchors(home).map((a) => (a.properties.className as string[]).includes("broken"))
assert.deepStrictEqual(broken, [true, false, true, false, false, false])
assert.strictEqual(marked, 2)
assert.strictEqual(anchors(home)[0].properties["data-missing"], "")
assert.deepStrictEqual([...changed], ["index"])
})
test("links to published folder notes and pages are not marked once page types ran", () => {
// `notes/index` is a content page (notes/index.md or a folder note), so no page type
// generates it: it is live because it is published, not because it was generated
const home = page("index", [
link("notes/index"),
link("projects/index"),
link("published"),
link("aka"),
link("tags/x"),
])
const notes = page("notes/index", [])
const projects = page("projects/index", [], { aliases: ["aka"] })
const published = page("published", [])
const changed = new Set<FullSlug>()
const marked = markUnpublishedLinks(
[home, notes, projects, published],
new Map(),
new Set(["tags/x"]),
changed,
)
assert.strictEqual(marked, 0)
for (const a of anchors(home)) {
assert.deepStrictEqual(a.properties.className, ["internal", "internal-link"])
assert.strictEqual(a.properties["data-missing"], undefined)
assert.strictEqual(a.properties["data-filtered"], undefined)
}
assert.deepStrictEqual([...changed], [])
})
test("a folder note that is a draft: its folder page is generated, or the link is missing", () => {
const home = page("index", [link("notes/index"), link("drafts/index")])
const notesIndex = page("notes/index", [])
const draftsIndex = page("drafts/index", [])
const all = [home, notesIndex, draftsIndex]
const removed = removedPages(all, [home], () => "RemoveDrafts")
// folder index notes are left to the generated pages
assert.deepStrictEqual([...removed], [])
markUnpublishedLinks([home], removed, new Set(["notes/index"]))
const [toNotes, toDrafts] = anchors(home)
assert.ok(!(toNotes.properties.className as string[]).includes("broken"))
assert.ok((toDrafts.properties.className as string[]).includes("broken"))
assert.strictEqual(toDrafts.properties["data-missing"], "")
assert.strictEqual(toDrafts.properties["data-filtered"], undefined)
})
test("reports the pages whose marks changed, so watch mode re-emits them", () => {
const home = page("index", [link("draft")])
const other = page("other", [link("published")])
const draft = page("draft", [])
const all = [home, other, draft]
const changed = new Set<FullSlug>()
markUnpublishedLinks([home, other], removedPages(all, [home, other]), new Set(), changed)
assert.deepStrictEqual([...changed], ["index"])
changed.clear()
// nothing changed: nothing to re-emit
markUnpublishedLinks([home, other], removedPages(all, [home, other]), new Set(), changed)
assert.deepStrictEqual([...changed], [])
// the draft is published: its link is unmarked, the page re-emitted
markUnpublishedLinks([home, other, draft], removedPages(all, all), new Set(), changed)
assert.deepStrictEqual([...changed], ["index"])
assert.deepStrictEqual(anchors(home)[0].properties.className, ["internal", "internal-link"])
})
test("the Links instance says whether it marks broken links", () => {
assert.strictEqual((Links() as LinksInstance).marksBrokenLinks, true)
assert.strictEqual(
@@ -1062,3 +1169,253 @@ describe("links to pages removed by filters (crawl-links#7)", () => {
)
})
})
describe("links built-in: options, other elements and edge cases", () => {
const el = (tagName: string, properties: Element["properties"], text?: string): Element => ({
type: "element",
tagName,
properties,
children: text === undefined ? [] : [{ type: "text", value: text }],
})
const a = (href: string, text = href) => el("a", { href }, text)
function run(
nodes: Element[],
{
slug = "folder/page",
opts = {},
allSlugs = ["folder/page"],
data = {},
permalinks,
}: {
slug?: string
opts?: Record<string, unknown>
allSlugs?: string[]
data?: Record<string, unknown>
permalinks?: Record<string, string>
} = {},
) {
const tree: Root = { type: "root", children: nodes }
const file = new VFile("")
file.data = { slug: slug as FullSlug, ...data } as VFile["data"]
const ctx = { allSlugs, permalinks } as unknown as BuildCtx
const [factory] = Links(opts).htmlPlugins!(ctx) as [() => (t: Root, f: VFile) => void]
factory()(tree, file)
return { nodes, file }
}
const classes = (e: Element) => e.properties.className as string[] | undefined
const text = (e: Element) => (e.children[0] as Text).value
test("defaults: pretty links, external links open in place with an icon, no lazy loading", () => {
const { nodes } = run([
a("https://example.com/a/b"),
a("other/note"),
el("img", { src: "pic.png", alt: "x" }),
])
const [external, internal, img] = nodes
assert.strictEqual(external.properties.target, undefined)
assert.strictEqual(text(external), "https://example.com/a/b")
assert.deepStrictEqual(external.children[1], {
type: "element",
tagName: "svg",
properties: {
"aria-hidden": "true",
class: "external-icon",
style: "max-width:0.8em;max-height:0.8em",
viewBox: "0 0 512 512",
},
children: [
{
type: "element",
tagName: "path",
properties: {
d: "M320 0H288V64h32 82.7L201.4 265.4 178.7 288 224 333.3l22.6-22.6L448 109.3V192v32h64V192 32 0H480 320zM32 32H0V64 480v32H32 456h32V480 352 320H424v32 96H64V96h96 32V32H160 32z",
},
children: [],
},
],
})
assert.strictEqual(text(internal), "note")
assert.strictEqual(img.properties.loading, undefined)
})
test("openLinksInNewTab and externalLinkIcon: false apply to external links only", () => {
const { nodes } = run([a("https://example.com"), a("other")], {
opts: { openLinksInNewTab: true, externalLinkIcon: false },
})
const [external, internal] = nodes
assert.strictEqual(external.properties.target, "_blank")
assert.strictEqual(external.children.length, 1)
assert.strictEqual(internal.properties.target, undefined)
})
test("prettyLinks: false keeps the link text; text that isn't a single text node is left alone", () => {
const off = run([a("folder/note")], { opts: { prettyLinks: false } }).nodes
assert.strictEqual(text(off[0]), "folder/note")
const formatted: Element = {
type: "element",
tagName: "a",
properties: { href: "folder/note" },
children: [el("em", {}, "folder/note"), { type: "text", value: " more" }],
}
run([formatted])
assert.strictEqual(text(formatted.children[0] as Element), "folder/note")
assert.strictEqual((formatted.children[1] as Text).value, " more")
assert.ok(!classes(formatted)!.includes("alias"))
})
test("lazyLoad and src resolution for img, video, audio and iframe; external sources are kept", () => {
const { nodes } = run(
[
el("img", { src: "a.png", alt: "a" }),
el("video", { src: "v.mp4" }),
el("audio", { src: "s.mp3" }),
el("iframe", { src: "doc.pdf" }),
el("img", { src: "https://cdn.example.com/x.png", alt: "x" }),
el("script", { src: "x.js" }),
],
{ opts: { lazyLoad: true, markdownLinkResolution: "absolute" } },
)
assert.deepStrictEqual(
nodes.map((n) => [n.properties.src, n.properties.loading]),
[
["../a.png", "lazy"],
["../v.mp4", "lazy"],
["../s.mp3", "lazy"],
["../doc.pdf", "lazy"],
["https://cdn.example.com/x.png", "lazy"],
["x.js", undefined],
],
)
})
test("only an image of a missing file gets its path as alt text", () => {
const { nodes } = run([el("video", { src: "missing.mp4" }), el("img", { src: "#x" })])
assert.strictEqual(nodes[0].properties.alt, undefined)
assert.strictEqual(nodes[1].properties.alt, undefined)
})
test("object[data] / source[src] that are empty, fragments or external are not rewritten", () => {
const values = ["", "#frag", "https://example.com/x.svg"]
const { nodes } = run([
...values.map((data) => el("object", { data })),
...values.map((src) => el("source", { src })),
])
assert.deepStrictEqual(
nodes.map((n) => n.properties.data ?? n.properties.src),
[...values, ...values],
)
})
test("anchors without an href are not links", () => {
const named = el("a", { id: "here" }, "folder/x")
run([named])
assert.deepStrictEqual(named.properties, { id: "here" })
assert.strictEqual(text(named), "folder/x")
})
test("the home page and folder pages: index always exists; a folder needs a page under it", () => {
const { nodes } = run([a("/"), a("/fold/"), a("/folder/"), a("/a/")], {
slug: "page",
allSlugs: ["page", "folder/note", "a/b"],
})
assert.deepStrictEqual(
nodes.map((n) => classes(n)!.includes("broken")),
[false, true, false, false],
)
})
test("a missing vault file's type is its last extension", () => {
const { nodes } = run([a("/missing.txt.png"), a("/missing.png.txt")], { slug: "page" })
assert.deepStrictEqual(
nodes.map((n) => classes(n)!.includes("broken")),
[true, false],
)
})
test("permalinks: a link's heading anchor is kept when it is rebased onto the permalink", () => {
const { nodes, file } = run([a("target#Some Heading", "Target"), a("#local")], {
slug: "home",
data: { relativePath: "folder/page.md" },
allSlugs: ["home", "t", "folder/page", "folder/target"],
permalinks: { "folder/page.md": "home", "folder/target.md": "t" },
})
assert.strictEqual(nodes[0].properties.href, "./t#some-heading")
assert.strictEqual(nodes[1].properties.href, "#local")
assert.deepStrictEqual(file.data.links, ["t"])
})
test("frontmatter links: a bare #heading adds no outgoing link, note#heading links the note", () => {
const { file } = run([], {
data: { frontmatterLinks: ["#intro", "other#part", "https://example.com"] },
opts: { markdownLinkResolution: "absolute" },
})
assert.deepStrictEqual(file.data.links, ["other"])
})
})
describe("links to removed pages: marks that change", () => {
const link = (slug: string): Element => ({
type: "element",
tagName: "a",
properties: { href: `./${slug}`, "data-slug": slug, className: ["internal"] },
children: [{ type: "text", value: slug }],
})
const page = (slug: string, children: Element[], data: Record<string, unknown> = {}) => {
const file = new VFile("")
file.data = { slug: slug as FullSlug, ...data } as VFile["data"]
return [{ type: "root", children } as Root, file] as ProcessedContent
}
test("a filter that changes re-marks the link once and re-emits the page", () => {
const home = page("index", [link("draft")])
const changed = new Set<FullSlug>()
markUnpublishedLinks([home], new Map([["draft", "Drafts"]]), undefined, changed)
markUnpublishedLinks([home], new Map([["draft", "Drafts"]]), undefined, changed)
const a = (home[0] as Root).children[0] as Element
assert.deepStrictEqual(a.properties.className, ["internal", "broken"])
changed.clear()
markUnpublishedLinks([home], new Map([["draft", "ExplicitPublish"]]), undefined, changed)
assert.deepStrictEqual([...changed], ["index"])
assert.strictEqual(a.properties["data-filtered"], "ExplicitPublish")
assert.deepStrictEqual(a.properties.className, ["internal", "broken"])
})
test("removedPages names the filter, 'filter' when unknown, and the first removed page wins", () => {
const home = page("index", [])
const a = page("a", [], { aliases: ["shared"] })
const b = page("b", [], { aliases: ["shared"] })
const noSlug = page("", [])
noSlug[1].data.slug = undefined
assert.deepStrictEqual(
[...removedPages([home, a, b, noSlug], [home])],
[
["a", "filter"],
["shared", "filter"],
["b", "filter"],
],
)
const reasons = removedPages([home, a, b], [home], (s) => (s === "a" ? "Drafts" : undefined))
assert.deepStrictEqual(
[...reasons],
[
["a", "Drafts"],
["shared", "Drafts"],
["b", "filter"],
],
)
})
test("only <a> elements are marked; the tags index is a generated target", () => {
const div: Element = {
type: "element",
tagName: "div",
properties: { "data-slug": "draft" },
children: [],
}
const home = page("index", [div, link("tags")])
markUnpublishedLinks([home], new Map([["draft", "Drafts"]]), new Set())
assert.deepStrictEqual(div.properties, { "data-slug": "draft" })
const tags = (home[0] as Root).children[1] as Element
assert.strictEqual(tags.properties["data-missing"], "")
})
})
+78 -46
View File
@@ -15,8 +15,6 @@ import {
resolveRelative,
simplifySlug,
slugifyFilePath,
applySlugOptions,
getSlugOptions,
splitAnchor,
stripSlashes,
transformLink,
@@ -116,21 +114,19 @@ export function linkTargetMissing(allSlugs: readonly string[], full: string): bo
/** The `broken` mark added after filtering, so a later rebuild can take it off again. */
const FILTERED_ATTR = "data-filtered"
/** The `broken` mark for links to folder and tag pages that no page type generated. */
const MISSING_ATTR = "data-missing"
/**
* Links are classified while the transformers run, before the filters decide what is
* published, so a link to a page a filter removes (a draft, a page without `publish: true`)
* still points at an address in `allSlugs` and is not marked `broken` — yet it 404s
* (crawl-links#7). This runs after the filters: links in published pages whose target was
* removed get the `broken` class and `data-filtered="<filter>"`. Links that were marked this
* way and whose target is published again (watch mode) lose both. Returns the number of links
* marked.
* The pages the filters removed (drafts, pages without `publish: true`, …) and their aliases,
* each with the filter that removed it. A folder's `index` note is left out: the folder may still
* get a generated folder page, which only the generated pages tell (markUnpublishedLinks).
*/
export function markLinksToRemovedPages(
export function removedPages(
all: ProcessedContent[],
published: ProcessedContent[],
filteredBy: (slug: string) => string | undefined = () => "filter",
): number {
): Map<string, string> {
const publishedSet = new Set(published)
const live = new Set<string>()
for (const item of published) {
@@ -146,61 +142,97 @@ export function markLinksToRemovedPages(
const reason = filteredBy(data.slug) ?? "filter"
// its aliases (and the file path of a page with a permalink) are gone with it
for (const slug of [data.slug, ...(data.aliases ?? [])]) {
// a folder whose index note is removed still gets a generated folder page
if (slug.endsWith("/index")) continue
if (!live.has(slug) && !removed.has(slug)) removed.set(slug, reason)
}
}
return removed
}
/** Link targets that page types generate (folder pages, tag pages), unknown while transforming. */
function isGeneratedTarget(slug: string): boolean {
return (
slug === "tags" || slug.startsWith("tags/") || (slug !== "index" && slug.endsWith("/index"))
)
}
/**
* Links are classified while the transformers run, before the filters decide what is
* published and before page types generate folder and tag pages, so two kinds of links that
* 404 are not marked `broken` then:
*
* - a link to a page a filter removes (a draft, a page without `publish: true`) still points at
* an address in `allSlugs` (crawl-links#7): it gets `data-filtered="<filter>"`;
* - a link to a folder or tag page (see pageExists) that no page type generated — a folder whose
* notes are all drafts or that holds only images, a tag no published page uses, any folder or
* tag when folder-page / tag-page isn't installed: it gets `data-missing`.
*
* With `generated` (the slugs of the virtual pages, once page types ran) both are checked;
* without it only removed pages, and folder pages are assumed to exist. Links marked this way
* whose target is published again (watch mode) lose the mark; pages whose tree changed are added
* to `changed`, so watch mode re-emits them. Returns the number of links marked.
*/
export function markUnpublishedLinks(
published: ProcessedContent[],
removed: ReadonlyMap<string, string>,
generated?: ReadonlySet<string>,
changed?: Set<FullSlug>,
): number {
const live = new Set<string>(generated ?? [])
for (const [, file] of published) {
if (file.data.slug) live.add(file.data.slug)
for (const alias of file.data.aliases ?? []) live.add(alias)
}
let marked = 0
for (const [tree] of published) {
for (const [tree, file] of published) {
let touched = false
visit(tree as Root, "element", (node: Element) => {
if (node.tagName !== "a" || !node.properties) return
const target = node.properties["data-slug"]
if (typeof target !== "string") return
const classes = Array.isArray(node.properties.className)
? (node.properties.className as string[])
: []
const reason = removed.get(target)
if (reason !== undefined) {
const props = node.properties
const classes = Array.isArray(props.className) ? (props.className as string[]) : []
let attr: string | undefined
let value = ""
// a parent tag's page is `tags/a/index`, served at `tags/a` too
if (!live.has(target) && !live.has(`${target}/index`)) {
const reason = removed.get(target)
if (reason !== undefined) [attr, value] = [FILTERED_ATTR, reason]
else if (generated && isGeneratedTarget(target)) attr = MISSING_ATTR
}
let cleared = false
for (const other of [FILTERED_ATTR, MISSING_ATTR]) {
if (other === attr || props[other] === undefined) continue
delete props[other]
cleared = touched = true
}
if (attr !== undefined) {
if (props[attr] !== value || !classes.includes("broken")) touched = true
if (!classes.includes("broken")) classes.push("broken")
node.properties.className = classes
node.properties[FILTERED_ATTR] = reason
props.className = classes
props[attr] = value
marked++
} else if (node.properties[FILTERED_ATTR] !== undefined) {
node.properties.className = classes.filter((c) => c !== "broken")
delete node.properties[FILTERED_ATTR]
} else if (cleared) {
props.className = classes.filter((c) => c !== "broken")
}
})
if (touched && changed && file.data.slug) changed.add(file.data.slug)
}
return marked
}
/** {@link removedPages} + {@link markUnpublishedLinks}, before page types ran. */
export function markLinksToRemovedPages(
all: ProcessedContent[],
published: ProcessedContent[],
filteredBy: (slug: string) => string | undefined = () => "filter",
): number {
return markUnpublishedLinks(published, removedPages(all, published, filteredBy))
}
/** The Links instance marks links to removed pages after filtering (see build.ts). */
export type LinksInstance = QuartzTransformerPluginInstance & { marksBrokenLinks: boolean }
/**
* Link targets are written as in the vault (`[[Čeština]]`, `../české/x.png`). With
* `configuration.slugs.stripDiacritics` the pages and files they point at have stripped slugs,
* so the path part of the target is stripped the same way before it is resolved (wikilinks
* from obsidian-flavored-markdown are slugged with the plain rules first). The `#anchor` is
* left alone: heading ids keep their diacritics.
*/
function slugOptionsOnLinkPath(raw: string): string {
if (!getSlugOptions().stripDiacritics) return raw
const hash = raw.indexOf("#")
const linkPath = hash === -1 ? raw : raw.slice(0, hash)
const anchor = hash === -1 ? "" : raw.slice(hash)
let decoded = linkPath
try {
decoded = decodeURI(linkPath)
} catch {
// not percent-encoded (or malformed): strip as written
}
const stripped = applySlugOptions(decoded)
return stripped === decoded ? raw : stripped + anchor
}
export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
const opts = { ...linksDefaults, ...userOpts }
const instance: LinksInstance = {
@@ -227,7 +259,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
: fileSlug
const rebase = targets.size > 0 || pathSlug !== fileSlug
const resolveLink = (raw: string): RelativeURL => {
const rel = transformLink(pathSlug, slugOptionsOnLinkPath(raw), transformOptions)
const rel = transformLink(pathSlug, raw, transformOptions)
if (!rebase) return rel
const hash = rel.indexOf("#")
const anchor = hash === -1 ? "" : rel.slice(hash)
@@ -0,0 +1,430 @@
import assert from "node:assert/strict"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { registerHooks } from "node:module"
import test, { after, describe } from "node:test"
import { createContext, runInContext } from "node:vm"
import type { BuildCtx } from "../../util/ctx"
import type { QuartzComponent } from "../../components/types"
import type { StaticResources } from "../../util/resources"
import type { GlobalConfiguration } from "../../cfg"
// The emitter imports SCSS and inline browser scripts that esbuild bundles in a real build. Under
// tsx each one is replaced by a marker: `.stub-<name>{--stub:<name>}` for SCSS, `window.__stub_<name>`
// for scripts, so the tests can tell where each one ends up.
registerHooks({
load(url, context, next) {
const name = path.basename(new URL(url).pathname).replace(/\.(inline\.ts|scss)$/, "")
if (url.endsWith(".scss")) {
const css = `.stub-${name.replace(/\W/g, "_")}{--stub:${name.replace(/\W/g, "_")}}`
return {
format: "module",
source: `export default ${JSON.stringify(css)}`,
shortCircuit: true,
}
}
if (/\.inline\.ts$/.test(url)) {
const js = `window.__stub_${name} = 1`
return {
format: "module",
source: `export default ${JSON.stringify(js)}`,
shortCircuit: true,
}
}
return next(url, context)
},
})
const { ComponentResources } = await import("./componentResources")
const theme = {
fontOrigin: "local",
cdnCaching: true,
typography: { header: "Header Font", body: "Body Font", code: "Code Font" },
colors: {
lightMode: {
light: "#fff",
lightgray: "#eee",
gray: "#999",
darkgray: "#444",
dark: "#222",
secondary: "#00f",
tertiary: "#0f0",
highlight: "#ff0",
textHighlight: "#ff08",
},
darkMode: {
light: "#000",
lightgray: "#111",
gray: "#666",
darkgray: "#bbb",
dark: "#ddd",
secondary: "#88f",
tertiary: "#8f8",
highlight: "#880",
textHighlight: "#8808",
},
},
}
const Widget: QuartzComponent = Object.assign(() => null, {
css: ".widget{color:blue}",
beforeDOMLoaded: "window.__widgetBefore = 1",
afterDOMLoaded: "window.__widgetAfter = 1",
})
const Other: QuartzComponent = Object.assign(() => null, {
css: [".other{color:green}"],
afterDOMLoaded: ["window.__otherAfter = 1"],
})
const dirs: string[] = []
after(() => {
for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true })
})
async function emit(
configuration: Partial<GlobalConfiguration>,
{
serve = false,
resources = { css: [], js: [], additionalHead: [] } as StaticResources,
// the same component from two emitters is collected once; an emitter may have none
emitters = [
{ getQuartzComponents: () => [Widget, Other] },
{ getQuartzComponents: () => [Widget] },
{},
] as unknown[],
} = {},
) {
const output = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-component-resources-"))
dirs.push(output)
const ctx = {
argv: { output, serve },
cfg: {
configuration: { enableSPA: true, enablePopovers: true, theme, ...configuration },
plugins: { emitters },
},
} as unknown as BuildCtx
const written: string[] = []
for await (const fp of ComponentResources().emit(ctx, [], resources) as AsyncIterable<string>) {
written.push(path.relative(output, fp).split(path.sep).join("/"))
}
const read = (name: string) => fs.readFileSync(path.join(output, name), "utf8")
return { ctx, written, read }
}
/** The script files postscript.js imports, in its order, with whether each is awaited alone. */
function importedScripts(postscript: string) {
return [...postscript.matchAll(/import\("\.\/([^"]+)"\)/g)].map((m) => m[1])
}
describe("ComponentResources emitter", () => {
test("production: content-hashed index.css / prescript / postscript, named in ctx.hashedResourceNames", async () => {
const { ctx, written, read } = await emit({})
const names = ctx.hashedResourceNames!
assert.match(names["index.css"], /^index-[0-9a-f]{8}\.css$/)
assert.match(names["prescript.js"], /^prescript-[0-9a-f]{8}\.js$/)
assert.match(names["postscript.js"], /^postscript-[0-9a-f]{8}\.js$/)
for (const file of Object.values(names)) assert.ok(written.includes(file), file)
// components' beforeDOMLoaded scripts go in the prescript (once, though listed twice)
const prescript = read(names["prescript.js"])
assert.equal(prescript.split("__widgetBefore").length, 2)
})
test("production: postscript loads component scripts in parallel and the SPA router last", async () => {
const { ctx, written, read } = await emit({ prefetch: "hover" })
const postscript = read(ctx.hashedResourceNames!["postscript.js"])
const scripts = importedScripts(postscript)
for (const s of scripts) {
assert.match(s, /^static\/scripts\/script-\d+-[0-9a-f]{8}\.js$/)
assert.ok(written.includes(s), s)
}
const contents = scripts.map(read)
// component scripts, then the global ones: popover, prefetch (with its settings), router
assert.deepEqual(
contents.map((c) =>
c.includes("__widgetAfter")
? "widget"
: c.includes("__otherAfter")
? "other"
: c.includes("__stub_popover")
? "popover"
: c.includes("__stub_prefetch")
? "prefetch"
: c.includes("__stub_spa")
? "spa"
: c,
),
["widget", "other", "popover", "prefetch", "spa"],
)
assert.match(
contents[3],
/window\.__quartzPrefetchMode = "hover";\nwindow\.__quartzSpa = true;/,
)
// all but the router are imported together; the router (which dispatches the first `nav`)
// only after they all registered their listeners
const last = scripts[scripts.length - 1]
const [parallel, rest] = postscript.split(`await import("./${last}")`)
assert.ok(parallel.startsWith("await Promise.all(["), postscript)
assert.ok(!parallel.includes("__stub_spa") && !parallel.includes(last), postscript)
for (const s of scripts.slice(0, -1)) assert.ok(parallel.includes(`import("./${s}")`), s)
assert.equal(rest.trim(), ";")
})
test("prefetching defaults to viewport mode", async () => {
const { ctx, read } = await emit({ prefetch: undefined })
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
const prefetch = scripts.find((s) => s.includes("__stub_prefetch"))!
assert.match(prefetch, /^window\.__quartzPrefetchMode = "viewport";/)
})
test("without SPA routing the last script dispatches the first nav itself; prefetch: false loads no prefetcher", async () => {
const { ctx, read } = await emit({
enableSPA: false,
enablePopovers: false,
prefetch: false as never,
})
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
assert.ok(!scripts.some((s) => s.includes("__stub_spa")))
assert.ok(!scripts.some((s) => s.includes("__stub_prefetch") || s.includes("__stub_popover")))
assert.match(scripts[scripts.length - 1], /new CustomEvent\("nav"/)
assert.ok(!read(ctx.hashedResourceNames!["index.css"]).includes("stub-popover"))
})
test("component CSS goes into one component stylesheet; index.css has theme, global and base styles", async () => {
const { ctx, written, read } = await emit({})
const componentFile = written.find((f) => /^component-[0-9a-f]{8}\.css$/.test(f))
assert.ok(componentFile, written.join(", "))
const componentCss = read(componentFile)
assert.match(componentCss, /\.widget\{color:#00f\}/)
assert.match(componentCss, /\.other\{color:green\}/)
assert.equal(ctx.componentCssMap!.get(".widget{color:blue}"), componentFile)
assert.equal(ctx.componentCssMap!.get(".other{color:green}"), componentFile)
const index = read(ctx.hashedResourceNames!["index.css"])
assert.ok(!index.includes(".widget"), "component CSS is not duplicated into index.css")
// the popover's CSS (added globally) and base styles in the quartz-base layer, then custom.scss
assert.match(
index,
/^@layer quartz-base\{.*\.stub-popover\{.*\.stub-base\{.*\}\.stub-custom\{/s,
)
assert.match(index, /--secondary:#00f/)
assert.match(index, /--titleFont:"Header Font"/)
})
test("inline plugin CSS/JS resources are moved to files named in ctx.extractedInlineResources", async () => {
const resources = {
css: [
{ content: ".plugin-inline { color: red; }", inline: true },
{ content: "https://example.com/external.css" },
],
js: [
{ script: "window.__early = 1", loadTime: "beforeDOMReady", contentType: "inline" },
{ script: "window.__late = 1", loadTime: "afterDOMReady", contentType: "inline" },
{ src: "https://example.com/x.js", loadTime: "afterDOMReady", contentType: "external" },
],
additionalHead: [],
} as unknown as StaticResources
const { ctx, written, read } = await emit({}, { resources })
const map = ctx.extractedInlineResources!
assert.equal(map.size, 3)
const css = map.get(".plugin-inline { color: red; }")!
assert.match(css, /^static\/resource-style-[0-9a-f]{8}\.css$/)
assert.equal(read(css), ".plugin-inline{color:red}")
const early = map.get("window.__early = 1")!
const late = map.get("window.__late = 1")!
assert.match(early, /^static\/resource-before-[0-9a-f]{8}\.js$/)
assert.match(late, /^static\/resource-after-[0-9a-f]{8}\.js$/)
assert.match(read(late), /window\.__late=1/)
for (const f of [css, early, late]) assert.ok(written.includes(f), f)
// the resources themselves are left as they are (partial rebuilds reuse them)
assert.equal(resources.css.length, 2)
})
test("CSS a plugin marks inline that lightningcss can't parse is written as it is", async () => {
const broken = ".a { color: red"
const resources = {
css: [
{ content: "@media (", inline: true },
{ content: broken, inline: true },
],
js: [],
additionalHead: [],
} as unknown as StaticResources
const { ctx, read } = await emit({}, { resources })
assert.equal(read(ctx.extractedInlineResources!.get("@media (")!), "@media (")
})
test("serve mode: unhashed names and one minified postscript bundle in order", async () => {
const { ctx, written, read } = await emit({}, { serve: true })
assert.deepEqual(ctx.hashedResourceNames, {
"index.css": "index.css",
"prescript.js": "prescript.js",
"postscript.js": "postscript.js",
})
assert.ok(!written.some((f) => f.startsWith("static/scripts/")))
const postscript = read("postscript.js")
const order = [
"__widgetAfter",
"__otherAfter",
"__stub_popover",
"__stub_prefetch",
"__stub_spa",
].map((marker) => postscript.indexOf(marker))
assert.ok(order.every((at) => at >= 0))
assert.deepEqual(
[...order].sort((a, b) => a - b),
order,
)
// minified by esbuild
assert.ok(!postscript.includes("window.__widgetAfter = 1"), postscript)
})
test("postscript.js is a valid module: the parallel imports are comma-separated", async () => {
const { ctx, read } = await emit({})
const postscript = read(ctx.hashedResourceNames!["postscript.js"])
const AsyncFunction = (async () => {}).constructor as new (code: string) => unknown
assert.doesNotThrow(() => new AsyncFunction(postscript), postscript)
assert.equal(importedScripts(postscript).length, 5)
})
test("without component CSS no component stylesheet is emitted", async () => {
const { ctx, written } = await emit({}, { emitters: [] })
assert.ok(!written.some((f) => f.startsWith("component-")), written.join(", "))
assert.equal(ctx.componentCssMap!.size, 0)
})
})
describe("analytics scripts", () => {
/** Run the site's analytics script in a fake page; returns the URLs of the scripts it loads. */
async function loadedScripts(analytics: Record<string, unknown>) {
const { ctx, read } = await emit(
{
analytics: analytics as GlobalConfiguration["analytics"],
enablePopovers: false,
prefetch: false as never,
},
{ emitters: [] },
)
const scripts = importedScripts(read(ctx.hashedResourceNames!["postscript.js"])).map(read)
// the analytics script(s), before the router
const ours = scripts.slice(0, -1)
const loaded: { src: string; attributes: Record<string, string> }[] = []
const element = () => ({
attributes: {} as Record<string, string>,
setAttribute(name: string, value: string) {
this.attributes[name] = value
},
})
const firstScript = { parentNode: { insertBefore: (s: never) => loaded.push(s) } }
const document = Object.assign(new EventTarget(), {
title: "Page",
createElement: element,
head: { appendChild: (s: never) => loaded.push(s) },
getElementsByTagName: () => [firstScript],
})
const context = createContext({
document,
location: { hostname: "garden.example", pathname: "/", href: "https://garden.example/" },
})
context.window = context
for (const script of ours) runInContext(script, context)
return { loaded: loaded.map((s) => ({ src: s.src, attributes: s.attributes })), context, ours }
}
const cases: [Record<string, unknown>, string, Record<string, string>?][] = [
[{ provider: "google", tagId: "G-1" }, "https://www.googletagmanager.com/gtag/js?id=G-1"],
[
{ provider: "plausible" },
"https://plausible.io/js/script.manual.js",
{ "data-domain": "garden.example" },
],
[{ provider: "plausible", host: "https://p.example" }, "https://p.example/js/script.manual.js"],
[
{ provider: "umami", websiteId: "w1" },
"https://analytics.umami.is/script.js",
{ "data-website-id": "w1" },
],
[
{ provider: "umami", websiteId: "w1", host: "https://u.example", script: "u.js" },
"https://u.example/u.js",
],
[{ provider: "goatcounter", websiteId: "g1" }, "https://gc.zgo.at/count.js"],
[{ provider: "posthog", apiKey: "k" }, "https://app.posthog.com/static/array.js"],
[
{ provider: "posthog", apiKey: "k", host: "https://ph.example" },
"https://ph.example/static/array.js",
],
[
{ provider: "posthog", apiKey: "k", host: "https://h", apiHost: "https://api.h" },
"https://api.h/static/array.js",
],
[{ provider: "tinylytics", siteId: "t 1" }, "https://tinylytics.app/embed/t%201.js?spa"],
[{ provider: "cabin" }, "https://scripts.withcabin.com/hello.js"],
[{ provider: "cabin", host: "https://c.example" }, "https://c.example/hello.js"],
[{ provider: "clarity", projectId: "c1" }, "https://www.clarity.ms/tag/c1"],
[{ provider: "matomo", host: "m.example", siteId: "3" }, "//m.example/matomo.js"],
[{ provider: "vercel" }, "/_vercel/insights/script.js"],
[
{ provider: "rybbit", siteId: "r1" },
"https://app.rybbit.io/api/script.js",
{ "data-site-id": "r1" },
],
[
{ provider: "rybbit", siteId: "r1", host: "https://r.example" },
"https://r.example/api/script.js",
],
]
for (const [analytics, src, attributes] of cases) {
test(`${JSON.stringify(analytics)} loads ${src}`, async () => {
const { loaded } = await loadedScripts(analytics)
assert.deepEqual(
loaded.map((s) => s.src),
[src],
)
for (const [name, value] of Object.entries(attributes ?? {})) {
assert.equal(loaded[0].attributes[name], value, name)
}
})
}
test("goatcounter counts at the site's endpoint; posthog gets its options", async () => {
const gc = await loadedScripts({ provider: "goatcounter", websiteId: "g1", host: "gc.example" })
assert.ok(gc.ours.join("\n").includes('"https://" + "g1" + "." + "gc.example" + "/count"'))
const ph = await loadedScripts({
provider: "posthog",
apiKey: "k",
uiHost: "https://ui.example",
personProfiles: "identified_only",
})
const init = (ph.context.posthog as { _i: [string, Record<string, unknown>][] })._i[0]
assert.deepEqual(init[0], "k")
assert.deepEqual(
{ ...init[1] },
{
api_host: "https://app.posthog.com",
ui_host: "https://ui.example",
person_profiles: "identified_only",
capture_pageview: false,
},
)
})
test("vercel's queue stub is defined in the prescript, before any script runs", async () => {
const { ctx, read } = await emit({ analytics: { provider: "vercel" } }, { emitters: [] })
const context = createContext({})
context.window = context
runInContext(read(ctx.hashedResourceNames!["prescript.js"]), context)
assert.equal(typeof context.va, "function")
context.va("event", "x")
assert.deepEqual(
[...(context.vaq as unknown[][])].map((args) => [...args]),
[["event", "x"]],
)
})
test("no analytics, no analytics script", async () => {
const { ours } = await loadedScripts({})
assert.deepEqual(ours, [])
})
})
+14 -9
View File
@@ -25,6 +25,7 @@ import {
import { Features, transform } from "lightningcss"
import { transform as transpile } from "esbuild"
import { write } from "./helpers"
import { componentStylesheet } from "../../util/componentCss"
/**
* Content hash for cache-busting file names (`postscript-<hash>.js`). Not a password or security
@@ -39,6 +40,8 @@ type ComponentResources = {
beforeDOMLoaded: string[]
afterDOMLoaded: string[]
componentCssStrings: Set<string>
/** Component CSS → the component that brought it, to name it in warnings. */
cssOwners: Map<string, string>
}
function getComponentResources(ctx: BuildCtx): ComponentResources {
@@ -61,9 +64,13 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
afterDOMLoaded: new Set<string>(),
}
const cssOwners = new Map<string, string>()
for (const component of allComponents) {
const { css, beforeDOMLoaded, afterDOMLoaded } = component
for (const c of normalizeResource(css)) componentResources.css.add(c)
for (const c of normalizeResource(css)) {
componentResources.css.add(c)
if (!cssOwners.has(c)) cssOwners.set(c, component.displayName ?? component.name ?? "")
}
for (const b of normalizeResource(beforeDOMLoaded)) componentResources.beforeDOMLoaded.add(b)
for (const a of normalizeResource(afterDOMLoaded)) componentResources.afterDOMLoaded.add(a)
}
@@ -73,6 +80,7 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
beforeDOMLoaded: [...componentResources.beforeDOMLoaded],
afterDOMLoaded: [...componentResources.afterDOMLoaded],
componentCssStrings: new Set(componentResources.css),
cssOwners,
}
}
@@ -436,14 +444,11 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
const cssStringToFilename = new Map<string, string>()
const componentCss = [...componentResources.componentCssStrings]
if (componentCss.length > 0) {
const wrapped = `@layer quartz-base {\n${componentCss.join("\n")}\n}`
const minified = transform({
filename: "component.css",
code: Buffer.from(wrapped),
minify: true,
targets: lightningTargets,
include: Features.MediaQueries,
}).code.toString()
const minified = componentStylesheet(
componentCss,
(c) => componentResources.cssOwners.get(c),
lightningTargets,
)
const hash = hashContent(minified)
const slug = `component-${hash}`
+1
View File
@@ -1,3 +1,4 @@
export { Assets } from "./assets"
export { Static } from "./static"
export { ComponentResources } from "./componentResources"
export { SlugRedirects } from "./slugRedirects"
@@ -0,0 +1,148 @@
import assert from "node:assert/strict"
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 { BuildCtx } from "../../util/ctx"
import type { StaticResources } from "../../util/resources"
import { SlugRedirects, strippedAddressMoves } from "./slugRedirects"
const page = (
relativePath: string,
frontmatter: Record<string, unknown> = {},
): ProcessedContent => {
const file = new VFile("")
file.data = {
relativePath: relativePath as FilePath,
slug: slugifyFilePath(relativePath as FilePath),
frontmatter: { title: relativePath, ...frontmatter },
} as VFile["data"]
return [{ type: "root", children: [] } as Root, file]
}
describe("redirects from addresses slugs.stripDiacritics changed", () => {
test("pages, their folders and aliases redirect from the unstripped address", () => {
setSlugOptions({ stripDiacritics: true })
try {
const content = [
page("české/Žluťoučký kůň/poznámka.md", { aliases: ["stará"] }),
page("plain/note.md"),
]
const live = new Set(content.map(([, f]) => f.data.slug!))
assert.deepEqual(Object.fromEntries(strippedAddressMoves(content, live)), {
"české/žluťoučký-kůň/poznámka": "ceske/zlutoucky-kun/poznamka",
"české/index": "ceske/index",
"české/žluťoučký-kůň/index": "ceske/zlutoucky-kun/index",
stará: "ceske/zlutoucky-kun/poznamka",
})
} finally {
setSlugOptions(undefined)
}
})
test("an old address that is a page of the site is left alone", () => {
setSlugOptions({ stripDiacritics: true })
try {
const content = [page("café.md")]
const live = new Set(["café" as FullSlug, "cafe" as FullSlug])
assert.equal(strippedAddressMoves(content, live).size, 0)
} finally {
setSlugOptions(undefined)
}
})
})
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á"] })]), {})
})
})
+105
View File
@@ -0,0 +1,105 @@
import { QuartzEmitterPlugin } from "../types"
import { ProcessedContent } from "../vfile"
import {
FilePath,
FullSlug,
getSlugOptions,
resolveRelative,
setSlugOptions,
simplifySlug,
slugifyFilePath,
} from "../../util/path"
import { write } from "./helpers"
import { BuildCtx } from "../../util/ctx"
/** The slug `fp` had without `slugs.stripDiacritics` (lowercased, diacritics kept). */
function unstrippedSlug(fp: string): FullSlug {
const options = getSlugOptions()
setSlugOptions({ ...options, stripDiacritics: false })
try {
return slugifyFilePath(fp as FilePath)
} finally {
setSlugOptions(options)
}
}
/**
* The addresses `slugs.stripDiacritics` changed → where they moved: every published page's
* address as it was without the option (`české/žluťoučký-kůň/poznámka` →
* `ceske/zlutoucky-kun/poznamka`), its folders' (`české/` → `ceske/`) and its aliases'. An old
* address that is a page of the site, or another old address's, is left alone.
*/
export function strippedAddressMoves(
content: ProcessedContent[],
live: ReadonlySet<string>,
): Map<FullSlug, FullSlug> {
const moves = new Map<FullSlug, FullSlug>()
const add = (from: FullSlug, to: FullSlug) => {
if (from === to || live.has(from) || moves.has(from)) return
moves.set(from, to)
}
for (const [, file] of content) {
const { slug, relativePath } = file.data
if (!slug || !relativePath) continue
const old = unstrippedSlug(relativePath)
const now = slugifyFilePath(relativePath as FilePath)
// a page at its file path (not a permalink) moved with it
if (now === slug) add(old, slug)
// its folders: `české/žluťoučký-kůň/x` → `české/index`, `české/žluťoučký-kůň/index`
const oldParts = old.split("/")
const nowParts = now.split("/")
if (oldParts.length === nowParts.length) {
for (let i = 1; i < oldParts.length; i++) {
add(
[...oldParts.slice(0, i), "index"].join("/") as FullSlug,
[...nowParts.slice(0, i), "index"].join("/") as FullSlug,
)
}
}
for (const alias of (file.data.frontmatter?.aliases as unknown[] | undefined) ?? []) {
if (typeof alias !== "string") continue
const fp = alias.endsWith(".md") ? alias : `${alias}.md`
add(unstrippedSlug(fp), slug)
}
}
return moves
}
function redirectHtml(to: string, url: string): string {
return `<!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>
`
}
async function* emitMoves(ctx: BuildCtx, content: ProcessedContent[]) {
if (!getSlugOptions().stripDiacritics) return
const live = new Set<string>()
for (const [, file] of content) {
if (file.data.slug) live.add(file.data.slug)
for (const alias of file.data.aliases ?? []) live.add(alias)
}
for (const [from, to] of strippedAddressMoves(content, live)) {
const url = resolveRelative(from, simplifySlug(to) as unknown as FullSlug)
yield write({ ctx, slug: from, ext: ".html", content: redirectHtml(simplifySlug(to), url) })
}
}
/**
* With `configuration.slugs.stripDiacritics`, pages, folders and aliases whose names have
* diacritics get new addresses. This writes a redirect at each old address (as Quartz 5 slugged
* it: lowercased, diacritics kept) to the new one, so links and bookmarks to the old site keep
* working. alias-redirects' case redirects only cover the address as spelled in the vault.
*/
export const SlugRedirects: QuartzEmitterPlugin = () => ({
name: "SlugRedirects",
emit: (ctx, content) => emitMoves(ctx, content),
partialEmit: (ctx, content) => emitMoves(ctx, content),
})
+240 -6
View File
@@ -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,85 @@ describe("resolveExtends", () => {
)
})
describe("keys starting with $ are reserved", () => {
const own = path.join(root, "quartz.config.yaml")
const opts = { quartzRoot: root, readFile }
test("in the extending file, at any depth", async () => {
for (const [data, where] of [
[
{ configuration: { ignorePatterns: { $append: ["drafts"] } } },
"configuration.ignorePatterns.$append",
],
[{ configuration: { $pageTitle: "x" } }, "configuration.$pageTitle"],
[
{ layout: { byPageType: { folder: { $exclude: [] } } } },
"layout.byPageType.folder.$exclude",
],
[
{ plugins: [{ source: "@quartz-community/explorer", options: { $merge: {} } }] },
"plugins.0.options.$merge",
],
[
{ plugins: [{ source: "@quartz-community/explorer", $remove: true }] },
"plugins.0.$remove",
],
[{ $plugins: [] }, "$plugins"],
] as const) {
await assert.rejects(
() => resolveExtends({ extends: "default", ...data }, own, opts),
{
name: "ConfigExtendsError",
message: `${own}: "${where}" — keys starting with "$" are reserved in configs that use "extends"`,
},
where,
)
}
})
test("in a base the config extends", async () => {
put("preset.yaml", { extends: "default", configuration: { $x: 1 } })
await assert.rejects(
() => resolveExtends({ extends: "./preset.yaml" }, own, opts),
/preset\.yaml: "configuration\.\$x" — keys starting with "\$" are reserved/,
)
})
test("the top-level $schema is allowed, and $ inside values is fine", async () => {
const merged = await resolveExtends(
{
$schema: "./quartz/plugins/quartz-plugins.schema.json",
extends: "default",
configuration: { pageTitle: "$5 tips", ignorePatterns: ["$tmp"] },
},
own,
opts,
)
assert.strictEqual(merged.configuration.pageTitle, "$5 tips")
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["$tmp"])
})
test("a config without extends is not checked", async () => {
const data = { configuration: { pageTitle: "x", $custom: 1 }, plugins: [] }
assert.strictEqual(await resolveExtends(data, own, opts), data as never)
})
})
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 +531,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 +581,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"),
)
})
})
+27
View File
@@ -342,6 +342,32 @@ export function resolveTarget(target: string, from: string, quartzRoot: string):
return resolved
}
/**
* Keys starting with `$` are reserved in every file of an `extends` chain (the top-level
* `$schema` aside), at any depth: they are kept free for merge operators, such as appending
* to a list instead of replacing it, so adding those later changes no existing config.
*/
export const RESERVED_KEY_PREFIX = "$"
function assertNoReservedKeys(data: PlainObject, file: string) {
const visit = (value: unknown, at: string[]) => {
if (Array.isArray(value)) {
value.forEach((item, i) => visit(item, [...at, String(i)]))
return
}
if (!isPlainObject(value)) return
for (const [key, child] of Object.entries(value)) {
if (key.startsWith(RESERVED_KEY_PREFIX) && !(at.length === 0 && key === "$schema")) {
throw new ConfigExtendsError(
`${file}: "${[...at, key].join(".")}" — keys starting with "${RESERVED_KEY_PREFIX}" are reserved in configs that use "extends"`,
)
}
visit(child, [...at, key])
}
}
visit(data, [])
}
interface ConfigLayer {
/** Resolved path or URL ("" for the config being resolved). */
file: string
@@ -443,6 +469,7 @@ async function extendsLayers(
await visit(parsed, targetFile, here)
}
const { extends: _drop, ...own } = node
assertNoReservedKeys(own, nodeFile)
layers.push({ file: chain.length === 0 ? "" : self, data: own })
applied.add(self)
}
@@ -0,0 +1,428 @@
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 { getDiagnostics, resetDiagnostics } from "../../util/diagnostics"
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"))
})
})
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.",
})
})
})
})
+302
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,302 @@ 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. An emitter (or a component)
// depending on a transformer with a higher order used to fail 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", () => {
const transformer = { category: "transformer", defaultOrder: 60 } as const
assert.deepStrictEqual(validate({ category: "emitter" }, transformer).errors, [])
assert.deepStrictEqual(validate({ category: "component" }, transformer).errors, [])
assert.deepStrictEqual(
validate({ category: "component" }, { category: "component", defaultOrder: 60 }).errors,
[],
)
})
test("a plugin of several stages is ordered against a dependency in a stage they share", () => {
const transformer = { category: "transformer", defaultOrder: 60 } as const
assert.match(
validate({ category: ["transformer", "emitter"] }, transformer).errors[0],
/"x" \(order: 50\) depends on "y" \(order: 60\)/,
)
// without a category the stage is unknown: still compared
assert.match(validate({}, { defaultOrder: 60 }).errors[0], /depends on "y" \(order: 60\)/)
})
})
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])
})
})
+55 -3
View File
@@ -31,6 +31,7 @@ import {
getPluginEntryPoint,
toFileUrl,
isLocalSource,
linkPeerDependencies,
} from "./gitLoader"
import { loadComponentsFromPackage } from "./componentLoader"
import { attributeComponentExport, shortPluginName } from "../../components/attribution"
@@ -50,6 +51,16 @@ import {
} from "../builtins"
import { registerPluginOrigin, reportError, warn } from "../../util/diagnostics"
import { firstPluginFrame } from "../../util/trace"
import { currentLockfilePath } from "../../cli/lockfile-path.js"
import {
ensureNpmPlugin,
isHostDependency,
isPinnedNpmPluginInstalled,
npmPackageName,
npmPluginDir,
readNpmLockEntry,
removeNpmPlugin,
} from "../../cli/npm-plugins.js"
import {
checkQuartzRequirement,
describeDeprecation,
@@ -159,6 +170,22 @@ interface DependencyValidationResult {
warnings: string[]
}
/** The pipeline stages a plugin's `order` decides its place in (a component has none). */
const ORDERED_STAGES = ["transformer", "filter", "emitter", "pageType"] as const
/**
* Whether `order` decides between the two plugins: they run in a stage they share (all
* transformers run before any filter or emitter, whatever their order). Without a category on
* either side the stage is unknown, and they are compared.
*/
function sameStage(a: PluginManifest, b: PluginManifest | undefined): boolean {
if (!a.category || !b?.category) return true
const stagesOfB = [b.category].flat()
return [a.category]
.flat()
.some((c) => stagesOfB.includes(c) && (ORDERED_STAGES as readonly string[]).includes(c))
}
export function validateDependencies(
entries: PluginJsonEntry[],
manifests: Map<string, PluginManifest>,
@@ -229,7 +256,7 @@ export function validateDependencies(
const depManifest = manifests.get(dep)
const depOrder = depEntry.order ?? depManifest?.defaultOrder ?? 50
if (pluginOrder < depOrder) {
if (pluginOrder < depOrder && sameStage(manifest, depManifest)) {
errors.push(
`Plugin "${pluginName}" (order: ${pluginOrder}) depends on "${depName}" (order: ${depOrder}), ` +
`but "${pluginName}" is configured to run first. Either increase "${pluginName}"'s order above ${depOrder} ` +
@@ -287,11 +314,22 @@ export function validateDependencies(
* so their init(options) and entry-module side effects never ran.)
*/
async function importPluginModule(spec: ReturnType<typeof parsePluginSource>) {
return spec.npmPackage
return spec.npmPackage && !isPinnedNpm(spec)
? await import(spec.name)
: await import(toFileUrl(getPluginEntryPoint(spec.name)))
}
const PLUGINS_DIR = path.join(process.cwd(), ".quartz", "plugins")
/**
* An npm plugin pinned in quartz.lock.json and installed in .quartz/plugins/@scope/name, because
* package.json doesn't list it (see cli/npm-plugins.js). One that package.json lists loads from
* node_modules.
*/
function isPinnedNpm(spec: ReturnType<typeof parsePluginSource>): boolean {
return !!spec.npmPackage && isPinnedNpmPluginInstalled(npmPackageName(spec.name), PLUGINS_DIR)
}
async function resolvePluginManifest(source: PluginSource): Promise<PluginManifest | null> {
try {
const module = await importPluginModule(parsePluginSource(source))
@@ -305,7 +343,7 @@ async function readManifestFromPackageJson(source: PluginSource): Promise<Plugin
try {
const gitSpec = parsePluginSource(source)
let pkgPath: string
if (gitSpec.npmPackage) {
if (gitSpec.npmPackage && !isPinnedNpm(gitSpec)) {
pkgPath = fileURLToPath(import.meta.resolve(`${gitSpec.name}/package.json`))
} else {
const pluginDir = path.join(process.cwd(), ".quartz", "plugins", gitSpec.name)
@@ -422,6 +460,19 @@ export async function loadQuartzConfig(
try {
const gitSpec = parsePluginSource(entry.source)
if (gitSpec.npmPackage) {
// npm plugins package.json doesn't list: installed at the version quartz.lock.json pins
// (the latest when it pins none), as a missing Git plugin is cloned below
const name = npmPackageName(gitSpec.name)
if (isHostDependency(name)) {
// package.json wins: a copy left from when it was pinned would shadow its components
removeNpmPlugin(name, PLUGINS_DIR)
continue
}
const installed = ensureNpmPlugin(name, {
lockEntry: readNpmLockEntry(name, currentLockfilePath()),
pluginsDir: PLUGINS_DIR,
})
if (installed) linkPeerDependencies(npmPluginDir(name, PLUGINS_DIR))
continue
}
const result = await installPlugin(gitSpec, { verbose: false })
@@ -749,6 +800,7 @@ export async function loadQuartzConfig(
builtinPlugins.ComponentResources(),
builtinPlugins.Assets(),
builtinPlugins.Static(),
builtinPlugins.SlugRedirects(),
]
const builtinPageTypes = [builtinPlugins.PageTypes.NotFoundPageType()]
+11 -9
View File
@@ -9,6 +9,8 @@ import {
npm,
} from "../../cli/subprocess.js"
import { writePluginIndex } from "../../cli/plugin-index.js"
import { listPluginDirNames } from "../../cli/npm-plugins.js"
import { currentLockfilePath } from "../../cli/lockfile-path.js"
import git from "isomorphic-git"
import http from "isomorphic-git/http/node"
import { styleText } from "util"
@@ -46,7 +48,6 @@ export interface GitPluginSpec {
export type PluginInstallSource = string | GitPluginSpec
const PLUGINS_CACHE_DIR = path.join(process.cwd(), ".quartz", "plugins")
const LOCKFILE_PATH = path.join(process.cwd(), "quartz.lock.json")
const GIT_TIMEOUT_MS = 300_000
/**
@@ -55,7 +56,7 @@ const GIT_TIMEOUT_MS = 300_000
*/
export function readLockedCommit(
spec: Pick<GitPluginSpec, "name" | "repo" | "subdir">,
lockfilePath: string = LOCKFILE_PATH,
lockfilePath: string = currentLockfilePath(),
): string | undefined {
try {
const lock = JSON.parse(fs.readFileSync(lockfilePath, "utf-8"))
@@ -366,12 +367,8 @@ function needsBuild(pluginDir: string): boolean {
function findPluginByPackageName(packageName: string): string | null {
if (!fs.existsSync(PLUGINS_CACHE_DIR)) return null
const plugins = fs.readdirSync(PLUGINS_CACHE_DIR).filter((entry) => {
const entryPath = path.join(PLUGINS_CACHE_DIR, entry)
return fs.statSync(entryPath).isDirectory()
})
for (const pluginDirName of plugins) {
// `name` for Git and local plugins, `@scope/name` for pinned npm plugins
for (const pluginDirName of listPluginDirNames(PLUGINS_CACHE_DIR)) {
const pkgPath = path.join(PLUGINS_CACHE_DIR, pluginDirName, "package.json")
if (!fs.existsSync(pkgPath)) continue
try {
@@ -406,7 +403,12 @@ export function linkPeerDependencies(pluginDir: string): void {
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"))
const peers: Record<string, string> = pkg.peerDependencies ?? {}
const quartzRoot = path.resolve(pluginDir, "..", "..", "..")
// .quartz/plugins/<name>, or .quartz/plugins/@scope/<name> for a pinned npm plugin
const scoped = path.basename(path.dirname(pluginDir)).startsWith("@")
const quartzRoot = path.resolve(
pluginDir,
...(scoped ? ["..", "..", "..", ".."] : ["..", "..", ".."]),
)
const hostNodeModules = path.join(quartzRoot, "node_modules")
// a local plugin is a symlink; relative links made through it would dangle
const realDir = fs.realpathSync(pluginDir)
+35 -2
View File
@@ -2,7 +2,21 @@
import fs from "fs"
import path from "path"
import YAML from "yaml"
import { installPlugins, parsePluginSource, regeneratePluginIndex } from "./gitLoader.js"
import {
installPlugins,
linkPeerDependencies,
parsePluginSource,
regeneratePluginIndex,
} from "./gitLoader.js"
import {
ensureNpmPlugin,
isHostDependency,
npmPackageName,
npmPluginDir,
readNpmLockEntry,
removeNpmPlugin,
} from "../../cli/npm-plugins.js"
import { currentLockfilePath } from "../../cli/lockfile-path.js"
import type { PluginSource, QuartzPluginsJson } from "./types.js"
import { absorbingBuiltin } from "../builtins/index.js"
import { resolveExtends } from "./config-extends.js"
@@ -89,8 +103,27 @@ async function main() {
}
if (npmSpecs.length > 0) {
// npm plugins package.json doesn't list are pinned in quartz.lock.json and installed into
// .quartz/plugins/@scope/name (see cli/npm-plugins.js); the others come from node_modules
const pluginsDir = path.join(process.cwd(), ".quartz", "plugins")
const lockfile = currentLockfilePath()
const hostPackages: string[] = []
for (const spec of npmSpecs) {
const name = npmPackageName(spec.name)
if (isHostDependency(name)) {
removeNpmPlugin(name, pluginsDir)
hostPackages.push(spec.name)
continue
}
const lockEntry = readNpmLockEntry(name, lockfile)
const installed = ensureNpmPlugin(name, { lockEntry, pluginsDir, verbose: true })
if (installed) {
linkPeerDependencies(npmPluginDir(name, pluginsDir))
console.log(`✓ Installed ${name}@${installed.version} from npm`)
}
}
console.log(`Found ${npmSpecs.length} npm plugin(s), regenerating plugin index...`)
await regeneratePluginIndex({ verbose: true, npmPackages: npmSpecs.map((s) => s.name) })
await regeneratePluginIndex({ verbose: true, npmPackages: hostPackages })
}
}
@@ -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"])
@@ -0,0 +1,309 @@
import assert from "node:assert/strict"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { registerHooks } from "node:module"
import test, { after, describe } from "node:test"
import { h } from "preact"
import type { BuildCtx } from "../../util/ctx"
import type { QuartzComponent, QuartzComponentProps } from "../../components/types"
import type { QuartzPageTypePluginInstance } from "../types"
import type { FilePath, FullSlug } from "../../util/path"
import type { StaticResources } from "../../util/resources"
import type { ChangeEvent } from "../types"
import type { Element, Root } from "hast"
import { toHtml } from "hast-util-to-html"
// Rendering a page imports components with SCSS and inline browser scripts, which esbuild bundles
// in a real build; under tsx they are stubbed out.
registerHooks({
load(url, context, next) {
if (url.endsWith(".scss") || /\.inline\.ts$/.test(url)) {
return { format: "module", source: "export default ''", shortCircuit: true }
}
return next(url, context)
},
})
const { PageTypeDispatcher } = await import("./dispatcher")
const { defaultProcessedContent } = await import("../vfile")
const Head: QuartzComponent = ({ fileData }: QuartzComponentProps) =>
h("head", null, h("title", null, String(fileData.frontmatter?.title ?? "")))
/** A page type whose body names it, so the emitted HTML tells which page type rendered a page. */
function pageType(
name: string,
overrides: Partial<QuartzPageTypePluginInstance> = {},
): QuartzPageTypePluginInstance {
const Body: QuartzComponent = ({ fileData }: QuartzComponentProps) =>
h("article", { "data-type": name }, `${name}:${fileData.slug}`)
return {
name,
layout: name,
match: () => true,
body: () => Body,
...overrides,
} as QuartzPageTypePluginInstance
}
const dirs: string[] = []
after(() => {
for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true })
})
function setup(
pageTypes: QuartzPageTypePluginInstance[],
removedPages?: Map<string, string>,
transformers: unknown[] = [],
) {
const output = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-dispatcher-"))
dirs.push(output)
const ctx = {
argv: { output, serve: false, directory: "content" },
cfg: {
configuration: { baseUrl: "example.com/sub", locale: "en-US" },
plugins: { pageTypes, transformers },
},
allSlugs: [],
virtualPages: [],
removedPages,
} as unknown as BuildCtx
const read = (slug: string) => fs.readFileSync(path.join(output, `${slug}.html`), "utf8")
return { ctx, output, read }
}
const resources: StaticResources = { css: [], js: [], additionalHead: [] }
const dispatcher = () => PageTypeDispatcher({ defaults: { head: Head } })
function page(slug: string, html = "", links: string[] = []) {
return defaultProcessedContent({
slug: slug as FullSlug,
relativePath: `${slug}.md` as FilePath,
filePath: `content/${slug}.md` as FilePath,
frontmatter: { title: slug, tags: [] },
links: links as never,
htmlAst: { type: "root", children: [] },
}).map((x, i) =>
i === 0 && html
? {
type: "root",
children: [
{
type: "element",
tagName: "a",
properties: { href: `./${html}`, "data-slug": html, className: ["internal"] },
children: [{ type: "text", value: html }],
},
],
}
: x,
) as ReturnType<typeof defaultProcessedContent>
}
const linkOf = ([tree]: ReturnType<typeof page>) => (tree as Root).children[0] as Element
async function collect(gen: AsyncGenerator<FilePath> | AsyncIterable<FilePath>, output: string) {
const out: string[] = []
for await (const fp of gen) out.push(path.relative(output, fp).split(path.sep).join("/"))
return out.sort()
}
describe("PageTypeDispatcher.emit", () => {
test("each page is rendered by the first matching page type in priority order", async () => {
const types = [
pageType("low", { priority: 1 }),
pageType("high", { priority: 10, match: ({ slug }) => slug.startsWith("special/") }),
pageType("none", { match: () => false, priority: 100 }),
]
const { ctx, output, read } = setup(types)
const content = [page("index"), page("special/a")]
const files = await collect(dispatcher().emit(ctx, content, resources) as never, output)
assert.deepEqual(files, ["index.html", "special/a.html"])
assert.match(read("index"), /<article data-type="low">low:index<\/article>/)
assert.match(read("special/a"), /<article data-type="high">high:special\/a<\/article>/)
assert.match(read("special/a"), /<title>special\/a<\/title>/)
})
test("virtual pages are emitted with their page type's body; the 404 page uses the site's base path", async () => {
const generated = pageType("tags", {
match: () => false,
generate: () => [
{ slug: "tags/x" as FullSlug, title: "Tag x", data: {} },
{ slug: "404" as FullSlug, title: "Not found", data: {} },
],
})
const { ctx, output, read } = setup([pageType("content"), generated])
const files = await collect(dispatcher().emit(ctx, [page("a/b")], resources) as never, output)
assert.deepEqual(files, ["404.html", "a/b.html", "tags/x.html"])
assert.match(read("tags/x"), /tags:tags\/x/)
assert.match(read("tags/x"), /<title>Tag x<\/title>/)
// the 404 page is served from any depth: its assets are under the absolute base path
assert.match(read("404"), /<script src="\/sub\/postscript\.js"/)
assert.match(read("a/b"), /<script src="\.\.\/postscript\.js"/)
assert.deepEqual(
ctx.virtualPages.map(([, f]) => f.data.slug),
["tags/x"],
)
})
test("links to a draft are marked broken in the emitted page", async () => {
const removed = new Map([["draft", "Drafts"]])
const { ctx, output } = setup([pageType("content")], removed)
const a = page("a", "draft")
await collect(dispatcher().emit(ctx, [a], resources) as never, output)
assert.deepEqual(linkOf(a).properties, {
href: "./draft",
"data-slug": "draft",
className: ["internal", "broken"],
"data-filtered": "Drafts",
})
})
})
describe("PageTypeDispatcher: pages that stand for files", () => {
test("virtualPageHtmlPlugins' result is what the page shows; a page whose body fails isn't emitted", async () => {
const Board: QuartzComponent = ({ fileData }: QuartzComponentProps) => {
if (fileData.slug === "broken.canvas") throw new Error("cannot render")
return h("p", null, `board ${fileData.slug}`)
}
const canvas = pageType("canvas", {
match: () => false,
fileExtensions: [".canvas"],
body: () => Board,
generate: () =>
["a.canvas", "secret.canvas", "broken.canvas"].map((slug) => ({
slug: slug as FullSlug,
title: slug,
data: {},
})),
})
const encrypt = {
name: "Encrypt",
virtualPageHtmlPlugins: () => [
() => (tree: Root, file: { data: { slug?: string } }) => {
if (file.data.slug === "secret.canvas") {
tree.children = [
{
type: "element",
tagName: "div",
properties: {},
children: [{ type: "text", value: "ciphertext" }],
},
]
}
},
],
}
// transformers without virtualPageHtmlPlugins are skipped
const { ctx, output, read } = setup([pageType("content"), canvas], undefined, [
{ name: "Plain" },
encrypt,
])
const files = await collect(dispatcher().emit(ctx, [page("index")], resources) as never, output)
assert.deepEqual(files, ["a.canvas.html", "index.html", "secret.canvas.html"])
assert.match(read("a.canvas"), /<p>board a\.canvas<\/p>/)
assert.match(read("secret.canvas"), /<div>ciphertext<\/div>/)
assert.doesNotMatch(read("secret.canvas"), /board/)
// later emitters read the processed tree from ctx.virtualPages; the failed page is gone
const trees = Object.fromEntries(
ctx.virtualPages.map(([tree, f]) => [f.data.slug, toHtml(tree as Root)]),
)
assert.deepEqual(Object.keys(trees), ["a.canvas", "secret.canvas"])
assert.equal(trees["secret.canvas"], "<div>ciphertext</div>")
assert.equal(trees["a.canvas"], "")
})
})
describe("PageTypeDispatcher: what page bodies see", () => {
// a body listing the pages it can embed (allFiles) and the files of folder "f" (ctx.trie)
const Lister: QuartzComponent = ({ allFiles, ctx }: QuartzComponentProps) =>
h(
"article",
null,
`files:${allFiles.map((f) => f.slug).join(",")};` +
`f:${(ctx.trie?.findNode(["f"])?.children ?? []).map((c) => c.slug).join(",")}`,
)
const types = () => [
pageType("content", { body: () => Lister }),
pageType("canvas", {
match: () => false,
fileExtensions: [".canvas"],
generate: () => [{ slug: "f/board.canvas" as FullSlug, title: "Board", data: {} }],
}),
pageType("tags", {
match: () => false,
generate: () => [{ slug: "tags/t" as FullSlug, title: "t", data: {} }],
}),
]
const expected = "files:f/note,f/board.canvas,tags/t;f:f/note,f/board.canvas"
test("emit: virtual pages are in allFiles; the folder trie holds the pages that stand for files", async () => {
const { ctx, output, read } = setup(types())
await collect(dispatcher().emit(ctx, [page("f/note")], resources) as never, output)
assert.match(read("f/note"), new RegExp(`<article>${expected}</article>`))
})
test("partialEmit: the same, for the pages it re-emits", async () => {
const { ctx, output, read } = setup(types())
const note = page("f/note")
const events = [
{ type: "change", path: "f/note.md", file: note[1] },
] as unknown as ChangeEvent[]
await collect(dispatcher().partialEmit!(ctx, [note], resources, events) as never, output)
assert.match(read("f/note"), new RegExp(`<article>${expected}</article>`))
})
test("partialEmit renders a changed page with the first matching page type by priority", async () => {
const { ctx, output, read } = setup([
pageType("low", { priority: 1 }),
pageType("high", { priority: 10, match: ({ slug }) => slug === "special" }),
])
const [a, b] = [page("special"), page("plain")]
const events = [
{ type: "change", path: "special.md", file: a[1] },
{ type: "change", path: "plain.md", file: b[1] },
] as unknown as ChangeEvent[]
await collect(dispatcher().partialEmit!(ctx, [a, b], resources, events) as never, output)
assert.match(read("special"), /data-type="high"/)
assert.match(read("plain"), /data-type="low"/)
})
})
describe("PageTypeDispatcher.partialEmit", () => {
test("re-emits changed Markdown pages and all virtual pages, removes deleted pages' output", async () => {
const generated = pageType("folder", {
match: () => false,
generate: () => [{ slug: "f/index" as FullSlug, title: "F", data: {} }],
})
const { ctx, output } = setup([pageType("content"), generated])
const [a, b] = [page("a"), page("b")]
await collect(dispatcher().emit(ctx, [a, b], resources) as never, output)
fs.writeFileSync(path.join(output, "gone.html"), "stale")
const events = [
{ type: "change", path: "a.md", file: a[1] },
{ type: "delete", path: "gone.md" },
// not Markdown: no page of its own
{ type: "change", path: "image.png" },
] as unknown as ChangeEvent[]
ctx.virtualPages = []
const files = await collect(
dispatcher().partialEmit!(ctx, [a, b], resources, events) as never,
output,
)
assert.deepEqual(files, ["a.html", "f/index.html"])
assert.ok(!fs.existsSync(path.join(output, "gone.html")))
})
test("a page whose link to a removed page changed is re-emitted although its source didn't", async () => {
const removed = new Map([["draft", "Drafts"]])
const { ctx, output } = setup([pageType("content")], removed)
const linking = page("linking", "draft")
const files = await collect(
dispatcher().partialEmit!(ctx, [linking, page("other")], resources, []) as never,
output,
)
assert.deepEqual(files, ["linking.html"])
assert.equal(linkOf(linking).properties["data-filtered"], "Drafts")
})
})
+114 -1
View File
@@ -8,6 +8,7 @@ import {
collectTreeTransforms,
folderTrie,
generateVirtualPages,
markLinksToUnpublishedPages,
pageOutputPath,
processVirtualPageHtml,
referencesByTarget,
@@ -19,7 +20,10 @@ import { QuartzComponent } from "../../components/types"
import { FilePath, FullSlug, SimpleSlug, setSlugOptions } from "../../util/path"
import { Root as HtmlRoot } from "hast"
import { BuildCtx } from "../../util/ctx"
import { defaultProcessedContent } from "../vfile"
import { defaultProcessedContent, ProcessedContent } from "../vfile"
import { removedPages } from "../builtins/links"
import { Element, Root } from "hast"
import { VFile } from "vfile"
const StubA: QuartzComponent = (() => null) as unknown as QuartzComponent
const StubB: QuartzComponent = (() => null) as unknown as QuartzComponent
@@ -557,3 +561,112 @@ describe("publish filters on pages that stand for files (bases-page#11)", () =>
assert.strictEqual(processVirtualPageHtml(ve, makeCtx(), []), true)
})
})
describe("links to unpublished pages, after the page types ran (crawl-links#7)", () => {
const link = (slug: string): Element => ({
type: "element",
tagName: "a",
properties: { href: `./${slug}`, "data-slug": slug, className: ["internal"] },
children: [],
})
const content = (slug: string, links: string[] = []): ProcessedContent => {
const file = new VFile("")
file.data = { slug: slug as FullSlug, frontmatter: { title: slug } } as VFile["data"]
return [{ type: "root", children: links.map(link) } as Root, file]
}
const marks = (item: ProcessedContent) =>
((item[0] as Root).children as Element[]).map((a) =>
(a.properties.className as string[]).includes("broken")
? (a.properties["data-filtered"] ?? (a.properties["data-missing"] === "" ? "missing" : "?"))
: "ok",
)
// a folder page type that generates a page for each folder with a published note, as folder-page does
const folders = makePageType({
name: "folders",
generate: ({ content }) =>
[...new Set(content.map(([, f]) => f.data.slug!.split("/").slice(0, -1).join("/")))]
.filter((f) => f !== "" && !content.some(([, g]) => g.data.slug === `${f}/index`))
.map((f) => ({ slug: `${f}/index` as FullSlug, title: f, data: {} })),
})
const setup = async (removedBy: ((slug: string) => string | undefined) | undefined) => {
const home = content("index", [
"notes/a",
"notes/index",
"drafts/index",
"drafts/b",
"projects/index",
"missing-in-source",
])
const all = [home, content("notes/a"), content("drafts/b"), content("projects/index")]
const published = all.filter(([, f]) => f.data.slug !== "drafts/b")
const ctx = {
cfg: { configuration: {} },
virtualPages: [],
removedPages: removedBy ? removedPages(all, published, removedBy) : undefined,
} as unknown as BuildCtx
const entries = await generateVirtualPages([folders], published, ctx, { head: StubHead }, {})
return { home, ctx, published, entries }
}
test("marks drafts with their filter and folders no page type generated as missing", async () => {
const { home, ctx, published, entries } = await setup(() => "RemoveDrafts")
assert.deepStrictEqual(
entries.map((e) => e.vpSlug),
["notes/index"],
)
const changed = markLinksToUnpublishedPages(ctx, published, entries)
assert.deepStrictEqual(marks(home), [
"ok", // notes/a: published
"ok", // notes/index: generated folder page
"missing", // drafts/index: its only note is a draft, so no folder page
"RemoveDrafts", // drafts/b
"ok", // projects/index: a published folder note
"ok", // not in the content: the Links transformer's own check, not this one
])
assert.deepStrictEqual([...changed], ["index"])
// run again (watch mode, nothing changed): nothing to re-emit
assert.deepStrictEqual([...markLinksToUnpublishedPages(ctx, published, entries)], [])
})
test("marks nothing when the Links transformer doesn't mark broken links", async () => {
const { home, ctx, published, entries } = await setup(undefined)
assert.deepStrictEqual([...markLinksToUnpublishedPages(ctx, published, entries)], [])
assert.ok(marks(home).every((m) => m === "ok"))
})
})
describe("resolveLayout: every slot", () => {
test("a page type's override replaces each default slot; the page type's body is the page body", () => {
const Body = (() => null) as unknown as QuartzComponent
const pt = makePageType({ body: () => Body })
const slots = ["header", "beforeBody", "afterBody", "left", "right", "footer"] as const
const defaults = Object.fromEntries(slots.map((s) => [s, [StubA]]))
const overrides = Object.fromEntries(slots.map((s) => [s, [StubB]]))
const OtherHead = (() => null) as unknown as QuartzComponent
const layout = resolveLayout(
pt,
{ head: StubHead, ...defaults },
{ [pt.layout]: { head: OtherHead, ...overrides } },
)
for (const slot of slots) assert.deepStrictEqual(layout[slot], [StubB], slot)
assert.strictEqual(layout.head, OtherHead)
assert.strictEqual(layout.pageBody, Body)
// without an override, the defaults
const plain = resolveLayout(pt, { head: StubHead, ...defaults }, {})
for (const slot of slots) assert.deepStrictEqual(plain[slot], [StubA], slot)
})
test("collectComponents leaves out a missing head", () => {
const components = collectComponents([makePageType()], { left: [StubA] }, {})
assert.ok(!components.includes(undefined as never))
assert.strictEqual(components.length, 2)
})
test("collectTreeTransforms: page types without treeTransforms add none", () => {
const t = (() => {}) as never
const ctx = { cfg: { plugins: { transformers: [] } } } as unknown as BuildCtx
const result = collectTreeTransforms(ctx, [{}, { treeTransforms: () => [t] }])
assert.deepStrictEqual(result, { before: [], treeTransforms: [t], after: [] })
})
})
+32 -4
View File
@@ -30,6 +30,7 @@ import { htmlToJsx } from "../../util/jsx"
import { trace } from "../../util/trace"
import { attributeError, originOf } from "../../util/pluginErrors"
import { rejectingFilter } from "../../processors/filter"
import { markUnpublishedLinks } from "../builtins/links"
import fs from "fs"
import path from "path"
@@ -294,9 +295,10 @@ const RenderedBody: QuartzComponent = ({ fileData, tree }: QuartzComponentProps)
*
* Run the transformers' `virtualPageHtmlPlugins` on the rendered body (`file.data.htmlAst`) of a
* page that stands for a file — e.g. encrypted-pages encrypting a canvas. When they change the
* tree, the page shows the changed tree instead of rendering its body again. A page whose body
* failed to render, or that a plugin throws on, is left unpublished: emitting it unprocessed could
* publish what the plugin protects.
* tree, the page shows the changed tree instead of rendering its body again. Both failures fail
* closed, as emitting the page unprocessed could publish what the plugin protects: a page whose
* body failed to render is left unpublished (returns false), and a plugin that throws fails the
* whole build (`trace` reports the error and exits the process, or throws in a worker).
*/
export function processVirtualPageHtml(
ve: VirtualEntry,
@@ -339,7 +341,8 @@ export function processVirtualPageHtml(
* Render each virtual page's Body component to HTML and parse it to a hast tree,
* populating vfile.data.htmlAst so that transclusion (e.g. ![[file.canvas]]) can inline the
* virtual page's content, then run `virtualPageHtmlPlugins` on it (pages that stand for files).
* Returns the entries to emit: those whose processing failed are removed from `ctx.virtualPages`.
* Returns the entries to emit: those whose body failed to render (so they can't be processed) are
* removed from `ctx.virtualPages`. A plugin throwing while processing fails the build.
*/
function populateVirtualPageHtmlAst(
virtualEntries: VirtualEntry[],
@@ -382,6 +385,24 @@ function populateVirtualPageHtmlAst(
return virtualEntries.filter((ve) => !failed.has(ve))
}
/**
* Mark links to pages that are not emitted: removed by a filter, or a folder / tag page no page
* type generated (markUnpublishedLinks). Returns the pages whose links changed, which watch mode
* re-emits although their source didn't change.
*/
export function markLinksToUnpublishedPages(
ctx: BuildCtx,
content: ProcessedContent[],
virtualEntries: VirtualEntry[],
): Set<FullSlug> {
const changed = new Set<FullSlug>()
if (ctx.removedPages) {
const generated = new Set<string>(virtualEntries.map((ve) => ve.vpSlug))
markUnpublishedLinks(content, ctx.removedPages, generated, changed)
}
return changed
}
export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>> = (userOpts) => {
const defaults = userOpts?.defaults ?? {}
const byPageType = userOpts?.byPageType ?? {}
@@ -413,6 +434,8 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
byPageType,
)
markLinksToUnpublishedPages(ctx, content, virtualEntries)
if (virtualEntries.some((ve) => ve.fileBacked)) {
ctx.trie = folderTrie(allFiles, virtualEntries)
}
@@ -507,6 +530,11 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
ctx.trie = folderTrie(allFiles, virtualEntries)
// a page whose links to a published / removed page changed is re-emitted too
for (const slug of markLinksToUnpublishedPages(ctx, content, virtualEntries)) {
changedSlugs.add(slug)
}
const allFilesWithVirtual = [...allFiles, ...virtualEntries.map((ve) => ve.vfile.data)]
// Render Body components to populate htmlAst for transclusion
+1 -1
View File
@@ -35,7 +35,7 @@
"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.",
"description": "Start from another config and apply this file on top: \"default\" (quartz.config.default.yaml), a path relative to this file, an https:// URL (experimental), 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. Keys starting with $ are reserved (except $schema). Without extends, this file is the whole configuration.",
"oneOf": [
{
"type": "string"
+96 -1
View File
@@ -3,7 +3,12 @@ import assert from "node:assert"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { readContentFile } from "./parse"
import { createHtmlProcessor, createMdProcessor, parseMarkdown, readContentFile } from "./parse"
import type { Root as MdRoot } from "mdast"
import type { Root as HtmlRoot } from "hast"
import type { VFile } from "vfile"
import { toHtml } from "hast-util-to-html"
import type { BuildCtx } from "../util/ctx"
import { isContentError } from "../util/pluginErrors"
import type { FilePath } from "../util/path"
@@ -39,3 +44,93 @@ describe("readContentFile", () => {
}
})
})
describe("parseMarkdown (one thread)", () => {
// a transformer that records which of its hooks ran, in which order
const recorder = (name: string, log: string[]) => ({
name,
textTransform: (_ctx: unknown, src: string) => {
log.push(`${name}:text`)
return `${src}\n\n${name}`
},
markdownPlugins: () => [
() => (tree: MdRoot) => {
log.push(`${name}:md`)
tree.children.push({ type: "paragraph", children: [{ type: "text", value: `md-${name}` }] })
},
],
htmlPlugins: () => [
() => (tree: HtmlRoot, file: VFile) => {
log.push(`${name}:html`)
file.data[`html-${name}` as "slug"] = toHtml(tree) as never
},
],
})
test("runs text, Markdown and HTML transforms in plugin order and sets the file's paths", async () => {
// Quartz passes POSIX-style paths (its glob yields them on Windows too)
const posix = (p: string) => p.split(path.sep).join("/")
const dir = posix(await fs.promises.mkdtemp(path.join(os.tmpdir(), "quartz-parse-")))
try {
await fs.promises.mkdir(`${dir}/Sub Folder`)
const a = `${dir}/Sub Folder/My Note.md`
const b = `${dir}/other.md`
await fs.promises.writeFile(a, "\n\n # Title \n\n")
await fs.promises.writeFile(b, "text")
const log: string[] = []
const ctx = {
argv: { directory: dir, verbose: false, concurrency: 1 },
// a transformer may implement any subset of the hooks
cfg: {
plugins: { transformers: [recorder("one", log), { name: "bare" }, recorder("two", log)] },
},
// a frontmatter permalink is the page's address
permalinks: { "other.md": "elsewhere/page" },
} as unknown as BuildCtx
const res = await parseMarkdown(ctx, [a, b] as FilePath[])
assert.deepStrictEqual(
res.map(([, file]) => [file.data.relativePath, file.data.slug, file.data.filePath]),
[
["Sub Folder/My Note.md", "sub-folder/my-note", a],
["other.md", "elsewhere/page", b],
],
)
// the text is trimmed before the first textTransform, which sees what the one before returned
assert.strictEqual(String(res[0][1].value), "# Title\n\none\n\ntwo")
// per file: all text transforms, then Markdown plugins, then (after all files) HTML plugins
assert.deepStrictEqual(log, [
"one:text",
"two:text",
"one:md",
"two:md",
"one:text",
"two:text",
"one:md",
"two:md",
"one:html",
"two:html",
"one:html",
"two:html",
])
const data = res[0][1].data as Record<string, string>
// Markdown plugins ran in order, and remark-rehype turned the Markdown AST into HTML
assert.strictEqual(
data["html-one"],
"<h1>Title</h1>\n<p>one</p>\n<p>two</p>\n<p>md-one</p>\n<p>md-two</p>",
)
assert.strictEqual(res[0][0].type, "root")
assert.strictEqual(toHtml(res[0][0] as HtmlRoot), data["html-two"])
} finally {
await fs.promises.rm(dir, { recursive: true })
}
})
test("raw HTML in Markdown is kept (allowDangerousHtml)", async () => {
const ctx = { cfg: { plugins: { transformers: [] } } } as unknown as BuildCtx
const md = createMdProcessor(ctx)
const ast = md.parse('<div class="x">hi</div>')
const html = await createHtmlProcessor(ctx).run(await md.run(ast))
assert.strictEqual(toHtml(html, { allowDangerousHtml: true }), '<div class="x">hi</div>')
})
})
+63
View File
@@ -0,0 +1,63 @@
import assert from "node:assert/strict"
import test, { beforeEach, describe } from "node:test"
import { Features, transform } from "lightningcss"
import { componentStylesheet, isolateComponentCss } from "./componentCss"
import { getDiagnostics, resetDiagnostics } from "./diagnostics"
/** The component stylesheet as ComponentResources builds it. */
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"],
["an unclosed comment", ".bad{color:blue} /* note"],
["an unclosed @media", ".bad{color:blue} @media (min-width: 1px) { .x { color: red }"],
["an unclosed string", '.bad{content:"x'],
]) {
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", () => {
const css = ".a{color:red;& .b{margin:0}}@media (max-width:800px){.a{display:none}}"
const raw = transform({
filename: "component.css",
code: Buffer.from(`@layer quartz-base {\n${css}\n${later}\n}`),
minify: true,
include: Features.MediaQueries,
}).code.toString()
assert.equal(sheet([css, later]), raw)
assert.deepEqual(getDiagnostics(), [])
})
})
+53
View File
@@ -0,0 +1,53 @@
import { Features, Targets, transform } from "lightningcss"
import { recordDiagnostic } from "./diagnostics"
/**
* One component's CSS, parsed on its own and printed back balanced. All components' CSS goes
* into one stylesheet: an unclosed `{`, `/*` or string in one would swallow every later
* component's rules, and a stray `}` close the shared layer (and fail the build). Parsed alone,
* the end of the chunk closes what it left open, as a stylesheet of its own would in a browser;
* a chunk that doesn't parse is printed with the rules that do, with a warning naming the
* component.
*/
export function isolateComponentCss(css: string, owner = ""): string {
const name = owner ? `component ${owner}` : "a component"
const parse = (errorRecovery: boolean) =>
transform({ filename: "component.css", code: Buffer.from(css), errorRecovery })
try {
return parse(false).code.toString()
} catch (err) {
const loc = (err as { loc?: { line: number; column: number } }).loc
recordDiagnostic({
severity: "warning",
area: "css",
message:
`The CSS of ${name} has a syntax error (${(err as Error).message}` +
`${loc ? ` at line ${loc.line}, column ${loc.column}` : ""}); the rules that parse are kept.`,
})
try {
return parse(true).code.toString()
} catch {
return ""
}
}
}
/**
* 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()
}
+6
View File
@@ -49,6 +49,12 @@ export interface BuildCtx {
* `.base` / `.canvas` pages).
*/
virtualPages: ProcessedContent[]
/**
* Pages the filters removed (and their aliases) → the filter, set after filtering when the
* Links transformer marks broken links. PageTypeDispatcher marks links to them, and to folder
* and tag pages no page type generated, once the virtual pages exist (markUnpublishedLinks).
*/
removedPages?: ReadonlyMap<string, string>
/** Content-hashed asset filenames, populated by ComponentResources emitter */
hashedResourceNames?: HashedResourceNames
/** Maps CSS content strings to their emitted hashed filenames. Populated by ComponentResources. */
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more