mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
fix(plugins): quartz.ts overrides for npm and component plugins (#2565); one shared plugin index generator
Overrides were registered under a sanitized key (quartz-community__explorer) but looked up by package name, and component constructors re-exported from a sub-module were not wrapped at all. Wrappers now also return the original's result. The CLI's copy of the generator dropped npm plugins from the index; both now use cli/plugin-index.js. Registry key approach from #2566. Co-authored-by: Shadorux <208887057+Shadorux@users.noreply.github.com>
This commit is contained in:
6 files changed
+408
-409
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
`quartz.ts` overrides (`ExternalPlugin.Explorer({...})`) work for npm plugins and for component plugins (#2565): overrides are registered under the key the loader looks up (the package name for npm plugins), and component constructors re-exported from a plugin's sub-module are wrapped too. The wrapper also returns what the plugin returns, so `ExternalPlugin.X(...)` works both as a statement and as a component in a layout override. `quartz plugin …` commands no longer drop npm plugins from the generated `.quartz/plugins/index.ts`; both generators are now one shared module.
|
||||
@@ -47,11 +47,10 @@ import {
|
||||
assertRef,
|
||||
assertRepoUrl,
|
||||
gitAsync,
|
||||
isIdentifier,
|
||||
jsString,
|
||||
npm,
|
||||
npmAsync,
|
||||
} from "./subprocess.js"
|
||||
import { writePluginIndex } from "./plugin-index.js"
|
||||
import {
|
||||
builtinMessage,
|
||||
describeBuiltins,
|
||||
@@ -60,8 +59,6 @@ import {
|
||||
officialPluginName,
|
||||
} from "./builtin-migration.js"
|
||||
|
||||
const INTERNAL_EXPORTS = new Set(["manifest", "default"])
|
||||
|
||||
/** Mark the current CLI invocation as failed (non-zero exit) without aborting. */
|
||||
function markFailed() {
|
||||
process.exitCode = 1
|
||||
@@ -376,155 +373,18 @@ function findPluginByPackageName(packageName) {
|
||||
return null
|
||||
}
|
||||
|
||||
const PLUGIN_TYPE_PATTERN =
|
||||
/Quartz(?:Emitter|Transformer|Filter|PageType)Plugin|QuartzComponentConstructor|\(.*\)\s*=>\s*QuartzComponent\b/
|
||||
|
||||
function resolveOriginalName(exportName, dtsContent) {
|
||||
const aliasPattern = new RegExp(`(\\w+)\\s+as\\s+${exportName}\\b`)
|
||||
const match = dtsContent.match(aliasPattern)
|
||||
return match ? match[1] : exportName
|
||||
}
|
||||
|
||||
function isOverridableExport(name, dtsContent) {
|
||||
const declName = resolveOriginalName(name, dtsContent)
|
||||
const declPattern = new RegExp(`declare\\s+const\\s+${declName}\\s*:\\s*(.+?)(?:;|$)`, "m")
|
||||
const match = dtsContent.match(declPattern)
|
||||
if (!match) return false
|
||||
return PLUGIN_TYPE_PATTERN.test(match[1])
|
||||
}
|
||||
|
||||
function parseExportsFromDts(content) {
|
||||
const exports = []
|
||||
const exportMatches = content.matchAll(/export\s*{\s*([^}]+)\s*}(?:\s*from\s*['"]([^'"]+)['"])?/g)
|
||||
for (const match of exportMatches) {
|
||||
const fromModule = match[2]
|
||||
if (fromModule?.startsWith("@")) continue
|
||||
|
||||
const names = match[1]
|
||||
.split(",")
|
||||
.map((n) => n.trim())
|
||||
.filter(Boolean)
|
||||
for (const name of names) {
|
||||
const cleanName = name.split(" as ").pop()?.trim() || name.trim()
|
||||
if (cleanName && !cleanName.startsWith("_") && !INTERNAL_EXPORTS.has(cleanName)) {
|
||||
const finalName = cleanName.replace(/^type\s+/, "")
|
||||
if (name.includes("type ")) {
|
||||
exports.push(`type ${finalName}`)
|
||||
} else {
|
||||
exports.push(finalName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return exports
|
||||
}
|
||||
|
||||
async function regeneratePluginIndex() {
|
||||
if (!fs.existsSync(PLUGINS_DIR)) return
|
||||
|
||||
const pluginDirs = fs.readdirSync(PLUGINS_DIR).filter((name) => {
|
||||
const pluginPath = path.join(PLUGINS_DIR, name)
|
||||
return fs.statSync(pluginPath).isDirectory()
|
||||
})
|
||||
|
||||
// Phase 1: Collect all exports per plugin, detect conflicts
|
||||
const pluginExports = new Map()
|
||||
const nameCount = new Map()
|
||||
|
||||
for (const pluginName of pluginDirs) {
|
||||
const pluginDir = path.join(PLUGINS_DIR, pluginName)
|
||||
const distIndex = path.join(pluginDir, "dist", "index.d.ts")
|
||||
|
||||
if (!fs.existsSync(distIndex)) continue
|
||||
|
||||
const dtsContent = fs.readFileSync(distIndex, "utf-8")
|
||||
const exportedNames = parseExportsFromDts(dtsContent)
|
||||
const named = exportedNames.filter((e) => !e.startsWith("type "))
|
||||
const types = exportedNames.filter((e) => e.startsWith("type ")).map((e) => e.slice(5))
|
||||
|
||||
const overridable = named.filter((n) => isOverridableExport(n, dtsContent))
|
||||
const passthrough = named.filter((n) => !isOverridableExport(n, dtsContent))
|
||||
|
||||
if (overridable.length > 0 || passthrough.length > 0 || types.length > 0) {
|
||||
pluginExports.set(pluginName, {
|
||||
overridable: overridable.filter(isIdentifier),
|
||||
passthrough: passthrough.filter(isIdentifier),
|
||||
types: types.filter(isIdentifier),
|
||||
})
|
||||
for (const n of [...overridable, ...passthrough]) {
|
||||
nameCount.set(n, (nameCount.get(n) ?? 0) + 1)
|
||||
}
|
||||
}
|
||||
// npm plugins in the config are part of the index too (they used to be dropped here until the
|
||||
// next build regenerated it); the generator is shared with the build, see plugin-index.js
|
||||
const npmPackages = []
|
||||
for (const entry of readPluginsJson()?.plugins ?? []) {
|
||||
if (builtinMessage(entry.source)) continue
|
||||
try {
|
||||
const parsed = parseGitSource(entry.source)
|
||||
if (parsed.npmPackage) npmPackages.push(parsed.name)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Phase 2: Generate index with registry import, plugin map, and conditional top-level exports
|
||||
const lines = []
|
||||
|
||||
lines.push(`import { componentRegistry } from "../../quartz/components/registry"`)
|
||||
lines.push("")
|
||||
|
||||
// Type re-exports
|
||||
for (const [pluginName, { types }] of pluginExports) {
|
||||
if (types.length > 0) {
|
||||
lines.push(`export type { ${types.join(", ")} } from ${jsString(`./${pluginName}`)}`)
|
||||
}
|
||||
}
|
||||
|
||||
// Direct re-exports for non-overridable values (constants, utility functions, etc.)
|
||||
for (const [pluginName, { passthrough }] of pluginExports) {
|
||||
if (passthrough.length === 0) continue
|
||||
const unique = passthrough.filter((n) => (nameCount.get(n) ?? 0) === 1)
|
||||
if (unique.length > 0) {
|
||||
lines.push(`export { ${unique.join(", ")} } from ${jsString(`./${pluginName}`)}`)
|
||||
}
|
||||
}
|
||||
lines.push("")
|
||||
|
||||
// Generate the plugins map with override wrappers (overridable exports only)
|
||||
lines.push(
|
||||
`export const plugins: Record<string, Record<string, (...args: unknown[]) => void>> = {`,
|
||||
)
|
||||
for (const [pluginName, { overridable }] of pluginExports) {
|
||||
if (overridable.length === 0) continue
|
||||
lines.push(` ${jsString(pluginName)}: {`)
|
||||
for (const n of overridable) {
|
||||
lines.push(
|
||||
` ${n}: (...args: unknown[]) => { componentRegistry.setOptionOverrides(${jsString(pluginName)}, args[0] as Record<string, unknown>); },`,
|
||||
)
|
||||
}
|
||||
lines.push(` },`)
|
||||
}
|
||||
lines.push(`}`)
|
||||
lines.push("")
|
||||
|
||||
// Top-level exports for overridable names: alias to the plugins map wrapper
|
||||
for (const [pluginName, { overridable }] of pluginExports) {
|
||||
if (overridable.length === 0) continue
|
||||
|
||||
const unique = overridable.filter((n) => (nameCount.get(n) ?? 0) === 1)
|
||||
const conflicting = overridable.filter((n) => (nameCount.get(n) ?? 0) > 1)
|
||||
|
||||
if (unique.length > 0) {
|
||||
for (const n of unique) {
|
||||
lines.push(`export const ${n} = plugins[${jsString(pluginName)}].${n}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (conflicting.length > 0) {
|
||||
for (const n of conflicting) {
|
||||
console.warn(
|
||||
styleText("yellow", `⚠`),
|
||||
`Export "${n}" conflicts across plugins — use plugins["${pluginName}"].${n} in quartz.ts`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.push("")
|
||||
|
||||
const indexContent = lines.join("\n")
|
||||
const indexPath = path.join(PLUGINS_DIR, "index.ts")
|
||||
fs.writeFileSync(indexPath, indexContent)
|
||||
writePluginIndex({ pluginsDir: PLUGINS_DIR, npmPackages, verbose: true })
|
||||
}
|
||||
|
||||
export async function handlePluginInstallUnified({
|
||||
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
export interface PluginIndexEntry {
|
||||
overridable: string[]
|
||||
passthrough: string[]
|
||||
types: string[]
|
||||
importPath: string
|
||||
registryKey: string
|
||||
}
|
||||
export function parseExportsFromDts(content: string): string[]
|
||||
export function isOverridableExport(
|
||||
name: string,
|
||||
dtsContent: string,
|
||||
dtsPath?: string,
|
||||
depth?: number,
|
||||
): boolean
|
||||
export function collectPluginExports(options: {
|
||||
pluginsDir: string
|
||||
npmPackages?: string[]
|
||||
verbose?: boolean
|
||||
}): Map<string, PluginIndexEntry>
|
||||
export function renderPluginIndex(
|
||||
entries: Map<string, PluginIndexEntry>,
|
||||
options?: { warn?: (message: string) => void },
|
||||
): string
|
||||
export function writePluginIndex(options: {
|
||||
pluginsDir: string
|
||||
npmPackages?: string[]
|
||||
verbose?: boolean
|
||||
}): Map<string, PluginIndexEntry>
|
||||
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* The generated plugin index (`.quartz/plugins/index.ts`), shared by `quartz plugin …` commands
|
||||
* and the install step before a build (which used to keep two diverging copies of this code).
|
||||
*
|
||||
* `quartz.ts` imports it as `ExternalPlugin`. Every plugin factory or component constructor is
|
||||
* wrapped: calling `ExternalPlugin.Explorer({...})` records the options as overrides (merged over
|
||||
* the YAML options when Quartz instantiates the plugin) AND returns what the original returns, so
|
||||
* it works both as a statement and as a component inside a layout override.
|
||||
*
|
||||
* 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 fs from "node:fs"
|
||||
import path from "node:path"
|
||||
import { styleText } from "node:util"
|
||||
import { isIdentifier, jsString } from "./subprocess.js"
|
||||
|
||||
const INTERNAL_EXPORTS = new Set(["manifest", "default"])
|
||||
|
||||
const PLUGIN_TYPE_PATTERN =
|
||||
/Quartz(?:Emitter|Transformer|Filter|PageType)Plugin|QuartzComponentConstructor|\(.*\)\s*=>\s*QuartzComponent\b/
|
||||
|
||||
/** Exported names of a `.d.ts` (types prefixed with "type "), excluding external re-exports. */
|
||||
export function parseExportsFromDts(content) {
|
||||
const exports = []
|
||||
const exportMatches = content.matchAll(/export\s*{\s*([^}]+)\s*}(?:\s*from\s*['"]([^'"]+)['"])?/g)
|
||||
for (const match of exportMatches) {
|
||||
const fromModule = match[2]
|
||||
if (fromModule?.startsWith("@")) continue
|
||||
const names = match[1]
|
||||
.split(",")
|
||||
.map((n) => n.trim())
|
||||
.filter(Boolean)
|
||||
for (const name of names) {
|
||||
const cleanName = name.split(" as ").pop()?.trim() || name.trim()
|
||||
if (cleanName && !cleanName.startsWith("_") && !INTERNAL_EXPORTS.has(cleanName)) {
|
||||
const finalName = cleanName.replace(/^type\s+/, "")
|
||||
exports.push(name.includes("type ") ? `type ${finalName}` : finalName)
|
||||
}
|
||||
}
|
||||
}
|
||||
return exports
|
||||
}
|
||||
|
||||
function resolveOriginalName(exportName, dtsContent) {
|
||||
const match = dtsContent.match(new RegExp(`(\\w+)\\s+as\\s+${exportName}\\b`))
|
||||
return match ? match[1] : exportName
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an export is a plugin factory or component constructor. Follows relative re-exports
|
||||
* (`export { Explorer } from './components/index.js'`), which is how most component plugins
|
||||
* expose their constructor.
|
||||
*/
|
||||
export function isOverridableExport(name, dtsContent, dtsPath, depth = 0) {
|
||||
const declName = resolveOriginalName(name, dtsContent)
|
||||
const declPattern = new RegExp(`declare\\s+const\\s+${declName}\\s*:\\s*(.+?)(?:;|$)`, "m")
|
||||
const match = dtsContent.match(declPattern)
|
||||
if (match) return PLUGIN_TYPE_PATTERN.test(match[1])
|
||||
if (!dtsPath || depth >= 4) return false
|
||||
|
||||
for (const reexport of dtsContent.matchAll(
|
||||
/export\s*{\s*([^}]+)\s*}\s*from\s*['"](\.[^'"]+)['"]/g,
|
||||
)) {
|
||||
const entry = reexport[1]
|
||||
.split(",")
|
||||
.map((n) => n.trim().replace(/^type\s+/, ""))
|
||||
.find((n) => (n.split(/\s+as\s+/).pop() ?? "").trim() === name)
|
||||
if (!entry) continue
|
||||
const original = entry.split(/\s+as\s+/)[0].trim()
|
||||
const target = path.resolve(path.dirname(dtsPath), reexport[2].replace(/\.js$/, ".d.ts"))
|
||||
if (!fs.existsSync(target)) return false
|
||||
return isOverridableExport(original, fs.readFileSync(target, "utf-8"), target, depth + 1)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Names `export { … }`-ed by the built JavaScript entry (to tell values from type-only names). */
|
||||
function jsExportNames(jsIndex) {
|
||||
const names = new Set()
|
||||
if (!fs.existsSync(jsIndex)) return names
|
||||
for (const m of fs.readFileSync(jsIndex, "utf-8").matchAll(/export\s*{\s*([^}]+)\s*}/g)) {
|
||||
for (const n of m[1].split(",")) {
|
||||
const clean = n
|
||||
.trim()
|
||||
.split(/\s+as\s+/)
|
||||
.pop()
|
||||
?.trim()
|
||||
if (clean) names.add(clean)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
function classify(distIndex) {
|
||||
const dtsContent = fs.readFileSync(distIndex, "utf-8")
|
||||
const exported = parseExportsFromDts(dtsContent)
|
||||
const dtsTypes = exported.filter((e) => e.startsWith("type ")).map((e) => e.slice(5))
|
||||
const dtsNamed = exported.filter((e) => !e.startsWith("type "))
|
||||
const jsExports = jsExportNames(path.join(path.dirname(distIndex), "index.js"))
|
||||
const named = jsExports.size > 0 ? dtsNamed.filter((n) => jsExports.has(n)) : dtsNamed
|
||||
const extraTypes = jsExports.size > 0 ? dtsNamed.filter((n) => !jsExports.has(n)) : []
|
||||
const overridable = named.filter((n) => isOverridableExport(n, dtsContent, distIndex))
|
||||
return {
|
||||
overridable: overridable.filter(isIdentifier),
|
||||
passthrough: named.filter((n) => !overridable.includes(n)).filter(isIdentifier),
|
||||
types: [...dtsTypes, ...extraTypes].filter(isIdentifier),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect the exports of the installed Git/local plugins (`<pluginsDir>/<name>/dist`) and of the
|
||||
* given npm packages. Returns entries keyed for the generated `plugins` map.
|
||||
*/
|
||||
export function collectPluginExports({ pluginsDir, npmPackages = [], verbose = false }) {
|
||||
const entries = new Map()
|
||||
const add = (key, info) => {
|
||||
const { overridable, passthrough, types } = info
|
||||
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")
|
||||
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 })
|
||||
}
|
||||
|
||||
for (const pkg of npmPackages) {
|
||||
let distIndex
|
||||
try {
|
||||
const pkgJson = new URL(import.meta.resolve(`${pkg}/package.json`)).pathname
|
||||
distIndex = path.join(path.dirname(decodeURIComponent(pkgJson)), "dist", "index.d.ts")
|
||||
} catch {
|
||||
if (verbose) console.log(styleText("yellow", `⚠`), `Skipping npm package ${pkg}: not found`)
|
||||
continue
|
||||
}
|
||||
if (!fs.existsSync(distIndex)) {
|
||||
if (verbose)
|
||||
console.log(styleText("yellow", `⚠`), `Skipping npm package ${pkg}: no dist/index.d.ts`)
|
||||
continue
|
||||
}
|
||||
const key = pkg.replace(/^@/, "").replace(/\//g, "__")
|
||||
add(key, { ...classify(distIndex), importPath: pkg, registryKey: pkg })
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
/** Source of the generated index for collected entries. */
|
||||
export function renderPluginIndex(entries, { warn = () => {} } = {}) {
|
||||
const nameCount = new Map()
|
||||
for (const { overridable, passthrough } of entries.values()) {
|
||||
for (const n of [...overridable, ...passthrough]) nameCount.set(n, (nameCount.get(n) ?? 0) + 1)
|
||||
}
|
||||
const unique = (n) => (nameCount.get(n) ?? 0) === 1
|
||||
|
||||
const lines = [`import { componentRegistry } from "../../quartz/components/registry"`, ""]
|
||||
for (const { types, importPath } of entries.values()) {
|
||||
if (types.length > 0)
|
||||
lines.push(`export type { ${types.join(", ")} } from ${jsString(importPath)}`)
|
||||
}
|
||||
for (const { passthrough, importPath } of entries.values()) {
|
||||
const names = passthrough.filter(unique)
|
||||
if (names.length > 0) lines.push(`export { ${names.join(", ")} } from ${jsString(importPath)}`)
|
||||
}
|
||||
|
||||
// The originals of wrapped exports, imported under collision-free local names
|
||||
const alias = new Map()
|
||||
let index = 0
|
||||
for (const [key, { overridable, importPath }] of entries) {
|
||||
if (overridable.length === 0) continue
|
||||
const specifiers = overridable.map((n) => {
|
||||
const local = `__quartzPlugin${index}_${n}`
|
||||
alias.set(`${key}\u0000${n}`, local)
|
||||
return `${n} as ${local}`
|
||||
})
|
||||
lines.push(`import { ${specifiers.join(", ")} } from ${jsString(importPath)}`)
|
||||
index++
|
||||
}
|
||||
lines.push("")
|
||||
|
||||
lines.push(`type AnyFn = (...args: unknown[]) => unknown`)
|
||||
lines.push(`export const plugins: Record<string, Record<string, AnyFn>> = {`)
|
||||
for (const [key, { overridable, registryKey }] of entries) {
|
||||
if (overridable.length === 0) continue
|
||||
lines.push(` ${jsString(key)}: {`)
|
||||
for (const n of overridable) {
|
||||
lines.push(
|
||||
` ${n}: (...args: unknown[]) => { componentRegistry.setOptionOverrides(${jsString(registryKey)}, args[0] as Record<string, unknown>); return (${alias.get(`${key}\u0000${n}`)} as unknown as AnyFn)(...args) },`,
|
||||
)
|
||||
}
|
||||
lines.push(` },`)
|
||||
}
|
||||
lines.push(`}`, "")
|
||||
|
||||
for (const [key, { overridable }] of entries) {
|
||||
for (const n of overridable) {
|
||||
if (unique(n)) {
|
||||
lines.push(
|
||||
`export const ${n} = plugins[${jsString(key)}].${n} as unknown as typeof ${alias.get(`${key}\u0000${n}`)}`,
|
||||
)
|
||||
} else {
|
||||
warn(
|
||||
`Export "${n}" conflicts across plugins — use plugins[${jsString(key)}].${n} in quartz.ts`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.push("")
|
||||
return lines.join("\n")
|
||||
}
|
||||
|
||||
/** Collect, render and write `<pluginsDir>/index.ts`. */
|
||||
export function writePluginIndex({ pluginsDir, npmPackages = [], verbose = false }) {
|
||||
fs.mkdirSync(pluginsDir, { recursive: true })
|
||||
const entries = collectPluginExports({ pluginsDir, npmPackages, verbose })
|
||||
const source = renderPluginIndex(entries, {
|
||||
warn: (message) => {
|
||||
if (verbose) console.warn(styleText("yellow", `⚠`), message)
|
||||
},
|
||||
})
|
||||
fs.writeFileSync(path.join(pluginsDir, "index.ts"), source)
|
||||
return entries
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import esbuild from "esbuild"
|
||||
import { componentRegistry } from "../components/registry"
|
||||
import {
|
||||
collectPluginExports,
|
||||
isOverridableExport,
|
||||
renderPluginIndex,
|
||||
writePluginIndex,
|
||||
} from "./plugin-index.js"
|
||||
|
||||
/** A fake Quartz checkout: <root>/quartz → this repo's quartz/, plus one installed plugin. */
|
||||
function fakeSite() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-plugin-index-"))
|
||||
fs.symlinkSync(path.resolve(import.meta.dirname, ".."), path.join(root, "quartz"), "dir")
|
||||
// like Quartz's own package.json, so the generated index.ts loads as an ES module
|
||||
fs.writeFileSync(path.join(root, "package.json"), `{"type":"module"}`)
|
||||
const dist = path.join(root, ".quartz", "plugins", "my-widget", "dist")
|
||||
fs.mkdirSync(path.join(dist, "components"), { recursive: true })
|
||||
// like most component plugins: the constructor is re-exported from a sub-module
|
||||
fs.writeFileSync(
|
||||
path.join(dist, "index.d.ts"),
|
||||
`export { Widget, WidgetOptions } from './components/index.js';\nexport { helper } from './util.js';\n`,
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(dist, "components", "index.d.ts"),
|
||||
`import { QuartzComponent } from '@quartz-community/types';\ninterface WidgetOptions { label: string }\ndeclare const _default: (userOpts?: Partial<WidgetOptions>) => QuartzComponent;\nexport { _default as Widget, type WidgetOptions };\n`,
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(dist, "util.d.ts"),
|
||||
`declare const helper: (x: number) => number;\nexport { helper };\n`,
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(dist, "index.js"),
|
||||
`const Widget = (opts) => ({ component: "widget", opts });\nconst helper = (x) => x * 2;\nexport { Widget, helper };\n`,
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(root, ".quartz", "plugins", "my-widget", "package.json"),
|
||||
`{"type":"module","main":"dist/index.js"}`,
|
||||
)
|
||||
return { root, pluginsDir: path.join(root, ".quartz", "plugins") }
|
||||
}
|
||||
|
||||
describe("plugin index", () => {
|
||||
test("component constructors re-exported from a sub-module are wrapped (#2565)", () => {
|
||||
const { root, pluginsDir } = fakeSite()
|
||||
const entry = collectPluginExports({ pluginsDir }).get("my-widget")!
|
||||
assert.deepStrictEqual(entry.overridable, ["Widget"])
|
||||
assert.deepStrictEqual(entry.passthrough, ["helper"])
|
||||
assert.deepStrictEqual(entry.types, ["WidgetOptions"])
|
||||
assert.strictEqual(entry.registryKey, "my-widget")
|
||||
fs.rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test("calling a wrapped export records overrides AND returns the original's result", async () => {
|
||||
const { root, pluginsDir } = fakeSite()
|
||||
writePluginIndex({ pluginsDir })
|
||||
// Bundle the index as the build does (esbuild resolves "./my-widget" through its package.json),
|
||||
// keeping the registry external so this test sees the same instance.
|
||||
const registry = path.resolve(import.meta.dirname, "..", "components", "registry.ts")
|
||||
const bundle = await esbuild.build({
|
||||
entryPoints: [path.join(pluginsDir, "index.ts")],
|
||||
bundle: true,
|
||||
format: "esm",
|
||||
platform: "node",
|
||||
write: false,
|
||||
plugins: [
|
||||
{
|
||||
name: "shared-registry",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /components\/registry$/ }, () => ({
|
||||
path: pathToFileURL(registry).href,
|
||||
external: true,
|
||||
}))
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
const out = path.join(root, "index.bundle.mjs")
|
||||
fs.writeFileSync(out, bundle.outputFiles[0].text)
|
||||
const index = await import(pathToFileURL(out).href)
|
||||
|
||||
const result = index.Widget({ label: "hi" })
|
||||
assert.deepStrictEqual(result, { component: "widget", opts: { label: "hi" } })
|
||||
assert.deepStrictEqual(componentRegistry.getOptionOverrides("my-widget"), { label: "hi" })
|
||||
assert.strictEqual(index.helper(2), 4)
|
||||
fs.rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test("npm plugins register under their package name", () => {
|
||||
const source = renderPluginIndex(
|
||||
new Map([
|
||||
[
|
||||
"quartz-community__explorer",
|
||||
{
|
||||
overridable: ["Explorer"],
|
||||
passthrough: [],
|
||||
types: [],
|
||||
importPath: "@quartz-community/explorer",
|
||||
registryKey: "@quartz-community/explorer",
|
||||
},
|
||||
],
|
||||
]),
|
||||
)
|
||||
assert.match(source, /setOptionOverrides\("@quartz-community\/explorer"/)
|
||||
assert.match(
|
||||
source,
|
||||
/import \{ Explorer as __quartzPlugin0_Explorer \} from "@quartz-community\/explorer"/,
|
||||
)
|
||||
assert.match(
|
||||
source,
|
||||
/export const Explorer = plugins\["quartz-community__explorer"\]\.Explorer as unknown as typeof __quartzPlugin0_Explorer/,
|
||||
)
|
||||
})
|
||||
|
||||
test("plain values and unknown declarations are not wrapped", () => {
|
||||
assert.strictEqual(isOverridableExport("x", "declare const x: number;"), false)
|
||||
assert.strictEqual(
|
||||
isOverridableExport("P", "declare const P: QuartzTransformerPlugin<Options>;"),
|
||||
true,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -6,14 +6,12 @@ import {
|
||||
assertRef,
|
||||
assertRepoUrl,
|
||||
git as runGit,
|
||||
jsString,
|
||||
isIdentifier,
|
||||
npm,
|
||||
} from "../../cli/subprocess.js"
|
||||
import { writePluginIndex } from "../../cli/plugin-index.js"
|
||||
import git from "isomorphic-git"
|
||||
import http from "isomorphic-git/http/node"
|
||||
import { styleText } from "util"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { pathToFileURL } from "url"
|
||||
import { PluginSource } from "./types"
|
||||
|
||||
@@ -989,262 +987,13 @@ export function validatePluginExternals(
|
||||
export async function regeneratePluginIndex(
|
||||
options: { verbose?: boolean; npmPackages?: string[] } = {},
|
||||
): Promise<void> {
|
||||
if (!fs.existsSync(PLUGINS_CACHE_DIR)) {
|
||||
fs.mkdirSync(PLUGINS_CACHE_DIR, { recursive: true })
|
||||
}
|
||||
|
||||
const pluginDirs = fs.readdirSync(PLUGINS_CACHE_DIR).filter((name) => {
|
||||
const pluginPath = path.join(PLUGINS_CACHE_DIR, name)
|
||||
return fs.statSync(pluginPath).isDirectory()
|
||||
// shared with `quartz plugin …` commands, see cli/plugin-index.js
|
||||
const entries = writePluginIndex({
|
||||
pluginsDir: PLUGINS_CACHE_DIR,
|
||||
npmPackages: options.npmPackages ?? [],
|
||||
verbose: options.verbose,
|
||||
})
|
||||
|
||||
// Phase 1: Collect all exports per plugin, detect conflicts
|
||||
// importPath maps plugin key → the import specifier used in generated index.ts
|
||||
const pluginExports = new Map<
|
||||
string,
|
||||
{ overridable: string[]; passthrough: string[]; types: string[] }
|
||||
>()
|
||||
const importPath = new Map<string, string>()
|
||||
const nameCount = new Map<string, number>()
|
||||
|
||||
for (const pluginName of pluginDirs) {
|
||||
const pluginDir = path.join(PLUGINS_CACHE_DIR, pluginName)
|
||||
const distIndex = path.join(pluginDir, "dist", "index.d.ts")
|
||||
|
||||
if (!fs.existsSync(distIndex)) {
|
||||
if (options.verbose) {
|
||||
console.log(styleText("yellow", `⚠`), `Skipping ${pluginName}: no dist/index.d.ts found`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const dtsContent = fs.readFileSync(distIndex, "utf-8")
|
||||
const exportedNames = parseExportsFromDts(dtsContent)
|
||||
const dtsTypes = exportedNames.filter((e) => e.startsWith("type ")).map((e) => e.slice(5))
|
||||
const dtsNamed = exportedNames.filter((e) => !e.startsWith("type "))
|
||||
|
||||
const jsIndex = path.join(pluginDir, "dist", "index.js")
|
||||
let jsExports = new Set<string>()
|
||||
if (fs.existsSync(jsIndex)) {
|
||||
const jsContent = fs.readFileSync(jsIndex, "utf-8")
|
||||
const jsExportMatches = jsContent.matchAll(/export\s*{\s*([^}]+)\s*}/g)
|
||||
for (const m of jsExportMatches) {
|
||||
for (const n of m[1].split(",")) {
|
||||
const clean = n
|
||||
.trim()
|
||||
.split(/\s+as\s+/)
|
||||
.pop()
|
||||
?.trim()
|
||||
if (clean) jsExports.add(clean)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const named = jsExports.size > 0 ? dtsNamed.filter((n) => jsExports.has(n)) : dtsNamed
|
||||
const extraTypes = jsExports.size > 0 ? dtsNamed.filter((n) => !jsExports.has(n)) : []
|
||||
const types = [...dtsTypes, ...extraTypes]
|
||||
|
||||
const overridable = named.filter((n) => isOverridableExport(n, dtsContent))
|
||||
const passthrough = named.filter((n) => !isOverridableExport(n, dtsContent))
|
||||
|
||||
if (overridable.length > 0 || passthrough.length > 0 || types.length > 0) {
|
||||
pluginExports.set(pluginName, {
|
||||
overridable: overridable.filter(isIdentifier),
|
||||
passthrough: passthrough.filter(isIdentifier),
|
||||
types: types.filter(isIdentifier),
|
||||
})
|
||||
importPath.set(pluginName, `./${pluginName}`)
|
||||
for (const n of [...overridable, ...passthrough]) {
|
||||
nameCount.set(n, (nameCount.get(n) ?? 0) + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const npmPkg of options.npmPackages ?? []) {
|
||||
let distIndex: string | undefined
|
||||
try {
|
||||
const pkgJsonPath = fileURLToPath(import.meta.resolve(`${npmPkg}/package.json`))
|
||||
distIndex = path.join(path.dirname(pkgJsonPath), "dist", "index.d.ts")
|
||||
} catch {
|
||||
if (options.verbose) {
|
||||
console.log(styleText("yellow", `⚠`), `Skipping npm package ${npmPkg}: not found`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (!distIndex || !fs.existsSync(distIndex)) {
|
||||
if (options.verbose) {
|
||||
console.log(styleText("yellow", `⚠`), `Skipping npm package ${npmPkg}: no dist/index.d.ts`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const dtsContent = fs.readFileSync(distIndex, "utf-8")
|
||||
const exportedNames = parseExportsFromDts(dtsContent)
|
||||
const dtsTypes = exportedNames.filter((e) => e.startsWith("type ")).map((e) => e.slice(5))
|
||||
const dtsNamed = exportedNames.filter((e) => !e.startsWith("type "))
|
||||
|
||||
const jsIndex = path.join(path.dirname(distIndex), "index.js")
|
||||
let jsExports = new Set<string>()
|
||||
if (fs.existsSync(jsIndex)) {
|
||||
const jsContent = fs.readFileSync(jsIndex, "utf-8")
|
||||
const jsExportMatches = jsContent.matchAll(/export\s*{\s*([^}]+)\s*}/g)
|
||||
for (const m of jsExportMatches) {
|
||||
for (const n of m[1].split(",")) {
|
||||
const clean = n
|
||||
.trim()
|
||||
.split(/\s+as\s+/)
|
||||
.pop()
|
||||
?.trim()
|
||||
if (clean) jsExports.add(clean)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const named = jsExports.size > 0 ? dtsNamed.filter((n) => jsExports.has(n)) : dtsNamed
|
||||
const extraTypes = jsExports.size > 0 ? dtsNamed.filter((n) => !jsExports.has(n)) : []
|
||||
const types = [...dtsTypes, ...extraTypes]
|
||||
|
||||
const overridable = named.filter((n) => isOverridableExport(n, dtsContent))
|
||||
const passthrough = named.filter((n) => !isOverridableExport(n, dtsContent))
|
||||
|
||||
const key = npmPkg.replace(/^@/, "").replace(/\//g, "__")
|
||||
if (overridable.length > 0 || passthrough.length > 0 || types.length > 0) {
|
||||
pluginExports.set(key, {
|
||||
overridable: overridable.filter(isIdentifier),
|
||||
passthrough: passthrough.filter(isIdentifier),
|
||||
types: types.filter(isIdentifier),
|
||||
})
|
||||
importPath.set(key, npmPkg)
|
||||
for (const n of [...overridable, ...passthrough]) {
|
||||
nameCount.set(n, (nameCount.get(n) ?? 0) + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: Generate index with registry import, plugin map, and conditional top-level exports
|
||||
const lines: string[] = []
|
||||
|
||||
lines.push(`import { componentRegistry } from "../../quartz/components/registry"`)
|
||||
lines.push("")
|
||||
|
||||
for (const [pluginKey, { types }] of pluginExports) {
|
||||
if (types.length > 0) {
|
||||
const safe = types.filter(isIdentifier)
|
||||
if (safe.length > 0)
|
||||
lines.push(`export type { ${safe.join(", ")} } from ${jsString(importPath.get(pluginKey))}`)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [pluginKey, { passthrough }] of pluginExports) {
|
||||
if (passthrough.length === 0) continue
|
||||
const unique = passthrough.filter((n) => (nameCount.get(n) ?? 0) === 1 && isIdentifier(n))
|
||||
if (unique.length > 0) {
|
||||
lines.push(`export { ${unique.join(", ")} } from ${jsString(importPath.get(pluginKey))}`)
|
||||
}
|
||||
}
|
||||
lines.push("")
|
||||
|
||||
// Generate the plugins map with override wrappers (overridable exports only)
|
||||
lines.push(
|
||||
`export const plugins: Record<string, Record<string, (...args: unknown[]) => void>> = {`,
|
||||
)
|
||||
for (const [pluginName, { overridable }] of pluginExports) {
|
||||
if (overridable.length === 0) continue
|
||||
lines.push(` ${jsString(pluginName)}: {`)
|
||||
for (const n of overridable) {
|
||||
lines.push(
|
||||
` ${n}: (...args: unknown[]) => { componentRegistry.setOptionOverrides(${jsString(pluginName)}, args[0] as Record<string, unknown>); },`,
|
||||
)
|
||||
}
|
||||
lines.push(` },`)
|
||||
}
|
||||
lines.push(`}`)
|
||||
lines.push("")
|
||||
|
||||
// Top-level exports for overridable names: alias to the plugins map wrapper
|
||||
for (const [pluginName, { overridable }] of pluginExports) {
|
||||
if (overridable.length === 0) continue
|
||||
|
||||
const unique = overridable.filter((n) => (nameCount.get(n) ?? 0) === 1)
|
||||
const conflicting = overridable.filter((n) => (nameCount.get(n) ?? 0) > 1)
|
||||
|
||||
if (unique.length > 0) {
|
||||
for (const n of unique) {
|
||||
lines.push(`export const ${n} = plugins[${jsString(pluginName)}].${n}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (conflicting.length > 0 && options.verbose) {
|
||||
for (const n of conflicting) {
|
||||
console.warn(
|
||||
styleText("yellow", `⚠`),
|
||||
`Export "${n}" conflicts across plugins — use plugins["${pluginName}"].${n} in quartz.ts`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.push("")
|
||||
|
||||
const indexContent = lines.join("\n")
|
||||
const indexPath = path.join(PLUGINS_CACHE_DIR, "index.ts")
|
||||
|
||||
fs.writeFileSync(indexPath, indexContent)
|
||||
|
||||
if (options.verbose) {
|
||||
console.log(
|
||||
styleText("green", `✓`),
|
||||
`Regenerated plugin index with ${pluginDirs.length} plugins`,
|
||||
)
|
||||
console.log(styleText("green", `✓`), `Regenerated plugin index with ${entries.size} plugins`)
|
||||
}
|
||||
}
|
||||
|
||||
const INTERNAL_EXPORTS = new Set(["manifest", "default"])
|
||||
|
||||
const PLUGIN_TYPE_PATTERN =
|
||||
/Quartz(?:Emitter|Transformer|Filter|PageType)Plugin|QuartzComponentConstructor|\(.*\)\s*=>\s*QuartzComponent\b/
|
||||
|
||||
function resolveOriginalName(exportName: string, dtsContent: string): string {
|
||||
const aliasPattern = new RegExp(`(\\w+)\\s+as\\s+${exportName}\\b`)
|
||||
const match = dtsContent.match(aliasPattern)
|
||||
return match ? match[1] : exportName
|
||||
}
|
||||
|
||||
function isOverridableExport(name: string, dtsContent: string): boolean {
|
||||
const declName = resolveOriginalName(name, dtsContent)
|
||||
const declPattern = new RegExp(`declare\\s+const\\s+${declName}\\s*:\\s*(.+?)(?:;|$)`, "m")
|
||||
const match = dtsContent.match(declPattern)
|
||||
if (!match) return false
|
||||
return PLUGIN_TYPE_PATTERN.test(match[1])
|
||||
}
|
||||
|
||||
function parseExportsFromDts(content: string): string[] {
|
||||
const exports: string[] = []
|
||||
|
||||
const exportMatches = content.matchAll(/export\s*{\s*([^}]+)\s*}(?:\s*from\s*['"]([^'"]+)['"])?/g)
|
||||
for (const match of exportMatches) {
|
||||
const fromModule = match[2]
|
||||
if (fromModule?.startsWith("@")) {
|
||||
continue
|
||||
}
|
||||
|
||||
const names = match[1]
|
||||
.split(",")
|
||||
.map((n) => n.trim())
|
||||
.filter(Boolean)
|
||||
for (const name of names) {
|
||||
const cleanName = name.split(" as ").pop()?.trim() || name.trim()
|
||||
if (cleanName && !cleanName.startsWith("_") && !INTERNAL_EXPORTS.has(cleanName)) {
|
||||
const finalName = cleanName.replace(/^type\s+/, "")
|
||||
if (name.includes("type ")) {
|
||||
exports.push(`type ${finalName}`)
|
||||
} else {
|
||||
exports.push(finalName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return exports
|
||||
}
|
||||
Reference in new issue
Block a user