crossnote 0.9.37 → 0.9.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/cli/index.cjs CHANGED
@@ -23371,6 +23371,7 @@ var fs21 = __toESM(require("fs"));
23371
23371
  var http = __toESM(require("http"));
23372
23372
  var path25 = __toESM(require("path"));
23373
23373
  var import_url2 = require("url");
23374
+ var import_crypto_js2 = require("crypto-js");
23374
23375
 
23375
23376
  // src/markdown-engine/heading-id-generator.ts
23376
23377
  var import_uslug = __toESM(require("uslug"));
@@ -31853,6 +31854,58 @@ var Search = class {
31853
31854
  // src/notebook/graph-view.ts
31854
31855
  var import_object_hash = __toESM(require("object-hash"));
31855
31856
  var import_path2 = require("path");
31857
+ function constructGraphView(notebook) {
31858
+ const nodes = [];
31859
+ const links = [];
31860
+ const addedNodes = {};
31861
+ const addNode = (filePath) => {
31862
+ if (filePath in addedNodes) {
31863
+ return;
31864
+ }
31865
+ const note = notebook.notes[filePath];
31866
+ if (note) {
31867
+ nodes.push({
31868
+ id: filePath,
31869
+ label: note.title
31870
+ });
31871
+ } else {
31872
+ const lastIndex = filePath.lastIndexOf(".");
31873
+ let label = filePath;
31874
+ if (lastIndex > 0) {
31875
+ label = filePath.slice(0, lastIndex);
31876
+ }
31877
+ nodes.push({
31878
+ id: filePath,
31879
+ label: (0, import_path2.basename)(label)
31880
+ });
31881
+ }
31882
+ addedNodes[filePath] = true;
31883
+ };
31884
+ for (const filePath in notebook.referenceMap.map) {
31885
+ if (notebook.referenceMap.map.hasOwnProperty(filePath)) {
31886
+ addNode(filePath);
31887
+ for (const referredByFilePath in notebook.referenceMap.map[filePath]) {
31888
+ if (
31889
+ // eslint-disable-next-line no-prototype-builtins
31890
+ notebook.referenceMap.map[filePath].hasOwnProperty(
31891
+ referredByFilePath
31892
+ ) && referredByFilePath !== filePath
31893
+ ) {
31894
+ addNode(referredByFilePath);
31895
+ links.push({
31896
+ source: referredByFilePath,
31897
+ target: filePath
31898
+ });
31899
+ }
31900
+ }
31901
+ }
31902
+ }
31903
+ return {
31904
+ hash: (0, import_object_hash.default)({ nodes, links }),
31905
+ nodes,
31906
+ links
31907
+ };
31908
+ }
31856
31909
 
31857
31910
  // src/notebook/index.ts
31858
31911
  var defaultMarkdownItConfig = {
@@ -36191,7 +36244,8 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36191
36244
  puppeteerConfig["fullPage"] = true;
36192
36245
  await page.screenshot(puppeteerConfig);
36193
36246
  }
36194
- browser.close();
36247
+ browser.close().catch(() => {
36248
+ });
36195
36249
  if (openFileAfterGeneration) {
36196
36250
  openFile(dest);
36197
36251
  }
@@ -37356,6 +37410,7 @@ ${result}
37356
37410
  };
37357
37411
 
37358
37412
  // src/wiki/index.ts
37413
+ var cheerio4 = __toESM(require("cheerio"));
37359
37414
  var fs18 = __toESM(require("fs"));
37360
37415
  var path22 = __toESM(require("path"));
37361
37416
 
@@ -37500,13 +37555,37 @@ async function updateVSCodeSetting(settingsPath, key, value) {
37500
37555
  `;
37501
37556
  } else {
37502
37557
  const head = trimmed.slice(0, lastBrace).replace(/\s+$/, "");
37503
- const needsComma = head.length > 0 && !head.endsWith("{");
37504
- text = head + (needsComma ? "," : "") + `
37558
+ const candidates = [",", "\n,", ""];
37559
+ const insertions = candidates.map(
37560
+ (separator) => head + separator + `
37505
37561
  "${MPE_SETTINGS_PREFIX}${key}": ${serialized}
37506
37562
  }
37507
- `;
37563
+ `
37564
+ );
37565
+ const valid = insertions.find((candidate) => {
37566
+ try {
37567
+ import_json53.default.parse(candidate);
37568
+ return true;
37569
+ } catch {
37570
+ return false;
37571
+ }
37572
+ });
37573
+ if (!valid) {
37574
+ throw new Error(
37575
+ `cannot insert "${MPE_SETTINGS_PREFIX}${key}" into ${settingsPath} while keeping it parseable`
37576
+ );
37577
+ }
37578
+ text = valid;
37508
37579
  }
37509
37580
  }
37581
+ try {
37582
+ import_json53.default.parse(text);
37583
+ } catch (error) {
37584
+ throw new Error(
37585
+ `refusing to write settings.json that no longer parses (${settingsPath}): ${error}`,
37586
+ { cause: error }
37587
+ );
37588
+ }
37510
37589
  await fs15.promises.mkdir(path19.dirname(settingsPath), { recursive: true });
37511
37590
  await fs15.promises.writeFile(settingsPath, text, "utf-8");
37512
37591
  }
@@ -37665,7 +37744,16 @@ function encodePathSegments(relativePath) {
37665
37744
  return relativePath.split("/").map((segment) => encodeURIComponent(segment)).join("/");
37666
37745
  }
37667
37746
  function isPathWithinRoot(root, candidate) {
37668
- return candidate === root || candidate.startsWith(root + path21.sep);
37747
+ return isPathWithinRootOn(process.platform, root, candidate);
37748
+ }
37749
+ function isPathWithinRootOn(platform, root, candidate) {
37750
+ if (platform === "win32") {
37751
+ const separator = "\\";
37752
+ const lowercaseRoot = root.toLowerCase();
37753
+ const lowercaseCandidate = candidate.toLowerCase();
37754
+ return lowercaseCandidate === lowercaseRoot || lowercaseCandidate.startsWith(lowercaseRoot + separator);
37755
+ }
37756
+ return candidate === root || candidate.startsWith(root + "/");
37669
37757
  }
37670
37758
  async function listMarkdownFiles(rootDirectory, limit = 5e3) {
37671
37759
  const gitignorePath = path21.join(rootDirectory, ".gitignore");
@@ -37717,6 +37805,7 @@ async function listMarkdownFiles(rootDirectory, limit = 5e3) {
37717
37805
 
37718
37806
  // src/wiki/index.ts
37719
37807
  var ASSET_TOKEN_PREFIX = "crossnote-wiki-asset:";
37808
+ var THEME_TOKEN_PREFIX = "crossnote-wiki-theme:";
37720
37809
  var WIKI_PREVIEW_HOST_SHIM = previewHostShimScript("'*'");
37721
37810
  var IMAGE_MIME_TYPES = {
37722
37811
  avif: "image/avif",
@@ -37750,6 +37839,14 @@ async function buildWiki(options) {
37750
37839
  globalConfigDirectory: options.globalConfigDirectory
37751
37840
  }
37752
37841
  );
37842
+ const multiRoot = rootDirectories.length > 1;
37843
+ const rootNames = rootDirectories.map((root) => path22.basename(root) || root);
37844
+ const noteKeyFor = (absolutePath, rootIndex) => {
37845
+ const relative11 = toPosixPath(
37846
+ path22.relative(rootDirectories[rootIndex], absolutePath)
37847
+ );
37848
+ return multiRoot ? `${rootNames[rootIndex]}/${relative11}` : relative11;
37849
+ };
37753
37850
  const assetIds = /* @__PURE__ */ new Map();
37754
37851
  let assetCounter = 0;
37755
37852
  const tokenFor = (filePath) => {
@@ -37762,17 +37859,28 @@ async function buildWiki(options) {
37762
37859
  return `${ASSET_TOKEN_PREFIX}${id}`;
37763
37860
  };
37764
37861
  const dataUriForImage = (filePath) => {
37862
+ const extension = path22.extname(filePath).toLowerCase().slice(1);
37863
+ const mime = IMAGE_MIME_TYPES[extension];
37864
+ if (!mime) {
37865
+ return null;
37866
+ }
37867
+ const cleanPath = resolvedPath(filePath);
37868
+ const candidates = [cleanPath];
37765
37869
  try {
37766
- const extension = path22.extname(filePath).toLowerCase().slice(1);
37767
- const mime = IMAGE_MIME_TYPES[extension];
37768
- if (!mime) {
37769
- return null;
37870
+ const decoded = decodeURIComponent(cleanPath);
37871
+ if (decoded !== cleanPath) {
37872
+ candidates.push(decoded);
37770
37873
  }
37771
- const base64 = fs18.readFileSync(resolvedPath(filePath)).toString("base64");
37772
- return `data:${mime};base64,${base64}`;
37773
37874
  } catch {
37774
- return null;
37775
37875
  }
37876
+ for (const candidate of candidates) {
37877
+ try {
37878
+ const base64 = fs18.readFileSync(candidate).toString("base64");
37879
+ return `data:${mime};base64,${base64}`;
37880
+ } catch {
37881
+ }
37882
+ }
37883
+ return null;
37776
37884
  };
37777
37885
  function resolvedPath(filePath) {
37778
37886
  return filePath.replace(/\?.+$/, "");
@@ -37782,6 +37890,18 @@ async function buildWiki(options) {
37782
37890
  (filePath) => {
37783
37891
  const cleanPath = resolvedPath(filePath);
37784
37892
  if (isPathWithinRoot(buildDirectory, cleanPath)) {
37893
+ const relativeToBuild = toPosixPath(
37894
+ path22.relative(buildDirectory, cleanPath)
37895
+ );
37896
+ if (relativeToBuild.startsWith("styles/preview_theme/")) {
37897
+ return `${THEME_TOKEN_PREFIX}preview`;
37898
+ }
37899
+ if (relativeToBuild.startsWith("styles/prism_theme/")) {
37900
+ return `${THEME_TOKEN_PREFIX}codeBlock`;
37901
+ }
37902
+ if (relativeToBuild.startsWith("dependencies/reveal/css/theme/")) {
37903
+ return `${THEME_TOKEN_PREFIX}reveal`;
37904
+ }
37785
37905
  return tokenFor(cleanPath);
37786
37906
  }
37787
37907
  for (const root of rootDirectories) {
@@ -37806,6 +37926,7 @@ async function buildWiki(options) {
37806
37926
  );
37807
37927
  const files = [];
37808
37928
  const failures = [];
37929
+ const remoteImageCache = /* @__PURE__ */ new Map();
37809
37930
  try {
37810
37931
  for (let rootIndex = 0; rootIndex < rootDirectories.length; rootIndex++) {
37811
37932
  const root = rootDirectories[rootIndex];
@@ -37822,12 +37943,14 @@ async function buildWiki(options) {
37822
37943
  hideFrontMatter: false,
37823
37944
  vscodePreviewPanel: dummyPanel
37824
37945
  });
37946
+ output.html = await embedRemoteImages(output.html, remoteImageCache);
37947
+ const noteKey = noteKeyFor(file.absolutePath, rootIndex);
37825
37948
  const html2 = await engine.generateHTMLTemplateForPreview({
37826
37949
  inputString: text,
37827
37950
  parsedOutput: output,
37828
37951
  vscodePreviewPanel: dummyPanel,
37829
37952
  config: {
37830
- sourceUri: file.absolutePath,
37953
+ sourceUri: noteKey,
37831
37954
  isVSCode: false,
37832
37955
  isServerApp: true,
37833
37956
  isWiki: true
@@ -37841,8 +37964,8 @@ async function buildWiki(options) {
37841
37964
  const title = typeof yamlConfig["title"] === "string" && yamlConfig["title"].trim() || path22.basename(file.absolutePath, path22.extname(file.absolutePath));
37842
37965
  const mtimeMs = (await fs18.promises.stat(file.absolutePath)).mtimeMs;
37843
37966
  files.push({
37844
- path: file.absolutePath,
37845
- root,
37967
+ path: noteKey,
37968
+ root: rootNames[rootIndex],
37846
37969
  title,
37847
37970
  mtimeMs,
37848
37971
  html: html2,
@@ -37851,7 +37974,7 @@ async function buildWiki(options) {
37851
37974
  html: output.html,
37852
37975
  tocHTML: output.tocHTML,
37853
37976
  totalLineCount: text.split("\n").length,
37854
- sourceUri: file.absolutePath,
37977
+ sourceUri: noteKey,
37855
37978
  sourceScheme: "file",
37856
37979
  id: yamlConfig["id"] || "",
37857
37980
  class: yamlConfig["class"] || "",
@@ -37884,10 +38007,54 @@ async function buildWiki(options) {
37884
38007
  for (const [filePath, id] of assetIds) {
37885
38008
  assets[id] = path22.extname(filePath).toLowerCase() === ".css" ? await readStylesheetWithInlinedUrls(filePath) : await fs18.promises.readFile(filePath, "utf-8").catch(() => "");
37886
38009
  }
38010
+ assets["graph-view.js"] = await fs18.promises.readFile(path22.join(buildDirectory, "webview", "graph-view.js"), "utf-8").catch(() => "");
38011
+ assets["graph-view.css"] = await readStylesheetWithInlinedUrls(
38012
+ path22.join(buildDirectory, "webview", "graph-view.css")
38013
+ ).catch(() => "");
38014
+ const themes = await collectThemeAssets(buildDirectory, notebooks[0]);
38015
+ const graph = {};
38016
+ const backlinks = {};
38017
+ for (let rootIndex = 0; rootIndex < rootDirectories.length; rootIndex++) {
38018
+ const notebook = notebooks[rootIndex];
38019
+ try {
38020
+ await notebook.refreshNotesIfNotLoaded({
38021
+ dir: ".",
38022
+ includeSubdirectories: true
38023
+ });
38024
+ graph[rootNames[rootIndex]] = constructGraphView(
38025
+ notebook
38026
+ );
38027
+ } catch (error) {
38028
+ console.error(
38029
+ `crossnote build-wiki: failed to build graph data for ${rootDirectories[rootIndex]}:`,
38030
+ error
38031
+ );
38032
+ }
38033
+ for (const file of files) {
38034
+ if (file.root !== rootNames[rootIndex]) {
38035
+ continue;
38036
+ }
38037
+ try {
38038
+ backlinks[file.path] = (await notebook.getNoteBacklinks(
38039
+ path22.join(rootDirectories[rootIndex], ...file.path.split("/"))
38040
+ ) ?? []).map(
38041
+ (backlink) => scrubBacklinkForWiki(backlink, rootDirectories[rootIndex])
38042
+ );
38043
+ } catch {
38044
+ backlinks[file.path] = [];
38045
+ }
38046
+ }
38047
+ }
37887
38048
  const html = buildShellHTML({
37888
- rootDirectories,
38049
+ rootNames,
37889
38050
  files,
37890
38051
  assets,
38052
+ themes,
38053
+ // The zen state the notes were built with — the baseline the
38054
+ // context-menu toggle flips (first root anchors, like the themes).
38055
+ zenEnabled: notebooks[0].config.enablePreviewZenMode,
38056
+ graph,
38057
+ backlinks,
37891
38058
  buildDirectory
37892
38059
  });
37893
38060
  return {
@@ -37902,6 +38069,147 @@ async function buildWiki(options) {
37902
38069
  failures
37903
38070
  };
37904
38071
  }
38072
+ function scrubBacklinkForWiki(backlink, rootDirectory) {
38073
+ return {
38074
+ note: {
38075
+ notebookPath: { scheme: "file", path: "/" },
38076
+ filePath: (backlink.note?.filePath ?? "").replace(/\\/g, "/"),
38077
+ title: backlink.note?.title ?? "",
38078
+ config: backlink.note?.config
38079
+ },
38080
+ references: (backlink.references ?? []).map((reference) => ({
38081
+ ...reference,
38082
+ html: typeof reference["html"] === "string" ? scrubWikiHtmlLinks(reference["html"], rootDirectory) : reference["html"]
38083
+ })),
38084
+ referenceHtmls: (backlink.referenceHtmls ?? []).map(
38085
+ (html) => scrubWikiHtmlLinks(html, rootDirectory)
38086
+ )
38087
+ };
38088
+ }
38089
+ function scrubWikiHtmlLinks(html, rootDirectory) {
38090
+ try {
38091
+ const $ = cheerio4.load(html);
38092
+ $("a[href], img[src]").each((_, element) => {
38093
+ for (const attribute of ["href", "src"]) {
38094
+ const value = $(element).attr(attribute);
38095
+ if (!value) {
38096
+ continue;
38097
+ }
38098
+ let decoded = value;
38099
+ try {
38100
+ decoded = decodeURIComponent(value);
38101
+ } catch {
38102
+ }
38103
+ const fileUrlMatch = decoded.match(/^file:\/\/\/+(.*)$/i);
38104
+ if (fileUrlMatch) {
38105
+ decoded = fileUrlMatch[1];
38106
+ if (!/^[A-Za-z]:/.test(decoded)) {
38107
+ decoded = "/" + decoded;
38108
+ }
38109
+ }
38110
+ const normalized = decoded.replace(/\//g, path22.sep);
38111
+ if (!isPathWithinRoot(rootDirectory, normalized)) {
38112
+ continue;
38113
+ }
38114
+ const relative11 = path22.relative(rootDirectory, normalized).split(path22.sep).join("/");
38115
+ $(element).attr(attribute, `file:///${relative11}`);
38116
+ }
38117
+ });
38118
+ return $.html();
38119
+ } catch {
38120
+ return html;
38121
+ }
38122
+ }
38123
+ async function collectThemeAssets(buildDirectory, notebook) {
38124
+ const readThemeDirectory = async (relativeDirectory) => {
38125
+ const absoluteDirectory = path22.join(
38126
+ buildDirectory,
38127
+ ...relativeDirectory.split("/")
38128
+ );
38129
+ const entries = await fs18.promises.readdir(absoluteDirectory).catch(() => []);
38130
+ const map = {};
38131
+ for (const entry of entries) {
38132
+ if (!entry.toLowerCase().endsWith(".css")) {
38133
+ continue;
38134
+ }
38135
+ map[entry] = await readStylesheetWithInlinedUrls(
38136
+ path22.join(absoluteDirectory, entry)
38137
+ );
38138
+ }
38139
+ return map;
38140
+ };
38141
+ return {
38142
+ preview: await readThemeDirectory("styles/preview_theme"),
38143
+ codeBlock: await readThemeDirectory("styles/prism_theme"),
38144
+ reveal: await readThemeDirectory("dependencies/reveal/css/theme"),
38145
+ codeBlockAuto: { ...MarkdownEngine.AutoPrismThemeMap },
38146
+ build: {
38147
+ preview: notebook.config.previewTheme,
38148
+ codeBlock: notebook.config.codeBlockTheme,
38149
+ reveal: notebook.config.revealjsTheme
38150
+ }
38151
+ };
38152
+ }
38153
+ var REMOTE_IMAGE_TIMEOUT_MS = 1e4;
38154
+ var REMOTE_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
38155
+ async function embedRemoteImages(html, cache) {
38156
+ const urls = /* @__PURE__ */ new Set();
38157
+ for (const match of html.matchAll(/<img[^>]*\ssrc="(https?:[^"]+)"/g)) {
38158
+ urls.add(match[1]);
38159
+ }
38160
+ if (urls.size === 0) {
38161
+ return html;
38162
+ }
38163
+ const replacements = /* @__PURE__ */ new Map();
38164
+ await Promise.all(
38165
+ Array.from(urls).map(async (url) => {
38166
+ let cached = cache.get(url);
38167
+ if (cached === void 0) {
38168
+ cached = await fetchRemoteImage(url);
38169
+ cache.set(url, cached);
38170
+ }
38171
+ if (cached) {
38172
+ replacements.set(url, cached);
38173
+ }
38174
+ })
38175
+ );
38176
+ if (replacements.size === 0) {
38177
+ return html;
38178
+ }
38179
+ return html.replace(
38180
+ /(<img[^>]*\ssrc=")(https?:[^"]+)(")/g,
38181
+ (match, prefix, url, suffix) => replacements.has(url) ? `${prefix}${replacements.get(url)}${suffix}` : match
38182
+ );
38183
+ }
38184
+ async function fetchRemoteImage(url) {
38185
+ try {
38186
+ const response = await fetch(url, {
38187
+ signal: AbortSignal.timeout(REMOTE_IMAGE_TIMEOUT_MS),
38188
+ redirect: "follow"
38189
+ });
38190
+ if (!response.ok) {
38191
+ return null;
38192
+ }
38193
+ const declaredLength = parseInt(
38194
+ response.headers.get("content-length") ?? "",
38195
+ 10
38196
+ );
38197
+ if (Number.isInteger(declaredLength) && declaredLength > REMOTE_IMAGE_MAX_BYTES) {
38198
+ return null;
38199
+ }
38200
+ const buffer = Buffer.from(await response.arrayBuffer());
38201
+ if (buffer.length === 0 || buffer.length > REMOTE_IMAGE_MAX_BYTES) {
38202
+ return null;
38203
+ }
38204
+ const mime = (response.headers.get("content-type") ?? "").split(";")[0];
38205
+ if (!mime.startsWith("image/")) {
38206
+ return null;
38207
+ }
38208
+ return `data:${mime};base64,${buffer.toString("base64")}`;
38209
+ } catch {
38210
+ return null;
38211
+ }
38212
+ }
37905
38213
  async function readStylesheetWithInlinedUrls(cssPath) {
37906
38214
  let css;
37907
38215
  try {
@@ -37935,9 +38243,13 @@ async function readStylesheetWithInlinedUrls(cssPath) {
37935
38243
  );
37936
38244
  }
37937
38245
  function buildShellHTML({
37938
- rootDirectories,
38246
+ rootNames,
37939
38247
  files,
37940
38248
  assets,
38249
+ themes,
38250
+ zenEnabled,
38251
+ graph,
38252
+ backlinks,
37941
38253
  buildDirectory
37942
38254
  }) {
37943
38255
  const appScriptPath = path22.join(
@@ -37962,13 +38274,17 @@ function buildShellHTML({
37962
38274
  );
37963
38275
  }
37964
38276
  const payload = JSON.stringify({
37965
- rootDirectories,
38277
+ rootDirectories: rootNames,
37966
38278
  assets,
38279
+ themes,
38280
+ zenEnabled,
38281
+ graph,
38282
+ backlinks,
37967
38283
  files
37968
38284
  }).replace(/</g, "\\u003c");
37969
38285
  const safeAppScript = appScript.replace(/<\/script/g, "<\\/script");
37970
38286
  const safeAppStyle = appStyle.replace(/<\/style/g, "<\\/style");
37971
- const title = `wiki \u2014 ${path22.basename(rootDirectories[0] ?? "")}`;
38287
+ const title = `wiki \u2014 ${rootNames[0] ?? ""}`;
37972
38288
  return `<!DOCTYPE html>
37973
38289
  <html>
37974
38290
  <head>
@@ -37998,6 +38314,89 @@ var utility = {
37998
38314
  uploadImage
37999
38315
  };
38000
38316
 
38317
+ // src/serve/graph-host-shim.ts
38318
+ function graphHostShimScript(options) {
38319
+ const isFetch = options.source === "fetch";
38320
+ const fileExpression = isFetch ? options.fileExpression ?? "''" : options.embeddedFileExpression ?? "''";
38321
+ const dataUrl = options.dataUrl ?? "/api/graph";
38322
+ const targetOrigin = isFetch ? "window.location.origin" : "'*'";
38323
+ const loadData = isFetch ? `fetch(${JSON.stringify(dataUrl)} + '?file=' + encodeURIComponent(FILE))
38324
+ .then(function (response) {
38325
+ if (!response.ok) { throw new Error('graph request failed'); }
38326
+ return response.json();
38327
+ })` : `Promise.resolve(globalThis.__CROSSNOTE_WIKI_GRAPH__ || null)`;
38328
+ return `<script>
38329
+ (function () {
38330
+ if (globalThis.acquireVsCodeApi) { return; }
38331
+ var api = null;
38332
+ var FILE = ${fileExpression};
38333
+ globalThis.acquireVsCodeApi = function () {
38334
+ if (api) { return api; }
38335
+ api = {
38336
+ postMessage: function (message) {
38337
+ if (!message || typeof message.command !== 'string') { return; }
38338
+ if (message.command === 'graphViewReady') {
38339
+ ${loadData}
38340
+ .then(function (payload) {
38341
+ if (!payload) { throw new Error('no graph data'); }
38342
+ globalThis.postMessage({
38343
+ command: 'graphData',
38344
+ data: payload.data,
38345
+ activeFilePath: payload.activeFilePath,
38346
+ }, '*');
38347
+ })
38348
+ .catch(function () {
38349
+ globalThis.postMessage({
38350
+ command: 'graphData',
38351
+ data: { hash: '', nodes: [], links: [] },
38352
+ activeFilePath: '',
38353
+ }, '*');
38354
+ });
38355
+ return;
38356
+ }
38357
+ if (message.command === 'openFile') {
38358
+ var rel = message.args && message.args[0];
38359
+ if (typeof rel === 'string') {
38360
+ globalThis.parent.postMessage(
38361
+ {
38362
+ command: '__serverAppOpenFile',
38363
+ args: [FILE, String(rel).replace(/\\\\/g, '/')],
38364
+ },
38365
+ ${targetOrigin}
38366
+ );
38367
+ }
38368
+ return;
38369
+ }
38370
+ if (message.command === 'saveSetting') {
38371
+ var setting = message.args && message.args[0];
38372
+ if (setting && typeof setting.key === 'string') {
38373
+ try {
38374
+ localStorage.setItem(
38375
+ 'crossnote.graphView.' + setting.key,
38376
+ JSON.stringify(setting.value === undefined ? null : setting.value)
38377
+ );
38378
+ } catch (error) { /* storage unavailable */ }
38379
+ }
38380
+ return;
38381
+ }
38382
+ },
38383
+ getState: function () {
38384
+ try {
38385
+ return JSON.parse(localStorage.getItem('crossnote.graphView.state') || 'null');
38386
+ } catch (error) { return null; }
38387
+ },
38388
+ setState: function (state) {
38389
+ try {
38390
+ localStorage.setItem('crossnote.graphView.state', JSON.stringify(state));
38391
+ } catch (error) { /* storage unavailable */ }
38392
+ },
38393
+ };
38394
+ return api;
38395
+ };
38396
+ })();
38397
+ </script>`;
38398
+ }
38399
+
38001
38400
  // src/serve/sse.ts
38002
38401
  var SSEHub = class {
38003
38402
  constructor() {
@@ -38281,6 +38680,10 @@ async function nonConflictingWikiPath(rootDirectory) {
38281
38680
  return path25.join(rootDirectory, `crossnote-wiki-${stamp}.html`);
38282
38681
  }
38283
38682
  var PREVIEW_HOST_SHIM = previewHostShimScript("window.location.origin");
38683
+ var GRAPH_HOST_SHIM = graphHostShimScript({
38684
+ source: "fetch",
38685
+ fileExpression: "new URLSearchParams(window.location.search).get('file') || ''"
38686
+ });
38284
38687
  function appShellHTML(serverInfo) {
38285
38688
  const serialized = JSON.stringify(serverInfo).replace(/</g, "\\u003c");
38286
38689
  return `<!DOCTYPE html>
@@ -38299,6 +38702,9 @@ function appShellHTML(serverInfo) {
38299
38702
  </html>`;
38300
38703
  }
38301
38704
  async function startServeServer(options) {
38705
+ process.on("unhandledRejection", (reason) => {
38706
+ console.error("crossnote serve: unhandled rejection:", reason);
38707
+ });
38302
38708
  const { rootDirectories, configContexts, notebooks } = await createNotebooksForDirectories(options.directories, {
38303
38709
  vscode: options.vscode,
38304
38710
  vscodeSettingsPath: options.vscodeSettingsPath,
@@ -38498,14 +38904,15 @@ async function startServeServer(options) {
38498
38904
  }
38499
38905
  case "setPreviewTheme":
38500
38906
  case "setCodeBlockTheme":
38501
- case "setRevealjsTheme": {
38502
- const configKey = command === "setPreviewTheme" ? "previewTheme" : command === "setCodeBlockTheme" ? "codeBlockTheme" : "revealjsTheme";
38503
- const theme = typeof args[1] === "string" ? args[1] : null;
38504
- if (!theme) {
38907
+ case "setRevealjsTheme":
38908
+ case "togglePreviewZenMode": {
38909
+ const configKey = command === "setPreviewTheme" ? "previewTheme" : command === "setCodeBlockTheme" ? "codeBlockTheme" : command === "setRevealjsTheme" ? "revealjsTheme" : "enablePreviewZenMode";
38910
+ const value = command === "togglePreviewZenMode" ? !notebooks[0].config.enablePreviewZenMode : typeof args[1] === "string" ? args[1] : null;
38911
+ if (value === null) {
38505
38912
  return;
38506
38913
  }
38507
38914
  try {
38508
- await updateServerConfigKey(configContexts[0], configKey, theme);
38915
+ await updateServerConfigKey(configContexts[0], configKey, value);
38509
38916
  await Promise.all(
38510
38917
  configContexts.map(async (context, index) => {
38511
38918
  const mergedConfig = await loadServerConfig(
@@ -38524,6 +38931,11 @@ async function startServeServer(options) {
38524
38931
  `crossnote serve: failed to persist ${configKey}:`,
38525
38932
  error
38526
38933
  );
38934
+ sse.broadcast({
38935
+ type: "notification",
38936
+ level: "error",
38937
+ message: `Failed to save "${configKey}": ${error instanceof Error ? error.message : String(error)}`
38938
+ });
38527
38939
  }
38528
38940
  return;
38529
38941
  }
@@ -38553,6 +38965,107 @@ async function startServeServer(options) {
38553
38965
  await renderFile(sourceUri, { triggeredBySave: true });
38554
38966
  return;
38555
38967
  }
38968
+ case "showBacklinks": {
38969
+ const info = args[0];
38970
+ const file = assertFileWithinRoots(String(info?.uri ?? ""));
38971
+ if (!file || !isMarkdownFile(file)) {
38972
+ return;
38973
+ }
38974
+ const fileNotebook = notebookForFile(file);
38975
+ if (!fileNotebook) {
38976
+ return;
38977
+ }
38978
+ try {
38979
+ if (info?.forceRefreshingNotes) {
38980
+ await fileNotebook.refreshNotesIncremental({
38981
+ dir: ".",
38982
+ includeSubdirectories: true
38983
+ });
38984
+ } else {
38985
+ await fileNotebook.refreshNotesIfNotLoaded({
38986
+ dir: ".",
38987
+ includeSubdirectories: true
38988
+ });
38989
+ }
38990
+ const backlinks = await fileNotebook.getNoteBacklinks(file);
38991
+ const sha = (0, import_crypto_js2.SHA256)(JSON.stringify(backlinks)).toString();
38992
+ const hasUpdate = sha !== info?.backlinksSha;
38993
+ sse.broadcast({
38994
+ type: "iframeMessage",
38995
+ file,
38996
+ iframeMessage: {
38997
+ command: "backlinks",
38998
+ sourceUri: file,
38999
+ backlinks: hasUpdate ? backlinks : null,
39000
+ hasUpdate
39001
+ }
39002
+ });
39003
+ } catch (error) {
39004
+ console.error(
39005
+ `crossnote serve: failed to compute backlinks for ${file}:`,
39006
+ error
39007
+ );
39008
+ }
39009
+ return;
39010
+ }
39011
+ case "htmlExport":
39012
+ case "chromeExport":
39013
+ case "princeExport":
39014
+ case "eBookExport":
39015
+ case "pandocExport":
39016
+ case "markdownExport": {
39017
+ const sourceUri = assertFileWithinRoots(String(args[0] ?? ""));
39018
+ const param = args[1];
39019
+ if (!sourceUri || !isMarkdownFile(sourceUri)) {
39020
+ return;
39021
+ }
39022
+ const engine = notebookForFile(sourceUri)?.getNoteMarkdownEngine(sourceUri);
39023
+ if (!engine) {
39024
+ return;
39025
+ }
39026
+ try {
39027
+ let dest;
39028
+ if (command === "htmlExport") {
39029
+ dest = await engine.htmlExport({ offline: param === true });
39030
+ } else if (command === "chromeExport") {
39031
+ dest = await engine.chromeExport({
39032
+ fileType: typeof param === "string" ? param : "pdf"
39033
+ });
39034
+ } else if (command === "princeExport") {
39035
+ dest = await engine.princeExport({});
39036
+ if (dest.endsWith("?print-pdf")) {
39037
+ sse.broadcast({
39038
+ type: "notification",
39039
+ level: "info",
39040
+ message: `Please open the link below in Chrome and print it as PDF: ${dest}`
39041
+ });
39042
+ return;
39043
+ }
39044
+ } else if (command === "eBookExport") {
39045
+ dest = await engine.eBookExport({
39046
+ fileType: typeof param === "string" ? param : "epub",
39047
+ runAllCodeChunks: false
39048
+ });
39049
+ } else if (command === "pandocExport") {
39050
+ dest = await engine.pandocExport({});
39051
+ } else {
39052
+ dest = await engine.markdownExport({});
39053
+ }
39054
+ sse.broadcast({
39055
+ type: "notification",
39056
+ level: "info",
39057
+ message: `Exported ${path25.basename(sourceUri)} to ${dest}`
39058
+ });
39059
+ } catch (error) {
39060
+ console.error(`crossnote serve: ${command} failed:`, error);
39061
+ sse.broadcast({
39062
+ type: "notification",
39063
+ level: "error",
39064
+ message: `${command} failed: ${error instanceof Error ? error.message : String(error)}`
39065
+ });
39066
+ }
39067
+ return;
39068
+ }
38556
39069
  case "exportStandaloneWiki": {
38557
39070
  try {
38558
39071
  const result = await buildWiki({
@@ -38677,6 +39190,63 @@ async function startServeServer(options) {
38677
39190
  }
38678
39191
  return;
38679
39192
  }
39193
+ if (request.method === "GET" && urlPath === "/graph-view") {
39194
+ const file = assertFileWithinRoots(
39195
+ requestUrl.searchParams.get("file") ?? "/"
39196
+ );
39197
+ if (!file || !isMarkdownFile(file)) {
39198
+ response.writeHead(400, { "content-type": "text/plain" });
39199
+ response.end("invalid file");
39200
+ return;
39201
+ }
39202
+ const graphNotebook = notebookForFile(file);
39203
+ if (!graphNotebook) {
39204
+ response.writeHead(404, { "content-type": "text/plain" });
39205
+ response.end("not found");
39206
+ return;
39207
+ }
39208
+ try {
39209
+ const engine = graphNotebook.getNoteMarkdownEngine(file);
39210
+ let html = engine.generateHTMLTemplateForGraphView({
39211
+ vscodePreviewPanel: dummyPanel
39212
+ });
39213
+ html = html.replace(/<script\b/, `${GRAPH_HOST_SHIM}<script`);
39214
+ response.writeHead(200, {
39215
+ "content-type": "text/html; charset=utf-8",
39216
+ ...BASE_SECURITY_HEADERS
39217
+ });
39218
+ response.end(html);
39219
+ } catch (error) {
39220
+ console.error("crossnote serve: failed to build graph view:", error);
39221
+ response.writeHead(500, { "content-type": "text/plain" });
39222
+ response.end("internal error");
39223
+ }
39224
+ return;
39225
+ }
39226
+ if (request.method === "GET" && urlPath === "/api/graph") {
39227
+ const file = assertFileWithinRoots(
39228
+ requestUrl.searchParams.get("file") ?? "/"
39229
+ );
39230
+ const graphNotebook = file ? notebookForFile(file) : null;
39231
+ if (!file || !graphNotebook) {
39232
+ sendJSON(response, 400, { error: "invalid file" });
39233
+ return;
39234
+ }
39235
+ try {
39236
+ await graphNotebook.refreshNotesIfNotLoaded({
39237
+ dir: ".",
39238
+ includeSubdirectories: true
39239
+ });
39240
+ const data = constructGraphView(graphNotebook);
39241
+ const rootIndex = rootIndexOf(file);
39242
+ const relativePath = rootIndex === -1 ? "" : path25.relative(rootDirectories[rootIndex], file).split(path25.sep).join("/");
39243
+ sendJSON(response, 200, { data, activeFilePath: relativePath });
39244
+ } catch (error) {
39245
+ console.error("crossnote serve: failed to build graph data:", error);
39246
+ sendJSON(response, 500, { error: "failed to build graph data" });
39247
+ }
39248
+ return;
39249
+ }
38680
39250
  if (request.method === "GET" && urlPath === "/api/events") {
38681
39251
  sse.addClient(response);
38682
39252
  return;