mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
feat(core): plugin assets (externalResources().assets → static/plugins/, window.quartzStaticUrl)
This commit is contained in:
9 files changed
+233
-1
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": minor
|
||||
---
|
||||
|
||||
Plugins can ship files with the site: `externalResources()` may return `assets: [{ from, to }]` (a file or directory on disk), which Quartz copies to `static/plugins/<to>`. Client scripts find them through the new `window.quartzStaticUrl` page global (absolute URL of `static/`, valid across SPA navigations). Use it for large or optional client code loaded with `import()` only where needed, instead of inline scripts, which every page downloads. Invalid or conflicting targets and missing sources are build warnings.
|
||||
@@ -614,6 +614,40 @@ Your plugin's `dist/` directory should be committed to the repository:
|
||||
|
||||
If `dist/` is missing or gitignored, Quartz falls back to the full install/build cycle (useful during local development with symlinked plugins).
|
||||
|
||||
### Shipping Files with Your Plugin
|
||||
|
||||
Since Quartz 5.1, `externalResources()` can return `assets`: files or directories that Quartz copies into the site at `static/plugins/<to>`. Client scripts find them through the `window.quartzStaticUrl` page global (the absolute URL of `static/`, valid across SPA navigations).
|
||||
|
||||
Use this for large or optional client code instead of an inline script: Quartz serves inline scripts to **every page**, while an asset is only downloaded where your script imports it.
|
||||
|
||||
```ts
|
||||
import path from "path"
|
||||
import { createRequire } from "module"
|
||||
|
||||
externalResources() {
|
||||
// resolve a dependency's browser build at build time
|
||||
const pkg = createRequire(import.meta.url).resolve("my-renderer/package.json")
|
||||
return {
|
||||
js: [{ script: loaderScript, loadTime: "afterDOMReady", contentType: "inline", moduleType: "module" }],
|
||||
assets: [{ from: path.join(path.dirname(pkg), "dist", "esm"), to: "my-plugin/renderer" }],
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```ts title="loader.inline.ts"
|
||||
document.addEventListener("nav", async () => {
|
||||
const nodes = document.querySelectorAll(".my-widget")
|
||||
if (nodes.length === 0 || !window.quartzStaticUrl) return // nothing to do on this page
|
||||
const url = new URL("plugins/my-plugin/renderer/index.js", window.quartzStaticUrl).href
|
||||
const { render } = await import(url)
|
||||
for (const node of nodes) render(node)
|
||||
})
|
||||
```
|
||||
|
||||
- `to` is relative to `static/plugins/`; use your plugin's name as the first segment. Invalid or conflicting targets and missing sources are reported as build warnings.
|
||||
- An ES module build with relative `import()`s keeps working when served this way, so only the chunks a page needs are downloaded.
|
||||
- Older Quartz versions ignore `assets` and leave `quartzStaticUrl` undefined. Either require `"quartzVersion": ">=5.1.0"` or fall back (for example to a CDN), as [[ObsidianFlavoredMarkdown]] does for [[Mermaid diagrams|Pele]].
|
||||
|
||||
### Plugins with Native Dependencies
|
||||
|
||||
Plugins that require native packages (e.g. `sharp` for image processing) cannot bundle those. For these plugins:
|
||||
|
||||
@@ -19,6 +19,8 @@ plugins:
|
||||
diagramRenderer: pele # default: mermaid
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
## Syntax
|
||||
|
||||
To add a Mermaid diagram, create a mermaid code block.
|
||||
|
||||
@@ -78,7 +78,10 @@ export function pageResources(
|
||||
const contentIndexScript =
|
||||
`const fetchData = fetch("${contentIndexPath}")` +
|
||||
`.then(r => { if (!r.ok) throw new Error("HTTP " + r.status); return r.json() })` +
|
||||
`.catch(e => { console.warn("[Quartz] Could not load ${contentIndexPath} (" + e.message + "); is configuration.contentIndex disabled?"); return {} })`
|
||||
`.catch(e => { console.warn("[Quartz] Could not load ${contentIndexPath} (" + e.message + "); is configuration.contentIndex disabled?"); return {} });` +
|
||||
// Absolute URL of static/ (plugin assets live in static/plugins/<to>). Resolved once on the
|
||||
// first page, so it stays valid across SPA navigations.
|
||||
`window.quartzStaticUrl = new URL(${JSON.stringify(joinSegments(baseDir, "static") + "/")}, location.href).href`
|
||||
|
||||
const resources: StaticResources = {
|
||||
css: [
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createHash } from "crypto"
|
||||
import { FullSlug, joinSegments } from "../../util/path"
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
|
||||
import { emitStaticAssets } from "./staticAssets"
|
||||
// @ts-ignore
|
||||
import spaRouterScript from "../../components/scripts/spa.inline"
|
||||
// @ts-ignore
|
||||
@@ -485,6 +486,9 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
|
||||
|
||||
ctx.extractedInlineResources = extractedInlineResources
|
||||
|
||||
// Files plugins ship with the site (externalResources().assets) → static/plugins/<to>
|
||||
yield* emitStaticAssets(ctx, resources.assets)
|
||||
|
||||
const cssHash = useHashing ? hashContent(cssContent) : null
|
||||
const prescriptHash = useHashing ? hashContent(prescript) : null
|
||||
const postscriptHash = useHashing ? hashContent(postscript) : null
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
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 { emitStaticAssets, normalizeAssetTarget } from "./staticAssets"
|
||||
import { getDiagnostics, resetDiagnostics } from "../../util/diagnostics"
|
||||
import type { BuildCtx } from "../../util/ctx"
|
||||
|
||||
async function collect<T>(gen: AsyncGenerator<T>): Promise<T[]> {
|
||||
const out: T[] = []
|
||||
for await (const item of gen) out.push(item)
|
||||
return out
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-assets-"))
|
||||
const src = path.join(root, "src")
|
||||
fs.mkdirSync(path.join(src, "chunks"), { recursive: true })
|
||||
fs.writeFileSync(path.join(src, "lazy.js"), "export {}")
|
||||
fs.writeFileSync(path.join(src, "chunks", "a.js"), "export const a = 1")
|
||||
fs.writeFileSync(path.join(root, "single.wasm"), Buffer.from([0, 97, 115, 109]))
|
||||
const ctx = { argv: { output: path.join(root, "public") } } as unknown as BuildCtx
|
||||
return { root, src, ctx }
|
||||
}
|
||||
|
||||
describe("normalizeAssetTarget", () => {
|
||||
test("accepts relative paths below static/plugins and rejects escapes", () => {
|
||||
assert.strictEqual(normalizeAssetTarget("ofm/pele"), "ofm/pele")
|
||||
assert.strictEqual(normalizeAssetTarget("/ofm/pele/"), "ofm/pele")
|
||||
for (const bad of ["", "..", "a/../b", "a//b", "./a", "a\\b"]) {
|
||||
assert.strictEqual(normalizeAssetTarget(bad), undefined, bad)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("emitStaticAssets", () => {
|
||||
beforeEach(() => resetDiagnostics())
|
||||
|
||||
test("copies directories recursively and single files, yielding written paths", async () => {
|
||||
const { root, src, ctx } = setup()
|
||||
const written = await collect(
|
||||
emitStaticAssets(ctx, [
|
||||
{ from: src, to: "ofm/pele" },
|
||||
{ from: path.join(root, "single.wasm"), to: "other/engine.wasm" },
|
||||
]),
|
||||
)
|
||||
const rel = written.map((f) => path.relative(ctx.argv.output, f)).sort()
|
||||
assert.deepStrictEqual(rel, [
|
||||
path.join("static/plugins/ofm/pele/chunks/a.js"),
|
||||
path.join("static/plugins/ofm/pele/lazy.js"),
|
||||
path.join("static/plugins/other/engine.wasm"),
|
||||
])
|
||||
assert.deepStrictEqual(
|
||||
[...fs.readFileSync(path.join(ctx.argv.output, "static/plugins/other/engine.wasm"))],
|
||||
[0, 97, 115, 109],
|
||||
)
|
||||
})
|
||||
|
||||
test("warns about invalid targets, missing sources and conflicting targets", async () => {
|
||||
const { root, src, ctx } = setup()
|
||||
const written = await collect(
|
||||
emitStaticAssets(ctx, [
|
||||
{ from: src, to: "../escape" },
|
||||
{ from: path.join(root, "nope"), to: "missing" },
|
||||
{ from: src, to: "dup" },
|
||||
{ from: path.join(root, "single.wasm"), to: "dup" },
|
||||
{ from: src, to: "dup" },
|
||||
]),
|
||||
)
|
||||
assert.strictEqual(written.length, 2) // only the first "dup"
|
||||
const messages = getDiagnostics().map((d) => d.message)
|
||||
assert.strictEqual(messages.length, 3)
|
||||
assert.match(messages[0], /invalid target/)
|
||||
assert.match(messages[1], /does not exist/)
|
||||
assert.match(messages[2], /Two plugin assets are copied to static\/plugins\/dup/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,87 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
import { FilePath, joinSegments } from "../../util/path"
|
||||
import { StaticAsset } from "../../util/resources"
|
||||
import { warn } from "../../util/diagnostics"
|
||||
|
||||
/** Output directory (below the site output) that plugin assets are copied to. */
|
||||
export const PLUGIN_ASSET_DIR = "static/plugins"
|
||||
|
||||
/** `to` must stay inside static/plugins/: relative, no `..`, no backslashes. */
|
||||
export function normalizeAssetTarget(to: string): string | undefined {
|
||||
if (typeof to !== "string") return undefined
|
||||
const trimmed = to.replace(/^\/+|\/+$/g, "")
|
||||
if (!trimmed || trimmed.includes("\\")) return undefined
|
||||
const parts = trimmed.split("/")
|
||||
if (parts.some((p) => p === "" || p === "." || p === "..")) return undefined
|
||||
return parts.join("/")
|
||||
}
|
||||
|
||||
async function* walk(dir: string): AsyncGenerator<string> {
|
||||
for (const entry of await fs.promises.readdir(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) yield* walk(full)
|
||||
else if (entry.isFile()) yield full
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the files and directories plugins return in `externalResources().assets` to
|
||||
* `<output>/static/plugins/<to>`. Invalid targets, missing sources and two plugins claiming the
|
||||
* same target are reported as warnings instead of failing the build.
|
||||
*/
|
||||
export async function* emitStaticAssets(
|
||||
ctx: BuildCtx,
|
||||
assets: StaticAsset[] | undefined,
|
||||
): AsyncGenerator<FilePath> {
|
||||
const claimed = new Map<string, string>()
|
||||
for (const asset of assets ?? []) {
|
||||
const target = normalizeAssetTarget(asset?.to)
|
||||
if (!target) {
|
||||
warn({
|
||||
area: "assets",
|
||||
message: `A plugin asset has an invalid target ${JSON.stringify(asset?.to)} (must be a relative path below static/plugins/).`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
const previous = claimed.get(target)
|
||||
if (previous !== undefined) {
|
||||
if (previous !== asset.from) {
|
||||
warn({
|
||||
area: "assets",
|
||||
message: `Two plugin assets are copied to static/plugins/${target} (${previous} and ${asset.from}); keeping the first.`,
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
claimed.set(target, asset.from)
|
||||
|
||||
let stat: fs.Stats
|
||||
try {
|
||||
stat = await fs.promises.stat(asset.from)
|
||||
} catch {
|
||||
warn({
|
||||
area: "assets",
|
||||
message: `Plugin asset ${asset.from} (for static/plugins/${target}) does not exist.`,
|
||||
hint: "Reinstall the plugin, or report it to the plugin's author.",
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
const destRoot = joinSegments(ctx.argv.output, PLUGIN_ASSET_DIR, target)
|
||||
const files = stat.isDirectory() ? walk(asset.from) : single(asset.from)
|
||||
for await (const file of files) {
|
||||
const dest = (
|
||||
stat.isDirectory() ? path.join(destRoot, path.relative(asset.from, file)) : destRoot
|
||||
) as FilePath
|
||||
await fs.promises.mkdir(path.dirname(dest), { recursive: true })
|
||||
await fs.promises.copyFile(file, dest)
|
||||
yield dest
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function* single(file: string): AsyncGenerator<string> {
|
||||
yield file
|
||||
}
|
||||
@@ -19,6 +19,9 @@ export function getStaticResourcesFromPlugins(ctx: BuildCtx) {
|
||||
if (res?.additionalHead) {
|
||||
staticResources.additionalHead.push(...res.additionalHead)
|
||||
}
|
||||
if (res?.assets) {
|
||||
;(staticResources.assets ??= []).push(...res.assets)
|
||||
}
|
||||
}
|
||||
|
||||
// if serving locally, listen for rebuilds and reload the page
|
||||
|
||||
@@ -61,10 +61,26 @@ export function CSSResourceToStyleElement(resource: CSSResource, preserve?: bool
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file or directory a plugin ships with the site (Quartz 5.1+), copied to
|
||||
* `<output>/static/plugins/<to>`. Client scripts get its URL from the `quartzStaticUrl` page
|
||||
* global: `new URL("plugins/<to>/…", window.quartzStaticUrl)`. Use this for large or optional
|
||||
* client code (load it with `import()` only on pages that need it) instead of inline scripts,
|
||||
* which every page downloads.
|
||||
*/
|
||||
export interface StaticAsset {
|
||||
/** Absolute path of a file or directory on disk (e.g. resolved from a dependency). */
|
||||
from: string
|
||||
/** Destination below `static/plugins/`, e.g. "obsidian-flavored-markdown/pele". */
|
||||
to: string
|
||||
}
|
||||
|
||||
export interface StaticResources {
|
||||
css: CSSResource[]
|
||||
js: JSResource[]
|
||||
additionalHead: (JSX.Element | ((pageData: QuartzPluginData) => JSX.Element))[]
|
||||
/** Files copied into the output (see StaticAsset). Ignored by Quartz versions before 5.1. */
|
||||
assets?: StaticAsset[]
|
||||
}
|
||||
|
||||
export type StringResource = string | string[] | undefined
|
||||
|
||||
Reference in new issue
Block a user