Compare commits

..
Author SHA1 Message Date
saberzero1 c92fed97c0 fix(popover): place popovers with position: fixed, and scroll to headings by their position on screen 2026-11-30 14:14:04 +01:00
Emile Bangma 79d3ea9875 fix(cli): reinstalling a pinned npm plugin keeps its quartz.lock.json entry 2026-11-30 13:38:13 +01:00
saberzero1 f2015a4c76 fix(cli): reinstalling a pinned npm plugin keeps its quartz.lock.json entry 2026-11-30 12:10:57 +01:00
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
27 changed files with 1414 additions and 98 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": minor
---
`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.
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Reinstalling an npm plugin at the version pinned in `quartz.lock.json` (after a fresh clone, or on a CI runner) no longer rewrites its `installedAt`, so `npx quartz plugin install` leaves the lockfile unchanged, as it does for Git plugins.
-5
View File
@@ -1,5 +0,0 @@
---
"@jackyzha0/quartz": patch
---
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
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Popovers show next to their link with Obsidian themes (quartz-themes-core) too: its Obsidian base styles made them `position: absolute`, so on a scrolled page they appeared a scroll's height above the link, often off screen — links to headings and an embed's "link to original" seemed to show no popover. A popover for a link to a heading now also scrolls the heading to the top of the popover when the theme positions the page's content box.
+12
View File
@@ -1,5 +1,17 @@
# @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
+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.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@jackyzha0/quartz",
"version": "5.3.1",
"version": "5.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@jackyzha0/quartz",
"version": "5.3.1",
"version": "5.4.0",
"license": "MIT",
"dependencies": {
"@clack/prompts": "^1.8.0",
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "@jackyzha0/quartz",
"description": "🌱 publish your digital garden and notes as a website",
"private": true,
"version": "5.3.1",
"version": "5.4.0",
"type": "module",
"author": "jackyzha0 <j.zhao2k19@gmail.com>",
"license": "MIT",
+20
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",
+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"))
})
})
+50
View File
@@ -0,0 +1,50 @@
/** 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 nextNpmLockEntry(
lockEntry: unknown,
source: unknown,
result: NpmInstallResult,
): NpmLockEntry
export function ensureNpmPlugin(
name: string,
options: {
lockEntry?: NpmLockEntry
fallbackVersion?: string
pluginsDir: string
verbose?: boolean
},
): NpmInstallResult | null
+289
View File
@@ -0,0 +1,289 @@
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 {}
}
}
/**
* The lock entry for an npm plugin just installed from `source`. Reinstalling the pinned version
* (a fresh clone, `npm ci`, a CI runner) keeps `lockEntry` as it is, `installedAt` included, so
* restoring plugins leaves quartz.lock.json unchanged, as it does for Git plugins.
*/
export function nextNpmLockEntry(lockEntry, source, result) {
if (
isNpmLockEntry(lockEntry) &&
lockEntry.source === source &&
lockEntry.version === result.version &&
(!lockEntry.integrity || !result.integrity || lockEntry.integrity === result.integrity)
) {
return lockEntry
}
return { source, ...result, installedAt: new Date().toISOString() }
}
/**
* 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,
})
}
+279
View File
@@ -0,0 +1,279 @@
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,
nextNpmLockEntry,
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)
})
})
describe("nextNpmLockEntry", () => {
const pinned = {
source: "@me/plugin",
version: "1.4.2",
integrity: "sha512-good",
resolved: "https://registry.npmjs.org/@me/plugin/-/plugin-1.4.2.tgz",
installedAt: "2026-01-01T00:00:00.000Z",
}
const result = { version: "1.4.2", integrity: "sha512-good", resolved: pinned.resolved }
test("reinstalling the pinned version keeps the lock entry, installedAt included", () => {
assert.strictEqual(nextNpmLockEntry(pinned, "@me/plugin", result), pinned)
})
test("a new version, source or package is a new entry", () => {
const updated = nextNpmLockEntry(pinned, "@me/plugin", { ...result, version: "2.0.0" })
assert.strictEqual(updated.version, "2.0.0")
assert.notStrictEqual(updated.installedAt, pinned.installedAt)
assert.notStrictEqual(nextNpmLockEntry(pinned, "@me/plugin@^1", result), pinned)
assert.notStrictEqual(
nextNpmLockEntry(pinned, "@me/plugin", { ...result, integrity: "sha512-other" }),
pinned,
)
const added = nextNpmLockEntry(undefined, "@me/plugin", result)
assert.deepStrictEqual(
{ ...added, installedAt: undefined },
{
source: "@me/plugin",
...result,
installedAt: undefined,
},
)
})
})
+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)
+382 -44
View File
@@ -17,7 +17,7 @@ import {
parseGitSource,
getGitCommit,
PLUGINS_DIR,
LOCKFILE_PATH,
getLockfilePath,
isLocalSource,
getSourceUrl,
formatSource,
@@ -56,6 +56,19 @@ import {
npmAsync,
} from "./subprocess.js"
import { writePluginIndex } from "./plugin-index.js"
import {
installedNpmPluginVersion,
installNpmPlugin,
isHostDependency,
isNpmLockEntry,
nextNpmLockEntry,
latestNpmVersion,
latestNpmVersionAsync,
listPluginDirNames,
npmPackageName,
npmPluginDir,
removeNpmPlugin,
} from "./npm-plugins.js"
import {
builtinKeyFor,
builtinMessage,
@@ -386,7 +399,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 +489,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 +511,153 @@ 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))
const next = nextNpmLockEntry(lockEntry, entry.source, result)
if (next !== lockEntry) {
lockfile.plugins[pkg] = next
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)`))
@@ -1288,7 +1458,7 @@ export async function handlePluginInstallUnified({
}
if (lockfileChanged) {
writeLockfile(lockfile)
writeLockfile(withNpmEntries(lockfile))
console.log()
console.log(styleText("gray", "Updated quartz.lock.json"))
}
@@ -1500,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 ?? []) {
@@ -1509,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 {}
@@ -1604,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
@@ -1912,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 = [
@@ -1942,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
}
@@ -1957,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",
@@ -2229,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),
@@ -2277,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", "✗")
@@ -2388,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
@@ -2482,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()
@@ -2519,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
}
@@ -2660,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",
@@ -2734,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++
@@ -2807,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.`,
)
@@ -2885,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 []
}
@@ -2949,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))
@@ -2974,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 })
}
+64 -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"),
[
@@ -358,3 +366,58 @@ describe("plugin install --latest with a plugin that can't be updated", () => {
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([
@@ -0,0 +1,37 @@
/**
* Where a popover goes, and how far its content scrolls to show a heading. Kept out of
* popover.inline.ts so tests can import them.
*/
/**
* The popover's inline style for a position from floating-ui's `fixed` strategy. The
* position is set here, not left to stylesheets: Obsidian's app.css, which quartz-themes-core
* bundles for Obsidian themes, makes `.popover` `position: absolute`, and the viewport
* coordinates then landed the popover a page's scroll above its link.
*/
export function popoverPlacement(x: number, y: number) {
return {
position: "fixed",
top: "0",
left: "0",
transform: `translate(${x.toFixed()}px, ${y.toFixed()}px)`,
}
}
interface Box {
getBoundingClientRect(): { top: number }
}
/**
* The scrollTop that shows `target` `buffer` px below the top of `inner`, measured on screen:
* `offsetTop` is relative to the nearest positioned ancestor, which a theme can put inside the
* popover (Obsidian themes position `.markdown-preview-view`).
*/
export function scrollTopFor(inner: Box & { scrollTop: number }, target: Box, buffer = 12) {
return (
target.getBoundingClientRect().top -
inner.getBoundingClientRect().top +
inner.scrollTop -
buffer
)
}
+3 -4
View File
@@ -1,6 +1,7 @@
import { computePosition, flip, inline, shift } from "@floating-ui/dom"
import { normalizeRelativeURLs } from "../../util/path"
import { fetchCanonical } from "./util"
import { popoverPlacement, scrollTopFor } from "./popover-layout"
const p = new DOMParser()
let activeAnchor: HTMLAnchorElement | null = null
@@ -19,9 +20,7 @@ async function mouseEnterHandler(
strategy: "fixed",
middleware: [inline({ x: clientX, y: clientY }), shift(), flip()],
})
Object.assign(popoverElement.style, {
transform: `translate(${x.toFixed()}px, ${y.toFixed()}px)`,
})
Object.assign(popoverElement.style, popoverPlacement(x, y))
}
function showPopover(popoverElement: HTMLElement) {
@@ -37,7 +36,7 @@ async function mouseEnterHandler(
const heading = inner.querySelector(targetAnchor) as HTMLElement | null
if (heading) {
// leave ~12px of buffer when scrolling to a heading
inner.scroll({ top: heading.offsetTop - 12, behavior: "instant" })
inner.scroll({ top: scrollTopFor(inner, heading), behavior: "instant" })
}
}
}
+31 -2
View File
@@ -1,10 +1,15 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import { popoverPlacement, scrollTopFor } from "./popover-layout"
type ScrollArg = { top: number; behavior?: ScrollBehavior }
// a heading `offsetTop` px from the top of the popover's content (not scrolled)
type FakeHeading = { offsetTop: number }
const box = (top: number) => ({ getBoundingClientRect: () => ({ top }) })
interface FakePopoverInner {
scrollTop: number
getBoundingClientRect: () => { top: number }
scroll: (arg: ScrollArg) => void
querySelector: (sel: string) => FakeHeading | null
_scrolled: ScrollArg | null
@@ -25,6 +30,8 @@ interface FakePopoverElement {
function makeInner(heading: FakeHeading | null = null): FakePopoverInner {
const inner: FakePopoverInner = {
scrollTop: 0,
getBoundingClientRect: () => ({ top: 0 }),
scroll(arg) {
this._scrolled = arg
},
@@ -84,7 +91,7 @@ function fixedShowPopover(
const targetAnchor = `#popover-internal-${hash.slice(1)}`
const heading = inner.querySelector(targetAnchor)
if (heading) {
inner.scroll({ top: heading.offsetTop - 12, behavior: "instant" })
inner.scroll({ top: scrollTopFor(inner, box(heading.offsetTop)), behavior: "instant" })
}
}
}
@@ -107,7 +114,7 @@ describe("showPopover on cache-hit with hash", () => {
assert.deepStrictEqual(
inner._scrolled,
{ top: 200 - 12, behavior: "instant" },
"scroll must target heading.offsetTop - 12",
"scroll must show the heading 12px below the top",
)
assert.deepStrictEqual(inner._selectorsQueried, ["#popover-internal-plugins"])
})
@@ -221,3 +228,25 @@ describe("bfcache popover cleanup", () => {
assert.strictEqual(queried, false)
})
})
describe("popover layout", () => {
test("the popover is placed with position: fixed, which its coordinates are for", () => {
// Obsidian's app.css (quartz-themes-core) sets .popover { position: absolute }
assert.deepStrictEqual(popoverPlacement(764.4, -4.6), {
position: "fixed",
top: "0",
left: "0",
transform: "translate(764px, -5px)",
})
})
test("scrolls to a heading by its position on screen, not its offsetTop", () => {
// the content box starts 100px into the popover (an Obsidian theme positions
// .markdown-preview-view, so the heading's offsetTop counts from there)
const inner = { scrollTop: 0, ...box(200) }
assert.strictEqual(scrollTopFor(inner, box(200 + 100 + 5944)), 100 + 5944 - 12)
// already scrolled: the same target
const scrolled = { scrollTop: 3000, ...box(200) }
assert.strictEqual(scrollTopFor(scrolled, box(200 + 100 + 5944 - 3000)), 100 + 5944 - 12)
})
})
+37 -2
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,
@@ -303,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))
@@ -321,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)
@@ -438,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 })
+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 })
}
}