crossnote 0.9.37 → 0.9.38

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 = {
@@ -37356,6 +37409,7 @@ ${result}
37356
37409
  };
37357
37410
 
37358
37411
  // src/wiki/index.ts
37412
+ var cheerio4 = __toESM(require("cheerio"));
37359
37413
  var fs18 = __toESM(require("fs"));
37360
37414
  var path22 = __toESM(require("path"));
37361
37415
 
@@ -37384,6 +37438,15 @@ function previewHostShimScript(targetOriginExpression) {
37384
37438
  };
37385
37439
  return api;
37386
37440
  };
37441
+ // The shell tells the frames when zen mode is on: Esc must then exit zen
37442
+ // (the welcome card and the exit button both promise that), instead of the
37443
+ // preview's own Esc behavior of toggling the sidebar TOC.
37444
+ var zenMode = false;
37445
+ window.addEventListener('message', function (event) {
37446
+ if (event.data && event.data.command === '__serverAppZenMode') {
37447
+ zenMode = !!event.data.enabled;
37448
+ }
37449
+ });
37387
37450
  document.addEventListener('keydown', function (event) {
37388
37451
  var key = event.key.toLowerCase();
37389
37452
  var action = null;
@@ -37393,6 +37456,8 @@ function previewHostShimScript(targetOriginExpression) {
37393
37456
  action = 'split-pane';
37394
37457
  } else if (event.altKey && key === 'w') {
37395
37458
  action = 'close-tab';
37459
+ } else if (key === 'escape' && zenMode) {
37460
+ action = 'exit-zen-mode';
37396
37461
  }
37397
37462
  if (action) {
37398
37463
  event.preventDefault();
@@ -37665,7 +37730,16 @@ function encodePathSegments(relativePath) {
37665
37730
  return relativePath.split("/").map((segment) => encodeURIComponent(segment)).join("/");
37666
37731
  }
37667
37732
  function isPathWithinRoot(root, candidate) {
37668
- return candidate === root || candidate.startsWith(root + path21.sep);
37733
+ return isPathWithinRootOn(process.platform, root, candidate);
37734
+ }
37735
+ function isPathWithinRootOn(platform, root, candidate) {
37736
+ if (platform === "win32") {
37737
+ const separator = "\\";
37738
+ const lowercaseRoot = root.toLowerCase();
37739
+ const lowercaseCandidate = candidate.toLowerCase();
37740
+ return lowercaseCandidate === lowercaseRoot || lowercaseCandidate.startsWith(lowercaseRoot + separator);
37741
+ }
37742
+ return candidate === root || candidate.startsWith(root + "/");
37669
37743
  }
37670
37744
  async function listMarkdownFiles(rootDirectory, limit = 5e3) {
37671
37745
  const gitignorePath = path21.join(rootDirectory, ".gitignore");
@@ -37717,6 +37791,7 @@ async function listMarkdownFiles(rootDirectory, limit = 5e3) {
37717
37791
 
37718
37792
  // src/wiki/index.ts
37719
37793
  var ASSET_TOKEN_PREFIX = "crossnote-wiki-asset:";
37794
+ var THEME_TOKEN_PREFIX = "crossnote-wiki-theme:";
37720
37795
  var WIKI_PREVIEW_HOST_SHIM = previewHostShimScript("'*'");
37721
37796
  var IMAGE_MIME_TYPES = {
37722
37797
  avif: "image/avif",
@@ -37750,6 +37825,14 @@ async function buildWiki(options) {
37750
37825
  globalConfigDirectory: options.globalConfigDirectory
37751
37826
  }
37752
37827
  );
37828
+ const multiRoot = rootDirectories.length > 1;
37829
+ const rootNames = rootDirectories.map((root) => path22.basename(root) || root);
37830
+ const noteKeyFor = (absolutePath, rootIndex) => {
37831
+ const relative11 = toPosixPath(
37832
+ path22.relative(rootDirectories[rootIndex], absolutePath)
37833
+ );
37834
+ return multiRoot ? `${rootNames[rootIndex]}/${relative11}` : relative11;
37835
+ };
37753
37836
  const assetIds = /* @__PURE__ */ new Map();
37754
37837
  let assetCounter = 0;
37755
37838
  const tokenFor = (filePath) => {
@@ -37762,17 +37845,28 @@ async function buildWiki(options) {
37762
37845
  return `${ASSET_TOKEN_PREFIX}${id}`;
37763
37846
  };
37764
37847
  const dataUriForImage = (filePath) => {
37848
+ const extension = path22.extname(filePath).toLowerCase().slice(1);
37849
+ const mime = IMAGE_MIME_TYPES[extension];
37850
+ if (!mime) {
37851
+ return null;
37852
+ }
37853
+ const cleanPath = resolvedPath(filePath);
37854
+ const candidates = [cleanPath];
37765
37855
  try {
37766
- const extension = path22.extname(filePath).toLowerCase().slice(1);
37767
- const mime = IMAGE_MIME_TYPES[extension];
37768
- if (!mime) {
37769
- return null;
37856
+ const decoded = decodeURIComponent(cleanPath);
37857
+ if (decoded !== cleanPath) {
37858
+ candidates.push(decoded);
37770
37859
  }
37771
- const base64 = fs18.readFileSync(resolvedPath(filePath)).toString("base64");
37772
- return `data:${mime};base64,${base64}`;
37773
37860
  } catch {
37774
- return null;
37775
37861
  }
37862
+ for (const candidate of candidates) {
37863
+ try {
37864
+ const base64 = fs18.readFileSync(candidate).toString("base64");
37865
+ return `data:${mime};base64,${base64}`;
37866
+ } catch {
37867
+ }
37868
+ }
37869
+ return null;
37776
37870
  };
37777
37871
  function resolvedPath(filePath) {
37778
37872
  return filePath.replace(/\?.+$/, "");
@@ -37782,6 +37876,18 @@ async function buildWiki(options) {
37782
37876
  (filePath) => {
37783
37877
  const cleanPath = resolvedPath(filePath);
37784
37878
  if (isPathWithinRoot(buildDirectory, cleanPath)) {
37879
+ const relativeToBuild = toPosixPath(
37880
+ path22.relative(buildDirectory, cleanPath)
37881
+ );
37882
+ if (relativeToBuild.startsWith("styles/preview_theme/")) {
37883
+ return `${THEME_TOKEN_PREFIX}preview`;
37884
+ }
37885
+ if (relativeToBuild.startsWith("styles/prism_theme/")) {
37886
+ return `${THEME_TOKEN_PREFIX}codeBlock`;
37887
+ }
37888
+ if (relativeToBuild.startsWith("dependencies/reveal/css/theme/")) {
37889
+ return `${THEME_TOKEN_PREFIX}reveal`;
37890
+ }
37785
37891
  return tokenFor(cleanPath);
37786
37892
  }
37787
37893
  for (const root of rootDirectories) {
@@ -37806,6 +37912,7 @@ async function buildWiki(options) {
37806
37912
  );
37807
37913
  const files = [];
37808
37914
  const failures = [];
37915
+ const remoteImageCache = /* @__PURE__ */ new Map();
37809
37916
  try {
37810
37917
  for (let rootIndex = 0; rootIndex < rootDirectories.length; rootIndex++) {
37811
37918
  const root = rootDirectories[rootIndex];
@@ -37822,12 +37929,14 @@ async function buildWiki(options) {
37822
37929
  hideFrontMatter: false,
37823
37930
  vscodePreviewPanel: dummyPanel
37824
37931
  });
37932
+ output.html = await embedRemoteImages(output.html, remoteImageCache);
37933
+ const noteKey = noteKeyFor(file.absolutePath, rootIndex);
37825
37934
  const html2 = await engine.generateHTMLTemplateForPreview({
37826
37935
  inputString: text,
37827
37936
  parsedOutput: output,
37828
37937
  vscodePreviewPanel: dummyPanel,
37829
37938
  config: {
37830
- sourceUri: file.absolutePath,
37939
+ sourceUri: noteKey,
37831
37940
  isVSCode: false,
37832
37941
  isServerApp: true,
37833
37942
  isWiki: true
@@ -37841,8 +37950,8 @@ async function buildWiki(options) {
37841
37950
  const title = typeof yamlConfig["title"] === "string" && yamlConfig["title"].trim() || path22.basename(file.absolutePath, path22.extname(file.absolutePath));
37842
37951
  const mtimeMs = (await fs18.promises.stat(file.absolutePath)).mtimeMs;
37843
37952
  files.push({
37844
- path: file.absolutePath,
37845
- root,
37953
+ path: noteKey,
37954
+ root: rootNames[rootIndex],
37846
37955
  title,
37847
37956
  mtimeMs,
37848
37957
  html: html2,
@@ -37851,7 +37960,7 @@ async function buildWiki(options) {
37851
37960
  html: output.html,
37852
37961
  tocHTML: output.tocHTML,
37853
37962
  totalLineCount: text.split("\n").length,
37854
- sourceUri: file.absolutePath,
37963
+ sourceUri: noteKey,
37855
37964
  sourceScheme: "file",
37856
37965
  id: yamlConfig["id"] || "",
37857
37966
  class: yamlConfig["class"] || "",
@@ -37884,10 +37993,51 @@ async function buildWiki(options) {
37884
37993
  for (const [filePath, id] of assetIds) {
37885
37994
  assets[id] = path22.extname(filePath).toLowerCase() === ".css" ? await readStylesheetWithInlinedUrls(filePath) : await fs18.promises.readFile(filePath, "utf-8").catch(() => "");
37886
37995
  }
37996
+ assets["graph-view.js"] = await fs18.promises.readFile(path22.join(buildDirectory, "webview", "graph-view.js"), "utf-8").catch(() => "");
37997
+ assets["graph-view.css"] = await readStylesheetWithInlinedUrls(
37998
+ path22.join(buildDirectory, "webview", "graph-view.css")
37999
+ ).catch(() => "");
38000
+ const themes = await collectThemeAssets(buildDirectory, notebooks[0]);
38001
+ const graph = {};
38002
+ const backlinks = {};
38003
+ for (let rootIndex = 0; rootIndex < rootDirectories.length; rootIndex++) {
38004
+ const notebook = notebooks[rootIndex];
38005
+ try {
38006
+ await notebook.refreshNotesIfNotLoaded({
38007
+ dir: ".",
38008
+ includeSubdirectories: true
38009
+ });
38010
+ graph[rootNames[rootIndex]] = constructGraphView(
38011
+ notebook
38012
+ );
38013
+ } catch (error) {
38014
+ console.error(
38015
+ `crossnote build-wiki: failed to build graph data for ${rootDirectories[rootIndex]}:`,
38016
+ error
38017
+ );
38018
+ }
38019
+ for (const file of files) {
38020
+ if (file.root !== rootNames[rootIndex]) {
38021
+ continue;
38022
+ }
38023
+ try {
38024
+ backlinks[file.path] = (await notebook.getNoteBacklinks(
38025
+ path22.join(rootDirectories[rootIndex], ...file.path.split("/"))
38026
+ ) ?? []).map(
38027
+ (backlink) => scrubBacklinkForWiki(backlink, rootDirectories[rootIndex])
38028
+ );
38029
+ } catch {
38030
+ backlinks[file.path] = [];
38031
+ }
38032
+ }
38033
+ }
37887
38034
  const html = buildShellHTML({
37888
- rootDirectories,
38035
+ rootNames,
37889
38036
  files,
37890
38037
  assets,
38038
+ themes,
38039
+ graph,
38040
+ backlinks,
37891
38041
  buildDirectory
37892
38042
  });
37893
38043
  return {
@@ -37902,6 +38052,147 @@ async function buildWiki(options) {
37902
38052
  failures
37903
38053
  };
37904
38054
  }
38055
+ function scrubBacklinkForWiki(backlink, rootDirectory) {
38056
+ return {
38057
+ note: {
38058
+ notebookPath: { scheme: "file", path: "/" },
38059
+ filePath: (backlink.note?.filePath ?? "").replace(/\\/g, "/"),
38060
+ title: backlink.note?.title ?? "",
38061
+ config: backlink.note?.config
38062
+ },
38063
+ references: (backlink.references ?? []).map((reference) => ({
38064
+ ...reference,
38065
+ html: typeof reference["html"] === "string" ? scrubWikiHtmlLinks(reference["html"], rootDirectory) : reference["html"]
38066
+ })),
38067
+ referenceHtmls: (backlink.referenceHtmls ?? []).map(
38068
+ (html) => scrubWikiHtmlLinks(html, rootDirectory)
38069
+ )
38070
+ };
38071
+ }
38072
+ function scrubWikiHtmlLinks(html, rootDirectory) {
38073
+ try {
38074
+ const $ = cheerio4.load(html);
38075
+ $("a[href], img[src]").each((_, element) => {
38076
+ for (const attribute of ["href", "src"]) {
38077
+ const value = $(element).attr(attribute);
38078
+ if (!value) {
38079
+ continue;
38080
+ }
38081
+ let decoded = value;
38082
+ try {
38083
+ decoded = decodeURIComponent(value);
38084
+ } catch {
38085
+ }
38086
+ const fileUrlMatch = decoded.match(/^file:\/\/\/+(.*)$/i);
38087
+ if (fileUrlMatch) {
38088
+ decoded = fileUrlMatch[1];
38089
+ if (!/^[A-Za-z]:/.test(decoded)) {
38090
+ decoded = "/" + decoded;
38091
+ }
38092
+ }
38093
+ const normalized = decoded.replace(/\//g, path22.sep);
38094
+ if (!isPathWithinRoot(rootDirectory, normalized)) {
38095
+ continue;
38096
+ }
38097
+ const relative11 = path22.relative(rootDirectory, normalized).split(path22.sep).join("/");
38098
+ $(element).attr(attribute, `file:///${relative11}`);
38099
+ }
38100
+ });
38101
+ return $.html();
38102
+ } catch {
38103
+ return html;
38104
+ }
38105
+ }
38106
+ async function collectThemeAssets(buildDirectory, notebook) {
38107
+ const readThemeDirectory = async (relativeDirectory) => {
38108
+ const absoluteDirectory = path22.join(
38109
+ buildDirectory,
38110
+ ...relativeDirectory.split("/")
38111
+ );
38112
+ const entries = await fs18.promises.readdir(absoluteDirectory).catch(() => []);
38113
+ const map = {};
38114
+ for (const entry of entries) {
38115
+ if (!entry.toLowerCase().endsWith(".css")) {
38116
+ continue;
38117
+ }
38118
+ map[entry] = await readStylesheetWithInlinedUrls(
38119
+ path22.join(absoluteDirectory, entry)
38120
+ );
38121
+ }
38122
+ return map;
38123
+ };
38124
+ return {
38125
+ preview: await readThemeDirectory("styles/preview_theme"),
38126
+ codeBlock: await readThemeDirectory("styles/prism_theme"),
38127
+ reveal: await readThemeDirectory("dependencies/reveal/css/theme"),
38128
+ codeBlockAuto: { ...MarkdownEngine.AutoPrismThemeMap },
38129
+ build: {
38130
+ preview: notebook.config.previewTheme,
38131
+ codeBlock: notebook.config.codeBlockTheme,
38132
+ reveal: notebook.config.revealjsTheme
38133
+ }
38134
+ };
38135
+ }
38136
+ var REMOTE_IMAGE_TIMEOUT_MS = 1e4;
38137
+ var REMOTE_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
38138
+ async function embedRemoteImages(html, cache) {
38139
+ const urls = /* @__PURE__ */ new Set();
38140
+ for (const match of html.matchAll(/<img[^>]*\ssrc="(https?:[^"]+)"/g)) {
38141
+ urls.add(match[1]);
38142
+ }
38143
+ if (urls.size === 0) {
38144
+ return html;
38145
+ }
38146
+ const replacements = /* @__PURE__ */ new Map();
38147
+ await Promise.all(
38148
+ Array.from(urls).map(async (url) => {
38149
+ let cached = cache.get(url);
38150
+ if (cached === void 0) {
38151
+ cached = await fetchRemoteImage(url);
38152
+ cache.set(url, cached);
38153
+ }
38154
+ if (cached) {
38155
+ replacements.set(url, cached);
38156
+ }
38157
+ })
38158
+ );
38159
+ if (replacements.size === 0) {
38160
+ return html;
38161
+ }
38162
+ return html.replace(
38163
+ /(<img[^>]*\ssrc=")(https?:[^"]+)(")/g,
38164
+ (match, prefix, url, suffix) => replacements.has(url) ? `${prefix}${replacements.get(url)}${suffix}` : match
38165
+ );
38166
+ }
38167
+ async function fetchRemoteImage(url) {
38168
+ try {
38169
+ const response = await fetch(url, {
38170
+ signal: AbortSignal.timeout(REMOTE_IMAGE_TIMEOUT_MS),
38171
+ redirect: "follow"
38172
+ });
38173
+ if (!response.ok) {
38174
+ return null;
38175
+ }
38176
+ const declaredLength = parseInt(
38177
+ response.headers.get("content-length") ?? "",
38178
+ 10
38179
+ );
38180
+ if (Number.isInteger(declaredLength) && declaredLength > REMOTE_IMAGE_MAX_BYTES) {
38181
+ return null;
38182
+ }
38183
+ const buffer = Buffer.from(await response.arrayBuffer());
38184
+ if (buffer.length === 0 || buffer.length > REMOTE_IMAGE_MAX_BYTES) {
38185
+ return null;
38186
+ }
38187
+ const mime = (response.headers.get("content-type") ?? "").split(";")[0];
38188
+ if (!mime.startsWith("image/")) {
38189
+ return null;
38190
+ }
38191
+ return `data:${mime};base64,${buffer.toString("base64")}`;
38192
+ } catch {
38193
+ return null;
38194
+ }
38195
+ }
37905
38196
  async function readStylesheetWithInlinedUrls(cssPath) {
37906
38197
  let css;
37907
38198
  try {
@@ -37935,9 +38226,12 @@ async function readStylesheetWithInlinedUrls(cssPath) {
37935
38226
  );
37936
38227
  }
37937
38228
  function buildShellHTML({
37938
- rootDirectories,
38229
+ rootNames,
37939
38230
  files,
37940
38231
  assets,
38232
+ themes,
38233
+ graph,
38234
+ backlinks,
37941
38235
  buildDirectory
37942
38236
  }) {
37943
38237
  const appScriptPath = path22.join(
@@ -37962,13 +38256,16 @@ function buildShellHTML({
37962
38256
  );
37963
38257
  }
37964
38258
  const payload = JSON.stringify({
37965
- rootDirectories,
38259
+ rootDirectories: rootNames,
37966
38260
  assets,
38261
+ themes,
38262
+ graph,
38263
+ backlinks,
37967
38264
  files
37968
38265
  }).replace(/</g, "\\u003c");
37969
38266
  const safeAppScript = appScript.replace(/<\/script/g, "<\\/script");
37970
38267
  const safeAppStyle = appStyle.replace(/<\/style/g, "<\\/style");
37971
- const title = `wiki \u2014 ${path22.basename(rootDirectories[0] ?? "")}`;
38268
+ const title = `wiki \u2014 ${rootNames[0] ?? ""}`;
37972
38269
  return `<!DOCTYPE html>
37973
38270
  <html>
37974
38271
  <head>
@@ -37998,6 +38295,89 @@ var utility = {
37998
38295
  uploadImage
37999
38296
  };
38000
38297
 
38298
+ // src/serve/graph-host-shim.ts
38299
+ function graphHostShimScript(options) {
38300
+ const isFetch = options.source === "fetch";
38301
+ const fileExpression = isFetch ? options.fileExpression ?? "''" : options.embeddedFileExpression ?? "''";
38302
+ const dataUrl = options.dataUrl ?? "/api/graph";
38303
+ const targetOrigin = isFetch ? "window.location.origin" : "'*'";
38304
+ const loadData = isFetch ? `fetch(${JSON.stringify(dataUrl)} + '?file=' + encodeURIComponent(FILE))
38305
+ .then(function (response) {
38306
+ if (!response.ok) { throw new Error('graph request failed'); }
38307
+ return response.json();
38308
+ })` : `Promise.resolve(globalThis.__CROSSNOTE_WIKI_GRAPH__ || null)`;
38309
+ return `<script>
38310
+ (function () {
38311
+ if (globalThis.acquireVsCodeApi) { return; }
38312
+ var api = null;
38313
+ var FILE = ${fileExpression};
38314
+ globalThis.acquireVsCodeApi = function () {
38315
+ if (api) { return api; }
38316
+ api = {
38317
+ postMessage: function (message) {
38318
+ if (!message || typeof message.command !== 'string') { return; }
38319
+ if (message.command === 'graphViewReady') {
38320
+ ${loadData}
38321
+ .then(function (payload) {
38322
+ if (!payload) { throw new Error('no graph data'); }
38323
+ globalThis.postMessage({
38324
+ command: 'graphData',
38325
+ data: payload.data,
38326
+ activeFilePath: payload.activeFilePath,
38327
+ }, '*');
38328
+ })
38329
+ .catch(function () {
38330
+ globalThis.postMessage({
38331
+ command: 'graphData',
38332
+ data: { hash: '', nodes: [], links: [] },
38333
+ activeFilePath: '',
38334
+ }, '*');
38335
+ });
38336
+ return;
38337
+ }
38338
+ if (message.command === 'openFile') {
38339
+ var rel = message.args && message.args[0];
38340
+ if (typeof rel === 'string') {
38341
+ globalThis.parent.postMessage(
38342
+ {
38343
+ command: '__serverAppOpenFile',
38344
+ args: [FILE, String(rel).replace(/\\\\/g, '/')],
38345
+ },
38346
+ ${targetOrigin}
38347
+ );
38348
+ }
38349
+ return;
38350
+ }
38351
+ if (message.command === 'saveSetting') {
38352
+ var setting = message.args && message.args[0];
38353
+ if (setting && typeof setting.key === 'string') {
38354
+ try {
38355
+ localStorage.setItem(
38356
+ 'crossnote.graphView.' + setting.key,
38357
+ JSON.stringify(setting.value === undefined ? null : setting.value)
38358
+ );
38359
+ } catch (error) { /* storage unavailable */ }
38360
+ }
38361
+ return;
38362
+ }
38363
+ },
38364
+ getState: function () {
38365
+ try {
38366
+ return JSON.parse(localStorage.getItem('crossnote.graphView.state') || 'null');
38367
+ } catch (error) { return null; }
38368
+ },
38369
+ setState: function (state) {
38370
+ try {
38371
+ localStorage.setItem('crossnote.graphView.state', JSON.stringify(state));
38372
+ } catch (error) { /* storage unavailable */ }
38373
+ },
38374
+ };
38375
+ return api;
38376
+ };
38377
+ })();
38378
+ </script>`;
38379
+ }
38380
+
38001
38381
  // src/serve/sse.ts
38002
38382
  var SSEHub = class {
38003
38383
  constructor() {
@@ -38281,6 +38661,10 @@ async function nonConflictingWikiPath(rootDirectory) {
38281
38661
  return path25.join(rootDirectory, `crossnote-wiki-${stamp}.html`);
38282
38662
  }
38283
38663
  var PREVIEW_HOST_SHIM = previewHostShimScript("window.location.origin");
38664
+ var GRAPH_HOST_SHIM = graphHostShimScript({
38665
+ source: "fetch",
38666
+ fileExpression: "new URLSearchParams(window.location.search).get('file') || ''"
38667
+ });
38284
38668
  function appShellHTML(serverInfo) {
38285
38669
  const serialized = JSON.stringify(serverInfo).replace(/</g, "\\u003c");
38286
38670
  return `<!DOCTYPE html>
@@ -38553,6 +38937,49 @@ async function startServeServer(options) {
38553
38937
  await renderFile(sourceUri, { triggeredBySave: true });
38554
38938
  return;
38555
38939
  }
38940
+ case "showBacklinks": {
38941
+ const info = args[0];
38942
+ const file = assertFileWithinRoots(String(info?.uri ?? ""));
38943
+ if (!file || !isMarkdownFile(file)) {
38944
+ return;
38945
+ }
38946
+ const fileNotebook = notebookForFile(file);
38947
+ if (!fileNotebook) {
38948
+ return;
38949
+ }
38950
+ try {
38951
+ if (info?.forceRefreshingNotes) {
38952
+ await fileNotebook.refreshNotesIncremental({
38953
+ dir: ".",
38954
+ includeSubdirectories: true
38955
+ });
38956
+ } else {
38957
+ await fileNotebook.refreshNotesIfNotLoaded({
38958
+ dir: ".",
38959
+ includeSubdirectories: true
38960
+ });
38961
+ }
38962
+ const backlinks = await fileNotebook.getNoteBacklinks(file);
38963
+ const sha = (0, import_crypto_js2.SHA256)(JSON.stringify(backlinks)).toString();
38964
+ const hasUpdate = sha !== info?.backlinksSha;
38965
+ sse.broadcast({
38966
+ type: "iframeMessage",
38967
+ file,
38968
+ iframeMessage: {
38969
+ command: "backlinks",
38970
+ sourceUri: file,
38971
+ backlinks: hasUpdate ? backlinks : null,
38972
+ hasUpdate
38973
+ }
38974
+ });
38975
+ } catch (error) {
38976
+ console.error(
38977
+ `crossnote serve: failed to compute backlinks for ${file}:`,
38978
+ error
38979
+ );
38980
+ }
38981
+ return;
38982
+ }
38556
38983
  case "exportStandaloneWiki": {
38557
38984
  try {
38558
38985
  const result = await buildWiki({
@@ -38677,6 +39104,63 @@ async function startServeServer(options) {
38677
39104
  }
38678
39105
  return;
38679
39106
  }
39107
+ if (request.method === "GET" && urlPath === "/graph-view") {
39108
+ const file = assertFileWithinRoots(
39109
+ requestUrl.searchParams.get("file") ?? "/"
39110
+ );
39111
+ if (!file || !isMarkdownFile(file)) {
39112
+ response.writeHead(400, { "content-type": "text/plain" });
39113
+ response.end("invalid file");
39114
+ return;
39115
+ }
39116
+ const graphNotebook = notebookForFile(file);
39117
+ if (!graphNotebook) {
39118
+ response.writeHead(404, { "content-type": "text/plain" });
39119
+ response.end("not found");
39120
+ return;
39121
+ }
39122
+ try {
39123
+ const engine = graphNotebook.getNoteMarkdownEngine(file);
39124
+ let html = engine.generateHTMLTemplateForGraphView({
39125
+ vscodePreviewPanel: dummyPanel
39126
+ });
39127
+ html = html.replace(/<script\b/, `${GRAPH_HOST_SHIM}<script`);
39128
+ response.writeHead(200, {
39129
+ "content-type": "text/html; charset=utf-8",
39130
+ ...BASE_SECURITY_HEADERS
39131
+ });
39132
+ response.end(html);
39133
+ } catch (error) {
39134
+ console.error("crossnote serve: failed to build graph view:", error);
39135
+ response.writeHead(500, { "content-type": "text/plain" });
39136
+ response.end("internal error");
39137
+ }
39138
+ return;
39139
+ }
39140
+ if (request.method === "GET" && urlPath === "/api/graph") {
39141
+ const file = assertFileWithinRoots(
39142
+ requestUrl.searchParams.get("file") ?? "/"
39143
+ );
39144
+ const graphNotebook = file ? notebookForFile(file) : null;
39145
+ if (!file || !graphNotebook) {
39146
+ sendJSON(response, 400, { error: "invalid file" });
39147
+ return;
39148
+ }
39149
+ try {
39150
+ await graphNotebook.refreshNotesIfNotLoaded({
39151
+ dir: ".",
39152
+ includeSubdirectories: true
39153
+ });
39154
+ const data = constructGraphView(graphNotebook);
39155
+ const rootIndex = rootIndexOf(file);
39156
+ const relativePath = rootIndex === -1 ? "" : path25.relative(rootDirectories[rootIndex], file).split(path25.sep).join("/");
39157
+ sendJSON(response, 200, { data, activeFilePath: relativePath });
39158
+ } catch (error) {
39159
+ console.error("crossnote serve: failed to build graph data:", error);
39160
+ sendJSON(response, 500, { error: "failed to build graph data" });
39161
+ }
39162
+ return;
39163
+ }
38680
39164
  if (request.method === "GET" && urlPath === "/api/events") {
38681
39165
  sse.addClient(response);
38682
39166
  return;