vde-open 0.1.14 → 0.1.16

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.
@@ -1,6 +1,6 @@
1
- import { C as roleAllowed, N as __commonJSMin, P as __toESM, S as isValidLogicalPath, _ as classifyLink, b as encodeLogicalPath, d as analyzeDocument, g as assetTypeOf, u as ParseLimitError, v as classifyReference, x as hasHiddenSegment, y as dirnameOfLogicalPath } from "./html-static-C_wwQAJx.js";
2
- import { $ as literal, A as successEnvelope, B as readParamsSchema, C as VdeError, D as ExitCode, E as isVdeError, F as htmlModeChangeParamsSchema, G as sha256Schema, H as reorderParamsSchema, I as htmlModeSchema, J as watchRuleSchema, K as sourceKindSchema, L as linkOpenParamsSchema, M as closeParamsSchema, N as documentFormatSchema, P as documentIdSchema, Q as boolean, R as listParamsSchema, S as validateAnswers, U as revisionSchema, V as renderGrantParamsSchema, W as searchParamsSchema, X as _enum, Y as LIMITS, Z as array, _ as feedbackWaitParamsSchema, a as uniqueTokens, at as canonicalJson, b as submissionSchema, c as feedbackAckParamsSchema, d as feedbackDraftParamsSchema, et as number, f as feedbackForgetParamsSchema, g as feedbackSubmitParamsSchema, h as feedbackStatusSchema, i as codePointLength, it as ZodError, j as assetRecordSchema, k as errorEnvelope, l as feedbackCancelParamsSchema, m as feedbackListParamsSchema, n as batchesOf, nt as strictObject, o as answersSchema, p as feedbackIdParamsSchema, q as sourceStateSchema, r as partsOf, rt as string, s as cancellationSchema, tt as record, u as feedbackCreateParamsSchema, v as questionnaireSchema, w as exitCodeForError, x as utf8Length, y as requestIdSchema, z as openParamsSchema } from "./search-index-B-hHn9RV.js";
3
- import { n as scanReferences, r as extractTitle } from "./render-BJa4uW0H.js";
1
+ import { C as isValidLogicalPath, F as __toESM, P as __commonJSMin, S as hasHiddenSegment, _ as assetTypeOf, b as dirnameOfLogicalPath, d as ParseLimitError, f as analyzeDocument, l as HTML_LINK_RELAY, v as classifyLink, w as roleAllowed, x as encodeLogicalPath, y as classifyReference } from "./html-static-Ct_9qmNR.js";
2
+ import { $ as 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
4
  import { n as measureHeap, t as collectGarbage } from "./heap-C3qHm7SE.js";
5
5
  import { accessSync, constants, existsSync, stat, statSync, unwatchFile, watch, watchFile } from "node:fs";
6
6
  import { appendFile, chmod, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat as stat$1, writeFile } from "node:fs/promises";
@@ -28,6 +28,11 @@ import { createServer as createServer$1 } from "node:net";
28
28
  const BRIDGE_HELLO = "vde-bridge-hello";
29
29
  const BRIDGE_PORT = "vde-bridge-port";
30
30
  //#endregion
31
+ //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/coerce.js
32
+ function number(params) {
33
+ return _coercedNumber(ZodNumber, params);
34
+ }
35
+ //#endregion
31
36
  //#region ../../packages/shared/src/strict-json.ts
32
37
  var StrictJsonError = class extends Error {
33
38
  reason;
@@ -154,7 +159,7 @@ function parseStrictJson(text) {
154
159
  }
155
160
  //#endregion
156
161
  //#region package.json
157
- var version = "0.1.14";
162
+ var version = "0.1.16";
158
163
  //#endregion
159
164
  //#region src/documents/cursor.ts
160
165
  function invalidCursor(reason) {
@@ -545,7 +550,7 @@ const revisionRecordSchema = strictObject({
545
550
  revision: revisionSchema,
546
551
  format: documentFormatSchema,
547
552
  sourceSha256: sha256Schema,
548
- byteLength: number().int().nonnegative(),
553
+ byteLength: number$1().int().nonnegative(),
549
554
  parserProfileVersion: string().min(1),
550
555
  createdAt: string(),
551
556
  documentLogicalPath: string().min(1),
@@ -584,7 +589,7 @@ const feedbackRecordSchema = strictObject({
584
589
  updatedAt: string(),
585
590
  operationId: string().nullable(),
586
591
  operationDigest: sha256Schema.nullable(),
587
- draftVersion: number().int().nonnegative(),
592
+ draftVersion: number$1().int().nonnegative(),
588
593
  draftAnswers: answersSchema,
589
594
  submission: submissionSchema.nullable(),
590
595
  submissionDigest: sha256Schema.nullable(),
@@ -592,7 +597,7 @@ const feedbackRecordSchema = strictObject({
592
597
  acknowledgedAt: string().nullable()
593
598
  });
594
599
  const statePayloadSchema = strictObject({
595
- catalogVersion: number().int().nonnegative(),
600
+ catalogVersion: number$1().int().nonnegative(),
596
601
  documents: record(documentIdSchema, documentRecordSchema),
597
602
  openOrder: array(documentIdSchema),
598
603
  activeDocumentId: documentIdSchema.nullable(),
@@ -601,7 +606,7 @@ const statePayloadSchema = strictObject({
601
606
  });
602
607
  const stateFileSchema = strictObject({
603
608
  formatVersion: literal(1),
604
- storeVersion: number().int().nonnegative(),
609
+ storeVersion: number$1().int().nonnegative(),
605
610
  checksum: sha256Schema,
606
611
  payload: statePayloadSchema
607
612
  });
@@ -4119,6 +4124,9 @@ function pruneRevisions(revisions, now, pinned) {
4119
4124
  return index >= revisions.length - LIMITS.retainedRevisions || pinned.has(entry.revision) || now - Date.parse(entry.createdAt) < LIMITS.revisionGraceMs;
4120
4125
  });
4121
4126
  }
4127
+ function lastOpenedRecord(state) {
4128
+ return lastOpenedDocument(state.openOrder.flatMap((id) => state.documents[id] ?? []));
4129
+ }
4122
4130
  function openSourceBytes(state) {
4123
4131
  let total = 0;
4124
4132
  for (const documentId of state.openOrder) {
@@ -4729,6 +4737,11 @@ var DocumentService = class {
4729
4737
  assets,
4730
4738
  assetScan: item.assetScanFailed ? "failed" : "complete"
4731
4739
  };
4740
+ let openedAt = timestamp;
4741
+ if (!existing?.isOpen) {
4742
+ const latest = lastOpenedRecord(state);
4743
+ if (latest && latest.openedAt >= timestamp) openedAt = new Date(Date.parse(latest.openedAt) + 1).toISOString();
4744
+ }
4732
4745
  if (!existing) {
4733
4746
  const documentId = `doc_${randomUUID()}`;
4734
4747
  const htmlMode = options.htmlMode ?? "static";
@@ -4743,7 +4756,7 @@ var DocumentService = class {
4743
4756
  displayPath: item.displayPath,
4744
4757
  pathSegments: item.pathSegments,
4745
4758
  isOpen: true,
4746
- openedAt: timestamp,
4759
+ openedAt,
4747
4760
  updatedAt: timestamp,
4748
4761
  sourceState: "ready",
4749
4762
  currentRevision: revision,
@@ -4765,7 +4778,7 @@ var DocumentService = class {
4765
4778
  let revisionChanged = false;
4766
4779
  if (!existing.isOpen) {
4767
4780
  existing.isOpen = true;
4768
- existing.openedAt = timestamp;
4781
+ existing.openedAt = openedAt;
4769
4782
  state.openOrder.push(existing.documentId);
4770
4783
  changed = true;
4771
4784
  openSetChanged = true;
@@ -5044,13 +5057,22 @@ var DocumentService = class {
5044
5057
  entry: this.#requireRevision(record, revision ?? record.currentRevision)
5045
5058
  };
5046
5059
  }
5047
- async openLinked(link) {
5048
- const { documentId, href } = link;
5060
+ async #linkTarget(documentId, href) {
5049
5061
  const record = this.#requireOpen(documentId);
5050
5062
  const target = classifyLink(href);
5051
5063
  const base = target.kind !== "document" ? null : target.fromRoot || record.canonicalPath === null ? record.assetsRoot : dirname(record.canonicalPath);
5052
5064
  if (target.kind !== "document" || base === null) throw new VdeError("E_INVALID_ARGUMENT", "This link does not point to a document that can be opened.");
5053
- const canonical = await canonicalizePath(resolve(base, ...target.segments));
5065
+ return canonicalizePath(resolve(base, ...target.segments));
5066
+ }
5067
+ async openDocumentOfLink(documentId, href) {
5068
+ const canonical = await this.#linkTarget(documentId, href).catch(() => null);
5069
+ if (canonical === null) return null;
5070
+ const existing = this.#existingFile(canonical);
5071
+ return existing?.isOpen ? existing.documentId : null;
5072
+ }
5073
+ async openLinked(link) {
5074
+ const { documentId, href } = link;
5075
+ const canonical = await this.#linkTarget(documentId, href);
5054
5076
  const now = this.#now().getTime();
5055
5077
  const offered = link.confirmation === void 0 ? void 0 : this.#linkConfirmations.get(link.confirmation);
5056
5078
  if (link.confirmation !== void 0) this.#linkConfirmations.delete(link.confirmation);
@@ -5147,7 +5169,7 @@ var DocumentService = class {
5147
5169
  }
5148
5170
  if (closed.length > 0) {
5149
5171
  state.openOrder = state.openOrder.filter((documentId) => !closed.includes(documentId));
5150
- if (state.activeDocumentId !== null && closed.includes(state.activeDocumentId)) state.activeDocumentId = state.openOrder[0] ?? null;
5172
+ if (state.activeDocumentId !== null && closed.includes(state.activeDocumentId)) state.activeDocumentId = lastOpenedRecord(state)?.documentId ?? null;
5151
5173
  state.catalogVersion += 1;
5152
5174
  changed = true;
5153
5175
  }
@@ -6931,7 +6953,7 @@ function createRenderService(options) {
6931
6953
  const { store, documents, parse } = options;
6932
6954
  const grants = /* @__PURE__ */ new Map();
6933
6955
  const snapshots = /* @__PURE__ */ new Map();
6934
- const snapshotOf = async (documentId, revision, mode = "static", withSdk = false) => {
6956
+ const snapshotOf = async (documentId, revision, mode, withSdk = false) => {
6935
6957
  const { record, entry } = documents.describeRevision(documentId, revision);
6936
6958
  const cacheKey = `${entry.revision}\n${entry.documentLogicalPath}\n${mode}\n${String(withSdk)}`;
6937
6959
  const cached = snapshots.get(cacheKey);
@@ -7048,16 +7070,17 @@ function createRenderService(options) {
7048
7070
  snapshot
7049
7071
  };
7050
7072
  };
7051
- const liveGrant = (key) => {
7073
+ const liveGrant = (key, audience = "pc") => {
7052
7074
  const grant = grants.get(key);
7053
- if (!grant) return null;
7054
- if (!documents.state.documents[grant.documentId]?.isOpen || documents.openEpoch(grant.documentId) !== grant.openEpoch || grant.mode === "interactive" && documents.interactiveGeneration(grant.documentId) !== grant.permission) {
7075
+ if (grant?.audience !== audience) return null;
7076
+ const record = documents.state.documents[grant.documentId];
7077
+ if (!record?.isOpen || documents.openEpoch(grant.documentId) !== grant.openEpoch || grant.mode === "interactive" && documents.interactiveGeneration(grant.documentId) !== grant.permission || audience === "mobile" && (record.currentRevision !== grant.revision || options.mobile?.viewEpochOf(grant.documentId) !== grant.viewEpoch)) {
7055
7078
  grants.delete(key);
7056
7079
  return null;
7057
7080
  }
7058
7081
  return grant;
7059
7082
  };
7060
- const issue = async (params, context) => {
7083
+ const issue = async (params, context, audience = "pc", stillCurrent = () => void 0) => {
7061
7084
  const interactive = params.mode === "interactive";
7062
7085
  const permissionOf = () => {
7063
7086
  if (!interactive) return null;
@@ -7075,6 +7098,7 @@ function createRenderService(options) {
7075
7098
  if (documents.openEpoch(params.documentId) !== openEpoch) throw new VdeError("E_DOCUMENT_NOT_OPEN", "The document is not open.", { documentId: params.documentId });
7076
7099
  }
7077
7100
  const permission = permissionOf();
7101
+ stillCurrent();
7078
7102
  const { record, entry, snapshot } = prepared;
7079
7103
  if (params.requestId !== null) {
7080
7104
  const request = Object.hasOwn(store.payload.feedbackRequests, params.requestId) ? store.payload.feedbackRequests[params.requestId] : void 0;
@@ -7099,7 +7123,10 @@ function createRenderService(options) {
7099
7123
  };
7100
7124
  }
7101
7125
  const key = randomBytes(32).toString("base64url");
7126
+ const viewEpoch = audience === "mobile" ? options.mobile?.viewEpochOf(record.documentId) ?? null : null;
7102
7127
  grants.set(key, {
7128
+ audience,
7129
+ viewEpoch,
7103
7130
  documentId: record.documentId,
7104
7131
  openEpoch,
7105
7132
  revision: entry.revision,
@@ -7109,14 +7136,18 @@ function createRenderService(options) {
7109
7136
  bridge,
7110
7137
  missing: /* @__PURE__ */ new Set()
7111
7138
  });
7112
- while (grants.size > LIMITS.renderGrants) {
7113
- const oldest = grants.keys().next().value;
7114
- if (oldest === void 0) break;
7115
- grants.delete(oldest);
7139
+ let count = 0;
7140
+ for (const grant of grants.values()) if (grant.audience === audience) count += 1;
7141
+ for (const [oldKey, grant] of grants) {
7142
+ if (count <= LIMITS.renderGrants) break;
7143
+ if (grant.audience !== audience) continue;
7144
+ grants.delete(oldKey);
7145
+ count -= 1;
7116
7146
  }
7117
- const filesBaseUrl = `${options.previewOrigin()}/r/${key}/files/`;
7147
+ const filesBaseUrl = `${audience === "mobile" ? options.mobile?.previewOrigin() ?? "" : options.previewOrigin()}/r/${key}/files/`;
7118
7148
  return {
7119
7149
  grant: key,
7150
+ viewEpoch,
7120
7151
  documentId: record.documentId,
7121
7152
  revision: entry.revision,
7122
7153
  format: snapshot.format,
@@ -7150,10 +7181,11 @@ function createRenderService(options) {
7150
7181
  },
7151
7182
  async createGrant(rawParams, context) {
7152
7183
  const params = renderGrantParamsSchema.parse(rawParams);
7153
- return issue({
7184
+ const { viewEpoch: _viewEpoch, ...result } = await issue({
7154
7185
  ...params,
7155
7186
  requestId: null
7156
7187
  }, context);
7188
+ return result;
7157
7189
  },
7158
7190
  async createGrantForRequest(requestId, context) {
7159
7191
  const request = Object.hasOwn(store.payload.feedbackRequests, requestId) ? store.payload.feedbackRequests[requestId] : void 0;
@@ -7163,12 +7195,13 @@ function createRenderService(options) {
7163
7195
  status: request.status
7164
7196
  });
7165
7197
  const interactive = request.renderMode === "interactive" && documents.interactiveAllowed(request.documentId);
7166
- return issue({
7198
+ const { viewEpoch: _viewEpoch, ...result } = await issue({
7167
7199
  documentId: request.documentId,
7168
7200
  revision: request.revision,
7169
7201
  mode: interactive ? "interactive" : "static",
7170
7202
  requestId: interactive ? request.requestId : null
7171
7203
  }, context);
7204
+ return result;
7172
7205
  },
7173
7206
  bridgeOf(key) {
7174
7207
  const grant = liveGrant(key);
@@ -7181,33 +7214,50 @@ function createRenderService(options) {
7181
7214
  };
7182
7215
  },
7183
7216
  release(keys) {
7184
- let released = 0;
7185
- for (const key of keys) if (grants.delete(key)) released += 1;
7186
- return released;
7217
+ return releaseOf(keys, "pc");
7218
+ },
7219
+ releaseMobile(keys) {
7220
+ return releaseOf(keys, "mobile");
7187
7221
  },
7188
7222
  async resolve(key, logicalPath) {
7189
- const grant = liveGrant(key);
7190
- if (!grant) return null;
7191
- const file = grant.snapshot.files.get(logicalPath);
7192
- if (!file) {
7193
- if (!grant.missing.has(logicalPath) && grant.missing.size < LIMITS.renderMissingPerGrant) {
7194
- grant.missing.add(logicalPath);
7195
- options.onMissing?.(grant.documentId);
7196
- }
7197
- return null;
7198
- }
7199
- const body = file.kind === "inline" ? file.body : file.kind === "bridged" ? Buffer.concat([
7200
- file.before,
7201
- grant.bridge?.config ?? Buffer.from("null"),
7202
- file.after
7203
- ]) : await store.readBlob(file.sha256);
7204
- if (!liveGrant(key)) return null;
7223
+ return resolveOf(key, logicalPath, "pc");
7224
+ },
7225
+ async resolveMobile(key, logicalPath) {
7226
+ return resolveOf(key, logicalPath, "mobile");
7227
+ },
7228
+ checkMobile(key) {
7229
+ return liveGrant(key, "mobile") !== null;
7230
+ },
7231
+ mobileLinkOf(key, linkId) {
7232
+ const grant = liveGrant(key, "mobile");
7233
+ const link = grant?.snapshot.links.find((candidate) => candidate.linkId === linkId);
7234
+ return grant && link ? {
7235
+ documentId: grant.documentId,
7236
+ link
7237
+ } : null;
7238
+ },
7239
+ async createMobileGrant(documentId, expected) {
7240
+ const mobile = options.mobile;
7241
+ if (!mobile) throw new VdeError("E_UNKNOWN_METHOD", "The phone reader is off.");
7242
+ const stillCurrent = () => {
7243
+ const record = documents.state.documents[documentId];
7244
+ if (!record?.isOpen) throw new VdeError("E_DOCUMENT_NOT_OPEN", "The document is not open.", { documentId });
7245
+ if (record.currentRevision !== expected.revision || mobile.viewEpochOf(documentId) !== expected.viewEpoch) throw new VdeError("E_VIEW_STALE", "The document changed. Fetch the list again.");
7246
+ };
7247
+ stillCurrent();
7248
+ const interactive = documents.interactiveAllowed(documentId);
7249
+ const { bridge: _bridge, diagnostics: _diagnostics, viewEpoch, ...result } = await issue({
7250
+ documentId,
7251
+ revision: expected.revision,
7252
+ mode: interactive ? "interactive" : "static",
7253
+ requestId: null
7254
+ }, { origin: "" }, "mobile", stillCurrent).catch((error) => {
7255
+ if (error instanceof VdeError && error.code === "E_INTERACTIVE_NOT_ALLOWED") throw new VdeError("E_VIEW_STALE", "The document changed. Fetch the list again.");
7256
+ throw error;
7257
+ });
7205
7258
  return {
7206
- body,
7207
- mime: file.mime,
7208
- role: file.role,
7209
- grant: key,
7210
- mode: grant.mode
7259
+ ...result,
7260
+ viewEpoch: viewEpoch ?? expected.viewEpoch
7211
7261
  };
7212
7262
  },
7213
7263
  missingOf(key) {
@@ -7218,8 +7268,8 @@ function createRenderService(options) {
7218
7268
  pruneClosed() {
7219
7269
  for (const [key, grant] of grants) if (!documents.state.documents[grant.documentId]?.isOpen) grants.delete(key);
7220
7270
  },
7221
- async linkOf(documentId, revision, linkId) {
7222
- const { snapshot } = await snapshotOf(documentId, revision);
7271
+ async linkOf({ documentId, revision, mode, linkId }) {
7272
+ const { snapshot } = await snapshotOf(documentId, revision, mode);
7223
7273
  const link = snapshot.links.find((candidate) => candidate.linkId === linkId);
7224
7274
  if (!link) throw new VdeError("E_LINK_NOT_FOUND", "The link was not found.", {
7225
7275
  documentId,
@@ -7228,6 +7278,80 @@ function createRenderService(options) {
7228
7278
  return link;
7229
7279
  }
7230
7280
  };
7281
+ function releaseOf(keys, audience) {
7282
+ let released = 0;
7283
+ for (const key of keys) if (grants.get(key)?.audience === audience && grants.delete(key)) released += 1;
7284
+ return released;
7285
+ }
7286
+ async function resolveOf(key, logicalPath, audience) {
7287
+ const grant = liveGrant(key, audience);
7288
+ if (!grant) return null;
7289
+ const file = grant.snapshot.files.get(logicalPath);
7290
+ if (!file) {
7291
+ if (!grant.missing.has(logicalPath) && grant.missing.size < LIMITS.renderMissingPerGrant) {
7292
+ grant.missing.add(logicalPath);
7293
+ options.onMissing?.(grant.documentId);
7294
+ }
7295
+ return null;
7296
+ }
7297
+ const body = file.kind === "inline" ? file.body : file.kind === "bridged" ? Buffer.concat([
7298
+ file.before,
7299
+ grant.bridge?.config ?? Buffer.from("null"),
7300
+ file.after
7301
+ ]) : await store.readBlob(file.sha256);
7302
+ if (!liveGrant(key, audience)) return null;
7303
+ return {
7304
+ body,
7305
+ mime: file.mime,
7306
+ role: file.role,
7307
+ grant: key,
7308
+ mode: grant.mode,
7309
+ hasDocumentLinks: file.role === "document" && grant.snapshot.links.some((link) => link.kind === "document")
7310
+ };
7311
+ }
7312
+ }
7313
+ //#endregion
7314
+ //#region src/render/view-epochs.ts
7315
+ function createViewEpochs(documents) {
7316
+ const seen = /* @__PURE__ */ new Map();
7317
+ const current = (documentId) => {
7318
+ const record = documents.state.documents[documentId];
7319
+ return {
7320
+ openEpoch: documents.openEpoch(documentId),
7321
+ revision: record?.currentRevision ?? "",
7322
+ permission: documents.interactiveGeneration(documentId)
7323
+ };
7324
+ };
7325
+ const update = (documentId) => {
7326
+ const now = current(documentId);
7327
+ const last = seen.get(documentId);
7328
+ let entry;
7329
+ if (last === void 0 || last.openEpoch !== now.openEpoch) entry = {
7330
+ ...now,
7331
+ generation: 0
7332
+ };
7333
+ else if (last.revision !== now.revision || last.permission !== now.permission) entry = {
7334
+ ...now,
7335
+ generation: last.generation + 1
7336
+ };
7337
+ else return last;
7338
+ seen.set(documentId, entry);
7339
+ return entry;
7340
+ };
7341
+ return {
7342
+ get size() {
7343
+ return seen.size;
7344
+ },
7345
+ observe() {
7346
+ const open = new Set(documents.state.openOrder);
7347
+ for (const documentId of seen.keys()) if (!open.has(documentId)) seen.delete(documentId);
7348
+ for (const documentId of open) update(documentId);
7349
+ },
7350
+ of(documentId) {
7351
+ const entry = update(documentId);
7352
+ return `${String(entry.openEpoch)}.${String(entry.generation)}`;
7353
+ }
7354
+ };
7231
7355
  }
7232
7356
  //#endregion
7233
7357
  //#region src/diagnostics/idle-collect.ts
@@ -11110,10 +11234,79 @@ function createEventQueue(options) {
11110
11234
  };
11111
11235
  }
11112
11236
  //#endregion
11237
+ //#region src/server/http/event-stream.ts
11238
+ function createEventStreams() {
11239
+ const streams = /* @__PURE__ */ new Map();
11240
+ return {
11241
+ open(c, options) {
11242
+ const response = streamSSE(c, async (stream) => {
11243
+ let closed = false;
11244
+ let wake = () => void 0;
11245
+ const done = new Promise((resolve) => {
11246
+ wake = resolve;
11247
+ });
11248
+ const finish = () => {
11249
+ closed = true;
11250
+ wake();
11251
+ };
11252
+ const queue = createEventQueue({
11253
+ writeEvent: (event) => {
11254
+ const frame = options.frame(event);
11255
+ return frame === null ? Promise.resolve() : stream.writeSSE(frame);
11256
+ },
11257
+ writeHeartbeat: () => stream.write(": heartbeat\n\n"),
11258
+ onError: finish
11259
+ });
11260
+ const drop = () => {
11261
+ queue.stop();
11262
+ finish();
11263
+ stream.abort();
11264
+ c.env.outgoing?.destroy();
11265
+ };
11266
+ streams.set(finish, queue);
11267
+ stream.onAbort(finish);
11268
+ const send = (event) => {
11269
+ if (!closed) queue.send(event);
11270
+ };
11271
+ send(options.hello);
11272
+ const unsubscribe = options.subscribe(send);
11273
+ const heartbeat = setInterval(() => {
11274
+ if (queue.stalledFor() >= (options.stallMs ?? LIMITS.sseStallMs)) {
11275
+ drop();
11276
+ return;
11277
+ }
11278
+ queue.heartbeat();
11279
+ }, options.heartbeatMs ?? LIMITS.sseHeartbeatMs);
11280
+ try {
11281
+ await done;
11282
+ } finally {
11283
+ clearInterval(heartbeat);
11284
+ unsubscribe();
11285
+ await queue.settled();
11286
+ streams.delete(finish);
11287
+ }
11288
+ });
11289
+ response.headers.set("Cache-Control", "no-store");
11290
+ return response;
11291
+ },
11292
+ stats() {
11293
+ let maxPending = 0;
11294
+ for (const queue of streams.values()) maxPending = Math.max(maxPending, queue.pending);
11295
+ return {
11296
+ streams: streams.size,
11297
+ maxPending
11298
+ };
11299
+ },
11300
+ finishAll() {
11301
+ for (const finish of streams.keys()) finish();
11302
+ }
11303
+ };
11304
+ }
11305
+ //#endregion
11113
11306
  //#region src/server/http/management.ts
11114
- const API_PREFIX = "/_/api/v1";
11115
- const STREAM_FLUSH_MS = 100;
11116
- const CLOSE_GRACE_MS$1 = 1e3;
11307
+ const API_PREFIX$1 = "/_/api/v1";
11308
+ const STREAM_FLUSH_MS$1 = 100;
11309
+ const CLOSE_GRACE_MS$2 = 1e3;
11117
11310
  const MIME_TYPES = {
11118
11311
  ".html": "text/html; charset=utf-8",
11119
11312
  ".js": "text/javascript; charset=utf-8",
@@ -11124,7 +11317,7 @@ const MIME_TYPES = {
11124
11317
  ".woff2": "font/woff2",
11125
11318
  ".map": "application/json; charset=utf-8"
11126
11319
  };
11127
- function uiCsp(previewOrigin) {
11320
+ function uiCsp$1(previewOrigin) {
11128
11321
  return [
11129
11322
  "default-src 'none'",
11130
11323
  "script-src 'self'",
@@ -11209,7 +11402,7 @@ function statusOf(code) {
11209
11402
  default: return 500;
11210
11403
  }
11211
11404
  }
11212
- function fail(c, error) {
11405
+ function fail$1(c, error) {
11213
11406
  const body = toErrorBody$1(error);
11214
11407
  return c.json(errorEnvelope(body), statusOf(body.code));
11215
11408
  }
@@ -11232,7 +11425,7 @@ async function startManagementServer(deps, options = {}) {
11232
11425
  const app = new Hono();
11233
11426
  let origin = "";
11234
11427
  let host = "";
11235
- const streams = /* @__PURE__ */ new Map();
11428
+ const streams = createEventStreams();
11236
11429
  app.use("*", async (c, next) => {
11237
11430
  await next();
11238
11431
  c.header("X-Content-Type-Options", "nosniff");
@@ -11242,28 +11435,28 @@ async function startManagementServer(deps, options = {}) {
11242
11435
  app.use("*", async (c, next) => {
11243
11436
  if (c.req.header("host") !== host) {
11244
11437
  deps.onEvent?.("http.rejected", { reason: "host" });
11245
- return fail(c, new VdeError("E_UNAUTHORIZED", "This Host is not allowed."));
11438
+ return fail$1(c, new VdeError("E_UNAUTHORIZED", "This Host is not allowed."));
11246
11439
  }
11247
11440
  return next();
11248
11441
  });
11249
- app.use(`${API_PREFIX}/*`, async (c, next) => {
11442
+ app.use(`${API_PREFIX$1}/*`, async (c, next) => {
11250
11443
  const requestOrigin = c.req.header("origin");
11251
11444
  const allowed = requestOrigin === origin || deps.devOrigin !== null && requestOrigin === deps.devOrigin;
11252
11445
  if (requestOrigin !== void 0 && !allowed) {
11253
11446
  deps.onEvent?.("http.rejected", { reason: "origin" });
11254
- return fail(c, new VdeError("E_UNAUTHORIZED", "This Origin is not allowed."));
11447
+ return fail$1(c, new VdeError("E_UNAUTHORIZED", "This Origin is not allowed."));
11255
11448
  }
11256
11449
  const site = c.req.header("sec-fetch-site");
11257
11450
  if (site !== void 0 && site !== "same-origin" && !(deps.devOrigin !== null && allowed)) {
11258
11451
  deps.onEvent?.("http.rejected", { reason: "fetch-site" });
11259
- return fail(c, new VdeError("E_UNAUTHORIZED", "This request is not accepted."));
11452
+ return fail$1(c, new VdeError("E_UNAUTHORIZED", "This request is not accepted."));
11260
11453
  }
11261
11454
  const method = c.req.method;
11262
11455
  if (method !== "GET" && method !== "HEAD") {
11263
- if (requestOrigin === void 0) return fail(c, new VdeError("E_UNAUTHORIZED", "A request without Origin cannot make changes."));
11264
- if (Number(c.req.header("content-length") ?? "0") > 0 && !(c.req.header("content-type") ?? "").startsWith("application/json")) return fail(c, new VdeError("E_INVALID_ARGUMENT", "The body must be sent as JSON."));
11456
+ 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."));
11265
11458
  }
11266
- if (deps.isStopping()) return fail(c, new VdeError("E_DAEMON_STOPPING", "The daemon is stopping."));
11459
+ if (deps.isStopping()) return fail$1(c, new VdeError("E_DAEMON_STOPPING", "The daemon is stopping."));
11267
11460
  return next();
11268
11461
  });
11269
11462
  const api = new Hono();
@@ -11417,7 +11610,7 @@ async function startManagementServer(deps, options = {}) {
11417
11610
  documentId: c.req.param("id"),
11418
11611
  linkId: c.req.param("linkId")
11419
11612
  });
11420
- const link = await deps.render.linkOf(params.documentId, params.revision, params.linkId);
11613
+ const link = await deps.render.linkOf(params);
11421
11614
  return ok(c, "documents.link-open", await deps.documents.openLinked({
11422
11615
  documentId: params.documentId,
11423
11616
  revision: params.revision,
@@ -11426,67 +11619,26 @@ async function startManagementServer(deps, options = {}) {
11426
11619
  confirmation: params.confirmation
11427
11620
  }));
11428
11621
  });
11429
- api.get("/events", (c) => {
11430
- const response = streamSSE(c, async (stream) => {
11431
- let closed = false;
11432
- let wake = () => void 0;
11433
- const done = new Promise((resolve) => {
11434
- wake = resolve;
11435
- });
11436
- const finish = () => {
11437
- closed = true;
11438
- wake();
11439
- };
11440
- const queue = createEventQueue({
11441
- writeEvent: (event) => stream.writeSSE({
11442
- event: event.type,
11443
- id: String(event.sequence),
11444
- data: JSON.stringify(event)
11445
- }),
11446
- writeHeartbeat: () => stream.write(": heartbeat\n\n"),
11447
- onError: finish
11448
- });
11449
- const drop = () => {
11450
- queue.stop();
11451
- finish();
11452
- stream.abort();
11453
- c.env.outgoing?.destroy();
11454
- };
11455
- streams.set(finish, queue);
11456
- stream.onAbort(finish);
11457
- const send = (event) => {
11458
- if (!closed) queue.send(event);
11459
- };
11460
- send({
11461
- type: "hello",
11462
- daemonId: deps.daemonId,
11463
- sequence: deps.events.sequence,
11464
- catalogVersion: deps.documents.state.catalogVersion
11465
- });
11466
- const unsubscribe = deps.events.subscribe(send);
11467
- const heartbeat = setInterval(() => {
11468
- if (queue.stalledFor() >= (deps.stallMs ?? LIMITS.sseStallMs)) {
11469
- drop();
11470
- return;
11471
- }
11472
- queue.heartbeat();
11473
- }, deps.heartbeatMs ?? LIMITS.sseHeartbeatMs);
11474
- try {
11475
- await done;
11476
- } finally {
11477
- clearInterval(heartbeat);
11478
- unsubscribe();
11479
- await queue.settled();
11480
- streams.delete(finish);
11481
- }
11482
- });
11483
- response.headers.set("Cache-Control", "no-store");
11484
- return response;
11485
- });
11486
- api.all("*", (c) => fail(c, new VdeError("E_UNKNOWN_METHOD", "Unknown API.")));
11487
- api.onError((error, c) => fail(c, error));
11488
- app.route(API_PREFIX, api);
11489
- app.all("/_/*", (c) => fail(c, new VdeError("E_UNKNOWN_METHOD", "Unknown API.")));
11622
+ api.get("/events", (c) => streams.open(c, {
11623
+ hello: {
11624
+ type: "hello",
11625
+ daemonId: deps.daemonId,
11626
+ sequence: deps.events.sequence,
11627
+ catalogVersion: deps.documents.state.catalogVersion
11628
+ },
11629
+ subscribe: (listener) => deps.events.subscribe(listener),
11630
+ frame: (event) => ({
11631
+ event: event.type,
11632
+ id: String(event.sequence),
11633
+ data: JSON.stringify(event)
11634
+ }),
11635
+ heartbeatMs: deps.heartbeatMs,
11636
+ stallMs: deps.stallMs
11637
+ }));
11638
+ api.all("*", (c) => fail$1(c, new VdeError("E_UNKNOWN_METHOD", "Unknown API.")));
11639
+ api.onError((error, c) => fail$1(c, error));
11640
+ app.route(API_PREFIX$1, api);
11641
+ app.all("/_/*", (c) => fail$1(c, new VdeError("E_UNKNOWN_METHOD", "Unknown API.")));
11490
11642
  app.on(["GET", "HEAD"], "*", (c) => {
11491
11643
  const asset = assets.get(c.req.path);
11492
11644
  if (!asset) {
@@ -11495,12 +11647,12 @@ async function startManagementServer(deps, options = {}) {
11495
11647
  }
11496
11648
  const headers = { "Content-Type": asset.type };
11497
11649
  if (asset.immutable) headers["Cache-Control"] = "public, max-age=31536000, immutable";
11498
- if (asset.type.startsWith("text/html")) headers["Content-Security-Policy"] = uiCsp(deps.previewOrigin);
11650
+ if (asset.type.startsWith("text/html")) headers["Content-Security-Policy"] = uiCsp$1(deps.previewOrigin);
11499
11651
  if (c.req.method === "HEAD") return c.body(null, 200, headers);
11500
11652
  return c.body(new Uint8Array(asset.body), 200, headers);
11501
11653
  });
11502
11654
  app.all("*", (c) => c.text("Method Not Allowed", 405));
11503
- app.onError((error, c) => fail(c, error));
11655
+ app.onError((error, c) => fail$1(c, error));
11504
11656
  const server = serve({
11505
11657
  fetch: app.fetch,
11506
11658
  hostname: "127.0.0.1",
@@ -11517,15 +11669,347 @@ async function startManagementServer(deps, options = {}) {
11517
11669
  port,
11518
11670
  origin,
11519
11671
  eventStreams() {
11520
- let maxPending = 0;
11521
- for (const queue of streams.values()) maxPending = Math.max(maxPending, queue.pending);
11522
- return {
11523
- streams: streams.size,
11524
- maxPending
11672
+ return streams.stats();
11673
+ },
11674
+ async close() {
11675
+ streams.finishAll();
11676
+ await new Promise((resolve) => setTimeout(resolve, STREAM_FLUSH_MS$1));
11677
+ await new Promise((resolve) => {
11678
+ server.close(() => resolve());
11679
+ server.closeIdleConnections();
11680
+ setTimeout(() => server.closeAllConnections(), CLOSE_GRACE_MS$2).unref();
11681
+ });
11682
+ }
11683
+ };
11684
+ }
11685
+ //#endregion
11686
+ //#region src/server/http/mobile.ts
11687
+ const API_PREFIX = "/_/mobile/v1";
11688
+ const STREAM_FLUSH_MS = 100;
11689
+ const CLOSE_GRACE_MS$1 = 1e3;
11690
+ const IDENTITY_HEADER = "tailscale-user-login";
11691
+ function hasExactlyOne(request, name, value) {
11692
+ const values = request.headersDistinct[name];
11693
+ return values?.length === 1 && values[0] === value;
11694
+ }
11695
+ function isConfiguredPerson(request, login) {
11696
+ return hasExactlyOne(request, IDENTITY_HEADER, login);
11697
+ }
11698
+ async function jsonBody(c) {
11699
+ if ((c.req.header("content-type") ?? "").split(";")[0]?.trim().toLowerCase() !== "application/json") throw new VdeError("E_INVALID_ARGUMENT", "JSON only.");
11700
+ try {
11701
+ return await c.req.json();
11702
+ } catch {
11703
+ throw new VdeError("E_INVALID_ARGUMENT", "Invalid JSON.");
11704
+ }
11705
+ }
11706
+ function uiCsp(previewOrigin) {
11707
+ return [
11708
+ "default-src 'none'",
11709
+ "script-src 'self'",
11710
+ "style-src 'self' 'unsafe-inline'",
11711
+ `img-src 'self' data: ${previewOrigin}`,
11712
+ "font-src 'self'",
11713
+ "connect-src 'self'",
11714
+ "worker-src 'self'",
11715
+ `frame-src ${previewOrigin}`,
11716
+ "object-src 'none'",
11717
+ "base-uri 'none'",
11718
+ "form-action 'none'",
11719
+ "frame-ancestors 'none'"
11720
+ ].join("; ");
11721
+ }
11722
+ const ERRORS = {
11723
+ E_UNAUTHORIZED: {
11724
+ status: 403,
11725
+ message: "This request is not allowed."
11726
+ },
11727
+ E_DOCUMENT_NOT_FOUND: {
11728
+ status: 404,
11729
+ message: "The document is not open."
11730
+ },
11731
+ E_DOCUMENT_NOT_OPEN: {
11732
+ status: 404,
11733
+ message: "The document is not open."
11734
+ },
11735
+ E_UNKNOWN_METHOD: {
11736
+ status: 404,
11737
+ message: "Unknown API."
11738
+ },
11739
+ E_VIEW_STALE: {
11740
+ status: 409,
11741
+ message: "The document changed. Fetch the list again."
11742
+ },
11743
+ E_CURSOR_STALE: {
11744
+ status: 409,
11745
+ message: "The list changed. Fetch it again from the start."
11746
+ },
11747
+ E_INVALID_CURSOR: {
11748
+ status: 409,
11749
+ message: "The cursor expired. Fetch again from the start."
11750
+ },
11751
+ E_REVISION_UNAVAILABLE: {
11752
+ status: 409,
11753
+ message: "The document changed. Fetch the list again."
11754
+ },
11755
+ E_INVALID_ARGUMENT: {
11756
+ status: 400,
11757
+ message: "The request is invalid."
11758
+ },
11759
+ E_UNSUPPORTED_FORMAT: {
11760
+ status: 400,
11761
+ message: "This document has no text to read here."
11762
+ },
11763
+ E_DAEMON_STOPPING: {
11764
+ status: 503,
11765
+ message: "The daemon is stopping."
11766
+ }
11767
+ };
11768
+ function fail(c, error) {
11769
+ const code = isVdeError(error) ? error.code : error instanceof ZodError ? "E_INVALID_ARGUMENT" : "E_INTERNAL";
11770
+ const known = ERRORS[code];
11771
+ return c.json(errorEnvelope({
11772
+ code: known ? code : "E_INTERNAL",
11773
+ message: known?.message ?? "An internal error occurred.",
11774
+ retryable: false,
11775
+ details: {}
11776
+ }), known?.status ?? 500);
11777
+ }
11778
+ const limitQuery = number().int().min(1).max(LIMITS.listLimitMax);
11779
+ async function startMobileServer(deps, options) {
11780
+ const assets = await loadStaticAssets(deps.webRoot);
11781
+ const { settings, documents, render, views, cursors } = deps;
11782
+ const host = `${settings.host}:${String(settings.uiPort)}`;
11783
+ const origin = `https://${host}`;
11784
+ const previewOrigin = `https://${settings.host}:${String(settings.previewPort)}`;
11785
+ const streams = createEventStreams();
11786
+ const app = new Hono();
11787
+ app.use("*", async (c, next) => {
11788
+ await next();
11789
+ c.header("X-Content-Type-Options", "nosniff");
11790
+ c.header("Referrer-Policy", "no-referrer");
11791
+ if (!c.res.headers.has("Cache-Control")) c.header("Cache-Control", "no-store");
11792
+ });
11793
+ app.use("*", async (c, next) => {
11794
+ if (!deps.isOpen()) return fail(c, new VdeError("E_DAEMON_STOPPING", "Not ready."));
11795
+ const incoming = c.env.incoming;
11796
+ if (!incoming || !hasExactlyOne(incoming, "host", host)) {
11797
+ deps.onEvent?.("mobile.rejected", { reason: "host" });
11798
+ return fail(c, new VdeError("E_UNAUTHORIZED", "Host."));
11799
+ }
11800
+ if (!isConfiguredPerson(incoming, settings.login)) {
11801
+ deps.onEvent?.("mobile.rejected", { reason: "identity" });
11802
+ return fail(c, new VdeError("E_UNAUTHORIZED", "Identity."));
11803
+ }
11804
+ return next();
11805
+ });
11806
+ app.use(`${API_PREFIX}/*`, async (c, next) => {
11807
+ const requestOrigin = c.req.header("origin");
11808
+ if (requestOrigin !== void 0 && requestOrigin !== origin) {
11809
+ deps.onEvent?.("mobile.rejected", { reason: "origin" });
11810
+ return fail(c, new VdeError("E_UNAUTHORIZED", "Origin."));
11811
+ }
11812
+ const site = c.req.header("sec-fetch-site");
11813
+ if (site !== void 0 && site !== "same-origin") {
11814
+ deps.onEvent?.("mobile.rejected", { reason: "fetch-site" });
11815
+ return fail(c, new VdeError("E_UNAUTHORIZED", "Fetch site."));
11816
+ }
11817
+ if (c.req.method !== "GET" && c.req.method !== "HEAD") {
11818
+ if (requestOrigin === void 0) return fail(c, new VdeError("E_UNAUTHORIZED", "Origin."));
11819
+ }
11820
+ if (deps.isStopping()) return fail(c, new VdeError("E_DAEMON_STOPPING", "Stopping."));
11821
+ return next();
11822
+ });
11823
+ const rowOf = (summary) => ({
11824
+ documentId: summary.documentId,
11825
+ title: summary.title,
11826
+ format: summary.format,
11827
+ openedAt: summary.openedAt,
11828
+ revision: summary.revision,
11829
+ sourceState: summary.sourceState,
11830
+ effectiveMode: summary.format === "html" ? summary.interactiveAllowed ? "interactive" : "static" : null,
11831
+ viewEpoch: views.of(summary.documentId)
11832
+ });
11833
+ const requireCurrent = (documentId, revision, viewEpoch) => {
11834
+ const record = documents.state.documents[documentId];
11835
+ if (!record?.isOpen) throw new VdeError("E_DOCUMENT_NOT_OPEN", "Not open.");
11836
+ if (record.currentRevision !== revision || views.of(documentId) !== viewEpoch) throw new VdeError("E_VIEW_STALE", "Stale.");
11837
+ return record;
11838
+ };
11839
+ const api = new Hono();
11840
+ api.get("/documents", (c) => {
11841
+ const cursor = c.req.query("cursor");
11842
+ const limit = c.req.query("limit");
11843
+ let inner;
11844
+ if (cursor !== void 0) {
11845
+ const payload = cursors.decode(cursor, "mobile-list");
11846
+ if (payload["catalogVersion"] !== documents.state.catalogVersion) throw new VdeError("E_CURSOR_STALE", "Stale.");
11847
+ inner = payload["inner"];
11848
+ }
11849
+ const result = documents.list({
11850
+ limit: limit === void 0 ? LIMITS.listLimitMax : limitQuery.parse(limit),
11851
+ ...inner === void 0 ? {} : { cursor: inner }
11852
+ });
11853
+ const data = {
11854
+ daemonId: deps.daemonId,
11855
+ catalogVersion: result.catalogVersion,
11856
+ documents: result.data.documents.map(rowOf),
11857
+ nextCursor: result.data.nextCursor === null ? null : cursors.encode({
11858
+ op: "mobile-list",
11859
+ inner: result.data.nextCursor,
11860
+ catalogVersion: result.catalogVersion
11861
+ })
11862
+ };
11863
+ return c.json(successEnvelope(data, {
11864
+ command: "mobile.documents",
11865
+ catalogVersion: result.catalogVersion
11866
+ }));
11867
+ });
11868
+ api.get("/documents/:id/content", async (c) => {
11869
+ const documentId = c.req.param("id");
11870
+ const cursor = c.req.query("cursor");
11871
+ let bound;
11872
+ if (cursor === void 0) bound = {
11873
+ revision: revisionSchema.parse(c.req.query("revision")),
11874
+ viewEpoch: viewEpochSchema.parse(c.req.query("viewEpoch")),
11875
+ inner: void 0
11876
+ };
11877
+ else {
11878
+ const payload = cursors.decode(cursor, "mobile-read");
11879
+ if (payload["documentId"] !== documentId) throw new VdeError("E_INVALID_CURSOR", "Other.");
11880
+ bound = {
11881
+ revision: payload["revision"],
11882
+ viewEpoch: payload["viewEpoch"],
11883
+ inner: payload["inner"]
11525
11884
  };
11885
+ }
11886
+ if (requireCurrent(documentId, bound.revision, bound.viewEpoch).format !== "markdown") throw new VdeError("E_UNSUPPORTED_FORMAT", "Format.");
11887
+ const read = await documents.read(bound.inner === void 0 ? {
11888
+ documentId,
11889
+ revision: bound.revision,
11890
+ maxBytes: LIMITS.readMaxBytesMax
11891
+ } : {
11892
+ documentId,
11893
+ cursor: bound.inner,
11894
+ maxBytes: LIMITS.readMaxBytesMax
11895
+ });
11896
+ requireCurrent(documentId, bound.revision, bound.viewEpoch);
11897
+ const data = {
11898
+ documentId,
11899
+ revision: read.data.revision,
11900
+ content: read.data.content ?? "",
11901
+ nextCursor: read.data.nextCursor === null ? null : cursors.encode({
11902
+ op: "mobile-read",
11903
+ documentId,
11904
+ revision: bound.revision,
11905
+ viewEpoch: bound.viewEpoch,
11906
+ inner: read.data.nextCursor
11907
+ })
11908
+ };
11909
+ return c.json(successEnvelope(data, {
11910
+ command: "mobile.content",
11911
+ catalogVersion: documents.state.catalogVersion
11912
+ }));
11913
+ });
11914
+ api.post("/documents/:id/render-grants", async (c) => {
11915
+ const expected = mobileGrantParamsSchema.parse(await jsonBody(c));
11916
+ const data = await render.createMobileGrant(c.req.param("id"), expected);
11917
+ return c.json(successEnvelope(data, {
11918
+ command: "mobile.render-grant",
11919
+ catalogVersion: documents.state.catalogVersion
11920
+ }));
11921
+ });
11922
+ api.post("/render-grants/release", async (c) => {
11923
+ const { grants } = mobileReleaseParamsSchema.parse(await jsonBody(c));
11924
+ return c.json(successEnvelope({ released: render.releaseMobile(grants) }, { command: "mobile.render-release" }));
11925
+ });
11926
+ api.post("/render-grants/check", async (c) => {
11927
+ const { grant } = mobileCheckParamsSchema.parse(await jsonBody(c));
11928
+ return c.json(successEnvelope({ valid: render.checkMobile(grant) }, { command: "mobile.render-check" }));
11929
+ });
11930
+ api.post("/links/resolve", async (c) => {
11931
+ const { grant, linkId } = mobileLinkParamsSchema.parse(await jsonBody(c));
11932
+ if (!render.checkMobile(grant)) throw new VdeError("E_VIEW_STALE", "Stale.");
11933
+ const found = render.mobileLinkOf(grant, linkId);
11934
+ const documentId = found?.link.kind === "document" ? await documents.openDocumentOfLink(found.documentId, found.link.href) : null;
11935
+ if (!render.checkMobile(grant)) throw new VdeError("E_VIEW_STALE", "Stale.");
11936
+ const data = documentId === null || !documents.state.documents[documentId]?.isOpen ? { status: "not-open" } : {
11937
+ status: "open",
11938
+ documentId
11939
+ };
11940
+ return c.json(successEnvelope(data, { command: "mobile.link-resolve" }));
11941
+ });
11942
+ const frameOf = (event) => {
11943
+ let type;
11944
+ switch (event.type) {
11945
+ case "hello":
11946
+ case "resync-required":
11947
+ case "daemon-stopping":
11948
+ type = event.type;
11949
+ break;
11950
+ case "catalog-changed":
11951
+ case "document-changed":
11952
+ case "document-status":
11953
+ type = "changed";
11954
+ break;
11955
+ default: return null;
11956
+ }
11957
+ const data = {
11958
+ type,
11959
+ daemonId: event.daemonId,
11960
+ ...type === "changed" && event.documentId !== void 0 ? { documentId: event.documentId } : {}
11961
+ };
11962
+ return {
11963
+ event: type,
11964
+ data: JSON.stringify(data)
11965
+ };
11966
+ };
11967
+ api.get("/events", (c) => streams.open(c, {
11968
+ hello: {
11969
+ type: "hello",
11970
+ daemonId: deps.daemonId,
11971
+ sequence: deps.events.sequence,
11972
+ catalogVersion: documents.state.catalogVersion
11526
11973
  },
11974
+ subscribe: (listener) => deps.events.subscribe(listener),
11975
+ frame: frameOf,
11976
+ heartbeatMs: deps.heartbeatMs,
11977
+ stallMs: deps.stallMs
11978
+ }));
11979
+ api.all("*", (c) => fail(c, new VdeError("E_UNKNOWN_METHOD", "Unknown.")));
11980
+ api.onError((error, c) => fail(c, error));
11981
+ app.route(API_PREFIX, api);
11982
+ app.all("/_/*", (c) => fail(c, new VdeError("E_UNKNOWN_METHOD", "Unknown.")));
11983
+ app.on(["GET", "HEAD"], "*", (c) => {
11984
+ const path = c.req.path;
11985
+ const asset = path === "/" ? assets.get("/mobile.html") : path.startsWith("/assets/") ? assets.get(path) : void 0;
11986
+ if (!asset) {
11987
+ if (path === "/") return c.text("The phone reader UI has not been built. Run pnpm build.", 503);
11988
+ return c.text("Not Found", 404);
11989
+ }
11990
+ const headers = { "Content-Type": asset.type };
11991
+ if (asset.immutable) headers["Cache-Control"] = "public, max-age=31536000, immutable";
11992
+ if (asset.type.startsWith("text/html")) headers["Content-Security-Policy"] = uiCsp(previewOrigin);
11993
+ if (c.req.method === "HEAD") return c.body(null, 200, headers);
11994
+ return c.body(new Uint8Array(asset.body), 200, headers);
11995
+ });
11996
+ app.all("*", (c) => c.text("Method Not Allowed", 405));
11997
+ app.onError((error, c) => fail(c, error));
11998
+ const server = serve({
11999
+ fetch: app.fetch,
12000
+ hostname: "127.0.0.1",
12001
+ port: options.port
12002
+ });
12003
+ await new Promise((resolve, reject) => {
12004
+ server.once("listening", resolve);
12005
+ server.once("error", reject);
12006
+ });
12007
+ const { port } = server.address();
12008
+ return {
12009
+ port,
12010
+ eventStreams: () => streams.stats(),
11527
12011
  async close() {
11528
- for (const finish of streams.keys()) finish();
12012
+ streams.finishAll();
11529
12013
  await new Promise((resolve) => setTimeout(resolve, STREAM_FLUSH_MS));
11530
12014
  await new Promise((resolve) => {
11531
12015
  server.close(() => resolve());
@@ -11540,11 +12024,12 @@ async function startManagementServer(deps, options = {}) {
11540
12024
  const CLOSE_GRACE_MS = 1e3;
11541
12025
  const PREVIEW_PATH = /^\/r\/([A-Za-z0-9_-]{43})\/files\/(.+)$/;
11542
12026
  const ENCODED_SEPARATOR_OR_NUL = /%(2f|5c|00)/i;
11543
- function documentCsp(mode, grantBase, ancestors) {
12027
+ const LINK_RELAY_HASH = `'sha256-${createHash("sha256").update(HTML_LINK_RELAY).digest("base64")}'`;
12028
+ function documentCsp(mode, grantBase, ancestors, hasDocumentLinks) {
11544
12029
  const interactive = mode === "interactive";
11545
12030
  return [
11546
12031
  "default-src 'none'",
11547
- interactive ? `script-src 'unsafe-inline' ${grantBase}` : "script-src 'none'",
12032
+ `script-src ${interactive ? `'unsafe-inline' ${grantBase}` : hasDocumentLinks ? LINK_RELAY_HASH : "'none'"}`,
11548
12033
  `style-src 'unsafe-inline' ${grantBase}`,
11549
12034
  `img-src ${grantBase} data:`,
11550
12035
  `font-src ${grantBase}`,
@@ -11555,7 +12040,7 @@ function documentCsp(mode, grantBase, ancestors) {
11555
12040
  "base-uri 'none'",
11556
12041
  "form-action 'none'",
11557
12042
  `frame-ancestors ${ancestors.length > 0 ? ancestors.join(" ") : "'none'"}`,
11558
- interactive ? "sandbox allow-scripts" : "sandbox"
12043
+ interactive || hasDocumentLinks ? "sandbox allow-scripts" : "sandbox"
11559
12044
  ].join("; ");
11560
12045
  }
11561
12046
  const ASSET_CSP = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
@@ -11566,7 +12051,7 @@ function headersFor(file, origin, ancestors) {
11566
12051
  "X-Content-Type-Options": "nosniff",
11567
12052
  "Referrer-Policy": "no-referrer",
11568
12053
  "Cache-Control": "no-store",
11569
- "Content-Security-Policy": file.role === "document" ? documentCsp(file.mode, `${origin}/r/${file.grant}/`, ancestors) : ASSET_CSP
12054
+ "Content-Security-Policy": file.role === "document" ? documentCsp(file.mode, `${origin}/r/${file.grant}/`, ancestors, file.hasDocumentLinks) : ASSET_CSP
11570
12055
  };
11571
12056
  if (file.role === "font" || file.role === "style" || file.role === "script" || file.role === "data") headers["Access-Control-Allow-Origin"] = "null";
11572
12057
  return headers;
@@ -11600,6 +12085,9 @@ async function startPreviewServer(deps, options = {}) {
11600
12085
  };
11601
12086
  const handle = async (request, response) => {
11602
12087
  if (request.headers.host !== host) return reject(response, 404);
12088
+ if (deps.publicHost !== void 0 && request.headersDistinct["host"]?.length !== 1) return reject(response, 404);
12089
+ if (deps.isOpen && !deps.isOpen()) return reject(response, 404);
12090
+ if (deps.authorize && !deps.authorize(request)) return reject(response, 404);
11603
12091
  const method = request.method ?? "";
11604
12092
  if (method !== "GET" && method !== "HEAD") return reject(response, 405, { Allow: "GET, HEAD" });
11605
12093
  let pathname;
@@ -11611,7 +12099,7 @@ async function startPreviewServer(deps, options = {}) {
11611
12099
  const match = PREVIEW_PATH.exec(pathname);
11612
12100
  const logicalPath = match ? logicalPathOf(match[2]) : null;
11613
12101
  if (!match || logicalPath === null) return reject(response, 404);
11614
- const file = await deps.render.resolve(match[1], logicalPath);
12102
+ const file = await deps.resolve(match[1], logicalPath);
11615
12103
  if (!file) return reject(response, 404);
11616
12104
  response.writeHead(200, headersFor(file, origin, deps.frameAncestors()));
11617
12105
  response.end(method === "HEAD" ? void 0 : file.body);
@@ -11628,8 +12116,8 @@ async function startPreviewServer(deps, options = {}) {
11628
12116
  server.listen(options.port ?? 0, "127.0.0.1", () => resolve());
11629
12117
  });
11630
12118
  const { port } = server.address();
11631
- host = `127.0.0.1:${String(port)}`;
11632
- origin = `http://${host}`;
12119
+ host = deps.publicHost ?? `127.0.0.1:${String(port)}`;
12120
+ origin = deps.publicHost === void 0 ? `http://${host}` : `https://${host}`;
11633
12121
  return {
11634
12122
  port,
11635
12123
  origin,
@@ -13786,8 +14274,8 @@ const execFileAsync = promisify(execFile);
13786
14274
  const GENERATION_DIGITS = 12;
13787
14275
  const ACQUIRE_ATTEMPTS = 8;
13788
14276
  const lockInfoSchema = strictObject({
13789
- generation: number().int().positive(),
13790
- pid: number().int().positive(),
14277
+ generation: number$1().int().positive(),
14278
+ pid: number$1().int().positive(),
13791
14279
  ownerId: string().min(1),
13792
14280
  startedAt: string(),
13793
14281
  released: boolean()
@@ -13973,6 +14461,100 @@ async function releaseLock(directory, name, ownerId) {
13973
14461
  await renameWithRetry(temp, join(directory, fileNameOf(name, current.generation)));
13974
14462
  }
13975
14463
  //#endregion
14464
+ //#region src/daemon/listener-config.ts
14465
+ const LISTENER_CONFIG_FILE = "listeners.json";
14466
+ const DEFAULT_PORTS = {
14467
+ management: 43180,
14468
+ preview: 43181,
14469
+ mobileUi: 43182,
14470
+ mobilePreview: 43183
14471
+ };
14472
+ const portSchema = number$1().int().min(1).max(65535);
14473
+ const pcConfigSchema = strictObject({
14474
+ managementPort: portSchema.optional(),
14475
+ previewPort: portSchema.optional(),
14476
+ mobile: unknown().optional()
14477
+ });
14478
+ function configError(path, reason, message) {
14479
+ return new VdeError("E_DAEMON_START_FAILED", `${message} (${path})`, {
14480
+ reason: "listener-config",
14481
+ path,
14482
+ issue: reason
14483
+ });
14484
+ }
14485
+ async function readListenerConfig(stateRoot) {
14486
+ const path = join(stateRoot, LISTENER_CONFIG_FILE);
14487
+ let text;
14488
+ try {
14489
+ text = await readFile(path, "utf8");
14490
+ } catch (error) {
14491
+ const code = error.code;
14492
+ if (code === "ENOENT") {
14493
+ if (await lstat(path).then(() => "present", (inspect) => inspect.code ?? "unreadable") === "ENOENT") return {};
14494
+ }
14495
+ throw configError(path, code ?? "unreadable", "The listener settings could not be read.");
14496
+ }
14497
+ let json;
14498
+ try {
14499
+ json = JSON.parse(text);
14500
+ } catch {
14501
+ throw configError(path, "json", "The listener settings are not valid JSON.");
14502
+ }
14503
+ const parsed = pcConfigSchema.safeParse(json);
14504
+ if (!parsed.success) {
14505
+ const issue = parsed.error.issues[0];
14506
+ const where = issue && issue.path.length > 0 ? issue.path.join(".") : "root";
14507
+ throw configError(path, `invalid:${where}`, `The listener settings are invalid at ${where}.`);
14508
+ }
14509
+ return parsed.data;
14510
+ }
14511
+ function ephemeralPortsAllowed(environment) {
14512
+ const home = environment.env["VDE_OPEN_HOME"];
14513
+ return environment.env["VDE_OPEN_TEST_EPHEMERAL_PORTS"] === "1" && home !== void 0 && home !== "" && isAbsolute(home);
14514
+ }
14515
+ function resolvePcPorts(explicit, config, ephemeral) {
14516
+ const pick = (argument, configured, fallback) => argument ?? configured ?? (ephemeral ? 0 : fallback);
14517
+ const ports = {
14518
+ management: pick(explicit.managementPort, config.managementPort, DEFAULT_PORTS.management),
14519
+ preview: pick(explicit.previewPort, config.previewPort, DEFAULT_PORTS.preview)
14520
+ };
14521
+ if (ports.management !== 0 && ports.management === ports.preview) throw new VdeError("E_DAEMON_START_FAILED", `The management and preview listeners cannot share port ${String(ports.management)}.`, {
14522
+ reason: "duplicate-port",
14523
+ port: ports.management
14524
+ });
14525
+ return ports;
14526
+ }
14527
+ const mobilePortSchema = portSchema.refine((port) => port !== 443, "must not be 443");
14528
+ const DNS_LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
14529
+ const DNS_NAME = new RegExp(`^(?=.{1,253}$)${DNS_LABEL}(?:\\.${DNS_LABEL})+$`);
14530
+ const mobileSchema = strictObject({
14531
+ host: string().transform((value) => value.toLowerCase().replace(/\.$/, "")).refine((value) => DNS_NAME.test(value), "must be a full DNS name without scheme, port, or path"),
14532
+ login: string().regex(/^[!-+\--~]{1,256}$/, "must be an ASCII login name"),
14533
+ uiPort: mobilePortSchema.default(DEFAULT_PORTS.mobileUi),
14534
+ previewPort: mobilePortSchema.default(DEFAULT_PORTS.mobilePreview)
14535
+ });
14536
+ function resolveMobileConfig(raw, pcPorts) {
14537
+ if (raw === void 0) return { state: "disabled" };
14538
+ const parsed = mobileSchema.safeParse(raw);
14539
+ if (!parsed.success) {
14540
+ const issue = parsed.error.issues[0];
14541
+ return {
14542
+ state: "error",
14543
+ reason: `invalid:${issue && issue.path.length > 0 ? `mobile.${issue.path.join(".")}` : "mobile"}`
14544
+ };
14545
+ }
14546
+ const settings = parsed.data;
14547
+ const taken = [pcPorts.management, pcPorts.preview].filter((port) => port !== 0);
14548
+ if (settings.uiPort === settings.previewPort || taken.includes(settings.uiPort) || taken.includes(settings.previewPort)) return {
14549
+ state: "error",
14550
+ reason: "duplicate-port"
14551
+ };
14552
+ return {
14553
+ state: "enabled",
14554
+ settings
14555
+ };
14556
+ }
14557
+ //#endregion
13976
14558
  //#region src/daemon/logger.ts
13977
14559
  const MAX_LOG_BYTES = 1048576;
13978
14560
  function createFileLogger(stateRoot) {
@@ -14009,8 +14591,8 @@ const START_LOCK_NAME = "start.lock";
14009
14591
  const POINTER_FILE = "runtime-pointer.json";
14010
14592
  const runtimePointerSchema = strictObject({
14011
14593
  daemonId: string().min(1),
14012
- pid: number().int().positive(),
14013
- protocolVersion: number().int(),
14594
+ pid: number$1().int().positive(),
14595
+ protocolVersion: number$1().int(),
14014
14596
  version: string(),
14015
14597
  startedAt: string(),
14016
14598
  runtimeDir: string().min(1),
@@ -14106,6 +14688,19 @@ async function requirePrivateDirectoryIfExists(path, options) {
14106
14688
  const LOCK_CHECK_INTERVAL_MS = 2e3;
14107
14689
  const SHUTDOWN_CLOSE_TIMEOUT_MS = 5e3;
14108
14690
  const diagnosticsParamsSchema = strictObject({ collectGarbage: boolean().default(false) });
14691
+ async function listenOrFail(listener, port, start) {
14692
+ try {
14693
+ return await start();
14694
+ } catch (error) {
14695
+ const cause = error?.code ?? "unknown";
14696
+ throw new VdeError("E_DAEMON_START_FAILED", `The ${listener} listener could not listen on 127.0.0.1:${String(port)} (${cause}).`, {
14697
+ reason: "listen",
14698
+ listener,
14699
+ port,
14700
+ cause
14701
+ }, { cause: error });
14702
+ }
14703
+ }
14109
14704
  async function startDaemon(options) {
14110
14705
  const { environment, version } = options;
14111
14706
  const probe = options.probe ?? systemProcessProbe;
@@ -14131,6 +14726,8 @@ async function startDaemon(options) {
14131
14726
  let ipc = null;
14132
14727
  let management = null;
14133
14728
  let preview = null;
14729
+ let mobileUi = null;
14730
+ let mobilePreview = null;
14134
14731
  let watcher = null;
14135
14732
  let parse = null;
14136
14733
  let printer = null;
@@ -14181,6 +14778,8 @@ async function startDaemon(options) {
14181
14778
  await step("management", () => management?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14182
14779
  await step("pdf", () => pdf?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14183
14780
  await step("preview", () => preview?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14781
+ await step("mobile-ui", () => mobileUi?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14782
+ await step("mobile-preview", () => mobilePreview?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14184
14783
  await step("store", () => store?.close());
14185
14784
  await step("parse", () => parse?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
14186
14785
  await step("print", () => printer?.close(), SHUTDOWN_CLOSE_TIMEOUT_MS);
@@ -14213,6 +14812,10 @@ async function startDaemon(options) {
14213
14812
  return stopping;
14214
14813
  };
14215
14814
  try {
14815
+ const listenerConfig = await readListenerConfig(stateRoot);
14816
+ const ephemeral = ephemeralPortsAllowed(environment);
14817
+ const ports = resolvePcPorts(options, listenerConfig, ephemeral);
14818
+ const mobileConfig = resolveMobileConfig(listenerConfig.mobile, ports);
14216
14819
  store = await StateStore.open({
14217
14820
  root: stateRoot,
14218
14821
  fs: options.fs ?? nodeStoreFs
@@ -14242,7 +14845,9 @@ async function startDaemon(options) {
14242
14845
  analyze: (format, text) => parser.analyze(format, text)
14243
14846
  });
14244
14847
  const searching = search;
14848
+ let views = null;
14245
14849
  const emit = (event) => {
14850
+ views?.observe();
14246
14851
  if (event.type !== "focus-requested" && event.type !== "feedback-changed" && event.type !== "render-diagnostics") searching.sync();
14247
14852
  events.publish(event);
14248
14853
  if (event.type === "catalog-changed") {
@@ -14259,6 +14864,8 @@ async function startDaemon(options) {
14259
14864
  scan: (kind, text) => parser.scan(kind, text),
14260
14865
  emit
14261
14866
  });
14867
+ const viewing = createViewEpochs(documents);
14868
+ views = viewing;
14262
14869
  await documents.initializeRepositories();
14263
14870
  feedback = new FeedbackService({
14264
14871
  store: openedStore,
@@ -14275,6 +14882,10 @@ async function startDaemon(options) {
14275
14882
  documents,
14276
14883
  parse: parser,
14277
14884
  previewOrigin: () => previewOrigin,
14885
+ mobile: mobileConfig.state === "enabled" ? {
14886
+ previewOrigin: () => `https://${mobileConfig.settings.host}:${String(mobileConfig.settings.previewPort)}`,
14887
+ viewEpochOf: (documentId) => viewing.of(documentId)
14888
+ } : void 0,
14278
14889
  onMissing: (documentId) => emit({
14279
14890
  type: "render-diagnostics",
14280
14891
  documentId
@@ -14291,13 +14902,13 @@ async function startDaemon(options) {
14291
14902
  onEvent: (event, fields) => logger.log(event, fields)
14292
14903
  });
14293
14904
  pdf = exporting;
14294
- preview = await startPreviewServer({
14295
- render,
14905
+ preview = await listenOrFail("preview", ports.preview, () => startPreviewServer({
14906
+ resolve: (grant, logicalPath) => render.resolve(grant, logicalPath),
14296
14907
  frameAncestors: () => [managementOrigin, devOrigin].filter((origin) => origin !== null),
14297
14908
  onEvent: (event, fields) => logger.log(event, fields)
14298
- }, options.previewPort === void 0 ? {} : { port: options.previewPort });
14909
+ }, { port: ports.preview }));
14299
14910
  previewOrigin = preview.origin;
14300
- management = await startManagementServer({
14911
+ management = await listenOrFail("management", ports.management, () => startManagementServer({
14301
14912
  daemonId,
14302
14913
  version,
14303
14914
  documents,
@@ -14311,9 +14922,72 @@ async function startDaemon(options) {
14311
14922
  devOrigin,
14312
14923
  isStopping: () => stopping !== null,
14313
14924
  onEvent: (event, fields) => logger.log(event, fields)
14314
- }, options.managementPort === void 0 ? {} : { port: options.managementPort });
14925
+ }, { port: ports.management }));
14315
14926
  managementOrigin = management.origin;
14316
14927
  const uiUrl = `${management.origin}/`;
14928
+ let mobileStatus = mobileConfig.state === "disabled" ? { state: "disabled" } : mobileConfig.state === "error" ? {
14929
+ state: "error",
14930
+ listener: null,
14931
+ port: null,
14932
+ reason: mobileConfig.reason
14933
+ } : { state: "disabled" };
14934
+ let mobileOpen = false;
14935
+ if (mobileConfig.state === "enabled") {
14936
+ const settings = mobileConfig.settings;
14937
+ const local = ephemeral ? {
14938
+ ui: 0,
14939
+ preview: 0
14940
+ } : {
14941
+ ui: settings.uiPort,
14942
+ preview: settings.previewPort
14943
+ };
14944
+ let failing = "preview";
14945
+ try {
14946
+ mobilePreview = await listenOrFail("mobile preview", local.preview, () => startPreviewServer({
14947
+ resolve: (grant, logicalPath) => render.resolveMobile(grant, logicalPath),
14948
+ frameAncestors: () => [`https://${settings.host}:${String(settings.uiPort)}`],
14949
+ publicHost: `${settings.host}:${String(settings.previewPort)}`,
14950
+ authorize: (request) => isConfiguredPerson(request, settings.login),
14951
+ isOpen: () => mobileOpen,
14952
+ onEvent: (event, fields) => logger.log(`mobile.${event}`, fields)
14953
+ }, { port: local.preview }));
14954
+ failing = "ui";
14955
+ mobileUi = await listenOrFail("mobile UI", local.ui, () => startMobileServer({
14956
+ daemonId,
14957
+ settings,
14958
+ documents,
14959
+ events,
14960
+ render,
14961
+ views: viewing,
14962
+ cursors,
14963
+ webRoot: webRootPath(),
14964
+ isStopping: () => stopping !== null,
14965
+ isOpen: () => mobileOpen,
14966
+ onEvent: (event, fields) => logger.log(event, fields)
14967
+ }, { port: local.ui }));
14968
+ mobileOpen = true;
14969
+ mobileStatus = {
14970
+ state: "ready",
14971
+ uiUrl: `https://${settings.host}:${String(settings.uiPort)}/`
14972
+ };
14973
+ } catch (error) {
14974
+ await mobileUi?.close();
14975
+ await mobilePreview?.close();
14976
+ mobileUi = null;
14977
+ mobilePreview = null;
14978
+ const cause = error instanceof VdeError && typeof error.details["cause"] === "string" ? error.details["cause"] : "unknown";
14979
+ mobileStatus = {
14980
+ state: "error",
14981
+ listener: failing,
14982
+ port: failing === "ui" ? settings.uiPort : settings.previewPort,
14983
+ reason: cause
14984
+ };
14985
+ logger.log("mobile.start-failed", {
14986
+ listener: failing,
14987
+ code: cause
14988
+ });
14989
+ }
14990
+ }
14317
14991
  watcher = createWatchService({
14318
14992
  documents,
14319
14993
  onEvent: (event, fields) => logger.log(event, fields)
@@ -14334,7 +15008,8 @@ async function startDaemon(options) {
14334
15008
  stateRoot,
14335
15009
  openDocuments: openedStore.payload.openOrder.length,
14336
15010
  catalogVersion: openedStore.payload.catalogVersion,
14337
- uiUrl
15011
+ uiUrl,
15012
+ mobile: mobileStatus
14338
15013
  },
14339
15014
  catalogVersion: openedStore.payload.catalogVersion
14340
15015
  };
@@ -14358,6 +15033,14 @@ async function startDaemon(options) {
14358
15033
  maxPending: 0
14359
15034
  },
14360
15035
  renderGrants: render.grantCount,
15036
+ mobileEventStreams: mobileUi?.eventStreams() ?? {
15037
+ streams: 0,
15038
+ maxPending: 0
15039
+ },
15040
+ ...ephemeral && mobileStatus.state === "ready" && mobileUi && mobilePreview ? { mobileBoundPorts: {
15041
+ ui: mobileUi.port,
15042
+ preview: mobilePreview.port
15043
+ } } : {},
14361
15044
  retained: {
14362
15045
  documents: documents.retainedCounts(),
14363
15046
  search: search?.retainedCounts() ?? {},
@@ -14459,4 +15142,4 @@ async function startDaemon(options) {
14459
15142
  };
14460
15143
  }
14461
15144
  //#endregion
14462
- export { decodeStateFile as C, daemonEntryPath as D, resolveStateRoot as E, referencedBlobs as O, renameWithRetry as S, resolveRuntimeLocation as T, HANDSHAKE_TIMEOUT_MS as _, DAEMON_LOCK_NAME as a, proofMatches as b, readIpcKey as c, inspectOwner as d, readCurrentLock as f, encodeFrame as g, FrameDecoder as h, requirePrivateDirectoryIfExists as i, version as k, readPointer as l, systemProcessProbe as m, ensurePrivateDirectory as n, POINTER_FILE as o, releaseLock as p, inspectPrivateDirectory as r, START_LOCK_NAME as s, startDaemon as t, acquireLock as u, computeProof as v, currentPathEnvironment as w, removeWithRetry as x, createNonce as y };
15145
+ 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 };