@vite-hub/comments 0.6.1 → 0.8.0

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 (70) hide show
  1. package/README.md +8 -12
  2. package/dist/anchor.d.ts +1 -1
  3. package/dist/{client-diagnostics-D987sEK7.js → client-diagnostics-DoXqdnBd.js} +8 -0
  4. package/dist/client-request-B1DCz3a9.js +29 -0
  5. package/dist/client.d.ts +48 -223
  6. package/dist/client.js +232 -569
  7. package/dist/database.d.ts +1 -2
  8. package/dist/database.js +1 -1
  9. package/dist/{define-C2tnAtBU.js → define-C-LUOouq.js} +1 -1
  10. package/dist/{errors-C0VwRHiy.js → errors-C5utwZ5H.js} +0 -24
  11. package/dist/{errors-ByCRdInk.js → errors-DeSEHzRf.js} +1 -13
  12. package/dist/hosted/hosted-comments/frame.js +4 -1
  13. package/dist/hosted/hosted-comments/tools.js +362 -0
  14. package/dist/hosted/hosted-comments.js +1 -19
  15. package/dist/{index-D1T7RJ4R.d.ts → index-d6NsDxu9.d.ts} +4 -112
  16. package/dist/index.d.ts +4 -5
  17. package/dist/index.js +6 -20
  18. package/dist/{install-D6hXZaSN.js → install-BueV_fJY.js} +22 -780
  19. package/dist/{install-9L4ASzUC.d.ts → install-F-_O7zDr.d.ts} +5 -11
  20. package/dist/{installed-bPUnazFf.js → installed-BqQKo6WC.js} +2 -7
  21. package/dist/{database-Cguz3hZL.js → migrate-oseJAYbm.js} +2 -46
  22. package/dist/{operations-B1ALn4VS.js → operations-0llC5kKO.js} +49 -51
  23. package/dist/{operations-8hqTi0DH.d.ts → operations-DFLer1fR.d.ts} +1 -0
  24. package/dist/{operations-BkkrI8a3.d.ts → operations-jaihyWw2.d.ts} +36 -4
  25. package/dist/operations.d.ts +3 -3
  26. package/dist/operations.js +2 -2
  27. package/dist/overlay/client-ZBsUybIe.js +4 -0
  28. package/dist/overlay/overlay.js +68 -37
  29. package/dist/page/loader.js +36 -30
  30. package/dist/page-BgvzzsJb.d.ts +32 -0
  31. package/dist/{page-2NzFladc.js → page-CDhmXO-y.js} +24 -1
  32. package/dist/{page-tools-shared-fvmJQCrP.js → page-tools-shared-BCdvqA4S.js} +41 -6
  33. package/dist/{plugin-l4sPt5-n.js → plugin-DGUqlc3C.js} +9 -9
  34. package/dist/realtime.d.ts +10 -9
  35. package/dist/realtime.js +2 -4
  36. package/dist/{rpc-BYmbVkr8.js → rpc-kkxzQ3Qy.js} +1 -1
  37. package/dist/rpc.js +1 -1
  38. package/dist/runtime/auth.d.ts +1 -2
  39. package/dist/runtime/auth.js +1 -1
  40. package/dist/runtime/client-request-plugin.d.ts +2 -0
  41. package/dist/runtime/client-request-plugin.js +21 -0
  42. package/dist/runtime/console.js +2 -2
  43. package/dist/runtime/index.d.ts +6 -8
  44. package/dist/runtime/index.js +25 -153
  45. package/dist/{server-DvSehkPP.js → server-CAMs6viR.js} +1 -1
  46. package/dist/server.d.ts +11 -7
  47. package/dist/server.js +8 -7
  48. package/dist/{store-DvNTDNgn.d.ts → service-CMVA_Ryv.d.ts} +67 -1
  49. package/dist/{service-BIGe1Hpo.js → service-DaMq8TBw.js} +35 -33
  50. package/dist/{session-CCRLR9bf.js → session-B7GDrqsK.js} +207 -41
  51. package/dist/{session-CN4irEqf.d.ts → session-EzQqBeE8.d.ts} +2 -3
  52. package/dist/{table-names-BIHjuEFK.js → table-names-DUmWROM4.js} +1 -3
  53. package/dist/testing.js +1 -1
  54. package/dist/{define-B1jLSPe9.d.ts → types-qzJKgWYS.d.ts} +157 -4
  55. package/dist/vite.d.ts +3 -20
  56. package/dist/vite.js +20 -52
  57. package/package.json +9 -8
  58. package/dist/database-CPua6Q6_.d.ts +0 -573
  59. package/dist/hosted/hosted-comments/client-Czl2zu9P.js +0 -4
  60. package/dist/hosted/hosted-comments/dist-DyVmH21U.js +0 -14
  61. package/dist/hosted/hosted-comments/overlay-DpS0P-nd.js +0 -186
  62. package/dist/hosted/hosted-comments/protocol-DuB0Zhs-.js +0 -1
  63. package/dist/hosted/hosted-comments/rest-transport-CKZG_jZ4.js +0 -1
  64. package/dist/hosted/hosted-comments/tools-D8xg-kDW.js +0 -126
  65. package/dist/overlay/client-C7ftI-CB.js +0 -4
  66. package/dist/overlay/dist-yIZmvSaU.js +0 -1
  67. package/dist/page-DE71P_gQ.d.ts +0 -11
  68. package/dist/request-origin-YPzfE2eh.js +0 -48
  69. package/dist/service-IvgrI4XM.d.ts +0 -71
  70. package/dist/types-l6GOb_yc.d.ts +0 -206
@@ -1,6 +1,19 @@
1
+ import { C as CommentsDefinition, T as CommentsPeople, j as CommentsUser } from "./types-qzJKgWYS.js";
1
2
  import { a as commentThreads, i as commentMessages, n as commentCounters } from "./database-DUs3c2al.js";
2
3
  import { D as CommentUser, S as CommentStatus, T as CommentThread, b as CommentMetadata, n as CommentActor, r as CommentAnchor, s as CommentContext, v as CommentListQuery, w as CommentSubject } from "./types-BX3vH18p.js";
4
+ import "valibot";
3
5
  import { LibSQLDatabase } from "drizzle-orm/libsql";
6
+ /** The part of `checkRateLimit()` from `vite-hub/rate-limit` that a public write calls. */
7
+ type SharedRateLimit = (request: Request, name: string, options: {
8
+ key: string;
9
+ limit: number;
10
+ window: `${number}${"ms" | "s" | "m" | "h" | "d"}`;
11
+ }) => Promise<[unknown, {
12
+ allowed: boolean;
13
+ reason?: string;
14
+ retryAfter?: number;
15
+ cause?: unknown;
16
+ } | undefined]>;
4
17
  /**
5
18
  * The Drizzle database that the store uses. The store calls `select`, `insert`, `update`, and `delete` (with
6
19
  * `onConflictDoNothing()` and `returning()`), which SQLite, libSQL, D1, and Postgres Drizzle databases all offer, and
@@ -92,4 +105,57 @@ interface CommentsStore {
92
105
  knownUsersByIds: (ids: readonly string[], canRead: (thread: CommentThread) => Promise<boolean>) => Promise<CommentUser[]>;
93
106
  }
94
107
  declare function createCommentsStore(database: CommentsDatabase, tables?: CommentsTables): CommentsStore;
95
- export { createCommentsStore as i, CommentsStore as n, CommentsTables as r, CommentsDatabase as t };
108
+ /** Longest message, in characters. */
109
+ declare const maximumCommentBodyLength = 10000;
110
+ /** The parts of a Blob store that attachments use: `blob` of `@vite-hub/blob`. */
111
+ interface CommentsAttachmentStore {
112
+ put: (pathname: string, body: Uint8Array, options: {
113
+ contentType: string;
114
+ }) => Promise<readonly [unknown, unknown]>;
115
+ get?: (pathname: string) => Promise<readonly [unknown, Blob | null | undefined]>;
116
+ }
117
+ /** A file to answer, with the headers that keep a browser from running it. */
118
+ interface CommentsAttachmentBody {
119
+ key: string;
120
+ name: string;
121
+ /** The stored media type when Comments attaches that type, else `application/octet-stream`. */
122
+ type: string;
123
+ size: number;
124
+ /** Whether a browser may show it in the page: images other than SVG. */
125
+ inline: boolean;
126
+ data: Blob;
127
+ }
128
+ /** The pull request sync of `defineComments({ forge })`. */
129
+ interface CommentsForgeHooks {
130
+ /** Starts the sync of a thread after a change. */
131
+ changed: (threadId: string) => void;
132
+ /** The threads with their `forge` link. */
133
+ attach: (threads: CommentThread[]) => Promise<CommentThread[]>;
134
+ }
135
+ /** Everything that the comment operations, the server API, and the overlay API share. */
136
+ interface CommentsRuntime {
137
+ definition: CommentsDefinition;
138
+ /**
139
+ * The app's `identify`, given the server event of a call. With it, the comment operations ask it for the user, as
140
+ * the overlay API does, instead of taking the Console's user.
141
+ */
142
+ identify?: (event: unknown) => Promise<CommentsUser | null>;
143
+ store: CommentsStore;
144
+ /** The Auth adapter. `people` wins over it. Without both, `@` finds the authors that the store knows. */
145
+ users?: CommentsPeople;
146
+ /** Vite's serve command, for the default guest policy. */
147
+ development?: boolean;
148
+ /** The Blob store for attachments, when the app has one and no `storeAttachment`. */
149
+ attachments?: CommentsAttachmentStore;
150
+ forge?: CommentsForgeHooks;
151
+ /**
152
+ * `checkRateLimit` of ViteHub Rate Limit, when it counts in a KV store that every server process shares. Guest writes
153
+ * then count under the Rate Limit name `comments`. Without it, they count in the memory of this process.
154
+ */
155
+ rateLimit?: SharedRateLimit;
156
+ /** Work that runs after the answer, such as `onMention`. `flush()` of the server API waits for it. */
157
+ background?: (task: Promise<unknown>) => void;
158
+ /** Tells the open pages of a thread that it changed, such as through a Realtime notice to its page room. */
159
+ changed?: (thread: CommentThread) => Promise<void>;
160
+ }
161
+ export { maximumCommentBodyLength as a, CommentsTables as c, CommentsRuntime as i, createCommentsStore as l, CommentsAttachmentStore as n, CommentsDatabase as o, CommentsForgeHooks as r, CommentsStore as s, CommentsAttachmentBody as t, SharedRateLimit as u };
@@ -1,9 +1,9 @@
1
1
  import { t as replyMessageId } from "./reply-id-Cm9FGOBs.js";
2
- import { t as commentsErrorDiagnostics } from "./errors-ByCRdInk.js";
3
2
  import { t as isPagePath } from "./path-8yqMd8zR.js";
3
+ import { t as commentsErrorDiagnostics } from "./errors-DeSEHzRf.js";
4
4
  import { t as foldName } from "./fold-name-g-xg0mQk.js";
5
5
  import { r as guestIdPrefix } from "./identity-CT7-UGmS.js";
6
- import { i as defaultPolicy, o as deniedForMissingPolicy, t as builtinCommentSubjects } from "./define-C2tnAtBU.js";
6
+ import { i as defaultPolicy, o as deniedForMissingPolicy, t as builtinCommentSubjects } from "./define-C-LUOouq.js";
7
7
  import { t as logFailure } from "./request-log-DllKQXj7.js";
8
8
  import * as v from "valibot";
9
9
  // ../internal/src/runtime/client-rate-limit.ts
@@ -228,7 +228,13 @@ function peopleOf(runtime, reader, gate, console) {
228
228
  }
229
229
  /** People that `@` suggests to `user`, without the ones that may not be mentioned in the thread. */
230
230
  async function suggest(runtime, input) {
231
- const found = await peopleOf(runtime, input.user, input.gate, input.console).search(input.query, input.limit * 2);
231
+ const subject = input.subject ?? input.thread?.subject;
232
+ const context = {
233
+ user: input.user,
234
+ ...input.thread ? { thread: input.thread } : {},
235
+ ...subject ? { subject } : {}
236
+ };
237
+ const found = await peopleOf(runtime, input.user, input.gate, input.console).search(input.query, input.limit * 2, context);
232
238
  const needle = foldName(input.query.trim());
233
239
  const people = [];
234
240
  for (const person of found) {
@@ -338,17 +344,34 @@ function newId(prefix) {
338
344
  return `${prefix}_${crypto.randomUUID()}`;
339
345
  }
340
346
  /**
341
- * Runs `onComment` before the answer and `onMention` after it, for one saved message. A failure is logged and never
342
- * fails the comment.
347
+ * Runs `onComment` before the answer and `onMention` after it, for one saved message. Work that `onComment` gives to
348
+ * `waitUntil` also runs after the answer. A failure is logged and never fails the comment.
343
349
  */
344
350
  async function announce(runtime, thread, message, mentions, fresh, options) {
345
351
  if (!message) return;
346
352
  const { onComment, onMention } = runtime.definition;
353
+ const keep = (promise) => {
354
+ options.waitUntil?.(promise);
355
+ runtime.background?.(promise);
356
+ };
357
+ const failedLater = (hook) => (error) => {
358
+ logFailure({
359
+ field: "comments",
360
+ fields: {
361
+ hook,
362
+ thread: thread.id
363
+ },
364
+ message: `Comments ${hook} failed`,
365
+ error,
366
+ waitUntil: keep
367
+ }, () => globalThis.console.error(`[vitehub] Comments ${hook} failed:`, error));
368
+ };
347
369
  if (options.comment && onComment) try {
348
370
  await onComment({
349
371
  mentions,
350
372
  message,
351
- thread
373
+ thread,
374
+ waitUntil: (promise) => keep(promise.catch(failedLater("onComment")))
352
375
  });
353
376
  } catch (error) {
354
377
  logFailure({
@@ -364,33 +387,12 @@ async function announce(runtime, thread, message, mentions, fresh, options) {
364
387
  }
365
388
  if (!onMention || !fresh.length) return;
366
389
  const link = subjectDefinition(runtime, thread.subject.kind)?.link?.(thread);
367
- const keep = (promise) => {
368
- options.waitUntil?.(promise);
369
- runtime.background?.(promise);
370
- };
371
- const task = (async () => {
372
- try {
373
- await onMention({
374
- message,
375
- thread,
376
- users: fresh,
377
- ...link ? { link } : {}
378
- });
379
- } catch (error) {
380
- logFailure({
381
- field: "comments",
382
- fields: {
383
- hook: "onMention",
384
- thread: thread.id
385
- },
386
- message: "Comments onMention failed",
387
- error,
388
- waitUntil: keep
389
- }, () => globalThis.console.error("[vitehub] Comments onMention failed:", error));
390
- }
391
- })();
392
- options.waitUntil?.(task);
393
- runtime.background?.(task);
390
+ keep((async () => onMention({
391
+ message,
392
+ thread,
393
+ users: fresh,
394
+ ...link ? { link } : {}
395
+ }))().catch(failedLater("onMention")));
394
396
  }
395
397
  /** The thread that an earlier `createThread` with this `requestId` stored. A retry gets it back before the create checks. */
396
398
  async function earlierThread(runtime, input) {
@@ -1,6 +1,6 @@
1
- import { f as viteHubPageToolsWanted, l as viteHubPageToolsLoader, n as viteHubBasePath, o as viteHubPageToolsHintCookie, p as withViteHubBase, r as viteHubPageSessionPath, s as viteHubPageToolsInlineScript, t as readViteHubPageAccount, u as viteHubPageToolsMarker } from "./page-tools-shared-fvmJQCrP.js";
2
- import { r as matchesPublicOrigin, t as forwardedRequestOrigin } from "./request-origin-YPzfE2eh.js";
3
- import { c as normalizeCommentPage } from "./page-2NzFladc.js";
1
+ import { a as viteHubPageSessionPath, c as viteHubPageToolsHintCookie, d as viteHubPageToolsLoader, f as viteHubPageToolsMarker, h as withViteHubBase, i as viteHubPageSessionHandoffScript, l as viteHubPageToolsInlineScript, m as viteHubPageToolsWanted, n as readViteHubPageSession, p as viteHubPageToolsQuery, r as viteHubBasePath, t as readViteHubPageAccount } from "./page-tools-shared-BCdvqA4S.js";
2
+ import { t as clientRequest } from "./client-request-B1DCz3a9.js";
3
+ import { p as normalizeCommentPage } from "./page-CDhmXO-y.js";
4
4
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
5
5
  // ../internal/src/runtime/page-tools-html.ts
6
6
  /** The effective script-element directive is shared by HTTP and HTML meta policies. */
@@ -30,7 +30,7 @@ function isGeneratedCheck(inline) {
30
30
  try {
31
31
  const path = JSON.parse(inline.slice(at + 7, -1));
32
32
  const nonce = tagNonce(inline);
33
- return typeof path === "string" && path.endsWith("/_vitehub/page/assets/loader.js?v=22") && viteHubPageToolsInlineScript(path.slice(0, -36), nonce) === `${inline}<\/script>`;
33
+ return typeof path === "string" && path.endsWith("/_vitehub/page/assets/loader.js?v=28") && viteHubPageToolsInlineScript(path.slice(0, -36), nonce) === `${inline}<\/script>`;
34
34
  } catch {
35
35
  return false;
36
36
  }
@@ -47,8 +47,12 @@ function tagEnd(text) {
47
47
  }
48
48
  return -1;
49
49
  }
50
- /** Scan HTML tokens across chunks; only active script elements can own the loader marker. */
51
- function pageToolsHtmlTransform(loader) {
50
+ /**
51
+ * Scan HTML tokens across chunks; only active script elements can own the loader marker. `late` gives more markup for
52
+ * the end of the body, with the nonce of the loader tag. It is called once, when the transform reaches `</body>` or the
53
+ * end of the page, so it can give what became known while the page streamed.
54
+ */
55
+ function pageToolsHtmlTransform(loader, late) {
52
56
  const decoder = new TextDecoder();
53
57
  const encoder = new TextEncoder();
54
58
  let pending = "";
@@ -58,6 +62,7 @@ function pageToolsHtmlTransform(loader) {
58
62
  let templates = 0;
59
63
  let present = false;
60
64
  let done = false;
65
+ const ending = () => late?.(tagNonce(loader)) ?? "";
61
66
  return new TransformStream({
62
67
  transform(chunk, controller) {
63
68
  pending += decoder.decode(chunk, { stream: true });
@@ -139,6 +144,7 @@ function pageToolsHtmlTransform(loader) {
139
144
  if (nonce) loader = loader.replace(` ${viteHubPageToolsMarker}`, ` nonce="${nonce}" ${viteHubPageToolsMarker}`);
140
145
  }
141
146
  if (name === "body" && closing && !templates) {
147
+ emit(ending());
142
148
  if (!present) emit(loader);
143
149
  done = true;
144
150
  }
@@ -159,10 +165,54 @@ function pageToolsHtmlTransform(loader) {
159
165
  },
160
166
  flush(controller) {
161
167
  const rest = inline + pending + decoder.decode();
162
- controller.enqueue(encoder.encode(rest + (done || present ? "" : loader)));
168
+ controller.enqueue(encoder.encode(rest + (done ? "" : ending()) + (done || present ? "" : loader)));
163
169
  }
164
170
  });
165
171
  }
172
+ // ../internal/src/runtime/request-origin.ts
173
+ function firstHeaderValue(headers, name) {
174
+ return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
175
+ }
176
+ const applicationOriginKey = Symbol.for("vitehub.request.application-origin");
177
+ const requestGlobals = globalThis;
178
+ function setApplicationRequestOrigin(request, origin) {
179
+ (requestGlobals[applicationOriginKey] ??= /* @__PURE__ */ new WeakMap()).set(request, origin);
180
+ }
181
+ function applicationRequestOrigin(request) {
182
+ return requestGlobals[applicationOriginKey]?.get(request) ?? forwardedRequestOrigin(request);
183
+ }
184
+ /**
185
+ * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
186
+ * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
187
+ * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
188
+ */
189
+ function forwardedRequestOrigin(request) {
190
+ const url = new URL(request.url);
191
+ const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
192
+ const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
193
+ const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
194
+ if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
195
+ try {
196
+ return new URL(`${protocol}://${host}`).origin;
197
+ } catch {
198
+ return url.origin;
199
+ }
200
+ }
201
+ /**
202
+ * Whether a request came in on one of the public `origins` of the app, such as the origin of `vitehub({ publicUrl })`.
203
+ * It compares the host that the client used, so a proxy that does not forward the scheme still matches. A loopback
204
+ * host, such as `localhost:3000` for a preview or a proxy that does not forward the host, also matches: it cannot be a
205
+ * second public hostname. Every request matches when `origins` is empty.
206
+ */
207
+ function matchesPublicOrigin(request, origins) {
208
+ if (origins.length === 0) return true;
209
+ const { host, hostname } = new URL(forwardedRequestOrigin(request));
210
+ return isLoopbackHostname(hostname) || origins.some((origin) => new URL(origin).host === host);
211
+ }
212
+ /** `localhost`, `[::1]`, or an IPv4 address in `127.0.0.0/8`. URL parsing writes IPv4 addresses as four decimal parts. */
213
+ function isLoopbackHostname(hostname) {
214
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(hostname);
215
+ }
166
216
  // ../internal/src/runtime/page-tools.ts
167
217
  const stateKey = Symbol.for("vitehub.page-tools");
168
218
  const scope = globalThis;
@@ -187,15 +237,16 @@ function registerViteHubPageTool(nitroApp, tool) {
187
237
  const grants = state().grants ??= /* @__PURE__ */ new Map();
188
238
  for (const grant of tool.grants ?? []) grants.set(grant.id, grant);
189
239
  }
190
- /** The account of a visitor, or `undefined` without a reader, without a session, or when the reader fails. */
240
+ /** The account of a visitor, none without a reader or a session, and `failed` when the reader throws. */
191
241
  async function readAccount(nitroApp, request) {
192
242
  const read = state().accounts?.get(nitroApp);
193
- if (!read) return void 0;
243
+ if (!read) return {};
194
244
  try {
195
- return readViteHubPageAccount(await read({ request }));
245
+ const account = readViteHubPageAccount(await read({ request }));
246
+ return account ? { account } : {};
196
247
  } catch (error) {
197
248
  console.error("[vitehub] The page tools could not read the signed-in person. The pill shows no account for this request.", error);
198
- return;
249
+ return { failed: true };
199
250
  }
200
251
  }
201
252
  /**
@@ -211,7 +262,8 @@ function viteHubSiteVisitorReader() {
211
262
  }
212
263
  /** Whether the app serves its page tools on the origin of the request. Every origin counts for an app without `origins`. */
213
264
  function servesOrigin(nitroApp, request) {
214
- return matchesPublicOrigin(request, state().origins?.get(nitroApp) ?? []);
265
+ const origins = state().origins?.get(nitroApp) ?? [];
266
+ return matchesPublicOrigin(request, typeof origins === "function" ? origins() : origins);
215
267
  }
216
268
  /** The path of a URL below the app base. A path outside the base stays as it is. */
217
269
  function pathBelow(base, pathname) {
@@ -236,12 +288,14 @@ function pageAddition(nitroApp, request, base) {
236
288
  function loaderTag(base, nonce) {
237
289
  return `<script type="module" src="${base}${viteHubPageToolsLoader}"${nonce ? ` nonce="${nonce}"` : ""} ${viteHubPageToolsMarker}><\/script>`;
238
290
  }
291
+ const sessionCompleteHeader = "x-vitehub-page-session";
239
292
  function sessionResponse(value, init = {}) {
240
293
  const headers = new Headers({
241
294
  "cache-control": "private, no-store",
242
295
  "content-type": "application/json; charset=utf-8"
243
296
  });
244
297
  if (init.cookie) headers.append("set-cookie", init.cookie);
298
+ if (init.complete) headers.set(sessionCompleteHeader, "complete");
245
299
  return new Response(JSON.stringify(value), {
246
300
  headers,
247
301
  status: init.status ?? 200
@@ -253,7 +307,8 @@ function sessionResponse(value, init = {}) {
253
307
  * each tool `script` path gets it. When at least one tool is allowed, the answer also has the `account` of a signed-in
254
308
  * visitor, from the reader of `registerViteHubPageAccount()`. An anonymous visitor never gets one. It sets the hint cookie to `1` when at least one tool is allowed, and to `0` when
255
309
  * none is, so a signed-in person without access does not ask again on each page. A tool whose check throws is not
256
- * allowed. Requests from other sites get 403 and run no check. An origin that the app does not serve its page tools on
310
+ * allowed. The answer has `x-vitehub-page-session: complete` when every check and the account reader answered without
311
+ * throwing, so a denied tool or a missing account is the decision for this visitor and not a failure. Requests from other sites get 403 and run no check. An origin that the app does not serve its page tools on
257
312
  * gets 404.
258
313
  */
259
314
  async function respondViteHubPageSession(nitroApp, request) {
@@ -262,7 +317,7 @@ async function respondViteHubPageSession(nitroApp, request) {
262
317
  why: "The page tools session accepts GET only."
263
318
  } }, { status: 405 });
264
319
  const origin = request.headers.get("origin");
265
- if (origin && origin !== forwardedRequestOrigin(request) || request.headers.get("sec-fetch-site") === "cross-site") return sessionResponse({ error: {
320
+ if (origin && origin !== applicationRequestOrigin(request) || request.headers.get("sec-fetch-site") === "cross-site") return sessionResponse({ error: {
266
321
  code: "VITEHUB_PAGE_TOOLS_CROSS_ORIGIN",
267
322
  why: "The page tools session answers the site's own pages only."
268
323
  } }, { status: 403 });
@@ -276,7 +331,7 @@ async function respondViteHubPageSession(nitroApp, request) {
276
331
  return await tool.allowed({ request });
277
332
  } catch (error) {
278
333
  console.error(`[vitehub] The visitor check of the page tool "${tool.id}" failed. The tool stays off for this request.`, error);
279
- return false;
334
+ return null;
280
335
  }
281
336
  }));
282
337
  const pathname = new URL(request.url).pathname;
@@ -287,11 +342,14 @@ async function respondViteHubPageSession(nitroApp, request) {
287
342
  ...checks[index] === "lazy" ? { lazy: true } : {},
288
343
  script: withViteHubBase(base, tool.script)
289
344
  }] : []);
290
- const account = tools.length > 0 ? await readAccount(nitroApp, request) : void 0;
345
+ const { account, failed } = tools.length > 0 ? await readAccount(nitroApp, request) : {};
291
346
  return sessionResponse(account ? {
292
347
  tools,
293
348
  account
294
- } : { tools }, { cookie: viteHubPageToolsHintCookie(tools.length > 0) });
349
+ } : { tools }, {
350
+ cookie: viteHubPageToolsHintCookie(tools.length > 0),
351
+ complete: !failed && !checks.includes(null)
352
+ });
295
353
  }
296
354
  /**
297
355
  * The route of `GET /_vitehub/page/tools`: a Fetchable (https://fetchable.org). `installViteHubPageTools()` binds
@@ -312,17 +370,109 @@ const viteHubPageSessionHandler = { async fetch(request) {
312
370
  function scriptNonce(headers) {
313
371
  return scriptPolicyNonce(headers.get("content-security-policy") ?? "");
314
372
  }
315
- /**
316
- * Inserts the loader script tag before `</body>` of a streamed HTML body, or at its end when it has none. `base` is the
317
- * path of the app base, such as `/portal`. A page that already has the loader, such as a single page app whose
318
- * `index.html` Vite changed, gets no second one. The generated SPA inline check becomes the external loader, with
319
- * the response policy's nonce when present. This supports header or meta policies that allow same-origin external
320
- * scripts but block inline scripts. The page varies per person, so it drops `content-length` and sends
321
- * `cache-control: private, no-store`. Other responses return unchanged, including compressed HTML. `policyHeaders`
322
- * supplies the effective CSP when the host keeps it outside the Response.
323
- */
324
- function injectPageToolsLoader(response, base = "", policyHeaders) {
325
- return transformPage(response, () => loaderTag(base, scriptNonce(policyHeaders ?? response.headers)), true);
373
+ function attribute(value) {
374
+ return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;");
375
+ }
376
+ function handoffMarkup(handoff, nonce) {
377
+ const preloads = handoff.session.tools.filter((tool) => !tool.lazy).map((tool) => `<link rel="modulepreload" href="${attribute(tool.script)}"${nonce ? ` nonce="${nonce}"` : ""}>`);
378
+ return `${viteHubPageSessionHandoffScript(handoff, nonce)}${preloads.join("")}`;
379
+ }
380
+ const sharedCacheHeader = /^(?:(?:[a-z0-9-]+-)?cdn-cache-control|surrogate-control)$/;
381
+ const sharedCacheRules = [
382
+ "isr",
383
+ "swr",
384
+ "cache",
385
+ "prerender"
386
+ ];
387
+ function sharedCacheMayStore(request, response) {
388
+ const control = response.headers.get("cache-control")?.toLowerCase() ?? "";
389
+ if (/(?:^|[\s,])(?:public|s-maxage)(?:[\s,=]|$)/.test(control)) return true;
390
+ for (const [name] of response.headers) if (sharedCacheHeader.test(name)) return true;
391
+ const context = Reflect.get(request, "context");
392
+ if (context === null || typeof context !== "object" || !Reflect.get(context, "nitro")) return true;
393
+ const rules = Reflect.get(context, "routeRules");
394
+ if (rules === void 0) return false;
395
+ if (rules === null || typeof rules !== "object") return true;
396
+ return sharedCacheRules.some((name) => {
397
+ const rule = Reflect.get(rules, name);
398
+ return rule !== void 0 && rule !== null && rule !== false;
399
+ });
400
+ }
401
+ function acceptsHtml(request) {
402
+ return request.headers.get("accept")?.split(",").some((range) => {
403
+ const [type, ...parameters] = range.split(";").map((part) => part.trim());
404
+ if (type?.toLowerCase() !== "text/html") return false;
405
+ const quality = parameters.find((part) => /^q\s*=/i.test(part))?.split("=")[1]?.trim();
406
+ return quality === void 0 || Number(quality) > 0 && Number(quality) <= 1;
407
+ }) === true;
408
+ }
409
+ function mayHandOffSession(request) {
410
+ return request.method === "GET" && !request.headers.has("x-nitro-prerender") && acceptsHtml(request) && (request.headers.has("cookie") || request.headers.has("authorization"));
411
+ }
412
+ function sessionRequestFor(request, base) {
413
+ const url = new URL(request.url);
414
+ const forwarded = request.headers.get("x-forwarded-proto")?.split(",", 1)[0]?.trim().toLowerCase();
415
+ if (forwarded && `${forwarded}:` !== url.protocol) return void 0;
416
+ const target = new URL(`${base}${viteHubPageSessionPath}`, url);
417
+ target.searchParams.set("page", url.pathname);
418
+ const activation = url.searchParams.get(viteHubPageToolsQuery);
419
+ if (activation) target.searchParams.set("open", activation);
420
+ const headers = new Headers(request.headers);
421
+ for (const name of [
422
+ ...pageConditions,
423
+ "origin",
424
+ "content-length",
425
+ "content-type",
426
+ "upgrade-insecure-requests",
427
+ "sec-fetch-user"
428
+ ]) headers.delete(name);
429
+ headers.set("accept", "application/json");
430
+ headers.set("sec-fetch-site", "same-origin");
431
+ headers.set("sec-fetch-mode", "cors");
432
+ headers.set("sec-fetch-dest", "empty");
433
+ const inner = new Request(target, { headers });
434
+ const runtime = Reflect.get(request, "runtime");
435
+ if (runtime !== null && typeof runtime === "object") Reflect.set(inner, "runtime", Object.fromEntries(Object.entries(runtime).filter(([key]) => key !== "node")));
436
+ for (const field of [
437
+ "ip",
438
+ "waitUntil",
439
+ "cf"
440
+ ]) {
441
+ const value = Reflect.get(request, field);
442
+ if (value === void 0) continue;
443
+ try {
444
+ Object.defineProperty(inner, field, {
445
+ configurable: true,
446
+ enumerable: true,
447
+ value
448
+ });
449
+ } catch {}
450
+ if (Reflect.get(inner, field) !== value) return void 0;
451
+ }
452
+ setApplicationRequestOrigin(inner, applicationRequestOrigin(request));
453
+ return inner;
454
+ }
455
+ function startHandoff(send, request, base) {
456
+ const inner = sessionRequestFor(request, base);
457
+ if (!inner) return void 0;
458
+ const pending = {};
459
+ const route = `${base}${viteHubPageSessionPath}`;
460
+ const page = new URL(request.url).pathname;
461
+ (async () => {
462
+ try {
463
+ const response = await send(inner);
464
+ if (!(response instanceof Response) || response.status !== 200 || response.headers.get(sessionCompleteHeader) !== "complete") return;
465
+ const session = readViteHubPageSession(await response.json());
466
+ const open = new URL(inner.url).searchParams.get("open");
467
+ if (session.tools.length > 0) pending.current = {
468
+ route,
469
+ page,
470
+ ...open ? { open } : {},
471
+ session
472
+ };
473
+ } catch {}
474
+ })();
475
+ return pending;
326
476
  }
327
477
  /**
328
478
  * Inserts the page tools bootstrap, `viteHubPageToolsInlineScript()`, before `</body>` of an HTML page for a request
@@ -346,12 +496,7 @@ function hasPageConditions(request) {
346
496
  /** Whether a request is a page navigation with validators, which must reach the app without them. */
347
497
  function revalidatesPage(request) {
348
498
  if (request.method !== "GET" && request.method !== "HEAD") return false;
349
- return request.headers.get("accept")?.split(",").some((range) => {
350
- const [type, ...parameters] = range.split(";").map((part) => part.trim());
351
- if (type?.toLowerCase() !== "text/html") return false;
352
- const quality = parameters.find((part) => /^q\s*=/i.test(part))?.split("=")[1]?.trim();
353
- return quality === void 0 || Number(quality) > 0 && Number(quality) <= 1;
354
- }) === true && hasPageConditions(request);
499
+ return acceptsHtml(request) && hasPageConditions(request);
355
500
  }
356
501
  /** The headers of the Node.js request that srvx keeps under `runtime.node.req`, when there is one. */
357
502
  function nodeRequestHeaders(request) {
@@ -383,7 +528,7 @@ function htmlCharset(type) {
383
528
  function isHtmlPage(response) {
384
529
  return response.status === 200 && (response.headers.get("content-type") ?? "").toLowerCase().startsWith("text/html");
385
530
  }
386
- function transformPage(response, tag, personal) {
531
+ function transformPage(response, tag, personal, late) {
387
532
  if (!isHtmlPage(response) || !response.body) return response;
388
533
  const type = response.headers.get("content-type") ?? "";
389
534
  const encoding = response.headers.get("content-encoding");
@@ -393,7 +538,7 @@ function transformPage(response, tag, personal) {
393
538
  const headers = new Headers(response.headers);
394
539
  for (const name of pageBodyHeaders) headers.delete(name);
395
540
  if (personal) headers.set("cache-control", "private, no-store");
396
- return new Response(response.body.pipeThrough(pageToolsHtmlTransform(tag())), {
541
+ return new Response(response.body.pipeThrough(pageToolsHtmlTransform(tag(), late)), {
397
542
  headers,
398
543
  status: response.status,
399
544
  statusText: response.statusText
@@ -409,12 +554,25 @@ function transformPage(response, tag, personal) {
409
554
  * It wraps `nitroApp.fetch`, the Web entry that every preset and the prerenderer call. The tag uses `options.base`.
410
555
  * It binds each request to the app in Nitro's `request` hook too, since another wrapper of `fetch` may pass a copy of
411
556
  * the request inward, such as the `security` policy of `vite-hub` on Node.js.
557
+ *
558
+ * With `sessionHandoff` enabled, it asks the session route beside the render for a navigation with credentials and puts a
559
+ * complete answer with at least one tool in the page: every visitor check and the account reader answered without
560
+ * throwing, so the tools and the account that it leaves out are the decision for this visitor. A page that a shared cache may
561
+ * store gets none: its headers say so (`public`, `s-maxage`, `Surrogate-Control`, any `*CDN-Cache-Control`), or the
562
+ * route rules that Nitro set on `request.context` have `isr`, `swr`, `cache` or `prerender`, which some presets turn
563
+ * into CDN headers after this point. A request without Nitro's `context.nitro`, such as a copy that another wrapper
564
+ * passed inward, has unknown rules and gets none. The server's request keeps the credentials and the host's request
565
+ * context (`runtime` without the Node.js request, `ip`, `waitUntil`, Cloudflare's `cf`). An app must not opt in if a
566
+ * browser-only input can change the session, or if a CDN can override the private cache policy. A proxy scheme that
567
+ * differs from the URL is left to the loader, since a `trustProxy`
568
+ * hook changes the URL of a real Node.js request and not of a copy.
412
569
  */
413
570
  function installViteHubPageTools(nitroApp, options = {}) {
414
571
  if (nitroApp === null || typeof nitroApp !== "object") return;
415
572
  const { installed, bases } = state();
416
573
  if (options.base !== void 0) bases.set(nitroApp, viteHubBasePath(options.base));
417
574
  if (options.origins !== void 0) (state().origins ??= /* @__PURE__ */ new WeakMap()).set(nitroApp, options.origins);
575
+ if (options.sessionHandoff === true) (state().sessionHandoffs ??= /* @__PURE__ */ new WeakSet()).add(nitroApp);
418
576
  if (installed.has(nitroApp)) return;
419
577
  installed.add(nitroApp);
420
578
  const hooks = Reflect.get(nitroApp, "hooks");
@@ -427,13 +585,21 @@ function installViteHubPageTools(nitroApp, options = {}) {
427
585
  Reflect.set(nitroApp, "fetch", async (request, ...rest) => {
428
586
  const base = state().bases.get(nitroApp) ?? "";
429
587
  const conditional = request instanceof Request && hasPageConditions(request);
430
- const early = conditional ? pageAddition(nitroApp, request, base) : void 0;
588
+ const handing = state().sessionHandoffs?.has(nitroApp) === true && request instanceof Request && mayHandOffSession(request);
589
+ const early = conditional || handing ? pageAddition(nitroApp, request, base) : void 0;
590
+ const pending = handing && early === "loader" ? startHandoff(async (inner) => {
591
+ state().apps.set(inner, nitroApp);
592
+ return await Reflect.apply(fetch, nitroApp, [inner]);
593
+ }, request, base) : void 0;
431
594
  if (early && revalidatesPage(request)) request = withoutPageConditions(request);
432
595
  if (request instanceof Request) state().apps.set(request, nitroApp);
433
596
  const response = await Reflect.apply(fetch, nitroApp, [request, ...rest]);
434
597
  if (!(response instanceof Response) || !(request instanceof Request) || !isHtmlPage(response)) return response;
435
- const addition = conditional ? early : pageAddition(nitroApp, request, base);
436
- if (addition === "loader") return injectPageToolsLoader(response, base);
598
+ const addition = conditional || handing ? early : pageAddition(nitroApp, request, base);
599
+ if (addition === "loader") {
600
+ const handoff = pending && !sharedCacheMayStore(request, response) ? pending : void 0;
601
+ return transformPage(response, () => loaderTag(base, scriptNonce(response.headers)), true, handoff && ((nonce) => handoff.current ? handoffMarkup(handoff.current, nonce) : ""));
602
+ }
437
603
  return addition === "bootstrap" ? injectPageToolsBootstrap(response, base) : response;
438
604
  });
439
605
  return;
@@ -494,7 +660,7 @@ async function resolveCommentsPage(comments, event, request, path) {
494
660
  } };
495
661
  getStandardContext(event);
496
662
  const mapped = await comments.options.page({
497
- url: new URL(id, forwardedRequestOrigin(request)),
663
+ url: new URL(id, applicationRequestOrigin(clientRequest(request))),
498
664
  event
499
665
  });
500
666
  if (!mapped) return { subject: {
@@ -509,4 +675,4 @@ async function resolveCommentsPage(comments, event, request, path) {
509
675
  ...mapped.revision === void 0 ? {} : { revision: mapped.revision }
510
676
  };
511
677
  }
512
- export { registerViteHubPageTool as a, installViteHubSiteVisitor as i, resolveCommentsPage as n, viteHubPageSessionHandler as o, installViteHubPageTools as r, resolveCommentsIdentity as t };
678
+ export { registerViteHubPageTool as a, installViteHubSiteVisitor as i, resolveCommentsPage as n, viteHubPageSessionHandler as o, installViteHubPageTools as r, applicationRequestOrigin as s, resolveCommentsIdentity as t };
@@ -1,6 +1,5 @@
1
- import "./index-D1T7RJ4R.js";
2
- import { g as CommentsUser } from "./define-B1jLSPe9.js";
3
- import { f as CommentsRequestEvent } from "./types-l6GOb_yc.js";
1
+ import "./index-d6NsDxu9.js";
2
+ import { j as CommentsUser, s as CommentsRequestEvent } from "./types-qzJKgWYS.js";
4
3
  interface CommentsSessionOptions {
5
4
  /** Reads the ViteHub Auth user only when no custom `identify` is configured. */
6
5
  session?: (event: CommentsRequestEvent) => Promise<CommentsUser | null | undefined>;
@@ -10,6 +10,4 @@ const commentsTableNames = {
10
10
  vitehubCommentCounters: "vitehub_comment_counters",
11
11
  vitehubCommentForge: "vitehub_comment_forge"
12
12
  };
13
- /** The tables of `commentSendsSchema`: each schema key and its SQL name. Comments adds them when `send` is on. */
14
- const commentSendsTableNames = { commentSends: "vitehub_comment_sends" };
15
- export { commentsTableNames as n, commentSendsTableNames as t };
13
+ export { commentsTableNames as t };
package/dist/testing.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as replyMessageId } from "./reply-id-Cm9FGOBs.js";
2
- import { t as commentsErrorDiagnostics } from "./errors-ByCRdInk.js";
2
+ import { t as commentsErrorDiagnostics } from "./errors-DeSEHzRf.js";
3
3
  // src/operations-core/testing.ts
4
4
  function checkOutboxAccount(input, user) {
5
5
  if (input.outbox && input.outbox.account !== user.id) throw Object.assign(commentsErrorDiagnostics.COMMENTS_OUTBOX_ACCOUNT_CHANGED(), { status: 401 });