An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Refresh PDF preview resources in development
Daniel11b5949ee908
diff --git a/app/src/protyle/export/index.ts b/app/src/protyle/export/index.tsindex fbd5891cf6..5eecb8a399 100644--- a/app/src/protyle/export/index.ts+++ b/app/src/protyle/export/index.ts@@ -224,6 +224,9 @@ const renderPDF = async (id: string) => {cmd: "getContentsId",});const defaultExportPath = await getAvailableExportPath();+ // 开发编译不会改变版本号,预览页需刷新导出样式和渲染脚本,避免沿用编译前的缓存。+ const exportResourceVersion = Constants.NODE_ENV === "development" ?+ `${Constants.SIYUAN_VERSION}-${Date.now()}` : Constants.SIYUAN_VERSION;// data-theme-mode="light" https://github.com/siyuan-note/siyuan/issues/7379const html = `<!DOCTYPE html><html lang="${window.siyuan.config.appearance.lang}" data-theme-mode="light" data-light-theme="${window.siyuan.config.appearance.themeLight}" data-dark-theme="${window.siyuan.config.appearance.themeDark}">@@ -234,7 +237,7 @@ const renderPDF = async (id: string) => {<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/><meta name="mobile-web-app-capable" content="yes"/><meta name="apple-mobile-web-app-status-bar-style" content="black">- <link rel="stylesheet" type="text/css" id="baseStyle" href="${servePath}stage/build/export/base.css?v=${Constants.SIYUAN_VERSION}"/>+ <link rel="stylesheet" type="text/css" id="baseStyle" href="${servePath}stage/build/export/base.css?v=${exportResourceVersion}"/><link rel="stylesheet" type="text/css" id="themeDefaultStyle" href="${servePath}appearance/themes/daylight/theme.css?v=${Constants.SIYUAN_VERSION}"/><script src="${servePath}stage/protyle/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}"></script>${themeStyle}@@ -544,7 +547,7 @@ const renderPDF = async (id: string) => {</div></div>${getIconScript(servePath)}-<script src="${servePath}stage/build/export/protyle-method.js?${Constants.SIYUAN_VERSION}"></script>+<script src="${servePath}stage/build/export/protyle-method.js?${exportResourceVersion}"></script><script src="${servePath}stage/protyle/js/lute/lute.min.js?${Constants.SIYUAN_VERSION}"></script><script>const previewElement = document.getElementById('preview');diff --git a/app/tests/pdfExportCache.test.js b/app/tests/pdfExportCache.test.jsnew file mode 100644index 0000000000..70a3586f33--- /dev/null+++ b/app/tests/pdfExportCache.test.js@@ -0,0 +1,99 @@+const assert = require("node:assert/strict");+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");+const http = require("node:http");+const path = require("node:path");+const os = require("node:os");+const ts = require("typescript");++const createPreview = mode => {+ const source = readFileSync(path.join(__dirname, "../src/protyle/export/index.ts"), "utf8");+ const compiled = ts.transpileModule(source.slice(source.indexOf("const renderPDF ="),+ source.indexOf("const getExportPath =")), {compilerOptions: {target: ts.ScriptTarget.ES2021}}).outputText;+ let html;+ let time = 1000;+ const renderPDF = new Function("window", "Constants", "ipcRenderer", "getAvailableExportPath", "getHostCapabilities",+ "getIconScript", "getSnippetCSS", "getSnippetJS", "getExportLanguages", "setInlineStyle", "getCustomFontStyle",+ "getPluginStyle", "fetchPost", "headingPageBreakControls", "Date", compiled + ";return renderPDF;")(+ {siyuan: {config: {appearance: {themeLight: "daylight"}, editor: {}, export: {}, system: {}},+ storage: {pdf: {paged: true}}, languages: {}}},+ {LOCAL_EXPORTPDF: "pdf", SIYUAN_VERSION: "test", NODE_ENV: mode}, {invoke: async () => 0},+ async () => "", () => ({}), () => "", () => "", () => "", () => "{}", async () => "", async () => "",+ async () => "", (_url, data) => html = data.content, () => "", {now: () => ++time});+ return async () => {+ await renderPDF("root");+ return {+ css: html.match(/id="baseStyle" href="([^"]+)"/)[1],+ js: html.match(/src="([^"]*stage\/build\/export\/protyle-method\.js[^"]*)"/)[1],+ };+ };+};++const runElectron = async () => {+ const {app, BrowserWindow} = require("electron");+ app.setPath("userData", process.argv[2]);+ await app.whenReady();+ const win = new BrowserWindow({show: false});+ let phase = 0;+ let resources;+ const server = http.createServer((request, response) => {+ const pathname = new URL(request.url, "http://localhost").pathname;+ if (pathname.endsWith(".css") || pathname.endsWith(".js")) {+ response.setHeader("Cache-Control", "public, max-age=3600");+ response.setHeader("Content-Type", pathname.endsWith(".css") ? "text/css" : "text/javascript");+ response.end(pathname.endsWith(".css") ? `.probe { height: ${phase ? 880 : 1500}px; }` :+ `window.exportGeneration = ${phase};`);+ } else {+ response.setHeader("Content-Type", "text/html");+ response.setHeader("Cache-Control", "no-store");+ response.end(`<link rel="stylesheet" href="${resources.css}"><div class="probe"></div><script src="${resources.js}"></script>`);+ }+ });+ let exitCode = 0;+ try {+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));+ const origin = "http://127.0.0.1:" + server.address().port;+ const preview = createPreview("development");+ resources = await preview();+ await win.loadURL(origin + "/first");+ assert.deepEqual(await win.webContents.executeJavaScript(`({height: document.querySelector(".probe").clientHeight,+ generation: window.exportGeneration})`), {height: 1500, generation: 0});+ phase = 1;+ resources = await preview();+ await win.loadURL(origin + "/second");+ assert.deepEqual(await win.webContents.executeJavaScript(`({height: document.querySelector(".probe").clientHeight,+ generation: window.exportGeneration})`), {height: 880, generation: 1},+ "A new development preview must load rebuilt CSS and rendering scripts despite a warm cache");+ const production = createPreview("production");+ assert.deepEqual(await production(), await production(), "Production exports retain versioned resource caching");+ console.log("PDF export resource cache cases passed");+ } catch (error) {+ console.error(error);+ exitCode = 1;+ } finally {+ win.destroy();+ await new Promise(resolve => server.close(resolve));+ app.exit(exitCode);+ }+};++if (process.versions.electron && process.type === "browser") {+ runElectron().catch(error => { console.error(error); require("electron").app.exit(1); });+} else {+ require("node:test").it("development PDF previews refresh rebuilt resources while production keeps versioned caching", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+ }, async () => {+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-pdf-cache-"));+ try {+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 25000});+ assert.match(stdout, /PDF export resource cache cases passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));+ assert.ok(path.basename(profile).startsWith("siyuan-pdf-cache-"));+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ }+ });+}diff --git a/app/tests/pdfImages.test.js b/app/tests/pdfImages.test.jsindex ee857157a2..d84e76c5c5 100644--- a/app/tests/pdfImages.test.js+++ b/app/tests/pdfImages.test.js@@ -29,7 +29,11 @@ const runElectron = async () => {path.join(__dirname, "../stage/protyle/js/pdf/", name))).toString("base64");const runtime = moduleURL("pdf.min.mjs");const worker = moduleURL("pdf.worker.min.mjs");+ const luteSource = readFileSync(path.join(__dirname, "../stage/protyle/js/lute/lute.min.js"), "utf8");const cases = [+ {name: "paragraph-default", scale: 1, margin: 1, realDOM: true},+ {name: "paragraph-full-width", scale: 1, margin: 1, realDOM: true, width: "100%"},+ {name: "paragraph-caption", scale: 1, margin: 1, realDOM: true, width: "100%", caption: true},{name: "full-size", scale: 1, margin: 1},{name: "landscape", scale: 1, margin: 0.42, landscape: true},{name: "scaled-up", scale: 1.5, margin: 0.5},@@ -44,6 +48,7 @@ const runElectron = async () => {for (const item of cases) {await win.loadURL("data:text/html,<!DOCTYPE html><html><body></body></html>");await win.webContents.insertCSS(css + (item.mobile ? mobileCSS : desktopCSS));+ await win.webContents.executeJavaScript(luteSource);const options = await win.webContents.executeJavaScript(`(async () => {const item = ${JSON.stringify(item)};document.body.innerHTML = '<div id="action"></div><div id="previewContainer"><div id="preview"></div></div>';@@ -77,6 +82,23 @@ const runElectron = async () => {'<div data-node-id="before" data-type="NodeParagraph" style="height:140px">Before image</div>' +'<div data-node-id="picture" data-type="NodeParagraph">' + image + '<hr style="margin:0;border:0"></div>' +'<div data-node-id="after" data-type="NodeHeading">After image</div></div>';+ if (item.realDOM) {+ const lute = Lute.New();+ lute.SetKramdownIAL(true);+ const markdown = 'Before image\\n\\n : '') + '")' ++ (item.width ? '{: style="width: ' + item.width + ';"}' : '') + '\\n\\n## After image';+ previewElement.firstElementChild.innerHTML = lute.Md2BlockDOM(markdown);+ previewElement.querySelector("[data-type=NodeParagraph]").style.height = "140px";+ previewElement.querySelectorAll("[data-node-id]").forEach(block => {+ if (block.querySelector(".img")) {+ block.insertAdjacentHTML("beforeend", '<hr style="margin:0;border:0">');+ }+ });+ const img = previewElement.querySelector("img");+ img.loading = "eager";+ img.src = canvas.toDataURL();+ }await previewElement.querySelector("img").decode();if (item.mobile) {previewElement.style.cssText = "max-width:800px;margin:0 auto";