vde-open 0.1.16 → 0.1.18

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.
Files changed (32) hide show
  1. package/README.md +20 -7
  2. package/THIRD_PARTY_NOTICES.md +159 -235
  3. package/dist/cli.js +929 -55
  4. package/dist/daemon.js +3 -4
  5. package/dist/{heap-C3qHm7SE.js → heap-wO8Issp7.js} +1 -2
  6. package/dist/{html-static-Ct_9qmNR.js → html-static-FxIbpM5b.js} +1630 -1216
  7. package/dist/{main-D-ZX3nEP.js → main-C6WuJzmz.js} +618 -320
  8. package/dist/{print-Bb6ArlQl.js → print-DNdOXOlQ.js} +281 -346
  9. package/dist/{render-CY_Mrhyl.js → render-CO37G_5o.js} +4 -7
  10. package/dist/rolldown-runtime-Bl4WtXjF.js +32 -0
  11. package/dist/{search-index-B0xpVDwG.js → search-index-CWn1X9n-.js} +160 -79
  12. package/dist/web/assets/apple-touch-icon-Be989aVe.png +0 -0
  13. package/dist/web/assets/favicon-Du9oTaDs.svg +1 -0
  14. package/dist/web/assets/main-cNlDXnWn.js +124 -0
  15. package/dist/web/assets/markdown.worker-iSTaa6gR.js +13 -0
  16. package/dist/web/assets/mobile-DlPHtOJc.js +1 -0
  17. package/dist/web/assets/rolldown-runtime-WkwZ5CU-.js +1 -0
  18. package/dist/web/assets/src-B8UfTgKw.js +40 -0
  19. package/dist/web/assets/src-DgGe2wbt.css +2 -0
  20. package/dist/web/index.html +6 -4
  21. package/dist/web/mobile.html +6 -4
  22. package/dist/workers/parse-worker.js +5 -6
  23. package/dist/workers/search-worker.js +3 -4
  24. package/docs/agent-usage.md +3 -0
  25. package/package.json +7 -6
  26. package/skills/vde-open/SKILL.md +9 -1
  27. package/dist/web/assets/main-DcvVu7FQ.js +0 -123
  28. package/dist/web/assets/markdown.worker-BhrAVXtB.js +0 -13
  29. package/dist/web/assets/mobile-HCpMXT2S.js +0 -1
  30. package/dist/web/assets/rolldown-runtime-CbXtAM7H.js +0 -1
  31. package/dist/web/assets/src--PpHwH7V.js +0 -41
  32. package/dist/web/assets/src-DinzSLDA.css +0 -2
@@ -1,8 +1,9 @@
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 sourceStateSchema, B as htmlModeChangeParamsSchema, C as questionnaireSchema, D as validateAnswers, E as utf8Length, F as successEnvelope, G as openParamsSchema, H as lastOpenedDocument, I as assetRecordSchema, J as reorderParamsSchema, K as readParamsSchema, L as closeParamsSchema, M as ExitCode, O as VdeError, P as errorEnvelope, Q as sourceKindSchema, R as documentFormatSchema, S as feedbackWaitParamsSchema, T as submissionSchema, U as linkOpenParamsSchema, V as htmlModeSchema, W as listParamsSchema, X as searchParamsSchema, Y as revisionSchema, Z as sha256Schema, _ as feedbackForgetParamsSchema, a as uniqueTokens, at as boolean, b as feedbackStatusSchema, c as mobileLinkParamsSchema, ct as record, d as answersSchema, dt as unknown, et as watchRuleSchema, f as cancellationSchema, ft as ZodError, g as feedbackDraftParamsSchema, h as feedbackCreateParamsSchema, i as codePointLength, it as array, j as isVdeError, k as exitCodeForError, l as mobileReleaseParamsSchema, lt as strictObject, m as feedbackCancelParamsSchema, mt as canonicalJson, n as batchesOf, nt as ZodNumber, o as mobileCheckParamsSchema, ot as literal, p as feedbackAckParamsSchema, pt as _coercedNumber, q as renderGrantParamsSchema, r as partsOf, rt as _enum, s as mobileGrantParamsSchema, st as number$1, tt as LIMITS, u as viewEpochSchema, ut as string, v as feedbackIdParamsSchema, w as requestIdSchema, x as feedbackSubmitParamsSchema, y as feedbackListParamsSchema, z as documentIdSchema } from "./search-index-B0xpVDwG.js";
3
- import { n as scanReferences, r as extractTitle } from "./render-CY_Mrhyl.js";
4
- import { n as measureHeap, t as collectGarbage } from "./heap-C3qHm7SE.js";
5
- import { accessSync, constants, existsSync, stat, statSync, unwatchFile, watch, watchFile } from "node:fs";
1
+ import { r as __toESM, t as __commonJSMin } from "./rolldown-runtime-Bl4WtXjF.js";
2
+ import { $ as sourceKindSchema, A as exitCodeForError, B as documentIdSchema, C as feedbackWaitParamsSchema, D as utf8Length, E as submissionSchema, F as errorEnvelope, G as listParamsSchema, H as htmlModeSchema, I as successEnvelope, J as renderGrantParamsSchema, K as openParamsSchema, L as assetRecordSchema, M as isVdeError, N as ExitCode, O as validateAnswers, Q as sha256Schema, R as closeParamsSchema, S as feedbackSubmitParamsSchema, T as requestIdSchema, U as lastOpenedDocument, V as htmlModeChangeParamsSchema, W as linkOpenParamsSchema, X as revisionSchema, Y as reorderParamsSchema, Z as searchParamsSchema, _ as feedbackDraftParamsSchema, a as uniqueTokens, at as array, b as feedbackListParamsSchema, c as mobileGrantParamsSchema, ct as number$1, d as viewEpochSchema, dt as string, et as sourceStateSchema, f as answersSchema, ft as unknown, g as feedbackCreateParamsSchema, h as feedbackCancelParamsSchema, ht as canonicalJson, i as codePointLength, it as _enum, k as VdeError, l as mobileLinkParamsSchema, lt as record, m as feedbackAckParamsSchema, mt as _coercedNumber, n as batchesOf, nt as LIMITS, o as mobileCheckParamsSchema, ot as boolean, p as cancellationSchema, pt as ZodError, q as readParamsSchema, r as partsOf, rt as ZodNumber, s as mobileCloseParamsSchema, st as literal, tt as watchRuleSchema, u as mobileReleaseParamsSchema, ut as strictObject, v as feedbackForgetParamsSchema, w as questionnaireSchema, x as feedbackStatusSchema, y as feedbackIdParamsSchema, z as documentFormatSchema } from "./search-index-CWn1X9n-.js";
3
+ import { C as isValidLogicalPath, 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-FxIbpM5b.js";
4
+ import { n as scanReferences, r as extractTitle } from "./render-CO37G_5o.js";
5
+ import { n as measureHeap, t as collectGarbage } from "./heap-wO8Issp7.js";
6
+ import { accessSync, constants, existsSync, stat, statSync, unwatchFile, watch as watch$1, watchFile } from "node:fs";
6
7
  import { appendFile, chmod, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat as stat$1, writeFile } from "node:fs/promises";
7
8
  import * as sp from "node:path";
8
9
  import { basename, delimiter, dirname, extname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
@@ -24,16 +25,102 @@ import { STATUS_CODES, ServerResponse, createServer } from "node:http";
24
25
  import { Http2ServerRequest, constants as constants$1 } from "node:http2";
25
26
  import { Readable } from "node:stream";
26
27
  import { createServer as createServer$1 } from "node:net";
27
- //#region ../../packages/shared/src/bridge.ts
28
+ // ../../packages/shared/src/bridge.ts
28
29
  const BRIDGE_HELLO = "vde-bridge-hello";
29
30
  const BRIDGE_PORT = "vde-bridge-port";
30
- //#endregion
31
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/coerce.js
31
+ // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/coerce.js
32
32
  function number(params) {
33
33
  return _coercedNumber(ZodNumber, params);
34
34
  }
35
- //#endregion
36
- //#region ../../packages/shared/src/strict-json.ts
35
+ // ../../packages/shared/src/repository-labels.ts
36
+ function placementOf(document) {
37
+ if (document.sourceKind !== "file") return { kind: "input" };
38
+ const repository = document.repository;
39
+ if (repository === null) return { kind: "outside" };
40
+ if (repository.state === "pending") return { kind: "pending" };
41
+ if (repository.state === "unresolved") return {
42
+ kind: "unresolved",
43
+ key: `unresolved:${repository.id}`,
44
+ repository
45
+ };
46
+ return {
47
+ kind: "repository",
48
+ key: `repository:${repository.id}`,
49
+ repository
50
+ };
51
+ }
52
+ function distinctSuffixes(paths) {
53
+ const labels = /* @__PURE__ */ new Map();
54
+ const byName = /* @__PURE__ */ new Map();
55
+ for (const [key, segments] of paths) {
56
+ const name = segments.at(-1) ?? "";
57
+ byName.set(name, [...byName.get(name) ?? [], key]);
58
+ }
59
+ for (const keys of byName.values()) for (const key of keys) {
60
+ const segments = paths.get(key) ?? [];
61
+ let length = 1;
62
+ const suffix = (of, size) => of.slice(-size).join("/");
63
+ while (length < segments.length && keys.some((other) => other !== key && suffix(paths.get(other) ?? [], length) === suffix(segments, length))) length += 1;
64
+ labels.set(key, suffix(segments, length));
65
+ }
66
+ return labels;
67
+ }
68
+ function buildLabels(documents) {
69
+ const locations = /* @__PURE__ */ new Map();
70
+ const ids = /* @__PURE__ */ new Map();
71
+ const checkouts = /* @__PURE__ */ new Map();
72
+ for (const document of documents) {
73
+ const placement = placementOf(document);
74
+ if (placement.kind !== "repository" && placement.kind !== "unresolved") continue;
75
+ locations.set(placement.key, placement.repository.nameSegments);
76
+ ids.set(placement.key, placement.repository.id);
77
+ if (placement.kind !== "repository") continue;
78
+ const checkout = placement.repository.checkout;
79
+ if (checkout?.kind !== "linked") continue;
80
+ let linked = checkouts.get(placement.key);
81
+ if (!linked) {
82
+ linked = /* @__PURE__ */ new Map();
83
+ checkouts.set(placement.key, linked);
84
+ }
85
+ linked.set(checkout.id, {
86
+ name: checkout.name,
87
+ branch: checkout.branch
88
+ });
89
+ }
90
+ const worktree = /* @__PURE__ */ new Map();
91
+ for (const linked of checkouts.values()) {
92
+ const shown = /* @__PURE__ */ new Map();
93
+ for (const [id, { name, branch }] of linked) {
94
+ const text = branch ?? name;
95
+ shown.set(text, [...shown.get(text) ?? [], id]);
96
+ }
97
+ for (const [text, sharing] of shown) for (const id of sharing) {
98
+ const name = linked.get(id)?.name ?? "";
99
+ worktree.set(id, sharing.length > 1 && name !== text ? `${text} (${name})` : text);
100
+ }
101
+ }
102
+ const byLocation = /* @__PURE__ */ new Map();
103
+ for (const [key, segments] of locations) {
104
+ const location = segments.join("/");
105
+ byLocation.set(location, [...byLocation.get(location) ?? [], key]);
106
+ }
107
+ for (const keys of byLocation.values()) {
108
+ if (keys.length < 2) continue;
109
+ for (const key of keys) {
110
+ const raw = (ids.get(key) ?? "").split(/[\\/]/).filter((part) => part !== "");
111
+ locations.set(key, raw.at(-1) === ".git" ? raw.slice(0, -1) : raw);
112
+ }
113
+ }
114
+ return {
115
+ repository: distinctSuffixes(locations),
116
+ worktree
117
+ };
118
+ }
119
+ function worktreeText(checkout, labels) {
120
+ const label = labels.worktree.get(checkout.id) ?? checkout.branch ?? checkout.name;
121
+ return label === checkout.name || label.endsWith(`(${checkout.name})`) ? label : `${label} (${checkout.name})`;
122
+ }
123
+ // ../../packages/shared/src/strict-json.ts
37
124
  var StrictJsonError = class extends Error {
38
125
  reason;
39
126
  pointer;
@@ -157,11 +244,9 @@ function parseStrictJson(text) {
157
244
  if (index !== text.length) fail("syntax", "", "There is extra content after the JSON.");
158
245
  return value;
159
246
  }
160
- //#endregion
161
- //#region package.json
162
- var version = "0.1.16";
163
- //#endregion
164
- //#region src/documents/cursor.ts
247
+ // package.json
248
+ var version = "0.1.18";
249
+ // src/documents/cursor.ts
165
250
  function invalidCursor(reason) {
166
251
  return new VdeError("E_INVALID_CURSOR", "The cursor is invalid or has expired. Fetch again from the start.", { reason });
167
252
  }
@@ -188,12 +273,10 @@ function createCursorCodec(secret, now = Date.now) {
188
273
  }
189
274
  };
190
275
  }
191
- //#endregion
192
- //#region ../../packages/document/src/profiles.ts
276
+ // ../../packages/document/src/profiles.ts
193
277
  const MARKDOWN_PARSER_PROFILE = "markdown-tanstack-v1";
194
278
  const HTML_STATIC_PARSER_PROFILE = "html-static-v2";
195
- //#endregion
196
- //#region ../../packages/document/src/source-lines.ts
279
+ // ../../packages/document/src/source-lines.ts
197
280
  const LF = 10;
198
281
  function buildLineIndex(source) {
199
282
  const lineStarts = [0];
@@ -228,8 +311,7 @@ function truncateAtCodePoint(source, start, end, maxBytes) {
228
311
  while (cut > start && (source[cut] & 192) === 128) cut -= 1;
229
312
  return cut;
230
313
  }
231
- //#endregion
232
- //#region src/documents/source-reader.ts
314
+ // src/documents/source-reader.ts
233
315
  const READ_ATTEMPTS$1 = 3;
234
316
  function statSignature(stats) {
235
317
  return `${String(stats.ino)}:${String(stats.size)}:${String(stats.mtimeMs)}`;
@@ -331,8 +413,7 @@ async function readSourceFile(path, format = "markdown") {
331
413
  }
332
414
  throw new VdeError("E_IO", `${path} keeps changing while being read.`, { path }, { retryable: true });
333
415
  }
334
- //#endregion
335
- //#region src/assets/asset-reader.ts
416
+ // src/assets/asset-reader.ts
336
417
  const READ_ATTEMPTS = 3;
337
418
  function isInside$1(root, path) {
338
419
  const fromRoot = relative(root, path);
@@ -440,8 +521,7 @@ async function readAssetFile(root, logicalPath) {
440
521
  reason: "unstable"
441
522
  };
442
523
  }
443
- //#endregion
444
- //#region src/assets/manifest.ts
524
+ // src/assets/manifest.ts
445
525
  const MAX_TRACKED = LIMITS.documentAssets * 2;
446
526
  function decodeCss(bytes) {
447
527
  if (bytes.includes(0)) return null;
@@ -544,8 +624,7 @@ async function buildManifest(input) {
544
624
  })).toSorted((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
545
625
  };
546
626
  }
547
- //#endregion
548
- //#region src/persistence/state-schema.ts
627
+ // src/persistence/state-schema.ts
549
628
  const revisionRecordSchema = strictObject({
550
629
  revision: revisionSchema,
551
630
  format: documentFormatSchema,
@@ -673,8 +752,7 @@ function referencedBlobs(payload) {
673
752
  }
674
753
  return blobs;
675
754
  }
676
- //#endregion
677
- //#region ../../node_modules/.pnpm/fdir@6.5.0_picomatch@4.0.7/node_modules/fdir/dist/index.mjs
755
+ // ../../node_modules/.pnpm/fdir@6.5.0_picomatch@4.0.7/node_modules/fdir/dist/index.mjs
678
756
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
679
757
  function cleanPath(path) {
680
758
  let normalized = normalize(path);
@@ -1062,7 +1140,7 @@ try {
1062
1140
  var Builder = class {
1063
1141
  globCache = {};
1064
1142
  options = {
1065
- maxDepth: Infinity,
1143
+ maxDepth: 1e400,
1066
1144
  suppressErrors: true,
1067
1145
  pathSeparator: sep$1,
1068
1146
  filters: []
@@ -1181,8 +1259,7 @@ var Builder = class {
1181
1259
  return this;
1182
1260
  }
1183
1261
  };
1184
- //#endregion
1185
- //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/constants.js
1262
+ // ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/constants.js
1186
1263
  var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1187
1264
  const WIN_SLASH = "\\\\/";
1188
1265
  const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
@@ -1350,8 +1427,7 @@ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1350
1427
  }
1351
1428
  };
1352
1429
  }));
1353
- //#endregion
1354
- //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/utils.js
1430
+ // ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/utils.js
1355
1431
  var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
1356
1432
  const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants();
1357
1433
  exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
@@ -1398,8 +1474,7 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
1398
1474
  return last;
1399
1475
  };
1400
1476
  }));
1401
- //#endregion
1402
- //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/scan.js
1477
+ // ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/scan.js
1403
1478
  var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1404
1479
  const utils = require_utils();
1405
1480
  const { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants();
@@ -1407,7 +1482,7 @@ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1407
1482
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
1408
1483
  };
1409
1484
  const depth = (token) => {
1410
- if (token.isPrefix !== true) token.depth = token.isGlobstar ? Infinity : 1;
1485
+ if (token.isPrefix !== true) token.depth = token.isGlobstar ? 1e400 : 1;
1411
1486
  };
1412
1487
  /**
1413
1488
  * Quickly scans a glob pattern and returns an object with a handful of
@@ -1695,8 +1770,7 @@ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1695
1770
  };
1696
1771
  module.exports = scan;
1697
1772
  }));
1698
- //#endregion
1699
- //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/parse.js
1773
+ // ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/parse.js
1700
1774
  var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1701
1775
  const constants = require_constants();
1702
1776
  const utils = require_utils();
@@ -2772,8 +2846,7 @@ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2772
2846
  };
2773
2847
  module.exports = parse;
2774
2848
  }));
2775
- //#endregion
2776
- //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/picomatch.js
2849
+ // ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/picomatch.js
2777
2850
  var require_picomatch$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2778
2851
  const scan = require_scan();
2779
2852
  const parse = require_parse();
@@ -3086,8 +3159,7 @@ var require_picomatch$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3086
3159
  */
3087
3160
  module.exports = picomatch;
3088
3161
  }));
3089
- //#endregion
3090
- //#region ../../node_modules/.pnpm/tinyglobby@0.2.17/node_modules/tinyglobby/dist/index.mjs
3162
+ // ../../node_modules/.pnpm/tinyglobby@0.2.17/node_modules/tinyglobby/dist/index.mjs
3091
3163
  var import_picomatch = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3092
3164
  const pico = require_picomatch$1();
3093
3165
  const utils = require_utils();
@@ -3376,8 +3448,7 @@ async function glob(globInput, options) {
3376
3448
  const [crawler, relative] = getCrawler(globInput, options);
3377
3449
  return crawler ? formatPaths(await crawler.withPromise(), relative) : [];
3378
3450
  }
3379
- //#endregion
3380
- //#region src/documents/enumerate.ts
3451
+ // src/documents/enumerate.ts
3381
3452
  const EXCLUDED_DIRECTORIES = /* @__PURE__ */ new Set([
3382
3453
  "node_modules",
3383
3454
  "vendor",
@@ -3522,8 +3593,7 @@ function watchBaseOf(target) {
3522
3593
  function isExcludedDirectoryName(name) {
3523
3594
  return isHidden(name) || EXCLUDED_DIRECTORIES.has(name);
3524
3595
  }
3525
- //#endregion
3526
- //#region src/documents/repository.ts
3596
+ // src/documents/repository.ts
3527
3597
  const METADATA_LIMIT = 4096;
3528
3598
  function kindOf(stats) {
3529
3599
  if (stats.isSymbolicLink()) return "symlink";
@@ -4066,8 +4136,7 @@ var RepositoryTracker = class {
4066
4136
  };
4067
4137
  }
4068
4138
  };
4069
- //#endregion
4070
- //#region src/documents/revision.ts
4139
+ // src/documents/revision.ts
4071
4140
  function sha256Hex(bytes) {
4072
4141
  return createHash("sha256").update(bytes).digest("hex");
4073
4142
  }
@@ -4080,8 +4149,7 @@ function computeRevision(input) {
4080
4149
  assets
4081
4150
  }))}`;
4082
4151
  }
4083
- //#endregion
4084
- //#region src/documents/service.ts
4152
+ // src/documents/service.ts
4085
4153
  const LINK_CONFIRMATION_TTL_MS = 3e5;
4086
4154
  const MAX_LINK_CONFIRMATIONS = 256;
4087
4155
  const INHERITED_ASSETS = {
@@ -5057,6 +5125,10 @@ var DocumentService = class {
5057
5125
  entry: this.#requireRevision(record, revision ?? record.currentRevision)
5058
5126
  };
5059
5127
  }
5128
+ async readCurrentSource(documentId) {
5129
+ const { entry } = this.describeRevision(documentId, void 0);
5130
+ return this.#store.readBlob(entry.sourceSha256);
5131
+ }
5060
5132
  async #linkTarget(documentId, href) {
5061
5133
  const record = this.#requireOpen(documentId);
5062
5134
  const target = classifyLink(href);
@@ -5493,8 +5565,7 @@ var DocumentService = class {
5493
5565
  return this.listWatchRules();
5494
5566
  }
5495
5567
  };
5496
- //#endregion
5497
- //#region src/export/browser.ts
5568
+ // src/export/browser.ts
5498
5569
  function executableFile(path) {
5499
5570
  try {
5500
5571
  accessSync(path, constants.X_OK);
@@ -5542,8 +5613,7 @@ function findBrowser(lookup) {
5542
5613
  if (found !== void 0) return found;
5543
5614
  throw new VdeError("E_BROWSER_NOT_FOUND", "Exporting a PDF needs Google Chrome or Microsoft Edge. Set VDE_OPEN_BROWSER to use another Chromium-based browser.", { source: "search" });
5544
5615
  }
5545
- //#endregion
5546
- //#region src/export/cdp.ts
5616
+ // src/export/cdp.ts
5547
5617
  const MAX_MESSAGE_BYTES = 16777216;
5548
5618
  var CdpError = class extends Error {
5549
5619
  method;
@@ -5641,8 +5711,7 @@ function connectCdp(toBrowser, fromBrowser) {
5641
5711
  close
5642
5712
  };
5643
5713
  }
5644
- //#endregion
5645
- //#region src/export/pdf-service.ts
5714
+ // src/export/pdf-service.ts
5646
5715
  const BROWSER_FLAGS = [
5647
5716
  "--headless",
5648
5717
  "--remote-debugging-pipe",
@@ -5978,8 +6047,7 @@ function createPdfService(options) {
5978
6047
  }
5979
6048
  };
5980
6049
  }
5981
- //#endregion
5982
- //#region src/feedback/service.ts
6050
+ // src/feedback/service.ts
5983
6051
  function sha256$1(text) {
5984
6052
  return createHash("sha256").update(text).digest("hex");
5985
6053
  }
@@ -6199,7 +6267,7 @@ var FeedbackService = class {
6199
6267
  }
6200
6268
  list(rawParams) {
6201
6269
  const params = feedbackListParamsSchema.parse(rawParams ?? {});
6202
- const requests = Object.values(this.#store.payload.feedbackRequests).filter((record) => params.status === void 0 || record.status === params.status).toSorted((a, b) => a.createdAt.localeCompare(b.createdAt)).map((record) => this.#toAgent(record));
6270
+ const requests = Object.values(this.#store.payload.feedbackRequests).filter((record) => params.status === void 0 || record.status === params.status).filter((record) => params.acknowledged === void 0 || record.acknowledgedAt !== null === params.acknowledged).toSorted((a, b) => a.createdAt.localeCompare(b.createdAt)).map((record) => this.#toAgent(record));
6203
6271
  return this.#result({ requests });
6204
6272
  }
6205
6273
  get(rawParams) {
@@ -6302,14 +6370,16 @@ var FeedbackService = class {
6302
6370
  async forget(rawParams) {
6303
6371
  const params = feedbackForgetParamsSchema.parse(rawParams);
6304
6372
  if (!params.confirmed) throw new VdeError("E_CONFIRMATION_REQUIRED", "Specify --yes to delete.", { requestId: params.requestId });
6305
- await this.#store.transaction((tx) => {
6373
+ const forgotten = await this.#store.transaction((tx) => {
6306
6374
  const state = tx.state;
6307
6375
  const record = this.#require(state, params.requestId);
6308
6376
  if (record.status === "pending") throw new VdeError("E_REQUEST_PENDING", "A pending question cannot be deleted. Cancel it first.", { requestId: params.requestId });
6309
6377
  delete state.feedbackRequests[params.requestId];
6310
6378
  const document = state.documents[record.documentId];
6311
6379
  if (document) document.revisions = pruneRevisions(document.revisions, this.#now().getTime(), pinnedRevisions(state, record.documentId));
6380
+ return structuredClone(record);
6312
6381
  });
6382
+ this.#changed(forgotten);
6313
6383
  await this.#store.collectGarbage().catch(() => 0);
6314
6384
  return this.#result({
6315
6385
  requestId: params.requestId,
@@ -6416,8 +6486,7 @@ var FeedbackService = class {
6416
6486
  for (const waiters of this.#waiters.values()) for (const waiter of waiters) waiter.fail(error);
6417
6487
  }
6418
6488
  };
6419
- //#endregion
6420
- //#region src/entry-paths.ts
6489
+ // src/entry-paths.ts
6421
6490
  const isSourceRun = import.meta.url.endsWith(".ts");
6422
6491
  function daemonEntryPath() {
6423
6492
  return fileURLToPath$1(new URL(isSourceRun ? "./daemon.ts" : "./daemon.js", import.meta.url));
@@ -6432,8 +6501,7 @@ function webRootPath() {
6432
6501
  const candidate = fileURLToPath$1(new URL(isSourceRun ? "../dist/web" : "./web", import.meta.url));
6433
6502
  return existsSync(candidate) ? candidate : null;
6434
6503
  }
6435
- //#endregion
6436
- //#region src/persistence/paths.ts
6504
+ // src/persistence/paths.ts
6437
6505
  const APP_DIR = "vde-open";
6438
6506
  function resolveStateRoot(environment) {
6439
6507
  const { env, platform, homeDir } = environment;
@@ -6477,8 +6545,7 @@ function currentPathEnvironment() {
6477
6545
  uid: typeof process.getuid === "function" ? process.getuid() : null
6478
6546
  };
6479
6547
  }
6480
- //#endregion
6481
- //#region src/persistence/state-store.ts
6548
+ // src/persistence/state-store.ts
6482
6549
  const STATE_FILE = "state.json";
6483
6550
  const PREVIOUS_FILE = "state.prev.json";
6484
6551
  const BLOB_DIR = "blobs";
@@ -6743,8 +6810,7 @@ var StateStore = class StateStore {
6743
6810
  return fatal;
6744
6811
  }
6745
6812
  };
6746
- //#endregion
6747
- //#region src/persistence/fs-retry.ts
6813
+ // src/persistence/fs-retry.ts
6748
6814
  const RETRY_CODES = /* @__PURE__ */ new Set([
6749
6815
  "EPERM",
6750
6816
  "EACCES",
@@ -6772,8 +6838,7 @@ function renameWithRetry(from, to) {
6772
6838
  function removeWithRetry(path) {
6773
6839
  return retryOnWindows(() => rm(path, { force: true }));
6774
6840
  }
6775
- //#endregion
6776
- //#region src/persistence/store-fs.ts
6841
+ // src/persistence/store-fs.ts
6777
6842
  function isNotFound(error) {
6778
6843
  return error.code === "ENOENT";
6779
6844
  }
@@ -6833,8 +6898,7 @@ const nodeStoreFs = {
6833
6898
  }
6834
6899
  }
6835
6900
  };
6836
- //#endregion
6837
- //#region src/render/bridge-sdk.ts
6901
+ // src/render/bridge-sdk.ts
6838
6902
  const PORT_WAIT_MS = 1e4;
6839
6903
  const HELLO_INTERVAL_MS = 500;
6840
6904
  function bridgeSdkScript(configSlot) {
@@ -6938,8 +7002,7 @@ function bridgeSdkScript(configSlot) {
6938
7002
  sendHello();
6939
7003
  })(${configSlot});`;
6940
7004
  }
6941
- //#endregion
6942
- //#region src/render/render-service.ts
7005
+ // src/render/render-service.ts
6943
7006
  const SNAPSHOT_CACHE_SIZE = 8;
6944
7007
  const HTML_MIME = "text/html; charset=utf-8";
6945
7008
  function decodeUtf8(bytes) {
@@ -7310,8 +7373,7 @@ function createRenderService(options) {
7310
7373
  };
7311
7374
  }
7312
7375
  }
7313
- //#endregion
7314
- //#region src/render/view-epochs.ts
7376
+ // src/render/view-epochs.ts
7315
7377
  function createViewEpochs(documents) {
7316
7378
  const seen = /* @__PURE__ */ new Map();
7317
7379
  const current = (documentId) => {
@@ -7353,8 +7415,7 @@ function createViewEpochs(documents) {
7353
7415
  }
7354
7416
  };
7355
7417
  }
7356
- //#endregion
7357
- //#region src/diagnostics/idle-collect.ts
7418
+ // src/diagnostics/idle-collect.ts
7358
7419
  const COLLECT_AFTER_IDLE_MS = 2e3;
7359
7420
  function createIdleTrigger(run, delayMs = COLLECT_AFTER_IDLE_MS) {
7360
7421
  let timer = null;
@@ -7455,8 +7516,7 @@ function startHeapWatch(options = {}) {
7455
7516
  timer.unref();
7456
7517
  return { stop: () => clearInterval(timer) };
7457
7518
  }
7458
- //#endregion
7459
- //#region src/diagnostics/until-aborted.ts
7519
+ // src/diagnostics/until-aborted.ts
7460
7520
  function untilAborted(promise, signal) {
7461
7521
  if (!signal) return promise;
7462
7522
  const stopping = () => new VdeError("E_DAEMON_STOPPING", "The daemon is stopping.");
@@ -7476,8 +7536,7 @@ function untilAborted(promise, signal) {
7476
7536
  });
7477
7537
  });
7478
7538
  }
7479
- //#endregion
7480
- //#region src/search/search-service.ts
7539
+ // src/search/search-service.ts
7481
7540
  const DEFAULT_TIMEOUT_MS = 1e4;
7482
7541
  const WAIT_STEP_MS = 20;
7483
7542
  const APPEND_BATCH_WEIGHT = 65536;
@@ -7929,8 +7988,7 @@ function createSearchService(options) {
7929
7988
  }
7930
7989
  };
7931
7990
  }
7932
- //#endregion
7933
- //#region src/server/event-hub.ts
7991
+ // src/server/event-hub.ts
7934
7992
  function createEventHub(daemonId, catalogVersion) {
7935
7993
  const listeners = /* @__PURE__ */ new Set();
7936
7994
  let sequence = 0;
@@ -7964,8 +8022,7 @@ function createEventHub(daemonId, catalogVersion) {
7964
8022
  }
7965
8023
  };
7966
8024
  }
7967
- //#endregion
7968
- //#region ../../node_modules/.pnpm/@hono+node-server@2.1.3_hono@4.13.12/node_modules/@hono/node-server/dist/index.mjs
8025
+ // ../../node_modules/.pnpm/@hono+node-server@2.1.9_hono@4.13.19/node_modules/@hono/node-server/dist/index.mjs
7969
8026
  var RequestError = class extends Error {
7970
8027
  constructor(message, options) {
7971
8028
  super(message, options);
@@ -8123,16 +8180,27 @@ const newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeader
8123
8180
  const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
8124
8181
  const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
8125
8182
  const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
8183
+ const validateRequestTarget = (target) => {
8184
+ const backslash = target.indexOf("\\");
8185
+ if (backslash !== -1) {
8186
+ const query = target.indexOf("?");
8187
+ if (query === -1 || backslash < query) throw new RequestError("Backslash in request path");
8188
+ }
8189
+ };
8126
8190
  const buildUrl = (scheme, host, incomingUrl) => {
8127
8191
  const url = `${scheme}://${host}${incomingUrl}`;
8128
8192
  if (!reValidHost.test(host)) {
8193
+ validateRequestTarget(incomingUrl);
8129
8194
  const urlObj = new URL(url);
8130
8195
  if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
8131
8196
  return urlObj.href;
8132
8197
  } else if (incomingUrl.length === 0) return url + "/";
8133
8198
  else {
8134
8199
  if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
8135
- if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
8200
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) {
8201
+ validateRequestTarget(incomingUrl);
8202
+ return new URL(url).href;
8203
+ }
8136
8204
  return url;
8137
8205
  }
8138
8206
  };
@@ -8141,7 +8209,11 @@ const toRequestError = (e) => {
8141
8209
  return new RequestError(e.message, { cause: e });
8142
8210
  };
8143
8211
  const GlobalRequest = global.Request;
8144
- var Request$1 = class extends GlobalRequest {
8212
+ var Request$1 = class Request$1 extends GlobalRequest {
8213
+ static [Symbol.hasInstance](instance) {
8214
+ if (this === Request$1) return instance instanceof GlobalRequest || Function.prototype[Symbol.hasInstance].call(this, instance);
8215
+ return Function.prototype[Symbol.hasInstance].call(this, instance);
8216
+ }
8145
8217
  constructor(input, options) {
8146
8218
  if (typeof input === "object" && getRequestCache in input) {
8147
8219
  const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
@@ -8180,8 +8252,8 @@ const readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
8180
8252
  else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
8181
8253
  else {
8182
8254
  const bodyChunks = chunks ?? [];
8183
- const chunk = incoming.read();
8184
- if (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
8255
+ let chunk;
8256
+ while ((chunk = incoming.read()) !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
8185
8257
  const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
8186
8258
  result = buffer;
8187
8259
  const contentLength = incoming.headers["content-length"];
@@ -8485,6 +8557,7 @@ Object.defineProperty(requestPrototype, "signal", { get() {
8485
8557
  "cache",
8486
8558
  "credentials",
8487
8559
  "destination",
8560
+ "duplex",
8488
8561
  "integrity",
8489
8562
  "mode",
8490
8563
  "redirect",
@@ -8517,6 +8590,9 @@ Object.defineProperty(requestPrototype, "blob", { value: function() {
8517
8590
  return new Response(buf, type ? { headers: { "content-type": type } } : void 0).blob();
8518
8591
  });
8519
8592
  } });
8593
+ Object.defineProperty(requestPrototype, "bytes", { value: function() {
8594
+ return this.arrayBuffer().then((buf) => new Uint8Array(buf));
8595
+ } });
8520
8596
  Object.defineProperty(requestPrototype, "json", { value: function() {
8521
8597
  if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
8522
8598
  return this.text().then(JSON.parse);
@@ -8541,6 +8617,7 @@ const newRequest = (incoming, defaultHostname) => {
8541
8617
  if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
8542
8618
  if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
8543
8619
  try {
8620
+ validateRequestTarget(incomingUrl);
8544
8621
  req[urlKey] = new URL(incomingUrl).href;
8545
8622
  } catch (e) {
8546
8623
  throw new RequestError("Invalid absolute URL", { cause: e });
@@ -8570,6 +8647,10 @@ const GlobalResponse = global.Response;
8570
8647
  var Response$1 = class Response$1 {
8571
8648
  #body;
8572
8649
  #init;
8650
+ static [Symbol.hasInstance](instance) {
8651
+ if (this === Response$1) return instance instanceof GlobalResponse || Function.prototype[Symbol.hasInstance].call(this, instance);
8652
+ return Function.prototype[Symbol.hasInstance].call(this, instance);
8653
+ }
8573
8654
  [getResponseCache]() {
8574
8655
  const cache = this[cacheKey];
8575
8656
  const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
@@ -8590,7 +8671,7 @@ var Response$1 = class Response$1 {
8590
8671
  this[getResponseCache]();
8591
8672
  return;
8592
8673
  }
8593
- this.#init = init instanceof Response$1 ? init.#init : init;
8674
+ this.#init = #init in init ? init.#init : init;
8594
8675
  headers = new Headers(init.headers);
8595
8676
  } else this.#init = init;
8596
8677
  if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
@@ -8631,6 +8712,7 @@ var Response$1 = class Response$1 {
8631
8712
  [
8632
8713
  "arrayBuffer",
8633
8714
  "blob",
8715
+ "bytes",
8634
8716
  "clone",
8635
8717
  "formData",
8636
8718
  "json",
@@ -8703,6 +8785,11 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
8703
8785
  const cancel = (error) => {
8704
8786
  reader.cancel(error).catch(() => {});
8705
8787
  };
8788
+ const stream = writable.stream;
8789
+ if (writable.destroyed || stream?.closed || stream?.destroyed) {
8790
+ cancel();
8791
+ return reader.closed;
8792
+ }
8706
8793
  writable.on("close", cancel);
8707
8794
  writable.on("error", cancel);
8708
8795
  (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
@@ -8720,7 +8807,7 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
8720
8807
  try {
8721
8808
  if (done) writable.end();
8722
8809
  else if (!writable.write(value)) writable.once("drain", onDrain);
8723
- else return reader.read().then(flow, handleStreamError);
8810
+ else reader.read().then(flow, handleStreamError);
8724
8811
  } catch (e) {
8725
8812
  handleStreamError(e);
8726
8813
  }
@@ -8728,7 +8815,10 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
8728
8815
  }
8729
8816
  function writeFromReadableStream(stream, writable) {
8730
8817
  if (stream.locked) throw new TypeError("ReadableStream is locked.");
8731
- else if (writable.destroyed) return;
8818
+ else if (writable.destroyed) {
8819
+ stream.cancel().catch(() => {});
8820
+ return;
8821
+ }
8732
8822
  return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
8733
8823
  }
8734
8824
  const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
@@ -8787,7 +8877,7 @@ const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
8787
8877
  if (incoming.errored) {
8788
8878
  recordBodyBufferedBeforeDisconnect(incoming);
8789
8879
  req[abortRequest](incoming.errored.toString());
8790
- } else if (!outgoing.writableFinished) {
8880
+ } else if (!outgoing.writableFinished || incoming instanceof Http2ServerRequest && incoming.aborted) {
8791
8881
  recordBodyBufferedBeforeDisconnect(incoming);
8792
8882
  req[abortRequest]("Client connection prematurely closed.");
8793
8883
  }
@@ -8919,10 +9009,7 @@ const responseViaResponseObject = async (res, outgoing, options = {}) => {
8919
9009
  let maxReadCount = 2;
8920
9010
  for (let i = 0; i < maxReadCount; i++) {
8921
9011
  currentReadPromise ||= reader.read();
8922
- const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
8923
- console.error(e);
8924
- done = true;
8925
- });
9012
+ const chunk = await readWithoutBlocking(currentReadPromise);
8926
9013
  if (!chunk) {
8927
9014
  if (i === 1) {
8928
9015
  await new Promise((resolve) => setTimeout(resolve));
@@ -9037,6 +9124,7 @@ const appendResponseHeaders = (headers, responseHeaders) => {
9037
9124
  });
9038
9125
  };
9039
9126
  const rejectUpgradeRequest = (socket, status, responseHeaders) => {
9127
+ if (socket.destroyed) return;
9040
9128
  const responseLines = ["Connection: close", "Content-Length: 0"];
9041
9129
  appendResponseHeaders(responseLines, responseHeaders);
9042
9130
  socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r
@@ -9044,7 +9132,12 @@ const rejectUpgradeRequest = (socket, status, responseHeaders) => {
9044
9132
  };
9045
9133
  const createUpgradeRequest = (request) => {
9046
9134
  const protocol = request.socket.encrypted ? "https" : "http";
9047
- const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
9135
+ const incomingUrl = request.url ?? "/";
9136
+ let url;
9137
+ if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
9138
+ validateRequestTarget(incomingUrl);
9139
+ url = new URL(incomingUrl).href;
9140
+ } else url = buildUrl(protocol, request.headers.host ?? "localhost", incomingUrl);
9048
9141
  const headers = new Headers();
9049
9142
  for (const key in request.headers) {
9050
9143
  const value = request.headers[key];
@@ -9081,6 +9174,10 @@ const setupWebSocket = (options) => {
9081
9174
  };
9082
9175
  server.on("upgrade", async (request, socket, head) => {
9083
9176
  if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
9177
+ const ignoreSocketError = () => {};
9178
+ const reclaimWaiterOnClose = () => rejectWaiter(request);
9179
+ socket.on("error", ignoreSocketError);
9180
+ socket.once("close", reclaimWaiterOnClose);
9084
9181
  const env = {
9085
9182
  incoming: request,
9086
9183
  outgoing: void 0,
@@ -9095,8 +9192,12 @@ const setupWebSocket = (options) => {
9095
9192
  status = response.status;
9096
9193
  responseHeaders = response.headers;
9097
9194
  }
9098
- } catch {
9099
- if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
9195
+ } catch (error) {
9196
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, error instanceof RequestError ? 400 : 500);
9197
+ return;
9198
+ }
9199
+ if (socket.destroyed) {
9200
+ rejectWaiter(request);
9100
9201
  return;
9101
9202
  }
9102
9203
  const waiter = waiterMap.get(request);
@@ -9108,12 +9209,11 @@ const setupWebSocket = (options) => {
9108
9209
  const addResponseHeaders = (headers) => {
9109
9210
  appendResponseHeaders(headers, responseHeaders);
9110
9211
  };
9111
- const reclaimWaiterOnClose = () => rejectWaiter(request);
9112
- socket.once("close", reclaimWaiterOnClose);
9113
9212
  wss.on("headers", addResponseHeaders);
9114
9213
  try {
9115
9214
  wss.handleUpgrade(request, socket, head, (ws) => {
9116
9215
  socket.off("close", reclaimWaiterOnClose);
9216
+ socket.off("error", ignoreSocketError);
9117
9217
  wss.emit("connection", ws, request);
9118
9218
  });
9119
9219
  } finally {
@@ -9150,16 +9250,66 @@ const serve = (options, listeningListener) => {
9150
9250
  });
9151
9251
  return server;
9152
9252
  };
9153
- //#endregion
9154
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/request/constants.js
9253
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/http-exception.js
9254
+ /**
9255
+ * `HTTPException` must be used when a fatal error such as authentication failure occurs.
9256
+ *
9257
+ * @see {@link https://hono.dev/docs/api/exception}
9258
+ *
9259
+ * @param {StatusCode} status - status code of HTTPException
9260
+ * @param {HTTPExceptionOptions} options - options of HTTPException
9261
+ * @param {HTTPExceptionOptions["res"]} options.res - response of options of HTTPException
9262
+ * @param {HTTPExceptionOptions["message"]} options.message - message of options of HTTPException
9263
+ * @param {HTTPExceptionOptions["cause"]} options.cause - cause of options of HTTPException
9264
+ *
9265
+ * @example
9266
+ * ```ts
9267
+ * import { HTTPException } from 'hono/http-exception'
9268
+ *
9269
+ * // ...
9270
+ *
9271
+ * app.post('/auth', async (c, next) => {
9272
+ * // authentication
9273
+ * if (authorized === false) {
9274
+ * throw new HTTPException(401, { message: 'Custom error message' })
9275
+ * }
9276
+ * await next()
9277
+ * })
9278
+ * ```
9279
+ */
9280
+ var HTTPException = class extends Error {
9281
+ res;
9282
+ status;
9283
+ /**
9284
+ * Creates an instance of `HTTPException`.
9285
+ * @param status - HTTP status code for the exception. Defaults to 500.
9286
+ * @param options - Additional options for the exception.
9287
+ */
9288
+ constructor(status = 500, options) {
9289
+ super(options?.message, { cause: options?.cause });
9290
+ this.res = options?.res;
9291
+ this.status = status;
9292
+ }
9293
+ /**
9294
+ * Returns the response object associated with the exception.
9295
+ * If a response object is not provided, a new response is created with the error message and status code.
9296
+ * @returns The response object.
9297
+ */
9298
+ getResponse() {
9299
+ if (this.res) return new Response(this.res.body, {
9300
+ status: this.status,
9301
+ headers: this.res.headers
9302
+ });
9303
+ return new Response(this.message, { status: this.status });
9304
+ }
9305
+ };
9306
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/request/constants.js
9155
9307
  const GET_MATCH_RESULT = Symbol();
9156
- //#endregion
9157
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/utils/buffer.js
9308
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/buffer.js
9158
9309
  const bufferToFormData = (arrayBuffer, contentType) => {
9159
9310
  return new Response(arrayBuffer, { headers: { "Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase()) } }).formData();
9160
9311
  };
9161
- //#endregion
9162
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/utils/body.js
9312
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/body.js
9163
9313
  const MAX_NESTED_OBJECTS = 1e4;
9164
9314
  const isRawRequest = (request) => "headers" in request;
9165
9315
  const parseBody = async (request, options = Object.create(null)) => {
@@ -9232,6 +9382,7 @@ const handleParsingAllValues = (form, key, value) => {
9232
9382
  * @param {BodyData} form - The form data object.
9233
9383
  * @param {string} key - The dot notation key.
9234
9384
  * @param {BodyDataValue} value - The value to assign.
9385
+ * @param {{ count: number }} state - The state object tracking nesting depth.
9235
9386
  */
9236
9387
  const handleParsingNestedValues = (form, key, value, state) => {
9237
9388
  if (/(?:^|\.)__proto__\./.test(key)) return;
@@ -9252,8 +9403,7 @@ const handleParsingNestedValues = (form, key, value, state) => {
9252
9403
  const throwNestingLimitExceeded = () => {
9253
9404
  throw new Error("Nesting limit exceeded");
9254
9405
  };
9255
- //#endregion
9256
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/utils/url.js
9406
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/url.js
9257
9407
  const splitPath = (path) => {
9258
9408
  const paths = path.split("/");
9259
9409
  if (paths[0] === "") paths.shift();
@@ -9325,16 +9475,7 @@ const tryDecode = (str, decoder) => {
9325
9475
  });
9326
9476
  }
9327
9477
  };
9328
- /**
9329
- * Try to apply decodeURI() to given string.
9330
- * If it fails, skip invalid percent encoding or invalid UTF-8 sequences, and apply decodeURI() to the rest as much as possible.
9331
- * @param str The string to decode.
9332
- * @returns The decoded string that sometimes contains undecodable percent encoding.
9333
- * @example
9334
- * tryDecodeURI('Hello%20World') // 'Hello World'
9335
- * tryDecodeURI('Hello%20World/%A4%A2') // 'Hello World/%A4%A2'
9336
- */
9337
- const tryDecodeURI = (str) => tryDecode(str, decodeURI);
9478
+ const decodeURIWithPreservedPercent = (value) => decodeURI(value.includes("%25") ? value.replace(/%25/g, "%2525") : value);
9338
9479
  const getPath = (request) => {
9339
9480
  const url = request.url;
9340
9481
  const start = url.indexOf("/", url.indexOf(":") + 4);
@@ -9346,7 +9487,13 @@ const getPath = (request) => {
9346
9487
  const hashIndex = url.indexOf("#", i);
9347
9488
  const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
9348
9489
  const path = url.slice(start, end);
9349
- return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
9490
+ const decoded = tryDecode(path, decodeURIWithPreservedPercent);
9491
+ if (/%(?![0-9A-Fa-f]{2})/.test(path)) {
9492
+ const rewritten = new URL("http://localhost");
9493
+ rewritten.pathname = decoded.replace(/[\\\t\n\r]/g, encodeURIComponent);
9494
+ if (tryDecode(rewritten.pathname, decodeURIWithPreservedPercent) !== decoded) return tryDecode(path.replace(/%(?![0-9A-Fa-f]{2})/g, "%25"), decodeURIWithPreservedPercent);
9495
+ }
9496
+ return decoded;
9350
9497
  } else if (charCode === 63 || charCode === 35) break;
9351
9498
  }
9352
9499
  return url.slice(start, i);
@@ -9397,17 +9544,22 @@ const _getQueryParam = (url, key, multiple) => {
9397
9544
  const hashIndex = url.indexOf("#", 8);
9398
9545
  if (hashIndex !== -1) url = url.slice(0, hashIndex);
9399
9546
  let encoded;
9400
- if (!multiple && key && key.indexOf("%") === -1 && key.indexOf("+") === -1) {
9401
- let keyIndex = url.indexOf("?", 8);
9547
+ if (!multiple && key && !/[%+&=]/.test(key)) {
9548
+ const queryIndex = url.indexOf("?", 8);
9549
+ let keyIndex = queryIndex;
9402
9550
  if (keyIndex === -1) return;
9403
9551
  if (!url.startsWith(key, keyIndex + 1)) keyIndex = url.indexOf(`&${key}`, keyIndex + 1);
9404
9552
  while (keyIndex !== -1) {
9405
9553
  const trailingKeyCode = url.charCodeAt(keyIndex + key.length + 1);
9406
- if (trailingKeyCode === 61) {
9407
- const valueIndex = keyIndex + key.length + 2;
9408
- const endIndex = url.indexOf("&", valueIndex);
9409
- return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
9410
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) return "";
9554
+ if (trailingKeyCode === 61 || trailingKeyCode === 38 || isNaN(trailingKeyCode)) {
9555
+ if (keyIndex > queryIndex && /(?:^|&)[^=&]*[%+]/.test(url.slice(queryIndex + 1, keyIndex))) break;
9556
+ if (trailingKeyCode === 61) {
9557
+ const valueIndex = keyIndex + key.length + 2;
9558
+ const endIndex = url.indexOf("&", valueIndex);
9559
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
9560
+ }
9561
+ return "";
9562
+ }
9411
9563
  keyIndex = url.indexOf(`&${key}`, keyIndex + 1);
9412
9564
  }
9413
9565
  encoded = /[%+]/.test(url);
@@ -9442,8 +9594,7 @@ const getQueryParams = (url, key) => {
9442
9594
  return _getQueryParam(url, key, true);
9443
9595
  };
9444
9596
  const decodeURIComponent_ = decodeURIComponent;
9445
- //#endregion
9446
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/request.js
9597
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/request.js
9447
9598
  var HonoRequest = class {
9448
9599
  /**
9449
9600
  * `.raw` can get the raw Request object.
@@ -9629,7 +9780,7 @@ var HonoRequest = class {
9629
9780
  return this.#validatedData?.[target];
9630
9781
  }
9631
9782
  /**
9632
- * `.url()` can get the request url strings.
9783
+ * `.url` can get the request url strings.
9633
9784
  *
9634
9785
  * @see {@link https://hono.dev/docs/api/request#url}
9635
9786
  *
@@ -9645,7 +9796,7 @@ var HonoRequest = class {
9645
9796
  return this.raw.url;
9646
9797
  }
9647
9798
  /**
9648
- * `.method()` can get the method name of the request.
9799
+ * `.method` can get the method name of the request.
9649
9800
  *
9650
9801
  * @see {@link https://hono.dev/docs/api/request#method}
9651
9802
  *
@@ -9663,7 +9814,7 @@ var HonoRequest = class {
9663
9814
  return this.#matchResult;
9664
9815
  }
9665
9816
  /**
9666
- * `.matchedRoutes()` can return a matched route in the handler
9817
+ * `.matchedRoutes` can return a matched route in the handler
9667
9818
  *
9668
9819
  * @deprecated
9669
9820
  *
@@ -9693,7 +9844,7 @@ var HonoRequest = class {
9693
9844
  return this.#matchResult[0].map(([[, route]]) => route);
9694
9845
  }
9695
9846
  /**
9696
- * `routePath()` can retrieve the path registered within the handler
9847
+ * `.routePath` can retrieve the path registered within the handler
9697
9848
  *
9698
9849
  * @deprecated
9699
9850
  *
@@ -9712,8 +9863,7 @@ var HonoRequest = class {
9712
9863
  return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
9713
9864
  }
9714
9865
  };
9715
- //#endregion
9716
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/utils/html.js
9866
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/html.js
9717
9867
  /**
9718
9868
  * @module
9719
9869
  * HTML utility.
@@ -9746,8 +9896,7 @@ const resolveCallback = async (str, phase, preserveCallbacks, context, buffer) =
9746
9896
  if (preserveCallbacks) return raw(await resStr, callbacks);
9747
9897
  else return resStr;
9748
9898
  };
9749
- //#endregion
9750
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/context.js
9899
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/context.js
9751
9900
  const TEXT_PLAIN = "text/plain; charset=UTF-8";
9752
9901
  const setDefaultContentType = (contentType, headers) => {
9753
9902
  return {
@@ -9944,7 +10093,7 @@ var Context = class {
9944
10093
  * ```
9945
10094
  */
9946
10095
  header = (name, value, options) => {
9947
- if (this.finalized) this.#res = createResponseInstance(this.#res.body, this.#res);
10096
+ if (this.finalized && !this.#res.bodyUsed) this.#res = createResponseInstance(this.#res.body, this.#res);
9948
10097
  const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
9949
10098
  if (value === void 0) headers.delete(name);
9950
10099
  else if (options?.append) headers.append(name, value);
@@ -10124,8 +10273,7 @@ var Context = class {
10124
10273
  return this.#notFoundHandler(this);
10125
10274
  };
10126
10275
  };
10127
- //#endregion
10128
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/compose.js
10276
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/compose.js
10129
10277
  /**
10130
10278
  * Compose middleware functions into a single function based on `koa-compose` package.
10131
10279
  *
@@ -10173,8 +10321,58 @@ const compose = (middleware, onError, onNotFound) => {
10173
10321
  }
10174
10322
  };
10175
10323
  };
10176
- //#endregion
10177
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/router.js
10324
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/helper/route/index.js
10325
+ /**
10326
+ * Get matched routes in the handler
10327
+ *
10328
+ * @param {Context} c - The context object
10329
+ * @returns An array of matched routes
10330
+ *
10331
+ * @example
10332
+ * ```ts
10333
+ * import { matchedRoutes } from 'hono/route'
10334
+ *
10335
+ * app.use('*', async function logger(c, next) {
10336
+ * await next()
10337
+ * matchedRoutes(c).forEach(({ handler, method, path }, i) => {
10338
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
10339
+ * console.log(
10340
+ * method,
10341
+ * ' ',
10342
+ * path,
10343
+ * ' '.repeat(Math.max(10 - path.length, 0)),
10344
+ * name,
10345
+ * i === c.req.routeIndex ? '<- respond from here' : ''
10346
+ * )
10347
+ * })
10348
+ * })
10349
+ * ```
10350
+ */
10351
+ const matchedRoutes = (c) => c.req[GET_MATCH_RESULT][0].map(([[, route]]) => route);
10352
+ /**
10353
+ * Get the route path registered within the handler
10354
+ *
10355
+ * @param {Context} c - The context object
10356
+ * @param {number} index - The index of the route from which to retrieve the path, similar to Array.prototype.at(), where a negative number is the index counted from the end of the matching route. Defaults to the current route index.
10357
+ * @returns The route path registered within the handler
10358
+ *
10359
+ * @example
10360
+ * ```ts
10361
+ * import { routePath } from 'hono/route'
10362
+ *
10363
+ * app.use('*', (c, next) => {
10364
+ * console.log(routePath(c)) // '*'
10365
+ * console.log(routePath(c, -1)) // '/posts/:id'
10366
+ * return next()
10367
+ * })
10368
+ *
10369
+ * app.get('/posts/:id', (c) => {
10370
+ * return c.text(routePath(c)) // '/posts/:id'
10371
+ * })
10372
+ * ```
10373
+ */
10374
+ const routePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.path ?? "";
10375
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router.js
10178
10376
  /**
10179
10377
  * Array of supported HTTP methods.
10180
10378
  */
@@ -10195,14 +10393,57 @@ const MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher
10195
10393
  * Error class representing an unsupported path error.
10196
10394
  */
10197
10395
  var UnsupportedPathError = class extends Error {};
10198
- //#endregion
10199
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/utils/constants.js
10396
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/constants.js
10200
10397
  /**
10201
10398
  * Constant used to mark a composed handler.
10202
10399
  */
10203
10400
  const COMPOSED_HANDLER = "__COMPOSED_HANDLER";
10204
- //#endregion
10205
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/hono-base.js
10401
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/mount.js
10402
+ const countTrailingSlashes = (path) => {
10403
+ let index = path.length;
10404
+ while (index > 0 && path.charCodeAt(index - 1) === 47) index--;
10405
+ return path.length - index;
10406
+ };
10407
+ const getPathPrefixLength = (c, pathPrefix, routePath) => {
10408
+ if (!/[:*]/.test(pathPrefix)) return pathPrefix.length;
10409
+ const path = c.req.path;
10410
+ const matchResult = c.req[GET_MATCH_RESULT];
10411
+ const paramNames = /* @__PURE__ */ new Set();
10412
+ let length = 0;
10413
+ for (const part of splitRoutingPath(pathPrefix)) {
10414
+ if (part[0] === ":" && part.endsWith("}?")) throw new Error(`mount(): Optional regular expression parameters are not supported in "${routePath}".`);
10415
+ const pattern = getPattern(part);
10416
+ if (pattern && pattern !== "*") {
10417
+ const name = pattern[1];
10418
+ if (paramNames.has(name)) throw new Error(`mount(): Duplicate path parameter "${name}" in "${routePath}".`);
10419
+ paramNames.add(name);
10420
+ }
10421
+ if (pattern && pattern !== "*" && pattern[2] !== true) {
10422
+ const value = matchResult.length === 2 ? matchResult[1][matchResult[0][c.req.routeIndex][1][pattern[1]]] : matchResult[0][c.req.routeIndex][1][pattern[1]];
10423
+ length += value.length + 1;
10424
+ } else if (pattern || part.endsWith("*")) {
10425
+ const end = path.indexOf("/", length + 1);
10426
+ length = end === -1 ? path.length : end;
10427
+ } else length += part.length + 1;
10428
+ }
10429
+ return length;
10430
+ };
10431
+ const createMountedRequest = (c, pathPrefix, routePath) => {
10432
+ if (/[^/]\*$/.test(routePath)) throw new Error(`mount(): Wildcard must follow "/" in "${routePath}".`);
10433
+ const prefixLength = getPathPrefixLength(c, pathPrefix, routePath);
10434
+ const path = c.req.path.slice(prefixLength) || "/";
10435
+ if (prefixLength > c.req.path.length || path[0] !== "/" || /\/(?:\.|%2e){1,2}(?:\/|$)/i.test(path)) throw new HTTPException(400, { message: "Invalid mounted path" });
10436
+ const rawUrl = c.req.raw.url;
10437
+ if (/^[^/?#]*\/\/[^/?#\\]*[?#\\]/.test(rawUrl)) throw new HTTPException(400, { message: "Invalid mounted path" });
10438
+ const rawPathEnd = rawUrl.search(/[?#]/);
10439
+ const rawTrailingSlashes = countTrailingSlashes(rawPathEnd === -1 ? rawUrl : rawUrl.slice(0, rawPathEnd));
10440
+ if (rawTrailingSlashes > 1 && countTrailingSlashes(c.req.path) === rawTrailingSlashes - 1) throw new HTTPException(400, { message: "Invalid mounted path" });
10441
+ const url = new URL(rawUrl);
10442
+ url.pathname = path.replace(/[\\\t\n\r]/g, encodeURIComponent);
10443
+ if (path.includes("%")) {}
10444
+ return new Request(url, c.req.raw);
10445
+ };
10446
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/hono-base.js
10206
10447
  /**
10207
10448
  * @module
10208
10449
  * This module is the base module for the Hono object.
@@ -10374,12 +10615,16 @@ var Hono$1 = class Hono {
10374
10615
  /**
10375
10616
  * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
10376
10617
  *
10618
+ * @deprecated Use `mount()` from `hono/mount` instead. `.mount()` will be removed in v5.
10619
+ *
10377
10620
  * @see {@link https://hono.dev/docs/api/hono#mount}
10378
10621
  *
10379
10622
  * @param {string} path - base Path
10380
10623
  * @param {Function} applicationHandler - other Request Handler
10381
10624
  * @param {MountOptions} [options] - options of `.mount()`
10382
10625
  * @returns {Hono} mounted Hono instance
10626
+ * @throws {Error} If automatic request rewriting encounters duplicate path parameter names or an optional regular expression parameter.
10627
+ * @throws {HTTPException} With status 400 if automatic request rewriting cannot safely preserve the routed path.
10383
10628
  *
10384
10629
  * @example
10385
10630
  * ```ts
@@ -10424,17 +10669,12 @@ var Hono$1 = class Hono {
10424
10669
  } catch {}
10425
10670
  return [c.env, executionContext];
10426
10671
  };
10427
- replaceRequest ||= (() => {
10428
- const mergedPath = mergePath(this._basePath, path);
10429
- const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
10430
- return (request) => {
10431
- const url = new URL(request.url);
10432
- url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
10433
- return new Request(url, request);
10434
- };
10435
- })();
10672
+ const defaultReplaceRequest = (c) => {
10673
+ const mountedRoutePath = routePath(c);
10674
+ return createMountedRequest(c, mountedRoutePath.replace(/\/?\*$/, ""), mountedRoutePath);
10675
+ };
10436
10676
  const handler = async (c, next) => {
10437
- const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
10677
+ const res = await applicationHandler(replaceRequest ? replaceRequest(c.req.raw) : defaultReplaceRequest(c), ...getOptions(c));
10438
10678
  if (res) return res;
10439
10679
  await next();
10440
10680
  };
@@ -10543,11 +10783,9 @@ var Hono$1 = class Hono {
10543
10783
  });
10544
10784
  };
10545
10785
  };
10546
- //#endregion
10547
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/router/utils.js
10786
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router/utils.js
10548
10787
  const createNullObject = () => Object.create(null);
10549
- //#endregion
10550
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/router/reg-exp-router/matcher.js
10788
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router/reg-exp-router/matcher.js
10551
10789
  const emptyParam = [];
10552
10790
  function match(method, path) {
10553
10791
  const matchers = this.buildAllMatchers();
@@ -10563,10 +10801,10 @@ function match(method, path) {
10563
10801
  this.match = match;
10564
10802
  return match(method, path);
10565
10803
  }
10566
- //#endregion
10567
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/router/reg-exp-router/node.js
10804
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router/reg-exp-router/node.js
10568
10805
  const LABEL_REG_EXP_STR = "[^/]+";
10569
- const TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
10806
+ const ONLY_WILDCARD_REG_EXP_STR = "[^]*";
10807
+ const TAIL_WILDCARD_REG_EXP_STR = "(?:|/[^]*)";
10570
10808
  const PATH_ERROR = Symbol();
10571
10809
  const regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
10572
10810
  /**
@@ -10579,8 +10817,8 @@ const regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
10579
10817
  function compareKey(a, b) {
10580
10818
  if (a.length === 1) return b.length === 1 ? a < b ? -1 : 1 : -1;
10581
10819
  if (b.length === 1) return 1;
10582
- if (a === ".*" || a === "(?:|/.*)") return b === "(?:|/.*)" ? -1 : 1;
10583
- else if (b === ".*" || b === "(?:|/.*)") return -1;
10820
+ if (a === "[^]*" || a === "(?:|/[^]*)") return b === "[^]*" ? -1 : 1;
10821
+ else if (b === "[^]*" || b === "(?:|/[^]*)") return -1;
10584
10822
  if (a === "[^/]+") return 1;
10585
10823
  else if (b === "[^/]+") return -1;
10586
10824
  return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
@@ -10589,14 +10827,14 @@ var Node$1 = class Node {
10589
10827
  #index;
10590
10828
  #varIndex;
10591
10829
  #children = createNullObject();
10592
- insert(tokens, index, paramMap, context, isStatic) {
10830
+ insert(tokens, index, paramMap, context, keys) {
10593
10831
  let node = this;
10594
10832
  for (let i = 0, len = tokens.length; i < len; i++) {
10595
10833
  const token = tokens[i];
10596
10834
  const pattern = token.length === 1 ? token === "*" ? i === len - 1 ? [
10597
10835
  "",
10598
10836
  "",
10599
- ".*"
10837
+ ONLY_WILDCARD_REG_EXP_STR
10600
10838
  ] : [
10601
10839
  "",
10602
10840
  "",
@@ -10611,15 +10849,16 @@ var Node$1 = class Node {
10611
10849
  const name = pattern[1];
10612
10850
  let regexpStr = pattern[2] || "[^/]+";
10613
10851
  if (name && pattern[2]) {
10614
- if (regexpStr === ".*") throw PATH_ERROR;
10852
+ if (new RegExp(regexpStr).test("")) throw PATH_ERROR;
10615
10853
  regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
10616
10854
  if (/\((?!\?:)/.test(regexpStr)) throw PATH_ERROR;
10617
10855
  if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) throw PATH_ERROR;
10618
10856
  }
10857
+ keys.push(regexpStr);
10619
10858
  nextNode = node.#children[regexpStr];
10620
10859
  if (!nextNode) {
10621
- if (regexpStr !== ".*" && regexpStr !== "(?:|/.*)") {
10622
- for (const k in node.#children) if ((regexpStr.length > 1 || k.length > 1) && k !== ".*" && k !== "(?:|/.*)") throw PATH_ERROR;
10860
+ if (regexpStr !== "[^]*" && regexpStr !== "(?:|/[^]*)") {
10861
+ for (const k in node.#children) if ((regexpStr.length > 1 || k.length > 1) && k !== "[^]*" && k !== "(?:|/[^]*)") throw PATH_ERROR;
10623
10862
  }
10624
10863
  nextNode = node.#children[regexpStr] = new Node();
10625
10864
  }
@@ -10628,16 +10867,17 @@ var Node$1 = class Node {
10628
10867
  paramMap.push([name, nextNode.#varIndex]);
10629
10868
  }
10630
10869
  } else {
10870
+ keys.push(token);
10631
10871
  nextNode = node.#children[token];
10632
10872
  if (!nextNode) {
10633
- for (const k in node.#children) if (k.length > 1 && k !== ".*" && k !== "(?:|/.*)") throw PATH_ERROR;
10873
+ for (const k in node.#children) if (k.length > 1 && k !== "[^]*" && k !== "(?:|/[^]*)") throw PATH_ERROR;
10634
10874
  nextNode = node.#children[token] = new Node();
10635
10875
  }
10636
10876
  }
10637
10877
  node = nextNode;
10638
10878
  }
10639
10879
  if (node.#index !== void 0) throw PATH_ERROR;
10640
- node.#index = isStatic ? -1 : index;
10880
+ node.#index = index;
10641
10881
  }
10642
10882
  buildRegExpStr() {
10643
10883
  const strList = Object.keys(this.#children).sort(compareKey).map((k) => {
@@ -10651,16 +10891,21 @@ var Node$1 = class Node {
10651
10891
  return "(?:" + strList.join("|") + ")";
10652
10892
  }
10653
10893
  };
10654
- //#endregion
10655
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/router/reg-exp-router/trie.js
10894
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router/reg-exp-router/trie.js
10656
10895
  var Trie = class {
10657
10896
  #context = { varIndex: 0 };
10658
10897
  #root = new Node$1();
10659
10898
  #index = 0;
10660
10899
  paths = createNullObject();
10661
10900
  insert(path, isStatic) {
10901
+ const keys = [];
10662
10902
  if (isStatic) {
10663
- this.#root.insert(path.split(""), 0, [], this.#context, true);
10903
+ this.#root.insert(path.split(""), -1, [], this.#context, keys);
10904
+ this.paths[path] = [
10905
+ -1,
10906
+ [],
10907
+ keys
10908
+ ];
10664
10909
  return;
10665
10910
  }
10666
10911
  const paramAssoc = [];
@@ -10668,7 +10913,7 @@ var Trie = class {
10668
10913
  let markedPath = path;
10669
10914
  for (let i = 0;;) {
10670
10915
  let replaced = false;
10671
- markedPath = markedPath.replace(/\{[^}]+\}/g, (m) => {
10916
+ markedPath = markedPath.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g, (m) => {
10672
10917
  const mark = `@\\${i}`;
10673
10918
  groups[i] = [mark, m];
10674
10919
  i++;
@@ -10682,7 +10927,7 @@ var Trie = class {
10682
10927
  * - /* wildcard
10683
10928
  * - character
10684
10929
  */
10685
- const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
10930
+ const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./gs) || [];
10686
10931
  for (let i = groups.length - 1; i >= 0; i--) {
10687
10932
  const [mark] = groups[i];
10688
10933
  for (let j = tokens.length - 1; j >= 0; j--) if (tokens[j].indexOf(mark) !== -1) {
@@ -10690,8 +10935,12 @@ var Trie = class {
10690
10935
  break;
10691
10936
  }
10692
10937
  }
10693
- this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false);
10694
- this.paths[path] = [this.#index++, paramAssoc];
10938
+ this.#root.insert(tokens, this.#index, paramAssoc, this.#context, keys);
10939
+ this.paths[path] = [
10940
+ this.#index++,
10941
+ paramAssoc,
10942
+ keys
10943
+ ];
10695
10944
  }
10696
10945
  buildRegExp() {
10697
10946
  let regexp = this.#root.buildRegExpStr();
@@ -10721,23 +10970,22 @@ var Trie = class {
10721
10970
  ];
10722
10971
  }
10723
10972
  };
10724
- //#endregion
10725
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/router/reg-exp-router/router.js
10726
- let wildcardRegExpCache = createNullObject();
10727
- function buildWildcardRegExp(path) {
10728
- return wildcardRegExpCache[path] ??= new RegExp(`^${path.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g, (match, metaChar) => metaChar ? `\\${metaChar}` : match === "/*" ? TAIL_WILDCARD_REG_EXP_STR : match === "*" ? ".*" : `/:${LABEL_REG_EXP_STR}`)}$`);
10973
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router/reg-exp-router/router.js
10974
+ function endsWithWildcard(keys) {
10975
+ const tail = keys[keys.length - 1];
10976
+ return tail === "[^]*" || tail === "(?:|/[^]*)";
10729
10977
  }
10730
- function findMiddleware(middleware, path) {
10731
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) if (buildWildcardRegExp(k).test(path)) return [...middleware[k]];
10978
+ function covers(wildcard, target) {
10979
+ const last = wildcard.length - 1;
10980
+ for (let i = 0; i < last; i++) if (wildcard[i] !== target[i]) return false;
10981
+ return wildcard[last] === "[^]*" || target.length === last || target[last] === "/";
10732
10982
  }
10733
10983
  var RegExpRouter = class {
10734
10984
  name = "RegExpRouter";
10735
- #middleware;
10736
- #routes;
10985
+ #handlers;
10737
10986
  #tries;
10738
10987
  constructor() {
10739
- this.#middleware = { ["ALL"]: createNullObject() };
10740
- this.#routes = { ["ALL"]: createNullObject() };
10988
+ this.#handlers = { ["ALL"]: [] };
10741
10989
  this.#tries = { ["ALL"]: new Trie() };
10742
10990
  }
10743
10991
  #insertPath(method, path) {
@@ -10748,65 +10996,53 @@ var RegExpRouter = class {
10748
10996
  }
10749
10997
  }
10750
10998
  add(method, path, handler) {
10751
- const middleware = this.#middleware;
10752
- const routes = this.#routes;
10753
- if (!middleware) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
10754
- if (!middleware[method]) {
10755
- this.#tries[method] = new Trie();
10756
- for (const handlerMap of [middleware, routes]) {
10757
- handlerMap[method] = createNullObject();
10758
- for (const p in handlerMap["ALL"]) {
10759
- handlerMap[method][p] = [...handlerMap["ALL"][p]];
10760
- this.#insertPath(method, p);
10761
- }
10762
- }
10999
+ const handlers = this.#handlers;
11000
+ if (!handlers) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
11001
+ const tries = this.#tries;
11002
+ if (!handlers[method]) {
11003
+ tries[method] = new Trie();
11004
+ handlers[method] = [...handlers["ALL"]];
11005
+ for (const p in tries["ALL"].paths) this.#insertPath(method, p);
10763
11006
  }
10764
11007
  if (path === "/*") path = "*";
10765
- const methods = method === "ALL" ? Object.keys(middleware) : [method];
10766
- if (/\*$/.test(path)) {
10767
- const re = buildWildcardRegExp(path);
10768
- for (const m of methods) if (!middleware[m][path]) {
10769
- this.#insertPath(m, path);
10770
- middleware[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware["ALL"], path) || [];
10771
- }
10772
- for (const handlerMap of [middleware, routes]) for (const m of methods) for (const p in handlerMap[m]) re.test(p) && handlerMap[m][p].push([handler, path]);
10773
- return;
10774
- }
11008
+ const methods = method === "ALL" ? Object.keys(handlers) : [method];
10775
11009
  const paths = checkOptionalParameter(path) || [path];
10776
11010
  for (const path of paths) for (const m of methods) {
10777
- if (!routes[m][path]) {
10778
- this.#insertPath(m, path);
10779
- routes[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware["ALL"], path) || [];
10780
- }
10781
- routes[m][path].push([handler, path]);
11011
+ if (!tries[m].paths[path]) this.#insertPath(m, path);
11012
+ handlers[m].push([handler, path]);
10782
11013
  }
10783
11014
  }
10784
11015
  match = match;
10785
11016
  buildAllMatchers() {
10786
11017
  const matchers = createNullObject();
10787
- for (const method of Object.keys(this.#routes)) matchers[method] = this.#buildMatcher(method);
10788
- this.#middleware = this.#routes = this.#tries = void 0;
10789
- wildcardRegExpCache = createNullObject();
11018
+ for (const method of Object.keys(this.#handlers)) matchers[method] = this.#buildMatcher(method);
11019
+ this.#handlers = this.#tries = void 0;
10790
11020
  return matchers;
10791
11021
  }
10792
11022
  #buildMatcher(method) {
10793
- const middleware = this.#middleware[method];
10794
- const routes = this.#routes[method];
11023
+ const handlers = this.#handlers[method];
10795
11024
  const trie = this.#tries[method];
10796
11025
  const staticMap = createNullObject();
10797
11026
  const handlerData = [];
10798
11027
  const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
10799
- for (const r of [middleware, routes]) for (const path in r) {
10800
- const handlers = r[path];
10801
- const pathData = trie.paths[path];
10802
- if (!pathData) {
10803
- staticMap[path] = [handlers.map(([h]) => [h, createNullObject()]), emptyParam];
10804
- continue;
10805
- }
10806
- handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [h, trie.paths[handlerPath][1].reduceRight((map, [key], i) => {
10807
- map[key] = paramReplacementMap[pathData[1][i][1]];
11028
+ const own = createNullObject();
11029
+ const entries = handlers.map(([h, p], i) => {
11030
+ (own[p] ??= []).push(i);
11031
+ return [h, trie.paths[p][1].reduceRight((map, [key, varIndex]) => {
11032
+ map[key] = paramReplacementMap[varIndex];
10808
11033
  return map;
10809
- }, createNullObject())]);
11034
+ }, createNullObject())];
11035
+ });
11036
+ const wildcards = Object.keys(own).filter((p) => endsWithWildcard(trie.paths[p][2]));
11037
+ for (const path in trie.paths) {
11038
+ const [index, , keys] = trie.paths[path];
11039
+ const indexes = [...own[path]];
11040
+ for (const p of wildcards) if (p !== path && covers(trie.paths[p][2], keys)) indexes.push(...own[p]);
11041
+ const data = indexes.sort((a, b) => a - b).map((i) => entries[i]);
11042
+ if (index === -1) {
11043
+ const last = Math.max(-1, ...data.flatMap(([, map]) => Object.values(map)));
11044
+ staticMap[path] = [data, last === -1 ? emptyParam : path.match(regexp).slice(0, last + 1)];
11045
+ } else handlerData[index] = data;
10810
11046
  }
10811
11047
  return [
10812
11048
  regexp,
@@ -10815,8 +11051,7 @@ var RegExpRouter = class {
10815
11051
  ];
10816
11052
  }
10817
11053
  };
10818
- //#endregion
10819
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/router/smart-router/router.js
11054
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router/smart-router/router.js
10820
11055
  var SmartRouter = class {
10821
11056
  name = "SmartRouter";
10822
11057
  #routers = [];
@@ -10862,8 +11097,7 @@ var SmartRouter = class {
10862
11097
  return this.#routers[0];
10863
11098
  }
10864
11099
  };
10865
- //#endregion
10866
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/router/trie-router/node.js
11100
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router/trie-router/node.js
10867
11101
  const emptyParams = createNullObject();
10868
11102
  let order = 0;
10869
11103
  var Node = class Node {
@@ -10959,7 +11193,7 @@ var Node = class Node {
10959
11193
  const restPathString = path.slice(partOffsets[i]);
10960
11194
  const m = matcher.exec(restPathString);
10961
11195
  if (m) {
10962
- params[name] = m[0];
11196
+ if (!Object.hasOwn(params, name)) params[name] = m[0];
10963
11197
  this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
10964
11198
  if (m[0].length === restPathString.length && child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, node.#params, params);
10965
11199
  for (const _ in child.#children) {
@@ -10972,7 +11206,7 @@ var Node = class Node {
10972
11206
  }
10973
11207
  }
10974
11208
  if (matcher === true || matcher.test(part)) {
10975
- params[name] = part;
11209
+ if (!Object.hasOwn(params, name)) params[name] = part;
10976
11210
  if (isLast) {
10977
11211
  this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
10978
11212
  if (child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
@@ -10992,8 +11226,7 @@ var Node = class Node {
10992
11226
  return [handlerSets.map(({ handler, params }) => [handler, params])];
10993
11227
  }
10994
11228
  };
10995
- //#endregion
10996
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/router/trie-router/router.js
11229
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router/trie-router/router.js
10997
11230
  var TrieRouter = class {
10998
11231
  name = "TrieRouter";
10999
11232
  #node = new Node();
@@ -11004,8 +11237,7 @@ var TrieRouter = class {
11004
11237
  return this.#node.search(method, path);
11005
11238
  }
11006
11239
  };
11007
- //#endregion
11008
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/hono.js
11240
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/hono.js
11009
11241
  /**
11010
11242
  * The Hono class extends the functionality of the HonoBase class.
11011
11243
  * It sets up routing and allows for custom options to be passed.
@@ -11025,8 +11257,7 @@ var Hono = class extends Hono$1 {
11025
11257
  this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()] });
11026
11258
  }
11027
11259
  };
11028
- //#endregion
11029
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/utils/stream.js
11260
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/stream.js
11030
11261
  /**
11031
11262
  * @module
11032
11263
  * Stream utility.
@@ -11112,8 +11343,7 @@ var StreamingApi = class {
11112
11343
  }
11113
11344
  }
11114
11345
  };
11115
- //#endregion
11116
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/helper/streaming/utils.js
11346
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/helper/streaming/utils.js
11117
11347
  let isOldBunVersion = () => {
11118
11348
  const version = typeof Bun !== "undefined" ? Bun.version : void 0;
11119
11349
  if (version === void 0) return false;
@@ -11121,8 +11351,7 @@ let isOldBunVersion = () => {
11121
11351
  isOldBunVersion = () => result;
11122
11352
  return result;
11123
11353
  };
11124
- //#endregion
11125
- //#region ../../node_modules/.pnpm/hono@4.13.12/node_modules/hono/dist/helper/streaming/sse.js
11354
+ // ../../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/helper/streaming/sse.js
11126
11355
  var SSEStreamingApi = class extends StreamingApi {
11127
11356
  constructor(writable, readable) {
11128
11357
  super(writable, readable);
@@ -11174,8 +11403,7 @@ const streamSSE = (c, cb, onError) => {
11174
11403
  run(stream, cb, onError);
11175
11404
  return c.newResponse(stream.responseReadable);
11176
11405
  };
11177
- //#endregion
11178
- //#region src/server/http/event-queue.ts
11406
+ // src/server/http/event-queue.ts
11179
11407
  function createEventQueue(options) {
11180
11408
  const limit = options.limit ?? LIMITS.ssePendingEvents;
11181
11409
  const now = options.now ?? Date.now;
@@ -11233,8 +11461,7 @@ function createEventQueue(options) {
11233
11461
  }
11234
11462
  };
11235
11463
  }
11236
- //#endregion
11237
- //#region src/server/http/event-stream.ts
11464
+ // src/server/http/event-stream.ts
11238
11465
  function createEventStreams() {
11239
11466
  const streams = /* @__PURE__ */ new Map();
11240
11467
  return {
@@ -11302,8 +11529,7 @@ function createEventStreams() {
11302
11529
  }
11303
11530
  };
11304
11531
  }
11305
- //#endregion
11306
- //#region src/server/http/management.ts
11532
+ // src/server/http/management.ts
11307
11533
  const API_PREFIX$1 = "/_/api/v1";
11308
11534
  const STREAM_FLUSH_MS$1 = 100;
11309
11535
  const CLOSE_GRACE_MS$2 = 1e3;
@@ -11420,6 +11646,7 @@ const linesQuerySchema = string().regex(/^\d+:\d+$/).transform((value) => {
11420
11646
  };
11421
11647
  });
11422
11648
  const integerQuery = string().regex(/^\d+$/).transform(Number);
11649
+ const booleanQuery = _enum(["true", "false"]).transform((value) => value === "true");
11423
11650
  async function startManagementServer(deps, options = {}) {
11424
11651
  const assets = await loadStaticAssets(deps.webRoot);
11425
11652
  const app = new Hono();
@@ -11454,7 +11681,7 @@ async function startManagementServer(deps, options = {}) {
11454
11681
  const method = c.req.method;
11455
11682
  if (method !== "GET" && method !== "HEAD") {
11456
11683
  if (requestOrigin === void 0) return fail$1(c, new VdeError("E_UNAUTHORIZED", "A request without Origin cannot make changes."));
11457
- if (Number(c.req.header("content-length") ?? "0") > 0 && !(c.req.header("content-type") ?? "").startsWith("application/json")) return fail$1(c, new VdeError("E_INVALID_ARGUMENT", "The body must be sent as JSON."));
11684
+ if ((Number(c.req.header("content-length") ?? "0") > 0 || c.req.header("transfer-encoding") !== void 0) && !(c.req.header("content-type") ?? "").startsWith("application/json")) return fail$1(c, new VdeError("E_INVALID_ARGUMENT", "The body must be sent as JSON."));
11458
11685
  }
11459
11686
  if (deps.isStopping()) return fail$1(c, new VdeError("E_DAEMON_STOPPING", "The daemon is stopping."));
11460
11687
  return next();
@@ -11468,7 +11695,8 @@ async function startManagementServer(deps, options = {}) {
11468
11695
  catalogVersion: state.catalogVersion,
11469
11696
  activeDocumentId: state.activeDocumentId,
11470
11697
  openDocuments: state.openOrder.length,
11471
- previewOrigin: deps.previewOrigin
11698
+ previewOrigin: deps.previewOrigin,
11699
+ phoneUrl: deps.phoneUrl
11472
11700
  };
11473
11701
  return c.json(successEnvelope(status, {
11474
11702
  command: "status",
@@ -11521,6 +11749,13 @@ async function startManagementServer(deps, options = {}) {
11521
11749
  "Content-Disposition": "attachment"
11522
11750
  });
11523
11751
  });
11752
+ api.get("/documents/:id/file", async (c) => {
11753
+ const bytes = await deps.documents.readCurrentSource(c.req.param("id"));
11754
+ return c.body(new Uint8Array(bytes), 200, {
11755
+ "Content-Type": "application/octet-stream",
11756
+ "Content-Disposition": "attachment"
11757
+ });
11758
+ });
11524
11759
  api.get("/search", async (c) => {
11525
11760
  const { query, mode, limit, maxBytes, cursor } = c.req.query();
11526
11761
  const documents = c.req.queries("document") ?? [];
@@ -11534,8 +11769,11 @@ async function startManagementServer(deps, options = {}) {
11534
11769
  }));
11535
11770
  });
11536
11771
  api.get("/feedback", (c) => {
11537
- const status = c.req.query("status");
11538
- return ok(c, "feedback.list", deps.feedback.list(status === void 0 ? {} : { status }));
11772
+ const { status, acknowledged } = c.req.query();
11773
+ return ok(c, "feedback.list", deps.feedback.list({
11774
+ ...status === void 0 ? {} : { status },
11775
+ ...acknowledged === void 0 ? {} : { acknowledged: booleanQuery.parse(acknowledged) }
11776
+ }));
11539
11777
  });
11540
11778
  api.get("/feedback/:id", (c) => ok(c, "feedback.get", deps.feedback.getForUi(requestIdSchema.parse(c.req.param("id")))));
11541
11779
  api.put("/feedback/:id/draft", async (c) => {
@@ -11682,8 +11920,49 @@ async function startManagementServer(deps, options = {}) {
11682
11920
  }
11683
11921
  };
11684
11922
  }
11685
- //#endregion
11686
- //#region src/server/http/mobile.ts
11923
+ // src/server/http/mobile-location.ts
11924
+ function mobileLocationOf(summary, labels, opaque) {
11925
+ const nameOf = (key, nameSegments) => {
11926
+ const label = labels.repository.get(key) ?? "";
11927
+ const parts = label.split("/").length;
11928
+ if (parts === 1 || parts === 2 && nameSegments.length > 2) return label;
11929
+ return `${nameSegments.at(-1) ?? ""} (${opaque(key).slice(0, 6)})`;
11930
+ };
11931
+ const pathOf = (folder, within) => dirname(folder) === folder ? within.slice(-1) : [...within];
11932
+ const placement = placementOf(summary);
11933
+ const fileName = summary.pathSegments.at(-1) ?? summary.title;
11934
+ switch (placement.kind) {
11935
+ case "input": return { kind: summary.sourceKind === "stdin" ? "stdin" : "generated" };
11936
+ case "outside":
11937
+ case "pending": return {
11938
+ kind: placement.kind,
11939
+ fileName
11940
+ };
11941
+ case "unresolved": return {
11942
+ kind: "unresolved",
11943
+ key: opaque(placement.key),
11944
+ name: nameOf(placement.key, placement.repository.nameSegments),
11945
+ reason: placement.repository.reason,
11946
+ path: pathOf(placement.repository.id, placement.repository.pathInCheckout)
11947
+ };
11948
+ case "repository": {
11949
+ const checkout = placement.repository.checkout;
11950
+ return {
11951
+ kind: "repository",
11952
+ key: opaque(placement.key),
11953
+ name: nameOf(placement.key, placement.repository.nameSegments),
11954
+ checkout: checkout === null ? { kind: "unknown" } : checkout.kind === "main" ? { kind: "main" } : {
11955
+ kind: "linked",
11956
+ key: opaque(`checkout:${checkout.id}`),
11957
+ label: labels.worktree.get(checkout.id) ?? checkout.name,
11958
+ full: worktreeText(checkout, labels)
11959
+ },
11960
+ path: pathOf(checkout?.id ?? dirname(placement.repository.id), placement.repository.pathInCheckout)
11961
+ };
11962
+ }
11963
+ }
11964
+ }
11965
+ // src/server/http/mobile.ts
11687
11966
  const API_PREFIX = "/_/mobile/v1";
11688
11967
  const STREAM_FLUSH_MS = 100;
11689
11968
  const CLOSE_GRACE_MS$1 = 1e3;
@@ -11820,11 +12099,15 @@ async function startMobileServer(deps, options) {
11820
12099
  if (deps.isStopping()) return fail(c, new VdeError("E_DAEMON_STOPPING", "Stopping."));
11821
12100
  return next();
11822
12101
  });
11823
- const rowOf = (summary) => ({
12102
+ const salt = randomBytes(32);
12103
+ const opaque = (value) => createHmac("sha256", salt).update(value).digest("base64url");
12104
+ const rowOf = (summary, labels) => ({
11824
12105
  documentId: summary.documentId,
11825
12106
  title: summary.title,
11826
12107
  format: summary.format,
12108
+ location: mobileLocationOf(summary, labels, opaque),
11827
12109
  openedAt: summary.openedAt,
12110
+ updatedAt: summary.updatedAt,
11828
12111
  revision: summary.revision,
11829
12112
  sourceState: summary.sourceState,
11830
12113
  effectiveMode: summary.format === "html" ? summary.interactiveAllowed ? "interactive" : "static" : null,
@@ -11836,6 +12119,19 @@ async function startMobileServer(deps, options) {
11836
12119
  if (record.currentRevision !== revision || views.of(documentId) !== viewEpoch) throw new VdeError("E_VIEW_STALE", "Stale.");
11837
12120
  return record;
11838
12121
  };
12122
+ const labelsOfAllOpen = () => {
12123
+ const all = [];
12124
+ let cursor = null;
12125
+ do {
12126
+ const page = documents.list({
12127
+ limit: LIMITS.listLimitMax,
12128
+ ...cursor === null ? {} : { cursor }
12129
+ });
12130
+ all.push(...page.data.documents);
12131
+ cursor = page.data.nextCursor;
12132
+ } while (cursor !== null);
12133
+ return buildLabels(all);
12134
+ };
11839
12135
  const api = new Hono();
11840
12136
  api.get("/documents", (c) => {
11841
12137
  const cursor = c.req.query("cursor");
@@ -11850,10 +12146,11 @@ async function startMobileServer(deps, options) {
11850
12146
  limit: limit === void 0 ? LIMITS.listLimitMax : limitQuery.parse(limit),
11851
12147
  ...inner === void 0 ? {} : { cursor: inner }
11852
12148
  });
12149
+ const labels = labelsOfAllOpen();
11853
12150
  const data = {
11854
12151
  daemonId: deps.daemonId,
11855
12152
  catalogVersion: result.catalogVersion,
11856
- documents: result.data.documents.map(rowOf),
12153
+ documents: result.data.documents.map((summary) => rowOf(summary, labels)),
11857
12154
  nextCursor: result.data.nextCursor === null ? null : cursors.encode({
11858
12155
  op: "mobile-list",
11859
12156
  inner: result.data.nextCursor,
@@ -11919,6 +12216,23 @@ async function startMobileServer(deps, options) {
11919
12216
  catalogVersion: documents.state.catalogVersion
11920
12217
  }));
11921
12218
  });
12219
+ api.post("/documents/:id/close", async (c) => {
12220
+ mobileCloseParamsSchema.parse(await jsonBody(c));
12221
+ const documentId = documentIdSchema.parse(c.req.param("id"));
12222
+ try {
12223
+ await documents.close({
12224
+ cwd: "/",
12225
+ targets: [documentId],
12226
+ all: false
12227
+ });
12228
+ } catch (error) {
12229
+ if (!isVdeError(error) || error.code !== "E_DOCUMENT_NOT_FOUND") throw error;
12230
+ }
12231
+ return c.json(successEnvelope({}, {
12232
+ command: "mobile.close",
12233
+ catalogVersion: documents.state.catalogVersion
12234
+ }));
12235
+ });
11922
12236
  api.post("/render-grants/release", async (c) => {
11923
12237
  const { grants } = mobileReleaseParamsSchema.parse(await jsonBody(c));
11924
12238
  return c.json(successEnvelope({ released: render.releaseMobile(grants) }, { command: "mobile.render-release" }));
@@ -12019,8 +12333,7 @@ async function startMobileServer(deps, options) {
12019
12333
  }
12020
12334
  };
12021
12335
  }
12022
- //#endregion
12023
- //#region src/server/http/preview.ts
12336
+ // src/server/http/preview.ts
12024
12337
  const CLOSE_GRACE_MS = 1e3;
12025
12338
  const PREVIEW_PATH = /^\/r\/([A-Za-z0-9_-]{43})\/files\/(.+)$/;
12026
12339
  const ENCODED_SEPARATOR_OR_NUL = /%(2f|5c|00)/i;
@@ -12154,8 +12467,7 @@ function proofMatches(expected, actual) {
12154
12467
  if (expectedBytes.byteLength !== actualBytes.byteLength) return false;
12155
12468
  return timingSafeEqual(expectedBytes, actualBytes);
12156
12469
  }
12157
- //#endregion
12158
- //#region src/server/ipc-frames.ts
12470
+ // src/server/ipc-frames.ts
12159
12471
  var FrameError = class extends Error {
12160
12472
  kind;
12161
12473
  constructor(kind) {
@@ -12209,8 +12521,7 @@ var FrameDecoder = class {
12209
12521
  return value;
12210
12522
  }
12211
12523
  };
12212
- //#endregion
12213
- //#region src/server/ipc-server.ts
12524
+ // src/server/ipc-server.ts
12214
12525
  function toErrorBody(error) {
12215
12526
  if (isVdeError(error)) return {
12216
12527
  code: error.code,
@@ -12368,8 +12679,7 @@ async function startIpcServer(options) {
12368
12679
  })
12369
12680
  };
12370
12681
  }
12371
- //#endregion
12372
- //#region ../../node_modules/.pnpm/readdirp@5.1.1/node_modules/readdirp/index.js
12682
+ // ../../node_modules/.pnpm/readdirp@5.1.1/node_modules/readdirp/index.js
12373
12683
  const EntryTypes = {
12374
12684
  FILE_TYPE: "files",
12375
12685
  DIR_TYPE: "directories",
@@ -12382,7 +12692,7 @@ const defaultOptions = {
12382
12692
  directoryFilter: (_entryInfo) => true,
12383
12693
  type: EntryTypes.FILE_TYPE,
12384
12694
  lstat: false,
12385
- depth: 2147483648,
12695
+ depth: 0x80000000,
12386
12696
  alwaysStat: false,
12387
12697
  highWaterMark: 256
12388
12698
  };
@@ -12626,8 +12936,7 @@ function readdirp(root, options = {}) {
12626
12936
  if (type) opts.type = type;
12627
12937
  return new ReaddirpStream(opts);
12628
12938
  }
12629
- //#endregion
12630
- //#region ../../node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/handler.js
12939
+ // ../../node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/handler.js
12631
12940
  const STR_DATA = "data";
12632
12941
  const STR_CLOSE = "close";
12633
12942
  const EMPTY_FN = () => {};
@@ -12963,7 +13272,7 @@ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
12963
13272
  if (evPath && path !== evPath) fsWatchBroadcast(sp.resolve(path, evPath), KEY_LISTENERS, sp.join(path, evPath));
12964
13273
  };
12965
13274
  try {
12966
- return watch(path, { persistent: options.persistent }, handleEvent);
13275
+ return watch$1(path, { persistent: options.persistent }, handleEvent);
12967
13276
  } catch (error) {
12968
13277
  errHandler(error);
12969
13278
  return;
@@ -13341,8 +13650,7 @@ var NodeFsHandler = class {
13341
13650
  }
13342
13651
  }
13343
13652
  };
13344
- //#endregion
13345
- //#region ../../node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/index.js
13653
+ // ../../node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/index.js
13346
13654
  /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
13347
13655
  const SLASH = "/";
13348
13656
  const SLASH_SLASH = "//";
@@ -13384,10 +13692,7 @@ function normalizePath(path) {
13384
13692
  }
13385
13693
  function matchPatterns(patterns, testString, stats) {
13386
13694
  const path = normalizePath(testString);
13387
- for (let index = 0; index < patterns.length; index++) {
13388
- const pattern = patterns[index];
13389
- if (pattern(path, stats)) return true;
13390
- }
13695
+ for (let index = 0; index < patterns.length; index++) if ((0, patterns[index])(path, stats)) return true;
13391
13696
  return false;
13392
13697
  }
13393
13698
  function anymatch(matchers, testString) {
@@ -13978,13 +14283,12 @@ var FSWatcher = class extends EventEmitter {
13978
14283
  * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
13979
14284
  * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
13980
14285
  */
13981
- function watch$1(paths, options = {}) {
14286
+ function watch(paths, options = {}) {
13982
14287
  const watcher = new FSWatcher(options);
13983
14288
  watcher.add(paths);
13984
14289
  return watcher;
13985
14290
  }
13986
- //#endregion
13987
- //#region src/watch/watch-service.ts
14291
+ // src/watch/watch-service.ts
13988
14292
  const FILE_CHECK_INTERVAL_MS = 5e3;
13989
14293
  const RULE_SCAN_INTERVAL_MS = 3e4;
13990
14294
  const REFRESH_CONCURRENCY = 4;
@@ -14077,7 +14381,7 @@ function createWatchService(options) {
14077
14381
  stats.closed += 1;
14078
14382
  };
14079
14383
  const startWatcher = (directory, recursive) => {
14080
- const watcher = watch$1(directory, {
14384
+ const watcher = watch(directory, {
14081
14385
  ignoreInitial: true,
14082
14386
  followSymlinks: false,
14083
14387
  ...recursive ? {} : { depth: 0 },
@@ -14153,8 +14457,7 @@ function createWatchService(options) {
14153
14457
  }
14154
14458
  };
14155
14459
  }
14156
- //#endregion
14157
- //#region src/workers/parse-service.ts
14460
+ // src/workers/parse-service.ts
14158
14461
  function createParseService(options = {}) {
14159
14462
  const timeoutMs = options.timeoutMs ?? LIMITS.parseTimeoutMs;
14160
14463
  const workerPath = options.workerPath ?? parseWorkerPath();
@@ -14268,8 +14571,7 @@ function createParseService(options = {}) {
14268
14571
  }
14269
14572
  };
14270
14573
  }
14271
- //#endregion
14272
- //#region src/daemon/lock.ts
14574
+ // src/daemon/lock.ts
14273
14575
  const execFileAsync = promisify(execFile);
14274
14576
  const GENERATION_DIGITS = 12;
14275
14577
  const ACQUIRE_ATTEMPTS = 8;
@@ -14460,8 +14762,7 @@ async function releaseLock(directory, name, ownerId) {
14460
14762
  }
14461
14763
  await renameWithRetry(temp, join(directory, fileNameOf(name, current.generation)));
14462
14764
  }
14463
- //#endregion
14464
- //#region src/daemon/listener-config.ts
14765
+ // src/daemon/listener-config.ts
14465
14766
  const LISTENER_CONFIG_FILE = "listeners.json";
14466
14767
  const DEFAULT_PORTS = {
14467
14768
  management: 43180,
@@ -14554,8 +14855,7 @@ function resolveMobileConfig(raw, pcPorts) {
14554
14855
  settings
14555
14856
  };
14556
14857
  }
14557
- //#endregion
14558
- //#region src/daemon/logger.ts
14858
+ // src/daemon/logger.ts
14559
14859
  const MAX_LOG_BYTES = 1048576;
14560
14860
  function createFileLogger(stateRoot) {
14561
14861
  const directory = join(stateRoot, "logs");
@@ -14584,8 +14884,7 @@ function createFileLogger(stateRoot) {
14584
14884
  }
14585
14885
  };
14586
14886
  }
14587
- //#endregion
14588
- //#region src/daemon/runtime-files.ts
14887
+ // src/daemon/runtime-files.ts
14589
14888
  const DAEMON_LOCK_NAME = "daemon.lock";
14590
14889
  const START_LOCK_NAME = "start.lock";
14591
14890
  const POINTER_FILE = "runtime-pointer.json";
@@ -14632,8 +14931,7 @@ async function readIpcKey(keyPath) {
14632
14931
  return null;
14633
14932
  }
14634
14933
  }
14635
- //#endregion
14636
- //#region src/daemon/secure-dir.ts
14934
+ // src/daemon/secure-dir.ts
14637
14935
  function insecure(path, reason) {
14638
14936
  return new VdeError("E_INSECURE_PATH", `${path} is not a secure directory (${reason}).`, {
14639
14937
  path,
@@ -14683,8 +14981,7 @@ async function requirePrivateDirectoryIfExists(path, options) {
14683
14981
  if (inspection !== "ok") throw insecure(path, inspection);
14684
14982
  return true;
14685
14983
  }
14686
- //#endregion
14687
- //#region src/daemon/main.ts
14984
+ // src/daemon/main.ts
14688
14985
  const LOCK_CHECK_INTERVAL_MS = 2e3;
14689
14986
  const SHUTDOWN_CLOSE_TIMEOUT_MS = 5e3;
14690
14987
  const diagnosticsParamsSchema = strictObject({ collectGarbage: boolean().default(false) });
@@ -14908,23 +15205,6 @@ async function startDaemon(options) {
14908
15205
  onEvent: (event, fields) => logger.log(event, fields)
14909
15206
  }, { port: ports.preview }));
14910
15207
  previewOrigin = preview.origin;
14911
- management = await listenOrFail("management", ports.management, () => startManagementServer({
14912
- daemonId,
14913
- version,
14914
- documents,
14915
- events,
14916
- render,
14917
- search: searching,
14918
- feedback: answering,
14919
- pdf: exporting,
14920
- previewOrigin,
14921
- webRoot: webRootPath(),
14922
- devOrigin,
14923
- isStopping: () => stopping !== null,
14924
- onEvent: (event, fields) => logger.log(event, fields)
14925
- }, { port: ports.management }));
14926
- managementOrigin = management.origin;
14927
- const uiUrl = `${management.origin}/`;
14928
15208
  let mobileStatus = mobileConfig.state === "disabled" ? { state: "disabled" } : mobileConfig.state === "error" ? {
14929
15209
  state: "error",
14930
15210
  listener: null,
@@ -14968,7 +15248,8 @@ async function startDaemon(options) {
14968
15248
  mobileOpen = true;
14969
15249
  mobileStatus = {
14970
15250
  state: "ready",
14971
- uiUrl: `https://${settings.host}:${String(settings.uiPort)}/`
15251
+ uiUrl: `https://${settings.host}:${String(settings.uiPort)}/`,
15252
+ previewPort: settings.previewPort
14972
15253
  };
14973
15254
  } catch (error) {
14974
15255
  await mobileUi?.close();
@@ -14988,6 +15269,24 @@ async function startDaemon(options) {
14988
15269
  });
14989
15270
  }
14990
15271
  }
15272
+ management = await listenOrFail("management", ports.management, () => startManagementServer({
15273
+ daemonId,
15274
+ version,
15275
+ documents,
15276
+ events,
15277
+ render,
15278
+ search: searching,
15279
+ feedback: answering,
15280
+ pdf: exporting,
15281
+ previewOrigin,
15282
+ phoneUrl: mobileStatus.state === "ready" ? mobileStatus.uiUrl : null,
15283
+ webRoot: webRootPath(),
15284
+ devOrigin,
15285
+ isStopping: () => stopping !== null,
15286
+ onEvent: (event, fields) => logger.log(event, fields)
15287
+ }, { port: ports.management }));
15288
+ managementOrigin = management.origin;
15289
+ const uiUrl = `${management.origin}/`;
14991
15290
  watcher = createWatchService({
14992
15291
  documents,
14993
15292
  onEvent: (event, fields) => logger.log(event, fields)
@@ -15141,5 +15440,4 @@ async function startDaemon(options) {
15141
15440
  stop
15142
15441
  };
15143
15442
  }
15144
- //#endregion
15145
15443
  export { resolveRuntimeLocation as A, computeProof as C, renameWithRetry as D, removeWithRetry as E, daemonEntryPath as M, referencedBlobs as N, decodeStateFile as O, version as P, HANDSHAKE_TIMEOUT_MS as S, proofMatches as T, readCurrentLock as _, DAEMON_LOCK_NAME as a, FrameDecoder as b, readIpcKey as c, LISTENER_CONFIG_FILE as d, readListenerConfig as f, inspectOwner as g, acquireLock as h, requirePrivateDirectoryIfExists as i, resolveStateRoot as j, currentPathEnvironment as k, readPointer as l, resolvePcPorts as m, ensurePrivateDirectory as n, POINTER_FILE as o, resolveMobileConfig as p, inspectPrivateDirectory as r, START_LOCK_NAME as s, startDaemon as t, DEFAULT_PORTS as u, releaseLock as v, createNonce as w, encodeFrame as x, systemProcessProbe as y };