diff --git a/quartz/build.ts b/quartz/build.ts index b98f4a8..38cdbdc 100644 --- a/quartz/build.ts +++ b/quartz/build.ts @@ -263,7 +263,13 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD ) let emittedFiles = 0 - for (const emitter of cfg.plugins.emitters) { + // Run ComponentResources before page/other emitters so staticResources.assetHashes + // is populated regardless of emitter order in quartz.config.ts. + const orderedEmitters = [ + ...cfg.plugins.emitters.filter((emitter) => emitter.name === "ComponentResources"), + ...cfg.plugins.emitters.filter((emitter) => emitter.name !== "ComponentResources"), + ] + for (const emitter of orderedEmitters) { // Try to use partialEmit if available, otherwise assume the output is static const emitFn = emitter.partialEmit ?? emitter.emit const emitted = await emitFn(ctx, processedFiles, staticResources, changeEvents) diff --git a/quartz/components/renderPage.tsx b/quartz/components/renderPage.tsx index 98293a6..97b0282 100644 --- a/quartz/components/renderPage.tsx +++ b/quartz/components/renderPage.tsx @@ -24,23 +24,28 @@ interface RenderComponents { } const headerRegex = new RegExp(/h[1-6]/) +function versionedAsset(assetPath: string, hash?: string): string { + return hash ? `${assetPath}?v=${hash}` : assetPath +} + export function pageResources( baseDir: FullSlug | RelativeURL, staticResources: StaticResources, ): StaticResources { const contentIndexPath = joinSegments(baseDir, "static/contentIndex.json") const contentIndexScript = `const fetchData = fetch("${contentIndexPath}").then(data => data.json())` + const assetHashes = staticResources.assetHashes const resources: StaticResources = { css: [ { - content: joinSegments(baseDir, "index.css"), + content: versionedAsset(joinSegments(baseDir, "index.css"), assetHashes?.css), }, ...staticResources.css, ], js: [ { - src: joinSegments(baseDir, "prescript.js"), + src: versionedAsset(joinSegments(baseDir, "prescript.js"), assetHashes?.prescript), loadTime: "beforeDOMReady", contentType: "external", }, @@ -56,7 +61,7 @@ export function pageResources( } resources.js.push({ - src: joinSegments(baseDir, "postscript.js"), + src: versionedAsset(joinSegments(baseDir, "postscript.js"), assetHashes?.postscript), loadTime: "afterDOMReady", moduleType: "module", contentType: "external", diff --git a/quartz/plugins/emitters/componentResources.test.ts b/quartz/plugins/emitters/componentResources.test.ts new file mode 100644 index 0000000..5bc8a60 --- /dev/null +++ b/quartz/plugins/emitters/componentResources.test.ts @@ -0,0 +1,336 @@ +import test, { after, before, describe } from "node:test" +import assert from "node:assert/strict" +import { createHash } from "node:crypto" +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { pathToFileURL } from "node:url" +import esbuild from "esbuild" +import { sassPlugin } from "esbuild-sass-plugin" +import type { QuartzConfig } from "../../cfg" +import type { QuartzComponent } from "../../components/types" +import type { QuartzEmitterPluginInstance } from "../types" +import type { BuildCtx } from "../../util/ctx" +import type { FilePath } from "../../util/path" +import type { StaticResources } from "../../util/resources" + +interface LoadedModules { + ComponentResources: () => QuartzEmitterPluginInstance + emitContent: (ctx: BuildCtx, content: []) => Promise + pageResources: (baseDir: string, staticResources: StaticResources) => StaticResources +} + +let loaded: LoadedModules +let bundleFile: string +let tempOutputRoot: string + +function sha256Hex8(content: string): string { + return createHash("sha256").update(content).digest("hex").slice(0, 8) +} + +function makeTestCtx(outputDir: string, emitters: QuartzEmitterPluginInstance[]): BuildCtx { + const cfg: QuartzConfig = { + configuration: { + pageTitle: "Test Site", + enableSPA: false, + enablePopovers: false, + analytics: null, + ignorePatterns: [], + defaultDateType: "modified", + baseUrl: "example.com", + locale: "en-US", + theme: { + fontOrigin: "local", + cdnCaching: true, + typography: { + header: "Schibsted Grotesk", + body: "Source Sans Pro", + code: "IBM Plex Mono", + }, + colors: { + lightMode: { + light: "#ffffff", + lightgray: "#eeeeee", + gray: "#888888", + darkgray: "#444444", + dark: "#111111", + secondary: "#224488", + tertiary: "#4488aa", + highlight: "rgba(0,0,0,0.05)", + textHighlight: "#ffff0055", + }, + darkMode: { + light: "#111111", + lightgray: "#222222", + gray: "#777777", + darkgray: "#cccccc", + dark: "#eeeeee", + secondary: "#6699ff", + tertiary: "#88bbdd", + highlight: "rgba(255,255,255,0.08)", + textHighlight: "#ffff0055", + }, + }, + }, + }, + plugins: { + transformers: [], + filters: [], + emitters, + }, + } + + return { + buildId: "test-build", + argv: { + directory: "content", + verbose: false, + output: outputDir, + serve: false, + watch: false, + port: 8080, + wsPort: 3001, + }, + cfg, + allSlugs: [], + allFiles: [], + incremental: false, + } +} + +function makeDummyComponentEmitter(opts: { + css: string + beforeDOMLoaded: string + afterDOMLoaded: string +}): QuartzEmitterPluginInstance { + const Component: QuartzComponent = () => null + Component.css = opts.css + Component.beforeDOMLoaded = opts.beforeDOMLoaded + Component.afterDOMLoaded = opts.afterDOMLoaded + + return { + name: "DummyComponentEmitter", + getQuartzComponents: () => [Component], + async emit() { + return [] + }, + } +} + +before(async () => { + const repoRoot = process.cwd() + tempOutputRoot = await fs.mkdtemp(path.join(os.tmpdir(), "quartz-component-resources-")) + bundleFile = path.join( + repoRoot, + "quartz", + "plugins", + "emitters", + `.tmp-component-resources-test-${process.pid}.mjs`, + ) + + await esbuild.build({ + stdin: { + contents: ` + export { ComponentResources } from "./quartz/plugins/emitters/componentResources" + export { emitContent } from "./quartz/processors/emit" + export { pageResources } from "./quartz/components/renderPage" + `, + resolveDir: repoRoot, + loader: "ts", + }, + outfile: bundleFile, + bundle: true, + platform: "node", + format: "esm", + jsx: "automatic", + jsxImportSource: "preact", + packages: "external", + plugins: [ + sassPlugin({ + type: "css-text", + cssImports: true, + }), + sassPlugin({ + filter: /\.inline\.scss$/, + type: "css", + cssImports: true, + }), + { + name: "inline-script-loader", + setup(build) { + build.onLoad({ filter: /\.inline\.(ts|js)$/ }, async (args) => { + let text = await fs.readFile(args.path, "utf8") + text = text.replace("export default", "").replace("export", "") + const transpiled = await esbuild.build({ + stdin: { + contents: text, + loader: "ts", + resolveDir: path.dirname(args.path), + sourcefile: args.path, + }, + write: false, + bundle: true, + minify: true, + platform: "browser", + format: "esm", + }) + return { + contents: transpiled.outputFiles[0].text, + loader: "text", + } + }) + }, + }, + ], + }) + + loaded = (await import(pathToFileURL(bundleFile).href)) as LoadedModules +}) + +after(async () => { + await fs.rm(bundleFile, { force: true }) + await fs.rm(tempOutputRoot, { recursive: true, force: true }) +}) + +describe("asset cache-busting hashes", () => { + test("pageResources appends ?v= when assetHashes is set and omits it when absent", () => { + const base: StaticResources = { + css: [], + js: [], + additionalHead: [], + } + + const unversioned = loaded.pageResources("..", base) + assert.equal(unversioned.css[0].content, "../index.css") + assert.deepEqual( + unversioned.js.filter((j) => j.contentType === "external").map((j) => j.src), + ["../prescript.js", "../postscript.js"], + ) + + const versioned = loaded.pageResources(".", { + ...base, + assetHashes: { + css: "11223344", + prescript: "aabbccdd", + postscript: "deadbeef", + }, + }) + assert.equal(versioned.css[0].content, "./index.css?v=11223344") + assert.deepEqual( + versioned.js.filter((j) => j.contentType === "external").map((j) => j.src), + ["./prescript.js?v=aabbccdd", "./postscript.js?v=deadbeef"], + ) + }) + + test("changing CSS or JS changes only the affected 8-hex hash matching emitted file bytes", async () => { + const runVariant = async ( + name: string, + opts: { css: string; beforeDOMLoaded: string; afterDOMLoaded: string }, + ) => { + const outDir = path.join(tempOutputRoot, name) + const plugin = loaded.ComponentResources() + const ctx = makeTestCtx(outDir, [makeDummyComponentEmitter(opts), plugin]) + const resources: StaticResources = { css: [], js: [], additionalHead: [] } + for await (const _ of plugin.emit(ctx, [], resources)) { + // exhaust async generator + } + + const [cssFile, preFile, postFile] = await Promise.all([ + fs.readFile(path.join(outDir, "index.css"), "utf8"), + fs.readFile(path.join(outDir, "prescript.js"), "utf8"), + fs.readFile(path.join(outDir, "postscript.js"), "utf8"), + ]) + + assert.match(resources.assetHashes?.css ?? "", /^[0-9a-f]{8}$/) + assert.match(resources.assetHashes?.prescript ?? "", /^[0-9a-f]{8}$/) + assert.match(resources.assetHashes?.postscript ?? "", /^[0-9a-f]{8}$/) + assert.equal(resources.assetHashes?.css, sha256Hex8(cssFile)) + assert.equal(resources.assetHashes?.prescript, sha256Hex8(preFile)) + assert.equal(resources.assetHashes?.postscript, sha256Hex8(postFile)) + + return resources.assetHashes! + } + + const base = await runVariant("base", { + css: ".probe { color: #112233; }", + beforeDOMLoaded: "window.__pre = 1;", + afterDOMLoaded: "window.__post = 1;", + }) + const cssChanged = await runVariant("css-changed", { + css: ".probe { color: #445566; }", + beforeDOMLoaded: "window.__pre = 1;", + afterDOMLoaded: "window.__post = 1;", + }) + assert.notEqual(cssChanged.css, base.css) + assert.equal(cssChanged.prescript, base.prescript) + assert.equal(cssChanged.postscript, base.postscript) + + const preChanged = await runVariant("pre-changed", { + css: ".probe { color: #112233; }", + beforeDOMLoaded: "window.__pre = 2;", + afterDOMLoaded: "window.__post = 1;", + }) + assert.equal(preChanged.css, base.css) + assert.notEqual(preChanged.prescript, base.prescript) + assert.equal(preChanged.postscript, base.postscript) + + const postChanged = await runVariant("post-changed", { + css: ".probe { color: #112233; }", + beforeDOMLoaded: "window.__pre = 1;", + afterDOMLoaded: "window.__post = 2;", + }) + assert.equal(postChanged.css, base.css) + assert.equal(postChanged.prescript, base.prescript) + assert.notEqual(postChanged.postscript, base.postscript) + }) + + test("emitContent populates assetHashes before page emitters even when ComponentResources is last", async () => { + const outDir = path.join(tempOutputRoot, "ordering") + let observedPageResources: StaticResources | undefined + + const pageLikeEmitter: QuartzEmitterPluginInstance = { + name: "PageLikeEmitter", + async emit(_ctx, _content, resources) { + observedPageResources = loaded.pageResources("..", resources) + return [] as FilePath[] + }, + } + + // Place ComponentResources LAST in cfg.plugins.emitters + const ctx = makeTestCtx(outDir, [pageLikeEmitter, loaded.ComponentResources()]) + await loaded.emitContent(ctx, []) + + const [cssFile, preFile, postFile] = await Promise.all([ + fs.readFile(path.join(outDir, "index.css"), "utf8"), + fs.readFile(path.join(outDir, "prescript.js"), "utf8"), + fs.readFile(path.join(outDir, "postscript.js"), "utf8"), + ]) + + assert.ok(observedPageResources) + assert.equal(observedPageResources.css[0].content, `../index.css?v=${sha256Hex8(cssFile)}`) + assert.deepEqual( + observedPageResources.js.filter((j) => j.contentType === "external").map((j) => j.src), + [`../prescript.js?v=${sha256Hex8(preFile)}`, `../postscript.js?v=${sha256Hex8(postFile)}`], + ) + }) + + test("ComponentResources.partialEmit preserves assetHashes onto fresh staticResources", async () => { + const outDir = path.join(tempOutputRoot, "partial") + const plugin = loaded.ComponentResources() + const ctx = makeTestCtx(outDir, [plugin]) + + const initialResources: StaticResources = { css: [], js: [], additionalHead: [] } + for await (const _ of plugin.emit(ctx, [], initialResources)) { + // exhaust async generator + } + + const freshResources: StaticResources = { css: [], js: [], additionalHead: [] } + const partial = plugin.partialEmit!(ctx, [], freshResources, []) + assert.ok(partial && Symbol.asyncIterator in partial) + for await (const _ of partial) { + // exhaust async generator + } + + assert.deepEqual(freshResources.assetHashes, initialResources.assetHashes) + }) +}) diff --git a/quartz/plugins/emitters/componentResources.ts b/quartz/plugins/emitters/componentResources.ts index 9c5ee18..f2dddd1 100644 --- a/quartz/plugins/emitters/componentResources.ts +++ b/quartz/plugins/emitters/componentResources.ts @@ -1,4 +1,6 @@ +import { createHash } from "crypto" import { FullSlug, joinSegments } from "../../util/path" +import { AssetHashes } from "../../util/resources" import { QuartzEmitterPlugin } from "../types" // @ts-ignore @@ -265,12 +267,18 @@ function addGlobalPageResources(ctx: BuildCtx, componentResources: ComponentReso } } -// This emitter should not update the `resources` parameter. If it does, partial -// rebuilds may not work as expected. +function hashAssetContent(content: string): string { + return createHash("sha256").update(content).digest("hex").slice(0, 8) +} + +// Populates `resources.assetHashes` on full emit and caches `lastHashes` so +// incremental `partialEmit` rebuilds preserve the same hashes on fresh `resources`. export const ComponentResources: QuartzEmitterPlugin = () => { + let lastHashes: AssetHashes | undefined + return { name: "ComponentResources", - async *emit(ctx, _content, _resources) { + async *emit(ctx, _content, resources) { const cfg = ctx.cfg.configuration // component specific scripts and styles const componentResources = getComponentResources(ctx) @@ -335,23 +343,33 @@ export const ComponentResources: QuartzEmitterPlugin = () => { joinScripts(componentResources.afterDOMLoaded), ]) + const cssContent = transform({ + filename: "index.css", + code: Buffer.from(stylesheet), + minify: true, + targets: { + safari: (15 << 16) | (6 << 8), // 15.6 + ios_saf: (15 << 16) | (6 << 8), // 15.6 + edge: 115 << 16, + firefox: 102 << 16, + chrome: 109 << 16, + }, + include: Features.MediaQueries, + }).code.toString() + + const hashes: AssetHashes = { + css: hashAssetContent(cssContent), + prescript: hashAssetContent(prescript), + postscript: hashAssetContent(postscript), + } + lastHashes = hashes + resources.assetHashes = hashes + yield write({ ctx, slug: "index" as FullSlug, ext: ".css", - content: transform({ - filename: "index.css", - code: Buffer.from(stylesheet), - minify: true, - targets: { - safari: (15 << 16) | (6 << 8), // 15.6 - ios_saf: (15 << 16) | (6 << 8), // 15.6 - edge: 115 << 16, - firefox: 102 << 16, - chrome: 109 << 16, - }, - include: Features.MediaQueries, - }).code.toString(), + content: cssContent, }) yield write({ @@ -368,6 +386,10 @@ export const ComponentResources: QuartzEmitterPlugin = () => { content: postscript, }) }, - async *partialEmit() {}, + async *partialEmit(_ctx, _content, resources) { + if (lastHashes) { + resources.assetHashes = lastHashes + } + }, } } diff --git a/quartz/processors/emit.ts b/quartz/processors/emit.ts index 7870295..fd4d3a0 100644 --- a/quartz/processors/emit.ts +++ b/quartz/processors/emit.ts @@ -1,5 +1,6 @@ import { PerfTimer } from "../util/perf" import { getStaticResourcesFromPlugins } from "../plugins" +import { QuartzEmitterPluginInstance } from "../plugins/types" import { ProcessedContent } from "../plugins/vfile" import { QuartzLogger } from "../util/log" import { trace } from "../util/trace" @@ -15,36 +16,49 @@ export async function emitContent(ctx: BuildCtx, content: ProcessedContent[]) { let emittedFiles = 0 const staticResources = getStaticResourcesFromPlugins(ctx) - await Promise.all( - cfg.plugins.emitters.map(async (emitter) => { - try { - const emitted = await emitter.emit(ctx, content, staticResources) - if (Symbol.asyncIterator in emitted) { - // Async generator case - for await (const file of emitted) { - emittedFiles++ - if (ctx.argv.verbose) { - console.log(`[emit:${emitter.name}] ${file}`) - } else { - log.updateText(`${emitter.name} -> ${styleText("gray", file)}`) - } - } - } else { - // Array case - emittedFiles += emitted.length - for (const file of emitted) { - if (ctx.argv.verbose) { - console.log(`[emit:${emitter.name}] ${file}`) - } else { - log.updateText(`${emitter.name} -> ${styleText("gray", file)}`) - } + + const runEmitter = async (emitter: QuartzEmitterPluginInstance) => { + try { + const emitted = await emitter.emit(ctx, content, staticResources) + if (Symbol.asyncIterator in emitted) { + // Async generator case + for await (const file of emitted) { + emittedFiles++ + if (ctx.argv.verbose) { + console.log(`[emit:${emitter.name}] ${file}`) + } else { + log.updateText(`${emitter.name} -> ${styleText("gray", file)}`) + } + } + } else { + // Array case + emittedFiles += emitted.length + for (const file of emitted) { + if (ctx.argv.verbose) { + console.log(`[emit:${emitter.name}] ${file}`) + } else { + log.updateText(`${emitter.name} -> ${styleText("gray", file)}`) } } - } catch (err) { - trace(`Failed to emit from plugin \`${emitter.name}\``, err as Error) } - }), + } catch (err) { + trace(`Failed to emit from plugin \`${emitter.name}\``, err as Error) + } + } + + // Run ComponentResources before page/other emitters so staticResources.assetHashes + // is populated regardless of emitter order in quartz.config.ts. + const componentResourceEmitters = cfg.plugins.emitters.filter( + (emitter) => emitter.name === "ComponentResources", ) + const otherEmitters = cfg.plugins.emitters.filter( + (emitter) => emitter.name !== "ComponentResources", + ) + + for (const emitter of componentResourceEmitters) { + await runEmitter(emitter) + } + await Promise.all(otherEmitters.map(runEmitter)) log.end(`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince()}`) } diff --git a/quartz/util/resources.tsx b/quartz/util/resources.tsx index 12dd77e..34c5408 100644 --- a/quartz/util/resources.tsx +++ b/quartz/util/resources.tsx @@ -61,10 +61,17 @@ export function CSSResourceToStyleElement(resource: CSSResource, preserve?: bool } } +export interface AssetHashes { + css?: string + prescript?: string + postscript?: string +} + export interface StaticResources { css: CSSResource[] js: JSResource[] additionalHead: (JSX.Element | ((pageData: QuartzPluginData) => JSX.Element))[] + assetHashes?: AssetHashes } export type StringResource = string | string[] | undefined