@vite-hub/comments 0.0.0 → 0.1.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 (59) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +243 -0
  3. package/dist/anchor.d.ts +40 -0
  4. package/dist/anchor.js +128 -0
  5. package/dist/client.d.ts +101 -0
  6. package/dist/client.js +553 -0
  7. package/dist/console-BIz9t2cO.d.ts +243 -0
  8. package/dist/database/postgres.d.ts +1011 -0
  9. package/dist/database/postgres.js +60 -0
  10. package/dist/database-BSnVrwHn.js +60 -0
  11. package/dist/database-C-ktS9Do.js +95 -0
  12. package/dist/database-Cb2xjC1V.d.ts +1096 -0
  13. package/dist/database.d.ts +104 -0
  14. package/dist/database.js +3 -0
  15. package/dist/define-BzW2Ychn.d.ts +46 -0
  16. package/dist/define-Cbhl6QVJ.js +32 -0
  17. package/dist/errors-BAQYcy3_.d.ts +89 -0
  18. package/dist/errors-DeD6wTCl.js +77 -0
  19. package/dist/h3-v1-request-DDGXJ9E7.js +166 -0
  20. package/dist/identity-3qtVC4rF.js +34 -0
  21. package/dist/index-DklG2Etf.d.ts +111 -0
  22. package/dist/index.d.ts +7 -0
  23. package/dist/index.js +5 -0
  24. package/dist/operations-0B0QTVWX.d.ts +138 -0
  25. package/dist/operations-NZG5dB8y.js +732 -0
  26. package/dist/operations.d.ts +7 -0
  27. package/dist/operations.js +2 -0
  28. package/dist/overlay/overlay.js +195 -0
  29. package/dist/page/loader.js +22 -0
  30. package/dist/page-BtXADR6d.d.ts +21 -0
  31. package/dist/page-BuroSMXO.js +38 -0
  32. package/dist/page-tools-shared-D-amu6sx.js +53 -0
  33. package/dist/plugin-QElKQYkA.js +725 -0
  34. package/dist/realtime.d.ts +18 -0
  35. package/dist/realtime.js +48 -0
  36. package/dist/request-DVc3M_AG.js +14 -0
  37. package/dist/rpc.d.ts +29 -0
  38. package/dist/rpc.js +75 -0
  39. package/dist/runtime/auth.d.ts +6 -0
  40. package/dist/runtime/auth.js +15 -0
  41. package/dist/runtime/connect/node.d.ts +1 -0
  42. package/dist/runtime/connect/node.js +2 -0
  43. package/dist/runtime/connect.d.ts +1 -0
  44. package/dist/runtime/connect.js +2 -0
  45. package/dist/runtime/console.d.ts +5 -0
  46. package/dist/runtime/console.js +59 -0
  47. package/dist/runtime/index.d.ts +222 -0
  48. package/dist/runtime/index.js +665 -0
  49. package/dist/server-BomGg3Gb.js +63 -0
  50. package/dist/server.d.ts +94 -0
  51. package/dist/server.js +326 -0
  52. package/dist/src-CRTwnaEG.js +1362 -0
  53. package/dist/testing.d.ts +30 -0
  54. package/dist/testing.js +175 -0
  55. package/dist/types-Cj8K7Vx7.d.ts +176 -0
  56. package/dist/types-Un2dcJWD.d.ts +288 -0
  57. package/dist/vite.d.ts +304 -0
  58. package/dist/vite.js +1921 -0
  59. package/package.json +156 -4
@@ -0,0 +1,725 @@
1
+ import { _ as commentsErrors, o as describeCommentContext, r as installComments } from "./src-CRTwnaEG.js";
2
+ import { n as commentsPageScope, o as normalizeCommentPage } from "./page-BuroSMXO.js";
3
+ import { n as guestFromHeaders, r as text, t as authorOf } from "./identity-3qtVC4rF.js";
4
+ import { n as toEventRequest, r as toH3V1Request, t as isH3V1Event } from "./h3-v1-request-DDGXJ9E7.js";
5
+ import { a as viteHubPageToolsInlineScript, c as viteHubPageToolsMarker, i as viteHubPageToolsCookie, n as viteHubPageSessionPath, o as viteHubPageToolsInlineStart, s as viteHubPageToolsLoader, t as viteHubBasePath, u as withViteHubBase } from "./page-tools-shared-D-amu6sx.js";
6
+ import { defineGrant } from "@vite-hub/runtime/internal/grant";
7
+ //#region ../internal/src/runtime/mcp-tools.ts
8
+ const registryKey = Symbol.for("vitehub.mcp.tools");
9
+ const scope$1 = globalThis;
10
+ /** Registers the tools of one owner, such as `comments`. A second call replaces them, as in development reloads. */
11
+ function registerViteHubMcpTools(owner, tools) {
12
+ (scope$1[registryKey] ??= /* @__PURE__ */ new Map()).set(owner, tools);
13
+ }
14
+ //#endregion
15
+ //#region ../internal/src/runtime/page-tools-html.ts
16
+ function isGeneratedCheck(inline) {
17
+ const at = inline.indexOf("import(");
18
+ if (at === -1) return false;
19
+ try {
20
+ const path = JSON.parse(inline.slice(at + 7, -1));
21
+ return typeof path === "string" && path.endsWith("/_vitehub/page/assets/loader.js?v=8") && viteHubPageToolsInlineScript(path.slice(0, -35)) === `${inline}<\/script>`;
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+ /** A tag ends at an unquoted `>`, so markup quoted in an attribute stays untouched. */
27
+ function tagEnd(text) {
28
+ let quote = "";
29
+ for (let index = 1; index < text.length; index++) {
30
+ const character = text[index];
31
+ if (quote) {
32
+ if (character === quote) quote = "";
33
+ } else if (character === "\"" || character === "'") quote = character;
34
+ else if (character === ">") return index + 1;
35
+ }
36
+ return -1;
37
+ }
38
+ /** Scan HTML tokens across chunks; only active script elements can own the loader marker. */
39
+ function pageToolsHtmlTransform(loader) {
40
+ const decoder = new TextDecoder();
41
+ const encoder = new TextEncoder();
42
+ let pending = "";
43
+ let opaqueEnd;
44
+ let rawText = "";
45
+ let inline = "";
46
+ let templates = 0;
47
+ let present = false;
48
+ let done = false;
49
+ return new TransformStream({
50
+ transform(chunk, controller) {
51
+ pending += decoder.decode(chunk, { stream: true });
52
+ const emit = (text) => {
53
+ if (text) controller.enqueue(encoder.encode(text));
54
+ };
55
+ while (pending) {
56
+ if (done) {
57
+ emit(pending);
58
+ pending = "";
59
+ return;
60
+ }
61
+ if (opaqueEnd) {
62
+ const end = opaqueEnd.exec(pending);
63
+ const length = end ? end.index + end[0].length : Math.max(0, pending.length - 3);
64
+ emit(pending.slice(0, length));
65
+ pending = pending.slice(length);
66
+ if (!end) return;
67
+ opaqueEnd = void 0;
68
+ continue;
69
+ }
70
+ if (rawText) {
71
+ if (rawText === "plaintext") {
72
+ emit(pending);
73
+ pending = "";
74
+ return;
75
+ }
76
+ const end = new RegExp(`</${rawText}(?=[\\t\\n\\f\\r />])`, "i").exec(pending);
77
+ const length = end ? end.index : Math.max(0, pending.length - rawText.length - 3);
78
+ if (inline) inline += pending.slice(0, length);
79
+ else emit(pending.slice(0, length));
80
+ pending = pending.slice(length);
81
+ if (!end) return;
82
+ const finish = tagEnd(pending);
83
+ if (finish === -1) return;
84
+ if (inline) {
85
+ emit(isGeneratedCheck(inline) ? loader : inline + pending.slice(0, finish));
86
+ inline = "";
87
+ present = true;
88
+ } else emit(pending.slice(0, finish));
89
+ pending = pending.slice(finish);
90
+ rawText = "";
91
+ continue;
92
+ }
93
+ const start = pending.indexOf("<");
94
+ if (start === -1) {
95
+ emit(pending);
96
+ pending = "";
97
+ return;
98
+ }
99
+ emit(pending.slice(0, start));
100
+ pending = pending.slice(start);
101
+ if ("<!--".startsWith(pending) || "<![CDATA[".startsWith(pending)) return;
102
+ if (pending.startsWith("<!--") || pending.startsWith("<![CDATA[")) {
103
+ opaqueEnd = pending.startsWith("<!--") ? /--!?>/ : /\]\]>/;
104
+ const length = pending.startsWith("<!--") ? 4 : 9;
105
+ emit(pending.slice(0, length));
106
+ pending = pending.slice(length);
107
+ continue;
108
+ }
109
+ if (!/^<[a-z!/?]/i.test(pending)) {
110
+ emit("<");
111
+ pending = pending.slice(1);
112
+ continue;
113
+ }
114
+ const finish = tagEnd(pending);
115
+ if (finish === -1) return;
116
+ const token = pending.slice(0, finish);
117
+ pending = pending.slice(finish);
118
+ const match = /^<(\/?)([a-z][a-z0-9:-]*)(?=[\t\n\f\r />])/i.exec(token);
119
+ const name = match?.[2]?.toLowerCase();
120
+ const closing = match?.[1] === "/";
121
+ if (name === "template") templates = Math.max(0, templates + (closing ? -1 : 1));
122
+ if (name === "body" && closing && !templates) {
123
+ if (!present) emit(loader);
124
+ done = true;
125
+ }
126
+ if (!closing && name && /^(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript|plaintext)$/.test(name)) {
127
+ rawText = name;
128
+ if (!templates && token === viteHubPageToolsInlineStart) {
129
+ inline = token;
130
+ present = true;
131
+ continue;
132
+ }
133
+ if (!templates && name === "script") {
134
+ const attributes = token.replace(/"[^"]*"|'[^']*'/g, "");
135
+ present ||= new RegExp(`\\s${viteHubPageToolsMarker}(?=[\\s=/>])`, "i").test(attributes);
136
+ }
137
+ }
138
+ emit(token);
139
+ }
140
+ },
141
+ flush(controller) {
142
+ const rest = inline + pending + decoder.decode();
143
+ controller.enqueue(encoder.encode(rest + (done || present ? "" : loader)));
144
+ }
145
+ });
146
+ }
147
+ //#endregion
148
+ //#region ../internal/src/runtime/request-origin.ts
149
+ function firstHeaderValue(headers, name) {
150
+ return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
151
+ }
152
+ /**
153
+ * The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
154
+ * `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
155
+ * Without these headers, or with values that are not valid, the result is the origin of `request.url`.
156
+ */
157
+ function forwardedRequestOrigin(request) {
158
+ const url = new URL(request.url);
159
+ const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
160
+ const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
161
+ const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
162
+ if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
163
+ try {
164
+ return new URL(`${protocol}://${host}`).origin;
165
+ } catch {
166
+ return url.origin;
167
+ }
168
+ }
169
+ //#endregion
170
+ //#region ../internal/src/runtime/page-tools.ts
171
+ const stateKey = Symbol.for("vitehub.page-tools");
172
+ const scope = globalThis;
173
+ function state() {
174
+ return scope[stateKey] ??= {
175
+ installed: /* @__PURE__ */ new WeakSet(),
176
+ tools: /* @__PURE__ */ new WeakMap(),
177
+ apps: /* @__PURE__ */ new WeakMap(),
178
+ bases: /* @__PURE__ */ new WeakMap()
179
+ };
180
+ }
181
+ /** Registers a page tool for one Nitro app, before or after installation. The same id replaces only that app's tool. */
182
+ function registerViteHubPageTool(nitroApp, tool) {
183
+ if (nitroApp === null || typeof nitroApp !== "object") return;
184
+ const { tools } = state();
185
+ let registry = tools.get(nitroApp);
186
+ if (!registry) {
187
+ registry = /* @__PURE__ */ new Map();
188
+ tools.set(nitroApp, registry);
189
+ }
190
+ registry.set(tool.id, tool);
191
+ }
192
+ /** The path of a URL below the app base. A path outside the base stays as it is. */
193
+ function pathBelow(base, pathname) {
194
+ return base && (pathname === base || pathname.startsWith(`${base}/`)) ? pathname.slice(base.length) || "/" : pathname;
195
+ }
196
+ /**
197
+ * Whether a request asks for the page tools: the `?vitehub` query, or the `vitehub-tools=1` cookie that the session
198
+ * route sets. It is a hint, never a credential. Paths under `<base>/_vitehub` and `<base>/api/` never get the page
199
+ * tools. `base` is the path of the app base, such as `/portal`.
200
+ */
201
+ function hasViteHubPageToolsHint(request, base = "") {
202
+ const url = new URL(request.url);
203
+ base = viteHubBasePath(base);
204
+ if (base && url.pathname !== base && !url.pathname.startsWith(`${base}/`)) return false;
205
+ const path = pathBelow(base, url.pathname);
206
+ if (path.startsWith("/_vitehub") || path === "/api" || path.startsWith("/api/")) return false;
207
+ if (url.searchParams.has("vitehub")) return true;
208
+ const cookie = request.headers.get("cookie");
209
+ return Boolean(cookie && cookie.split(";").some((part) => part.trim() === `vitehub-tools=1`));
210
+ }
211
+ /** Whether ViteHub adds the loader to the page of this request: it has the hint, and a tool is registered. */
212
+ function wantsLoader(nitroApp, request, base) {
213
+ return (state().tools.get(nitroApp)?.size ?? 0) > 0 && hasViteHubPageToolsHint(request, base);
214
+ }
215
+ function loaderTag(base, nonce) {
216
+ return `<script type="module" src="${base}${viteHubPageToolsLoader}"${nonce ? ` nonce="${nonce}"` : ""} ${viteHubPageToolsMarker}><\/script>`;
217
+ }
218
+ const hintMaxAge = 2592e3;
219
+ function sessionResponse(value, init = {}) {
220
+ const headers = new Headers({
221
+ "cache-control": "private, no-store",
222
+ "content-type": "application/json; charset=utf-8"
223
+ });
224
+ if (init.cookie) headers.append("set-cookie", init.cookie);
225
+ return new Response(JSON.stringify(value), {
226
+ headers,
227
+ status: init.status ?? 200
228
+ });
229
+ }
230
+ /**
231
+ * Answers `GET <base>/_vitehub/page/session`: the tools whose `allowed` check passes for this visitor, in registration
232
+ * order. The app base is the part of the request path before the session path, as the Console finds its own base, and
233
+ * each tool `script` path gets it. It sets the hint cookie when at least one tool is allowed, and clears it when none
234
+ * is. A tool whose check throws is not allowed. Requests from other sites get 403 and run no check.
235
+ */
236
+ async function respondViteHubPageSession(nitroApp, request, event) {
237
+ if (request.method !== "GET" && request.method !== "HEAD") return sessionResponse({ error: {
238
+ code: "VITEHUB_PAGE_TOOLS_METHOD",
239
+ why: "The page tools session accepts GET only."
240
+ } }, { status: 405 });
241
+ const origin = request.headers.get("origin");
242
+ if (origin && origin !== forwardedRequestOrigin(request) || request.headers.get("sec-fetch-site") === "cross-site") return sessionResponse({ error: {
243
+ code: "VITEHUB_PAGE_TOOLS_CROSS_ORIGIN",
244
+ why: "The page tools session answers the site's own pages only."
245
+ } }, { status: 403 });
246
+ const registered = [...state().tools.get(nitroApp)?.values() ?? []];
247
+ const checks = await Promise.all(registered.map(async (tool) => {
248
+ try {
249
+ return await tool.allowed({
250
+ request,
251
+ event
252
+ });
253
+ } catch (error) {
254
+ console.error(`[vitehub] The visitor check of the page tool "${tool.id}" failed. The tool stays off for this request.`, error);
255
+ return false;
256
+ }
257
+ }));
258
+ const pathname = new URL(request.url).pathname;
259
+ const at = pathname.lastIndexOf(viteHubPageSessionPath);
260
+ const base = at > 0 ? pathname.slice(0, at) : "";
261
+ const tools = registered.filter((_, index) => checks[index] === true).map(({ allowed: _allowed, ...tool }) => ({
262
+ ...tool,
263
+ script: withViteHubBase(base, tool.script)
264
+ }));
265
+ return sessionResponse({ tools }, { cookie: tools.length ? `${viteHubPageToolsCookie}=1; Path=/; Max-Age=${hintMaxAge}; SameSite=Lax` : `${viteHubPageToolsCookie}=; Path=/; Max-Age=0; SameSite=Lax` });
266
+ }
267
+ /** The Web request of an H3 2 or H3 1 event. */
268
+ function eventRequest(event) {
269
+ if (event === null || typeof event !== "object") return void 0;
270
+ if (isH3V1Event(event)) return toH3V1Request(event);
271
+ const request = Reflect.get(event, "req");
272
+ return request instanceof Request ? request : void 0;
273
+ }
274
+ /**
275
+ * The Nitro handler of `GET /_vitehub/page/session`. H3 2 and H3 1 both call a plain function with their event, so it
276
+ * serves Nitro 3 and Nitro 2.
277
+ */
278
+ async function viteHubPageSessionHandler(event) {
279
+ const request = eventRequest(event);
280
+ if (!request) return sessionResponse({ error: {
281
+ code: "VITEHUB_PAGE_TOOLS_REQUEST",
282
+ why: "The page tools session got no request."
283
+ } }, { status: 400 });
284
+ const nitroApp = state().apps.get(request) ?? (event !== null && typeof event === "object" ? state().apps.get(event) : void 0);
285
+ if (!nitroApp) return sessionResponse({ error: {
286
+ code: "VITEHUB_PAGE_TOOLS_APP",
287
+ why: "The page tools session has no Nitro app."
288
+ } }, { status: 503 });
289
+ return await respondViteHubPageSession(nitroApp, request, event);
290
+ }
291
+ /**
292
+ * The script nonce of a page's Content Security Policy. A policy with `'strict-dynamic'`, such as the one of
293
+ * nuxt-security, blocks a script without it, even from the same origin.
294
+ */
295
+ function scriptNonce(headers) {
296
+ const directives = (headers.get("content-security-policy") ?? "").split(";").map((part) => part.trim());
297
+ const directive = [
298
+ "script-src-elem",
299
+ "script-src",
300
+ "default-src"
301
+ ].map((name) => directives.find((part) => part.toLowerCase().startsWith(`${name} `))).find(Boolean);
302
+ return directive ? /'nonce-([\w+/=-]+)'/.exec(directive)?.[1] : void 0;
303
+ }
304
+ /**
305
+ * Inserts the loader script tag before `</body>` of a streamed HTML body, or at its end when it has none. `base` is the
306
+ * path of the app base, such as `/portal`. A page that already has the loader, such as a single page app whose
307
+ * `index.html` Vite changed, gets no second one. The generated SPA inline check becomes the external loader, with
308
+ * the response policy's nonce when present. This supports header or meta policies that allow same-origin external
309
+ * scripts but block inline scripts. The page varies per person, so it drops `content-length` and sends
310
+ * `cache-control: private, no-store`. Other responses return unchanged, including compressed HTML. `policyHeaders`
311
+ * supplies the effective CSP when the host keeps it outside the Response.
312
+ */
313
+ function injectPageToolsLoader(response, base = "", policyHeaders = response.headers) {
314
+ const type = response.headers.get("content-type") ?? "";
315
+ if (!response.body || response.status !== 200 || !type.includes("text/html")) return response;
316
+ const encoding = response.headers.get("content-encoding");
317
+ if (encoding && encoding.toLowerCase() !== "identity") return response;
318
+ const tag = loaderTag(base, scriptNonce(policyHeaders));
319
+ const headers = new Headers(response.headers);
320
+ headers.delete("content-length");
321
+ headers.set("cache-control", "private, no-store");
322
+ return new Response(response.body.pipeThrough(pageToolsHtmlTransform(tag)), {
323
+ headers,
324
+ status: response.status,
325
+ statusText: response.statusText
326
+ });
327
+ }
328
+ /** The Web request of an H3 1 event. Only the path, query, and headers matter to the hint. */
329
+ function nitro2Request(event) {
330
+ const node = event.node?.req;
331
+ const path = node?.originalUrl || node?.url;
332
+ return event.web?.request ?? (path ? new Request(new URL(path, "http://localhost"), { headers: node?.headers }) : void 0);
333
+ }
334
+ /**
335
+ * The app base of an H3 1 event, such as `/portal` for Nuxt `app.baseURL: "/portal/"`. Nitro 2 serves its routes below
336
+ * its `baseURL`, and H3 1 removes that part from `url` and keeps the full path in `originalUrl`. It follows a base that
337
+ * the server gets at runtime, such as `NUXT_APP_BASE_URL`.
338
+ */
339
+ function nitro2Base(event) {
340
+ const original = event.node?.req?.originalUrl?.split("?")[0];
341
+ const current = event.node?.req?.url?.split("?")[0];
342
+ if (!original || !current || original === current || !original.endsWith(current)) return "";
343
+ return viteHubBasePath(original.slice(0, original.length - current.length));
344
+ }
345
+ /**
346
+ * Adds the loader of the page tools to the HTML pages of a Nitro app, for requests with the hint, when at least one
347
+ * tool is registered. Call it from each owner's Nitro plugin: it installs once per app, whatever the number of calls.
348
+ * It reads that app's registry and configured base on each request, so plugin order does not matter.
349
+ * - Nitro 3: it wraps `nitroApp.fetch`, the Web entry that every preset calls. The tag uses `options.base`.
350
+ * - Nitro 2 with Nuxt: it hooks `render:html` for rendered pages, and `beforeResponse` for pages that a route returns
351
+ * as a `Response`, string, or uncompressed byte buffer explicitly declared as UTF-8, including prerendered files.
352
+ * The tag uses the base of the request.
353
+ */
354
+ function installViteHubPageTools(nitroApp, options = {}) {
355
+ if (nitroApp === null || typeof nitroApp !== "object") return;
356
+ const { installed, bases } = state();
357
+ if (options.base !== void 0) bases.set(nitroApp, viteHubBasePath(options.base));
358
+ if (installed.has(nitroApp)) return;
359
+ installed.add(nitroApp);
360
+ const fetch = Reflect.get(nitroApp, "fetch");
361
+ if (fetch instanceof Function) {
362
+ Reflect.set(nitroApp, "fetch", async (request, ...rest) => {
363
+ if (request instanceof Request) state().apps.set(request, nitroApp);
364
+ const response = await Reflect.apply(fetch, nitroApp, [request, ...rest]);
365
+ const base = state().bases.get(nitroApp) ?? "";
366
+ return response instanceof Response && request instanceof Request && wantsLoader(nitroApp, request, base) ? injectPageToolsLoader(response, base) : response;
367
+ });
368
+ return;
369
+ }
370
+ const hooks = Reflect.get(nitroApp, "hooks");
371
+ const hook = hooks !== null && typeof hooks === "object" ? Reflect.get(hooks, "hook") : void 0;
372
+ if (!(hook instanceof Function)) return;
373
+ Reflect.apply(hook, hooks, ["request", (event) => {
374
+ state().apps.set(event, nitroApp);
375
+ }]);
376
+ Reflect.apply(hook, hooks, ["render:html", (html, context) => {
377
+ const request = nitro2Request(context.event);
378
+ const base = nitro2Base(context.event) || state().bases.get(nitroApp) || "";
379
+ if (!request || !wantsLoader(nitroApp, request, base)) return;
380
+ const res = context.event.node?.res;
381
+ const policy = res?.getHeader?.("content-security-policy");
382
+ html.bodyAppend.push(loaderTag(base, typeof policy === "string" ? scriptNonce(new Headers({ "content-security-policy": policy })) : void 0));
383
+ res?.setHeader?.("cache-control", "private, no-store");
384
+ }]);
385
+ Reflect.apply(hook, hooks, ["beforeResponse", async (event, response) => {
386
+ const request = nitro2Request(event);
387
+ const base = nitro2Base(event) || state().bases.get(nitroApp) || "";
388
+ if (!request || !wantsLoader(nitroApp, request, base)) return;
389
+ if (response.body instanceof Response) {
390
+ const headers = new Headers(response.body.headers);
391
+ const policy = event.node?.res?.getHeader?.("content-security-policy");
392
+ if (!headers.has("content-security-policy") && typeof policy === "string") headers.set("content-security-policy", policy);
393
+ response.body = injectPageToolsLoader(response.body, base, headers);
394
+ return;
395
+ }
396
+ const res = event.node?.res;
397
+ const type = res?.getHeader?.("content-type");
398
+ if (typeof type !== "string" || !type.toLowerCase().startsWith("text/html")) return;
399
+ if (res?.getHeader?.("content-encoding") || (res?.statusCode ?? 200) !== 200) return;
400
+ const body = response.body;
401
+ if (typeof body !== "string" && !(body instanceof Uint8Array)) return;
402
+ const charset = /;\s*charset\s*=\s*"?([^";]*)/i.exec(type)?.[1]?.trim();
403
+ if (body instanceof Uint8Array && !/^utf-?8$/i.test(charset ?? "")) return;
404
+ const html = typeof body === "string" ? body : new TextDecoder().decode(body);
405
+ const policy = res?.getHeader?.("content-security-policy");
406
+ const tag = loaderTag(base, typeof policy === "string" ? scriptNonce(new Headers({ "content-security-policy": policy })) : void 0);
407
+ response.body = await new Response(new Blob([html]).stream().pipeThrough(pageToolsHtmlTransform(tag))).text();
408
+ res?.removeHeader?.("content-length");
409
+ res?.removeHeader?.("etag");
410
+ res?.setHeader?.("cache-control", "private, no-store");
411
+ }]);
412
+ }
413
+ //#endregion
414
+ //#region src/runtime/session.ts
415
+ /** The effective Comments user, shared by the overlay API and MCP tools. */
416
+ async function resolveCommentsUser(comments, event, options = {}, action = "read") {
417
+ const consoleUser = await options.consoleSession?.(event, action).catch(() => false);
418
+ if (consoleUser === false) return false;
419
+ if (comments.options.identify) return await comments.options.identify({ event }) ?? null;
420
+ if (options.consoleSession) return consoleUser ?? null;
421
+ return await options.session?.(event).catch(() => null) ?? null;
422
+ }
423
+ //#endregion
424
+ //#region src/runtime/mcp.ts
425
+ /** A user supplied by an app's own MCP server. Missing identities remain anonymous. */
426
+ function commentsUser(user) {
427
+ const id = text(user?.id) ?? text(user?.email);
428
+ return user && id ? {
429
+ ...user,
430
+ id
431
+ } : null;
432
+ }
433
+ function guestFor(context) {
434
+ return context.event instanceof Object ? guestFromHeaders(toEventRequest(context.event).headers) : void 0;
435
+ }
436
+ function failure(why) {
437
+ return {
438
+ text: why,
439
+ isError: true
440
+ };
441
+ }
442
+ /** The catalog's COMMENTS_FORBIDDEN, as the overlay API answers it. */
443
+ function forbidden(action) {
444
+ const error = commentsErrors.COMMENTS_FORBIDDEN({ action });
445
+ return failure(`${error.why} ${error.fix}`);
446
+ }
447
+ /** Issued after `authorize` allows a tool's action on a thread. The reply and resolve writes need it. */
448
+ const toolGrant = defineGrant("vitehub.comments.mcp-action", (input) => Object.freeze({ ...input }));
449
+ function spend(grant, action, threadId) {
450
+ const allowed = toolGrant.consume(grant);
451
+ if (allowed.action !== action || allowed.threadId !== threadId) throw new TypeError(`[vitehub] A Comments tool wrote ${action} with the grant of ${allowed.action}.`);
452
+ }
453
+ /** One thread as text an Agent reads: where it is, what the person saw, and the conversation. */
454
+ function describeThread(thread) {
455
+ const lines = [
456
+ `Thread #${thread.number} ${thread.id} (${thread.status}) on ${thread.page}`,
457
+ ...thread.anchor ? [`Anchor: ${thread.anchor.field ? `Content field ${thread.anchor.field}` : thread.anchor.label} (${thread.anchor.selector})`] : [],
458
+ ...describeCommentContext(thread.context).map((field) => `${field.label}: ${field.value}`),
459
+ "",
460
+ ...thread.comments.map((comment) => `${comment.author.name}${comment.author.guest ? " (guest)" : ""}, ${comment.createdAt}: ${comment.body}`)
461
+ ];
462
+ if (thread.resolvedBy) lines.push("", `Resolved by ${thread.resolvedBy.name} at ${thread.resolvedAt}`);
463
+ return lines.join("\n");
464
+ }
465
+ function summary(thread) {
466
+ return {
467
+ id: thread.id,
468
+ page: thread.page,
469
+ status: thread.status,
470
+ comment: thread.comments[0]?.body ?? "",
471
+ author: thread.createdBy.name,
472
+ replies: Math.max(0, thread.comments.length - 1),
473
+ components: thread.context?.components?.map((component) => component.name) ?? [],
474
+ updatedAt: thread.updatedAt
475
+ };
476
+ }
477
+ /**
478
+ * The Comments tools of the ViteHub MCP server. Each call resolves the Comments identity and checks `authorize`,
479
+ * as the overlay does. Pass the overlay's session reader; an app's own MCP server can instead supply `context.user`.
480
+ * With a request event, Console denial is final; otherwise `identify` takes precedence over the session user.
481
+ * Without an event, the tools use the checked `context.user` directly. Replies and resolves show that user as the author.
482
+ */
483
+ function commentsMcpTools(comments, options = {}) {
484
+ async function userFor(context, action) {
485
+ if (context.event === void 0 || context.event === null) return commentsUser(context.user);
486
+ return resolveCommentsUser(comments, context.event, {
487
+ ...options,
488
+ session: options.session ?? (async () => commentsUser(context.user))
489
+ }, action);
490
+ }
491
+ async function threadFor(input, user, action) {
492
+ if (user === false) return forbidden(action);
493
+ const id = text(input.id);
494
+ if (!id) return failure("Give the thread id from comments_list_threads.");
495
+ const [error, thread] = await comments.get(id);
496
+ if (error) return failure(error.why);
497
+ if (thread.scope !== "pages") return failure(`No thread ${id} on the app's pages.`);
498
+ if (!await comments.can({
499
+ user,
500
+ action,
501
+ thread
502
+ })) return forbidden(action);
503
+ return {
504
+ thread,
505
+ grant: toolGrant.issue({
506
+ action,
507
+ threadId: thread.id
508
+ })
509
+ };
510
+ }
511
+ return [
512
+ {
513
+ name: "comments_list_threads",
514
+ title: "List comment threads",
515
+ description: "List the comment threads that the team left on the app's pages, newest activity first. Each has the page, the first comment, and the Vue components where it was left. Read one with comments_get_thread; after you change the code, reply with comments_reply and resolve it with comments_resolve_thread.",
516
+ section: "comments",
517
+ annotations: { readOnlyHint: true },
518
+ inputSchema: {
519
+ type: "object",
520
+ properties: {
521
+ page: {
522
+ type: "string",
523
+ description: "Only threads of this pathname, such as /pricing."
524
+ },
525
+ status: {
526
+ type: "string",
527
+ enum: ["open", "resolved"],
528
+ description: "Default: open."
529
+ },
530
+ search: {
531
+ type: "string",
532
+ description: "Only threads whose comments contain this text."
533
+ },
534
+ limit: {
535
+ type: "integer",
536
+ minimum: 1,
537
+ maximum: 100,
538
+ description: "Default 25."
539
+ }
540
+ },
541
+ additionalProperties: false
542
+ },
543
+ async call(input, context) {
544
+ const user = await userFor(context, "read");
545
+ if (user === false || !await comments.can({
546
+ user,
547
+ action: "read"
548
+ })) return forbidden("read");
549
+ const status = input.status === "resolved" ? "resolved" : "open";
550
+ const page = text(input.page);
551
+ const search = text(input.search)?.toLowerCase();
552
+ const limit = Math.min(Math.max(Number(input.limit) || 25, 1), 100);
553
+ const [error, threads] = await comments.list({
554
+ scope: commentsPageScope,
555
+ status,
556
+ limit: search ? 500 : limit,
557
+ ...page ? { page: normalizeCommentPage(page) } : {}
558
+ });
559
+ if (error) return failure(error.why);
560
+ const found = (search ? threads.filter((thread) => thread.comments.some((comment) => comment.body.toLowerCase().includes(search))) : threads).slice(0, limit);
561
+ const line = (thread) => {
562
+ const components = thread.context?.components?.map((component) => component.name) ?? [];
563
+ const replies = Math.max(0, thread.comments.length - 1);
564
+ return `- ${thread.id} ${thread.page}: ${(thread.comments[0]?.body ?? "").slice(0, 120)} (${thread.createdBy.name}, ${replies} replies${components.length ? `, in ${components.join(" › ")}` : ""})`;
565
+ };
566
+ return {
567
+ text: found.length ? found.map(line).join("\n") : `No ${status} threads.`,
568
+ structured: { threads: found.map(summary) }
569
+ };
570
+ }
571
+ },
572
+ {
573
+ name: "comments_get_thread",
574
+ title: "Read a comment thread",
575
+ description: "Read one thread: its page, the element and Vue components with their source files, the browser and build, and every comment. Use it to find the code to change.",
576
+ section: "comments",
577
+ annotations: { readOnlyHint: true },
578
+ inputSchema: {
579
+ type: "object",
580
+ properties: { id: {
581
+ type: "string",
582
+ description: "The thread id."
583
+ } },
584
+ required: ["id"],
585
+ additionalProperties: false
586
+ },
587
+ async call(input, context) {
588
+ const found = await threadFor(input, await userFor(context, "read"), "read");
589
+ if (!("thread" in found)) return found;
590
+ const { thread } = found;
591
+ return {
592
+ text: describeThread(thread),
593
+ structured: { thread: { ...thread } }
594
+ };
595
+ }
596
+ },
597
+ {
598
+ name: "comments_reply",
599
+ title: "Reply to a comment thread",
600
+ description: "Reply to an open thread, for example to say what you changed. The reply shows the signed-in Console user as its author.",
601
+ section: "comments",
602
+ inputSchema: {
603
+ type: "object",
604
+ properties: {
605
+ id: {
606
+ type: "string",
607
+ description: "The thread id."
608
+ },
609
+ body: {
610
+ type: "string",
611
+ description: "Plain text, at most 4,000 characters."
612
+ }
613
+ },
614
+ required: ["id", "body"],
615
+ additionalProperties: false
616
+ },
617
+ async call(input, context) {
618
+ const user = await userFor(context, "comment");
619
+ const found = await threadFor(input, user, "comment");
620
+ if (!("thread" in found)) return found;
621
+ const { thread, grant } = found;
622
+ const author = user ? authorOf(user) : guestFor(context);
623
+ if (!author) return forbidden("comment");
624
+ spend(grant, "comment", thread.id);
625
+ const [error, comment] = await comments.reply(thread.id, {
626
+ body: text(input.body) ?? "",
627
+ author
628
+ });
629
+ if (error) return failure(error.why);
630
+ await comments.flush();
631
+ return {
632
+ text: `Replied to thread ${thread.id}.`,
633
+ structured: { comment: { ...comment } }
634
+ };
635
+ }
636
+ },
637
+ {
638
+ name: "comments_resolve_thread",
639
+ title: "Resolve or reopen a comment thread",
640
+ description: "Resolve a thread after the change it asks for is done, or reopen it. Resolved threads leave the page.",
641
+ section: "comments",
642
+ inputSchema: {
643
+ type: "object",
644
+ properties: {
645
+ id: {
646
+ type: "string",
647
+ description: "The thread id."
648
+ },
649
+ resolved: {
650
+ type: "boolean",
651
+ description: "Default true. False reopens the thread."
652
+ }
653
+ },
654
+ required: ["id"],
655
+ additionalProperties: false
656
+ },
657
+ async call(input, context) {
658
+ const user = await userFor(context, "resolve");
659
+ const found = await threadFor(input, user, "resolve");
660
+ if (!("thread" in found)) return found;
661
+ const { thread, grant } = found;
662
+ spend(grant, "resolve", thread.id);
663
+ const author = user ? authorOf(user) : guestFor(context) ?? {
664
+ id: "anonymous",
665
+ name: "Someone"
666
+ };
667
+ const [error, updated] = input.resolved === false ? await comments.reopen(thread.id) : await comments.resolve(thread.id, { by: author });
668
+ if (error) return failure(error.why);
669
+ await comments.flush();
670
+ return {
671
+ text: `Thread ${updated.id} is ${updated.status}.`,
672
+ structured: { thread: summary(updated) }
673
+ };
674
+ }
675
+ }
676
+ ];
677
+ }
678
+ //#endregion
679
+ //#region src/runtime/plugin.ts
680
+ const runtimeKey = Symbol.for("vitehub.comments.runtime");
681
+ /** The Comments definition that the Nitro plugin installed, for the Console reader. */
682
+ function installedComments() {
683
+ const value = Reflect.get(globalThis, runtimeKey);
684
+ return value === void 0 ? void 0 : value;
685
+ }
686
+ /**
687
+ * The Nitro plugin of Comments. It connects the definition to its Database, and registers the overlay as the
688
+ * `comments` page tool: a visitor may load it when `authorize` allows `read` or GitHub sign-in is available.
689
+ */
690
+ function defineCommentsPlugin(options) {
691
+ return (nitroApp) => {
692
+ const database = options.database();
693
+ if (database) installComments(options.comments, {
694
+ database,
695
+ development: options.development
696
+ });
697
+ else console.warn(options.missingDatabase ?? "[vitehub] Comments has no Database. Enable one with `vitehub({ database: true })`, or set `defineComments({ database })` to a Database name.");
698
+ Reflect.set(globalThis, runtimeKey, options.comments);
699
+ registerViteHubMcpTools("comments", commentsMcpTools(options.comments, {
700
+ session: options.session,
701
+ consoleSession: options.consoleSession
702
+ }));
703
+ registerViteHubPageTool(nitroApp, {
704
+ id: "comments",
705
+ label: "Comments",
706
+ icon: "i-lucide-message-square-text",
707
+ script: options.overlay,
708
+ lazy: true,
709
+ async allowed({ event }) {
710
+ const user = await resolveCommentsUser(options.comments, event, {
711
+ ...options,
712
+ session: options.session ?? options.githubLogin?.user
713
+ });
714
+ if (user === false) return false;
715
+ return await options.comments.can({
716
+ user,
717
+ action: "read"
718
+ }) || Boolean(!options.comments.options.identify && options.githubLogin?.configured() && (!user || user.github));
719
+ }
720
+ });
721
+ installViteHubPageTools(nitroApp, { base: options.base });
722
+ };
723
+ }
724
+ //#endregion
725
+ export { viteHubPageSessionHandler as a, resolveCommentsUser as i, installedComments as n, forwardedRequestOrigin as o, commentsMcpTools as r, defineCommentsPlugin as t };