vde-open 0.1.14 → 0.1.15

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/README.md CHANGED
@@ -28,7 +28,7 @@ To install from a clone of this repository (Node.js 24.22.1 is pinned in `mise.t
28
28
  pnpm install --frozen-lockfile
29
29
  pnpm build
30
30
  pnpm test:pack # builds artifacts/vde-open-<version>.tgz and verifies an install in a separate directory
31
- bun add -g "$PWD/artifacts/vde-open-0.1.14.tgz" # bun add -g needs an absolute path
31
+ bun add -g "$PWD/artifacts/vde-open-0.1.15.tgz" # bun add -g needs an absolute path
32
32
  ```
33
33
 
34
34
  ## `vde-open` and `vo`
@@ -77,9 +77,10 @@ ln -s ~/.bun/install/global/node_modules/vde-open/skills/vde-open ~/.codex/skill
77
77
 
78
78
  ## HTML display limits
79
79
 
80
- - By default (static), scripts do not run. Scripts, event attributes, iframe/object/embed, base, automatic navigation (meta refresh), form targets, and external images, CSS, and fonts are removed. Links cannot be clicked inside the view; open them from "Links in this document".
80
+ - By default (Static), the view removes the document's scripts, event attributes, iframe/object/embed, base, automatic navigation (meta refresh), form targets, and external images, CSS, and fonts.
81
+ - In Static and Interactive, select a local document link in the preview to switch to an open document or confirm opening a new one. Heading links jump within the preview. Open external links from "Links in this document".
81
82
  - Only files that the document references, inside the assets root (by default the document's directory), can be loaded. Files whose names start with "." such as `.env` and `.git` are never loaded. Set the scope with `--assets-root` and individual files with `--asset`.
82
- - Scripts run only in HTML opened with `--html-mode interactive`. Use it only with HTML that you or the agent prepared and trust: scripts can load only registered files and cannot reach the management UI, the management API, or other files, but this does not block every outbound request (navigation inside the view, for example). After the daemon restarts, the HTML is static until you allow scripts again in the management UI.
83
+ - Document scripts run only in Interactive HTML. You can enable it with `--html-mode interactive` or allow scripts in the management UI. Use it only with HTML that you or the agent prepared and trust: scripts can load only registered files and cannot reach the management UI, the management API, or other files, but this does not block every outbound request (navigation inside the view, for example). After the daemon restarts, the HTML is static until you allow scripts again in the management UI.
83
84
  - "Differences" in the management UI lists what the view changed, why, and what to do.
84
85
 
85
86
  ## Markdown display
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { C as decodeStateFile, D as daemonEntryPath, E as resolveStateRoot, O as referencedBlobs, S as renameWithRetry, T as resolveRuntimeLocation, a as DAEMON_LOCK_NAME, b as proofMatches, c as readIpcKey, d as inspectOwner, f as readCurrentLock, g as encodeFrame, h as FrameDecoder, i as requirePrivateDirectoryIfExists, k as version, l as readPointer, m as systemProcessProbe, n as ensurePrivateDirectory, o as POINTER_FILE, p as releaseLock, r as inspectPrivateDirectory, s as START_LOCK_NAME, t as startDaemon, u as acquireLock, v as computeProof, w as currentPathEnvironment, x as removeWithRetry, y as createNonce } from "./main-ChphixE8.js";
3
- import { A as successEnvelope, C as VdeError, D as ExitCode, E as isVdeError, O as envelopeSchema, T as isErrorCode, Y as LIMITS, k as errorEnvelope, w as exitCodeForError } from "./search-index-B-hHn9RV.js";
2
+ import { C as decodeStateFile, D as daemonEntryPath, E as resolveStateRoot, O as referencedBlobs, S as renameWithRetry, T as resolveRuntimeLocation, a as DAEMON_LOCK_NAME, b as proofMatches, c as readIpcKey, d as inspectOwner, f as readCurrentLock, g as encodeFrame, h as FrameDecoder, i as requirePrivateDirectoryIfExists, k as version, l as readPointer, m as systemProcessProbe, n as ensurePrivateDirectory, o as POINTER_FILE, p as releaseLock, r as inspectPrivateDirectory, s as START_LOCK_NAME, t as startDaemon, u as acquireLock, v as computeProof, w as currentPathEnvironment, x as removeWithRetry, y as createNonce } from "./main-BaV6ocLQ.js";
3
+ import { A as successEnvelope, C as VdeError, D as ExitCode, E as isVdeError, O as envelopeSchema, T as isErrorCode, X as LIMITS, k as errorEnvelope, w as exitCodeForError } from "./search-index-ed_S_eI7.js";
4
4
  import fs, { fstatSync } from "node:fs";
5
5
  import { lstat, readFile, readdir, stat as stat$1, writeFile } from "node:fs/promises";
6
6
  import path, { dirname, join, resolve } from "node:path";
package/dist/daemon.js CHANGED
@@ -1,5 +1,5 @@
1
- import { k as version, t as startDaemon, w as currentPathEnvironment } from "./main-ChphixE8.js";
2
- import { E as isVdeError } from "./search-index-B-hHn9RV.js";
1
+ import { k as version, t as startDaemon, w as currentPathEnvironment } from "./main-BaV6ocLQ.js";
2
+ import { E as isVdeError } from "./search-index-ed_S_eI7.js";
3
3
  //#region src/daemon.ts
4
4
  function notifyParent(message) {
5
5
  if (!process.send) return;
@@ -8752,6 +8752,30 @@ function analyzeDocument(source, format) {
8752
8752
  return format === "markdown" ? analyzeMarkdown(source) : analyzeHtml(source);
8753
8753
  }
8754
8754
  //#endregion
8755
+ //#region ../../packages/document/src/html-link-relay.ts
8756
+ const HTML_LINK_ATTRIBUTE = "data-vde-document-link";
8757
+ const HTML_LINK_RELAY = `(() => {
8758
+ if (parent === window) return;
8759
+ const channel = new MessageChannel();
8760
+ const send = channel.port1.postMessage.bind(channel.port1);
8761
+ const closest = Function.call.bind(Element.prototype.closest);
8762
+ const attribute = Function.call.bind(Element.prototype.getAttribute);
8763
+ const targetOf = Function.call.bind(Object.getOwnPropertyDescriptor(Event.prototype, 'target').get);
8764
+ const preventDefault = Function.call.bind(Event.prototype.preventDefault);
8765
+ const ElementType = Element;
8766
+ const Anchor = HTMLAnchorElement;
8767
+ const Area = HTMLAreaElement;
8768
+ window.addEventListener('click', (event) => {
8769
+ const target = targetOf(event);
8770
+ if (!(target instanceof ElementType)) return;
8771
+ const link = closest(target, 'a[href="#"][${HTML_LINK_ATTRIBUTE}], area[href="#"][${HTML_LINK_ATTRIBUTE}]');
8772
+ if (!(link instanceof Anchor || link instanceof Area)) return;
8773
+ preventDefault(event);
8774
+ if (event.isTrusted) send(attribute(link, '${HTML_LINK_ATTRIBUTE}'));
8775
+ }, true);
8776
+ parent.postMessage('vde-open:document-links', '*', [channel.port2]);
8777
+ })();`;
8778
+ //#endregion
8755
8779
  //#region ../../packages/document/src/rendering-rules.ts
8756
8780
  function renderedLinkOf(href) {
8757
8781
  if (href === void 0 || href === "") return "text";
@@ -14527,6 +14551,7 @@ function rewriteElement(element, policy) {
14527
14551
  for (const attribute of element.attrs) {
14528
14552
  const name = attribute.name;
14529
14553
  if (!ATTRIBUTE_NAME.test(name)) continue;
14554
+ if (policy.relayDocumentLinks && name === "data-vde-document-link") continue;
14530
14555
  if (name.startsWith("on")) {
14531
14556
  if (policy.interactive) kept.push(attribute);
14532
14557
  else handlers += 1;
@@ -14547,8 +14572,19 @@ function rewriteElement(element, policy) {
14547
14572
  if (name === "href") {
14548
14573
  if (tag === "link") kept.push(attribute);
14549
14574
  else if (isAnchor) {
14550
- if (classifyLink(attribute.value).kind === "fragment") kept.push(attribute);
14551
- else policy.link(attribute.value, textOf(element));
14575
+ const { kind } = classifyLink(attribute.value);
14576
+ if (kind === "fragment") kept.push(attribute);
14577
+ else {
14578
+ const linkId = policy.link(attribute.value, textOf(element), kind);
14579
+ if (linkId === null) policy.note("link-disabled", null);
14580
+ else kept.push({
14581
+ ...attribute,
14582
+ value: "#"
14583
+ }, {
14584
+ name: HTML_LINK_ATTRIBUTE,
14585
+ value: linkId
14586
+ });
14587
+ }
14552
14588
  }
14553
14589
  continue;
14554
14590
  }
@@ -14630,7 +14666,7 @@ function rewriteTree(root, policy) {
14630
14666
  if (child.tagName === "style") {
14631
14667
  child.childNodes = [{
14632
14668
  nodeName: "#text",
14633
- value: rewriteCss(textOfStyle(child), "stylesheet", policy),
14669
+ value: rewriteCss(rawTextOf(child), "stylesheet", policy),
14634
14670
  parentNode: child
14635
14671
  }];
14636
14672
  kept.push(child);
@@ -14644,17 +14680,20 @@ function rewriteTree(root, policy) {
14644
14680
  for (const child of kept) child.parentNode = parent;
14645
14681
  }
14646
14682
  }
14647
- function textOfStyle(element) {
14683
+ function rawTextOf(element) {
14648
14684
  let text = "";
14649
14685
  for (const child of element.childNodes) if (child.nodeName === "#text" && "value" in child) text += child.value;
14650
14686
  return text;
14651
14687
  }
14652
- function assertOutput(html, interactive) {
14653
- const stack = [parse$50(html, { scriptingEnabled: false })];
14688
+ function assertOutput(html, interactive, withLinkRelay) {
14689
+ const document = parse$50(html, { scriptingEnabled: false });
14690
+ const relay = withLinkRelay ? headOf(document).childNodes[0] : void 0;
14691
+ if (withLinkRelay && (!relay || !isElement(relay) || relay.tagName !== "script" || relay.attrs.length !== 0 || rawTextOf(relay) !== HTML_LINK_RELAY)) throw new Error("unsafe output: document link relay");
14692
+ const stack = [document];
14654
14693
  while (stack.length > 0) {
14655
14694
  const node = stack.pop();
14656
14695
  if (isElement(node)) {
14657
- if (node.namespaceURI !== HTML_NAMESPACE || REMOVED_ELEMENTS[node.tagName] !== void 0 && !(interactive && node.tagName === "script") || interactive && node.tagName === "noscript" || node.attrs.some((attribute) => attribute.name.startsWith("on") && !interactive || REMOVED_ATTRIBUTES.has(attribute.name))) throw new Error(`unsafe output: ${node.tagName}`);
14696
+ if (node.namespaceURI !== HTML_NAMESPACE || node !== relay && REMOVED_ELEMENTS[node.tagName] !== void 0 && !(interactive && node.tagName === "script") || interactive && node.tagName === "noscript" || node.attrs.some((attribute) => attribute.name.startsWith("on") && !interactive || REMOVED_ATTRIBUTES.has(attribute.name))) throw new Error(`unsafe output: ${node.tagName}`);
14658
14697
  if (node.tagName === "template" && "content" in node) stack.push(node.content);
14659
14698
  }
14660
14699
  if (isParent(node)) for (const child of node.childNodes) stack.push(child);
@@ -14716,29 +14755,32 @@ function resolveAssetUrl(url, context, baseDir, assets, log, options = {}) {
14716
14755
  function transformStaticHtml(input, log = new DiagnosticLog()) {
14717
14756
  const baseDir = dirnameOfLogicalPath(input.documentLogicalPath);
14718
14757
  const links = [];
14719
- const linkIds = /* @__PURE__ */ new Set();
14758
+ const linksByHref = /* @__PURE__ */ new Map();
14720
14759
  const interactive = input.interactive === true;
14760
+ const relayDocumentLinks = input.relayDocumentLinks === true;
14721
14761
  const policy = {
14722
14762
  interactive,
14763
+ relayDocumentLinks,
14723
14764
  note: (code, target) => log.note(code, target),
14724
14765
  asset: (url, context) => resolveAssetUrl(url, context, baseDir, input.assets, log, {
14725
14766
  scripts: interactive,
14726
14767
  ...input.assetUrls === void 0 ? {} : { assetUrls: input.assetUrls }
14727
14768
  }),
14728
- link(href, text) {
14729
- log.note("link-disabled", null);
14730
- const target = classifyLink(href);
14731
- if (target.kind === "fragment" || links.length >= MAX_LINKS) return;
14769
+ link(href, text, kind) {
14732
14770
  const shown = href.trim().slice(0, 2e3);
14733
- if (linkIds.has(shown)) return;
14734
- linkIds.add(shown);
14735
- const linkId = `lnk_${String(links.length + 1).padStart(4, "0")}`;
14736
- links.push({
14737
- linkId,
14738
- href: shown,
14739
- text,
14740
- kind: target.kind
14741
- });
14771
+ let link = linksByHref.get(shown);
14772
+ if (link === void 0) {
14773
+ if (links.length >= MAX_LINKS) return null;
14774
+ link = {
14775
+ linkId: `lnk_${String(links.length + 1).padStart(4, "0")}`,
14776
+ href: shown,
14777
+ text,
14778
+ kind
14779
+ };
14780
+ linksByHref.set(shown, link);
14781
+ links.push(link);
14782
+ }
14783
+ return relayDocumentLinks && kind === "document" && link.kind === "document" ? link.linkId : null;
14742
14784
  }
14743
14785
  };
14744
14786
  const document = parse$50(input.source, { scriptingEnabled: false });
@@ -14746,8 +14788,10 @@ function transformStaticHtml(input, log = new DiagnosticLog()) {
14746
14788
  for (const heading of headings) setId(heading.element, heading.anchor);
14747
14789
  rewriteTree(document, policy);
14748
14790
  if (interactive && input.sdkScript !== void 0) insertFirstScript(document, input.sdkScript);
14791
+ const withLinkRelay = relayDocumentLinks && links.some((link) => link.kind === "document");
14792
+ if (withLinkRelay) insertFirstScript(document, HTML_LINK_RELAY);
14749
14793
  const html = serialize(document);
14750
- assertOutput(html, interactive);
14794
+ assertOutput(html, interactive, withLinkRelay);
14751
14795
  return {
14752
14796
  html,
14753
14797
  links,
@@ -14788,10 +14832,14 @@ function reachable(document, headings) {
14788
14832
  anchor
14789
14833
  }));
14790
14834
  }
14791
- function insertFirstScript(document, source) {
14792
- if (source.toLowerCase().includes("<\/script")) throw new Error("script text must not close itself");
14835
+ function headOf(document) {
14793
14836
  const head = document.childNodes.find((node) => isElement(node) && node.tagName === "html")?.childNodes.find((node) => isElement(node) && node.tagName === "head");
14794
14837
  if (!head) throw new Error("document has no head");
14838
+ return head;
14839
+ }
14840
+ function insertFirstScript(document, source) {
14841
+ if (source.toLowerCase().includes("<\/script")) throw new Error("script text must not close itself");
14842
+ const head = headOf(document);
14795
14843
  const script = {
14796
14844
  nodeName: "script",
14797
14845
  tagName: "script",
@@ -14819,10 +14867,10 @@ function scanHtmlReferences(source) {
14819
14867
  });
14820
14868
  return url;
14821
14869
  },
14822
- link: () => void 0,
14870
+ link: () => null,
14823
14871
  note: () => void 0
14824
14872
  });
14825
14873
  return references;
14826
14874
  }
14827
14875
  //#endregion
14828
- export { escapeAttr as A, roleAllowed as C, defaultTreeAdapter as D, serialize as E, footnoteReferenceId as M, __commonJSMin as N, NS as O, __toESM as P, isValidLogicalPath as S, parseFragment as T, classifyLink as _, scanCssReferences as a, encodeLogicalPath as b, renderedLinkOf as c, analyzeDocument as d, assertWithinLimits as f, assetTypeOf as g, parseMarkdownDocument as h, transformStaticHtml as i, escapeHtml as j, parseMarkdown as k, MARKDOWN_PARSE_OPTIONS as l, markdownUrlTransform as m, resolveAssetUrl as n, transformCss as o, inlineText as p, scanHtmlReferences as r, localImagePath as s, DiagnosticLog as t, ParseLimitError as u, classifyReference as v, parse$50 as w, hasHiddenSegment as x, dirnameOfLogicalPath as y };
14876
+ export { parseMarkdown as A, isValidLogicalPath as C, serialize as D, parseFragment as E, __toESM as F, escapeHtml as M, footnoteReferenceId as N, defaultTreeAdapter as O, __commonJSMin as P, hasHiddenSegment as S, parse$50 as T, assetTypeOf as _, scanCssReferences as a, dirnameOfLogicalPath as b, renderedLinkOf as c, ParseLimitError as d, analyzeDocument as f, parseMarkdownDocument as g, markdownUrlTransform as h, transformStaticHtml as i, escapeAttr as j, NS as k, HTML_LINK_RELAY as l, inlineText as m, resolveAssetUrl as n, transformCss as o, assertWithinLimits as p, scanHtmlReferences as r, localImagePath as s, DiagnosticLog as t, MARKDOWN_PARSE_OPTIONS as u, classifyLink as v, roleAllowed as w, encodeLogicalPath as x, classifyReference as y };
@@ -1,6 +1,6 @@
1
- import { C as roleAllowed, N as __commonJSMin, P as __toESM, S as isValidLogicalPath, _ as classifyLink, b as encodeLogicalPath, d as analyzeDocument, g as assetTypeOf, u as ParseLimitError, v as classifyReference, x as hasHiddenSegment, y as dirnameOfLogicalPath } from "./html-static-C_wwQAJx.js";
2
- import { $ as literal, A as successEnvelope, B as readParamsSchema, C as VdeError, D as ExitCode, E as isVdeError, F as htmlModeChangeParamsSchema, G as sha256Schema, H as reorderParamsSchema, I as htmlModeSchema, J as watchRuleSchema, K as sourceKindSchema, L as linkOpenParamsSchema, M as closeParamsSchema, N as documentFormatSchema, P as documentIdSchema, Q as boolean, R as listParamsSchema, S as validateAnswers, U as revisionSchema, V as renderGrantParamsSchema, W as searchParamsSchema, X as _enum, Y as LIMITS, Z as array, _ as feedbackWaitParamsSchema, a as uniqueTokens, at as canonicalJson, b as submissionSchema, c as feedbackAckParamsSchema, d as feedbackDraftParamsSchema, et as number, f as feedbackForgetParamsSchema, g as feedbackSubmitParamsSchema, h as feedbackStatusSchema, i as codePointLength, it as ZodError, j as assetRecordSchema, k as errorEnvelope, l as feedbackCancelParamsSchema, m as feedbackListParamsSchema, n as batchesOf, nt as strictObject, o as answersSchema, p as feedbackIdParamsSchema, q as sourceStateSchema, r as partsOf, rt as string, s as cancellationSchema, tt as record, u as feedbackCreateParamsSchema, v as questionnaireSchema, w as exitCodeForError, x as utf8Length, y as requestIdSchema, z as openParamsSchema } from "./search-index-B-hHn9RV.js";
3
- import { n as scanReferences, r as extractTitle } from "./render-BJa4uW0H.js";
1
+ import { C as isValidLogicalPath, F as __toESM, P as __commonJSMin, S as hasHiddenSegment, _ as assetTypeOf, b as dirnameOfLogicalPath, d as ParseLimitError, f as analyzeDocument, l as HTML_LINK_RELAY, v as classifyLink, w as roleAllowed, x as encodeLogicalPath, y as classifyReference } from "./html-static-Ct_9qmNR.js";
2
+ import { $ as boolean, A as successEnvelope, B as openParamsSchema, C as VdeError, D as ExitCode, E as isVdeError, F as htmlModeChangeParamsSchema, G as searchParamsSchema, H as renderGrantParamsSchema, I as htmlModeSchema, J as sourceStateSchema, K as sha256Schema, L as lastOpenedDocument, M as closeParamsSchema, N as documentFormatSchema, P as documentIdSchema, Q as array, R as linkOpenParamsSchema, S as validateAnswers, U as reorderParamsSchema, V as readParamsSchema, W as revisionSchema, X as LIMITS, Y as watchRuleSchema, Z as _enum, _ as feedbackWaitParamsSchema, a as uniqueTokens, at as ZodError, b as submissionSchema, c as feedbackAckParamsSchema, d as feedbackDraftParamsSchema, et as literal, f as feedbackForgetParamsSchema, g as feedbackSubmitParamsSchema, h as feedbackStatusSchema, i as codePointLength, it as string, j as assetRecordSchema, k as errorEnvelope, l as feedbackCancelParamsSchema, m as feedbackListParamsSchema, n as batchesOf, nt as record, o as answersSchema, ot as canonicalJson, p as feedbackIdParamsSchema, q as sourceKindSchema, r as partsOf, rt as strictObject, s as cancellationSchema, tt as number, u as feedbackCreateParamsSchema, v as questionnaireSchema, w as exitCodeForError, x as utf8Length, y as requestIdSchema, z as listParamsSchema } from "./search-index-ed_S_eI7.js";
3
+ import { n as scanReferences, r as extractTitle } from "./render-CY_Mrhyl.js";
4
4
  import { n as measureHeap, t as collectGarbage } from "./heap-C3qHm7SE.js";
5
5
  import { accessSync, constants, existsSync, stat, statSync, unwatchFile, watch, watchFile } from "node:fs";
6
6
  import { appendFile, chmod, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat as stat$1, writeFile } from "node:fs/promises";
@@ -154,7 +154,7 @@ function parseStrictJson(text) {
154
154
  }
155
155
  //#endregion
156
156
  //#region package.json
157
- var version = "0.1.14";
157
+ var version = "0.1.15";
158
158
  //#endregion
159
159
  //#region src/documents/cursor.ts
160
160
  function invalidCursor(reason) {
@@ -4119,6 +4119,9 @@ function pruneRevisions(revisions, now, pinned) {
4119
4119
  return index >= revisions.length - LIMITS.retainedRevisions || pinned.has(entry.revision) || now - Date.parse(entry.createdAt) < LIMITS.revisionGraceMs;
4120
4120
  });
4121
4121
  }
4122
+ function lastOpenedRecord(state) {
4123
+ return lastOpenedDocument(state.openOrder.flatMap((id) => state.documents[id] ?? []));
4124
+ }
4122
4125
  function openSourceBytes(state) {
4123
4126
  let total = 0;
4124
4127
  for (const documentId of state.openOrder) {
@@ -4729,6 +4732,11 @@ var DocumentService = class {
4729
4732
  assets,
4730
4733
  assetScan: item.assetScanFailed ? "failed" : "complete"
4731
4734
  };
4735
+ let openedAt = timestamp;
4736
+ if (!existing?.isOpen) {
4737
+ const latest = lastOpenedRecord(state);
4738
+ if (latest && latest.openedAt >= timestamp) openedAt = new Date(Date.parse(latest.openedAt) + 1).toISOString();
4739
+ }
4732
4740
  if (!existing) {
4733
4741
  const documentId = `doc_${randomUUID()}`;
4734
4742
  const htmlMode = options.htmlMode ?? "static";
@@ -4743,7 +4751,7 @@ var DocumentService = class {
4743
4751
  displayPath: item.displayPath,
4744
4752
  pathSegments: item.pathSegments,
4745
4753
  isOpen: true,
4746
- openedAt: timestamp,
4754
+ openedAt,
4747
4755
  updatedAt: timestamp,
4748
4756
  sourceState: "ready",
4749
4757
  currentRevision: revision,
@@ -4765,7 +4773,7 @@ var DocumentService = class {
4765
4773
  let revisionChanged = false;
4766
4774
  if (!existing.isOpen) {
4767
4775
  existing.isOpen = true;
4768
- existing.openedAt = timestamp;
4776
+ existing.openedAt = openedAt;
4769
4777
  state.openOrder.push(existing.documentId);
4770
4778
  changed = true;
4771
4779
  openSetChanged = true;
@@ -5147,7 +5155,7 @@ var DocumentService = class {
5147
5155
  }
5148
5156
  if (closed.length > 0) {
5149
5157
  state.openOrder = state.openOrder.filter((documentId) => !closed.includes(documentId));
5150
- if (state.activeDocumentId !== null && closed.includes(state.activeDocumentId)) state.activeDocumentId = state.openOrder[0] ?? null;
5158
+ if (state.activeDocumentId !== null && closed.includes(state.activeDocumentId)) state.activeDocumentId = lastOpenedRecord(state)?.documentId ?? null;
5151
5159
  state.catalogVersion += 1;
5152
5160
  changed = true;
5153
5161
  }
@@ -6931,7 +6939,7 @@ function createRenderService(options) {
6931
6939
  const { store, documents, parse } = options;
6932
6940
  const grants = /* @__PURE__ */ new Map();
6933
6941
  const snapshots = /* @__PURE__ */ new Map();
6934
- const snapshotOf = async (documentId, revision, mode = "static", withSdk = false) => {
6942
+ const snapshotOf = async (documentId, revision, mode, withSdk = false) => {
6935
6943
  const { record, entry } = documents.describeRevision(documentId, revision);
6936
6944
  const cacheKey = `${entry.revision}\n${entry.documentLogicalPath}\n${mode}\n${String(withSdk)}`;
6937
6945
  const cached = snapshots.get(cacheKey);
@@ -7207,7 +7215,8 @@ function createRenderService(options) {
7207
7215
  mime: file.mime,
7208
7216
  role: file.role,
7209
7217
  grant: key,
7210
- mode: grant.mode
7218
+ mode: grant.mode,
7219
+ hasDocumentLinks: file.role === "document" && grant.snapshot.links.some((link) => link.kind === "document")
7211
7220
  };
7212
7221
  },
7213
7222
  missingOf(key) {
@@ -7218,8 +7227,8 @@ function createRenderService(options) {
7218
7227
  pruneClosed() {
7219
7228
  for (const [key, grant] of grants) if (!documents.state.documents[grant.documentId]?.isOpen) grants.delete(key);
7220
7229
  },
7221
- async linkOf(documentId, revision, linkId) {
7222
- const { snapshot } = await snapshotOf(documentId, revision);
7230
+ async linkOf({ documentId, revision, mode, linkId }) {
7231
+ const { snapshot } = await snapshotOf(documentId, revision, mode);
7223
7232
  const link = snapshot.links.find((candidate) => candidate.linkId === linkId);
7224
7233
  if (!link) throw new VdeError("E_LINK_NOT_FOUND", "The link was not found.", {
7225
7234
  documentId,
@@ -11417,7 +11426,7 @@ async function startManagementServer(deps, options = {}) {
11417
11426
  documentId: c.req.param("id"),
11418
11427
  linkId: c.req.param("linkId")
11419
11428
  });
11420
- const link = await deps.render.linkOf(params.documentId, params.revision, params.linkId);
11429
+ const link = await deps.render.linkOf(params);
11421
11430
  return ok(c, "documents.link-open", await deps.documents.openLinked({
11422
11431
  documentId: params.documentId,
11423
11432
  revision: params.revision,
@@ -11540,11 +11549,12 @@ async function startManagementServer(deps, options = {}) {
11540
11549
  const CLOSE_GRACE_MS = 1e3;
11541
11550
  const PREVIEW_PATH = /^\/r\/([A-Za-z0-9_-]{43})\/files\/(.+)$/;
11542
11551
  const ENCODED_SEPARATOR_OR_NUL = /%(2f|5c|00)/i;
11543
- function documentCsp(mode, grantBase, ancestors) {
11552
+ const LINK_RELAY_HASH = `'sha256-${createHash("sha256").update(HTML_LINK_RELAY).digest("base64")}'`;
11553
+ function documentCsp(mode, grantBase, ancestors, hasDocumentLinks) {
11544
11554
  const interactive = mode === "interactive";
11545
11555
  return [
11546
11556
  "default-src 'none'",
11547
- interactive ? `script-src 'unsafe-inline' ${grantBase}` : "script-src 'none'",
11557
+ `script-src ${interactive ? `'unsafe-inline' ${grantBase}` : hasDocumentLinks ? LINK_RELAY_HASH : "'none'"}`,
11548
11558
  `style-src 'unsafe-inline' ${grantBase}`,
11549
11559
  `img-src ${grantBase} data:`,
11550
11560
  `font-src ${grantBase}`,
@@ -11555,7 +11565,7 @@ function documentCsp(mode, grantBase, ancestors) {
11555
11565
  "base-uri 'none'",
11556
11566
  "form-action 'none'",
11557
11567
  `frame-ancestors ${ancestors.length > 0 ? ancestors.join(" ") : "'none'"}`,
11558
- interactive ? "sandbox allow-scripts" : "sandbox"
11568
+ interactive || hasDocumentLinks ? "sandbox allow-scripts" : "sandbox"
11559
11569
  ].join("; ");
11560
11570
  }
11561
11571
  const ASSET_CSP = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
@@ -11566,7 +11576,7 @@ function headersFor(file, origin, ancestors) {
11566
11576
  "X-Content-Type-Options": "nosniff",
11567
11577
  "Referrer-Policy": "no-referrer",
11568
11578
  "Cache-Control": "no-store",
11569
- "Content-Security-Policy": file.role === "document" ? documentCsp(file.mode, `${origin}/r/${file.grant}/`, ancestors) : ASSET_CSP
11579
+ "Content-Security-Policy": file.role === "document" ? documentCsp(file.mode, `${origin}/r/${file.grant}/`, ancestors, file.hasDocumentLinks) : ASSET_CSP
11570
11580
  };
11571
11581
  if (file.role === "font" || file.role === "style" || file.role === "script" || file.role === "data") headers["Access-Control-Allow-Origin"] = "null";
11572
11582
  return headers;
@@ -1,4 +1,4 @@
1
- import { A as escapeAttr, D as defaultTreeAdapter, E as serialize, M as footnoteReferenceId, O as NS, T as parseFragment, c as renderedLinkOf, h as parseMarkdownDocument, i as transformStaticHtml, j as escapeHtml$2, k as parseMarkdown, l as MARKDOWN_PARSE_OPTIONS, n as resolveAssetUrl, o as transformCss, s as localImagePath, t as DiagnosticLog, w as parse, y as dirnameOfLogicalPath } from "./html-static-C_wwQAJx.js";
1
+ import { A as parseMarkdown, D as serialize, E as parseFragment, M as escapeHtml$2, N as footnoteReferenceId, O as defaultTreeAdapter, T as parse, b as dirnameOfLogicalPath, c as renderedLinkOf, g as parseMarkdownDocument, i as transformStaticHtml, j as escapeAttr, k as NS, n as resolveAssetUrl, o as transformCss, s as localImagePath, t as DiagnosticLog, u as MARKDOWN_PARSE_OPTIONS } from "./html-static-Ct_9qmNR.js";
2
2
  //#region ../../node_modules/.pnpm/@tanstack+markdown@1.0.0_react@19.3.0/node_modules/@tanstack/markdown/dist/html.js
3
3
  function renderHtml(input, options = {}) {
4
4
  return (typeof input === "string" ? parseMarkdown(input, options) : input).children.map((node) => renderBlock(node, options)).join("\n");
@@ -1,4 +1,4 @@
1
- import { _ as classifyLink, a as scanCssReferences, f as assertWithinLimits, i as transformStaticHtml, k as parseMarkdown, l as MARKDOWN_PARSE_OPTIONS, m as markdownUrlTransform, n as resolveAssetUrl, o as transformCss, p as inlineText$1, r as scanHtmlReferences, t as DiagnosticLog, w as parse, y as dirnameOfLogicalPath } from "./html-static-C_wwQAJx.js";
1
+ import { A as parseMarkdown, T as parse, a as scanCssReferences, b as dirnameOfLogicalPath, h as markdownUrlTransform, i as transformStaticHtml, m as inlineText$1, n as resolveAssetUrl, o as transformCss, p as assertWithinLimits, r as scanHtmlReferences, t as DiagnosticLog, u as MARKDOWN_PARSE_OPTIONS, v as classifyLink } from "./html-static-Ct_9qmNR.js";
2
2
  //#region ../../packages/document/src/title.ts
3
3
  const TITLE_SCAN_CHARS = 65536;
4
4
  const MAX_TITLE_LENGTH = 160;
@@ -161,6 +161,7 @@ function renderDocument(input) {
161
161
  }
162
162
  const result = transformStaticHtml({
163
163
  ...staticInput,
164
+ relayDocumentLinks: true,
164
165
  interactive: input.mode === "interactive",
165
166
  ...input.mode === "interactive" && input.sdkScript !== null ? { sdkScript: input.sdkScript } : {}
166
167
  }, log);
@@ -5724,6 +5724,11 @@ const documentSummarySchema = strictObject({
5724
5724
  htmlMode: htmlModeSchema.nullable(),
5725
5725
  interactiveAllowed: boolean()
5726
5726
  });
5727
+ function lastOpenedDocument(documents) {
5728
+ let latest;
5729
+ for (const document of documents) if (latest === void 0 || document.openedAt > latest.openedAt || document.openedAt === latest.openedAt && document.documentId > latest.documentId) latest = document;
5730
+ return latest;
5731
+ }
5727
5732
  const sourceRangeSchema = strictObject({
5728
5733
  startByte: number().int().nonnegative(),
5729
5734
  endByteExclusive: number().int().nonnegative(),
@@ -5931,6 +5936,7 @@ const htmlModeChangeParamsSchema = strictObject({
5931
5936
  const linkOpenParamsSchema = strictObject({
5932
5937
  documentId: documentIdSchema,
5933
5938
  revision: revisionSchema,
5939
+ mode: htmlModeSchema,
5934
5940
  linkId: string().regex(/^lnk_\d{4,}$/),
5935
5941
  confirmation: string().min(1).max(64).optional()
5936
5942
  });
@@ -8867,4 +8873,4 @@ var SearchIndex = class {
8867
8873
  }
8868
8874
  };
8869
8875
  //#endregion
8870
- export { literal as $, successEnvelope as A, readParamsSchema as B, VdeError as C, ExitCode as D, isVdeError as E, htmlModeChangeParamsSchema as F, sha256Schema as G, reorderParamsSchema as H, htmlModeSchema as I, watchRuleSchema as J, sourceKindSchema as K, linkOpenParamsSchema as L, closeParamsSchema as M, documentFormatSchema as N, envelopeSchema as O, documentIdSchema as P, boolean as Q, listParamsSchema as R, validateAnswers as S, isErrorCode as T, revisionSchema as U, renderGrantParamsSchema as V, searchParamsSchema as W, _enum as X, LIMITS as Y, array as Z, feedbackWaitParamsSchema as _, uniqueTokens as a, canonicalJson as at, submissionSchema as b, feedbackAckParamsSchema as c, feedbackDraftParamsSchema as d, number as et, feedbackForgetParamsSchema as f, feedbackSubmitParamsSchema as g, feedbackStatusSchema as h, codePointLength as i, ZodError as it, assetRecordSchema as j, errorEnvelope as k, feedbackCancelParamsSchema as l, feedbackListParamsSchema as m, batchesOf as n, strictObject as nt, answersSchema as o, feedbackIdParamsSchema as p, sourceStateSchema as q, partsOf as r, string as rt, cancellationSchema as s, SearchIndex as t, record as tt, feedbackCreateParamsSchema as u, questionnaireSchema as v, exitCodeForError as w, utf8Length as x, requestIdSchema as y, openParamsSchema as z };
8876
+ export { boolean as $, successEnvelope as A, openParamsSchema as B, VdeError as C, ExitCode as D, isVdeError as E, htmlModeChangeParamsSchema as F, searchParamsSchema as G, renderGrantParamsSchema as H, htmlModeSchema as I, sourceStateSchema as J, sha256Schema as K, lastOpenedDocument as L, closeParamsSchema as M, documentFormatSchema as N, envelopeSchema as O, documentIdSchema as P, array as Q, linkOpenParamsSchema as R, validateAnswers as S, isErrorCode as T, reorderParamsSchema as U, readParamsSchema as V, revisionSchema as W, LIMITS as X, watchRuleSchema as Y, _enum as Z, feedbackWaitParamsSchema as _, uniqueTokens as a, ZodError as at, submissionSchema as b, feedbackAckParamsSchema as c, feedbackDraftParamsSchema as d, literal as et, feedbackForgetParamsSchema as f, feedbackSubmitParamsSchema as g, feedbackStatusSchema as h, codePointLength as i, string as it, assetRecordSchema as j, errorEnvelope as k, feedbackCancelParamsSchema as l, feedbackListParamsSchema as m, batchesOf as n, record as nt, answersSchema as o, canonicalJson as ot, feedbackIdParamsSchema as p, sourceKindSchema as q, partsOf as r, strictObject as rt, cancellationSchema as s, SearchIndex as t, number as tt, feedbackCreateParamsSchema as u, questionnaireSchema as v, exitCodeForError as w, utf8Length as x, requestIdSchema as y, listParamsSchema as z };