@vite-hub/comments 0.3.1 → 0.4.1

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 (56) hide show
  1. package/README.md +20 -10
  2. package/dist/anchor.d.ts +2 -2
  3. package/dist/{client-diagnostics-CcFpkbAk.js → client-diagnostics-Bubm7Shd.js} +20 -5
  4. package/dist/client-files-CJZl5Kc4.js +53 -0
  5. package/dist/client.d.ts +151 -10
  6. package/dist/client.js +807 -32
  7. package/dist/database.js +1 -1
  8. package/dist/{define-B3TF9zzn.d.ts → define-CHTWfHPo.d.ts} +1 -1
  9. package/dist/{define-43mMR39K.js → define-CX_Yr_hz.js} +1 -1
  10. package/dist/{errors-CyQyKAvy.d.ts → errors-BEChnUo7.d.ts} +14 -2
  11. package/dist/{errors-C6qptPoG.js → errors-BHsVXlpd.js} +7 -3
  12. package/dist/{index-DNhy69Wt.d.ts → index-iPGlSAgj.d.ts} +13 -4
  13. package/dist/index.d.ts +7 -7
  14. package/dist/index.js +41 -7
  15. package/dist/{install-W9ghhGoh.d.ts → install-96NXWnrw.d.ts} +3 -3
  16. package/dist/{install-BcMPgPk_.js → install-jRKmuLHK.js} +72 -26
  17. package/dist/{installed-B-PfERBU.js → installed-g6nDr5ac.js} +1 -1
  18. package/dist/{migrate-BDQ8xqUs.js → migrate-Bpw3xL5e.js} +1 -1
  19. package/dist/{operations-D4A1Fcgf.d.ts → operations-7ycAhDCw.d.ts} +5 -0
  20. package/dist/{operations-DMMIfYPW.js → operations-9tskoLsk.js} +22 -11
  21. package/dist/{operations-GLeOqgMt.d.ts → operations-D93EV10O.d.ts} +5 -4
  22. package/dist/operations.d.ts +2 -2
  23. package/dist/operations.js +2 -2
  24. package/dist/overlay/client-lZesR40x.js +4 -0
  25. package/dist/overlay/overlay.js +20 -40
  26. package/dist/{page-DtbMOEMd.d.ts → page-CWwnmF3K.d.ts} +1 -1
  27. package/dist/{page-B41ozN63.js → page-DRz_sDY4.js} +1 -1
  28. package/dist/{plugin-PS8PMYus.js → plugin-BNFd1zGz.js} +27 -6
  29. package/dist/realtime.d.ts +2 -2
  30. package/dist/realtime.js +2 -2
  31. package/dist/reply-id-P_bSuEng.js +12 -0
  32. package/dist/{rpc-RKPAusHp.js → rpc-BQqYx8kb.js} +23 -7
  33. package/dist/{rpc-HBcWtg0T.d.ts → rpc-BZ1QNkCC.d.ts} +1 -1
  34. package/dist/rpc.d.ts +1 -1
  35. package/dist/rpc.js +1 -1
  36. package/dist/runtime/auth.d.ts +2 -2
  37. package/dist/runtime/auth.js +2 -2
  38. package/dist/runtime/console.js +3 -3
  39. package/dist/runtime/index.d.ts +38 -11
  40. package/dist/runtime/index.js +83 -15
  41. package/dist/{server-D8k-0GXe.js → server-CqyzrqTI.js} +1 -1
  42. package/dist/server.d.ts +5 -5
  43. package/dist/server.js +6 -6
  44. package/dist/{service-GHhhyQj4.js → service-C8ZgFWvy.js} +34 -5
  45. package/dist/{service-CFVm23k7.d.ts → service-wC9kx9EX.d.ts} +11 -4
  46. package/dist/{session-EkudzUmm.js → session-ByjMyTak.js} +1 -1
  47. package/dist/{session-DVx-1Tym.d.ts → session-CKfW6DGE.d.ts} +3 -3
  48. package/dist/table-names-DfiKUlOV.js +14 -0
  49. package/dist/testing.d.ts +1 -1
  50. package/dist/testing.js +37 -4
  51. package/dist/{types-BIS0hCEl.d.ts → types-C1qzObs2.d.ts} +12 -3
  52. package/dist/{types-CZujrMFd.d.ts → types-C7LzhgRb.d.ts} +47 -3
  53. package/dist/vite.d.ts +6 -6
  54. package/dist/vite.js +187 -113
  55. package/package.json +9 -9
  56. package/dist/overlay/client-DmsSMOzi.js +0 -4
@@ -7,7 +7,7 @@ declare const commentsPageScope = "site";
7
7
  /** Name of the Realtime Definition that holds one presence room per page. */
8
8
  declare const commentsRealtimeDefinition = "comments";
9
9
  /** The route prefix of the Comments API, below the app base. */
10
- declare const commentsRoute = "/api/_vitehub/comments";
10
+ declare const commentsRoute = "/_vitehub/comments";
11
11
  /** Mount Comments under the application path, ignoring Vite asset URLs such as a CDN origin. */
12
12
  declare function mountedCommentsRoute(base?: string): string;
13
13
  /**
@@ -8,7 +8,7 @@ const commentsPageScope = "site";
8
8
  /** Name of the Realtime Definition that holds one presence room per page. */
9
9
  const commentsRealtimeDefinition = "comments";
10
10
  /** The route prefix of the Comments API, below the app base. */
11
- const commentsRoute = "/api/_vitehub/comments";
11
+ const commentsRoute = "/_vitehub/comments";
12
12
  /** Mount Comments under the application path, ignoring Vite asset URLs such as a CDN origin. */
13
13
  function mountedCommentsRoute(base = "/") {
14
14
  return base.startsWith("/") && !base.startsWith("//") ? `${base.replace(/\/+$/, "")}${commentsRoute}` : commentsRoute;
@@ -1,9 +1,21 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
2
- import { r as commentsRoleGrants } from "./define-43mMR39K.js";
3
- import { i as installCommentsRuntime } from "./server-D8k-0GXe.js";
4
- import { i as runtimeBuilds } from "./installed-B-PfERBU.js";
5
- import { i as registerViteHubPageTool, n as resolveCommentsPage, r as installViteHubPageTools, t as resolveCommentsIdentity } from "./session-EkudzUmm.js";
1
+ import { t as commentsErrorDiagnostics } from "./errors-BHsVXlpd.js";
2
+ import { r as commentsRoleGrants } from "./define-CX_Yr_hz.js";
3
+ import { i as installCommentsRuntime } from "./server-CqyzrqTI.js";
4
+ import { i as runtimeBuilds } from "./installed-g6nDr5ac.js";
5
+ import { i as registerViteHubPageTool, n as resolveCommentsPage, r as installViteHubPageTools, t as resolveCommentsIdentity } from "./session-ByjMyTak.js";
6
+ import { t as commentsTableNames } from "./table-names-DfiKUlOV.js";
6
7
  import { installRequestStandardContext } from "@vite-hub/runtime/internal/h3";
8
+ //#region ../internal/src/runtime/user-data.ts
9
+ const stateKey = Symbol.for("vitehub.user-data");
10
+ const scope = globalThis;
11
+ function registerViteHubUserData(app, data) {
12
+ if (!app || typeof app !== "object") return;
13
+ const apps = scope[stateKey] ??= /* @__PURE__ */ new WeakMap();
14
+ let owners = apps.get(app);
15
+ if (!owners) apps.set(app, owners = /* @__PURE__ */ new Map());
16
+ owners.set(data.owner, data);
17
+ }
18
+ //#endregion
7
19
  //#region src/runtime/plugin.ts
8
20
  const runtimeKey = Symbol.for("vitehub.comments.installed");
9
21
  /** The Comments definition that the Nitro plugin installed, for the Console reader. */
@@ -26,7 +38,7 @@ function defineCommentsPlugin(options) {
26
38
  warned = true;
27
39
  throw Object.assign(commentsErrorDiagnostics.COMMENTS_R0010(), { status: 503 });
28
40
  }
29
- const { installComments } = await import("./install-BcMPgPk_.js").then((n) => n.n);
41
+ const { installComments } = await import("./install-jRKmuLHK.js").then((n) => n.n);
30
42
  return installComments(options.comments, {
31
43
  database,
32
44
  development: options.development === true,
@@ -44,6 +56,15 @@ function defineCommentsPlugin(options) {
44
56
  runtimeBuilds.set(options.comments, build);
45
57
  installCommentsRuntime(build);
46
58
  Reflect.set(globalThis, runtimeKey, options.comments);
59
+ registerViteHubUserData(nitroApp, {
60
+ owner: "comments",
61
+ tables: [commentsTableNames.vitehubCommentThreads, commentsTableNames.vitehubCommentMessages],
62
+ async delete(userId) {
63
+ if (!await options.database()) return;
64
+ const runtime = await build();
65
+ for (const threadId of await runtime.store.deleteUser(userId)) runtime.forge?.changed(threadId);
66
+ }
67
+ });
47
68
  if (options.overlay === false) return;
48
69
  const script = options.overlay;
49
70
  registerViteHubPageTool(nitroApp, {
@@ -1,5 +1,5 @@
1
- import { t as Comments } from "./index-DNhy69Wt.js";
2
- import { t as CommentsSessionOptions } from "./session-DVx-1Tym.js";
1
+ import { t as Comments } from "./index-iPGlSAgj.js";
2
+ import { t as CommentsSessionOptions } from "./session-CKfW6DGE.js";
3
3
  import { RealtimeDefinition } from "@vite-hub/realtime";
4
4
  //#region src/realtime.d.ts
5
5
  /**
package/dist/realtime.js CHANGED
@@ -1,6 +1,6 @@
1
- import { o as normalizeCommentPage, t as commentRoom } from "./page-B41ozN63.js";
1
+ import { o as normalizeCommentPage, t as commentRoom } from "./page-DRz_sDY4.js";
2
2
  import { i as text } from "./identity-CBOzgxSf.js";
3
- import { n as resolveCommentsPage, t as resolveCommentsIdentity } from "./session-EkudzUmm.js";
3
+ import { n as resolveCommentsPage, t as resolveCommentsIdentity } from "./session-ByjMyTak.js";
4
4
  //#region src/realtime.ts
5
5
  function toRealtimeUser(user) {
6
6
  const result = { id: user.id };
@@ -0,0 +1,12 @@
1
+ //#region src/reply-id.ts
2
+ /**
3
+ * The id of the message that a reply with `requestId` stores in a thread. Every retry gets the same id, so the primary
4
+ * key of the messages refuses a second message, and the client's outbox finds the server copy of its waiting reply.
5
+ * The server and the browser client both import it, so it has no other import.
6
+ */
7
+ async function replyMessageId(threadId, requestId) {
8
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([threadId, requestId]))));
9
+ return `message_${Array.from(digest.subarray(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
10
+ }
11
+ //#endregion
12
+ export { replyMessageId as t };
@@ -1,4 +1,5 @@
1
- import { i as commentsUnansweredError, t as commentsAnswerError } from "./client-diagnostics-CcFpkbAk.js";
1
+ import { i as commentsUnansweredError, t as commentsAnswerError } from "./client-diagnostics-Bubm7Shd.js";
2
+ import { i as withCommentFiles, n as outboxAccountHeader, r as retryAfterOf } from "./client-files-CJZl5Kc4.js";
2
3
  import { n as isRecordOrFunction, t as isRecord } from "./object-Da1zyPCR.js";
3
4
  import { createBirpc } from "birpc";
4
5
  //#region ../internal/src/operation-rpc.ts
@@ -96,7 +97,7 @@ async function callOperationRpc(name, input, send) {
96
97
  */
97
98
  function createRpcTransport(options = {}) {
98
99
  const base = (options.base ?? "").replace(/\/+$/, "");
99
- async function call(operation, input) {
100
+ async function call(operation, input, account) {
100
101
  const send = options.fetch ?? globalThis.fetch;
101
102
  let outcome;
102
103
  try {
@@ -107,7 +108,8 @@ function createRpcTransport(options = {}) {
107
108
  credentials: "same-origin",
108
109
  headers: {
109
110
  "content-type": "application/json",
110
- "x-vitehub-console": "1"
111
+ "x-vitehub-console": "1",
112
+ ...account === void 0 ? {} : { [outboxAccountHeader]: encodeURIComponent(account) }
111
113
  },
112
114
  method: "POST"
113
115
  });
@@ -124,27 +126,41 @@ function createRpcTransport(options = {}) {
124
126
  const { message, ...failure } = outcome.error;
125
127
  throw commentsAnswerError({
126
128
  ...failure,
127
- why: message
129
+ why: message,
130
+ retryAfter: retryAfterOf(outcome.answer.response)
128
131
  });
129
132
  }
130
133
  const { body, response } = outcome.answer;
131
- if (!isRecordOrFunction(body) || typeof body.code !== "string" || typeof body.message !== "string") throw commentsUnansweredError(response.status);
134
+ const retryAfter = retryAfterOf(response);
135
+ if (!isRecordOrFunction(body) || typeof body.code !== "string" || typeof body.message !== "string") throw commentsUnansweredError(response.status, void 0, retryAfter);
132
136
  throw commentsAnswerError({
133
137
  code: body.code,
134
138
  status: typeof body.status === "number" ? body.status : response.status,
135
139
  why: body.message,
140
+ ...retryAfter === void 0 ? {} : { retryAfter },
136
141
  ...typeof body.fix === "string" ? { fix: body.fix } : {},
137
142
  ...isRecordOrFunction(body.details) ? { details: body.details } : {}
138
143
  });
139
144
  }
145
+ const upload = (input, account) => call("comments.upload", input, account);
140
146
  return {
141
- create: (input) => call("comments.create", input),
147
+ async create({ files, outbox, ...input }) {
148
+ return call("comments.create", await withCommentFiles(input, {
149
+ files,
150
+ outbox
151
+ }, input.subject, (data) => upload(data, outbox?.account)), outbox?.account);
152
+ },
142
153
  delete: (input) => call("comments.delete", input),
143
154
  edit: (input) => call("comments.edit", input),
144
155
  get: (input) => call("comments.get", input),
145
156
  list: (query) => call("comments.list", query),
146
157
  reopen: (input) => call("comments.reopen", input),
147
- reply: (input) => call("comments.reply", input),
158
+ async reply({ subject, files, outbox, ...input }) {
159
+ return call("comments.reply", await withCommentFiles(input, {
160
+ files,
161
+ outbox
162
+ }, subject, (data) => upload(data, outbox?.account)), outbox?.account);
163
+ },
148
164
  resolve: (input) => call("comments.resolve", input),
149
165
  users: (input) => call("comments.users", input)
150
166
  };
@@ -1,4 +1,4 @@
1
- import { E as CommentsTransport } from "./types-CZujrMFd.js";
1
+ import { k as CommentsTransport } from "./types-C7LzhgRb.js";
2
2
  //#region src/operations-core/rpc.d.ts
3
3
  interface RpcTransportOptions {
4
4
  /** The app origin and mount, such as `https://app.example.com` or `/portal`. Defaults to the page origin. */
package/dist/rpc.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-HBcWtg0T.js";
1
+ import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-BZ1QNkCC.js";
2
2
  export { RpcTransportOptions, createRpcTransport };
package/dist/rpc.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as createRpcTransport } from "./rpc-RKPAusHp.js";
1
+ import { t as createRpcTransport } from "./rpc-BQqYx8kb.js";
2
2
  export { createRpcTransport };
@@ -1,5 +1,5 @@
1
- import { d as CommentsPeople, g as CommentsUser } from "../define-B3TF9zzn.js";
2
- import { s as CommentsRequestEvent } from "../types-BIS0hCEl.js";
1
+ import { d as CommentsPeople, g as CommentsUser } from "../define-CHTWfHPo.js";
2
+ import { s as CommentsRequestEvent } from "../types-C1qzObs2.js";
3
3
  //#region src/runtime/auth.d.ts
4
4
  /** The ViteHub Auth user of a request, or null. Generated Comments files pass it as `session` when the app has Auth. */
5
5
  export declare function commentsAuthSession(event: CommentsRequestEvent): Promise<CommentsUser | null>;
@@ -1,7 +1,7 @@
1
- import { n as createAuthUsers } from "../server-D8k-0GXe.js";
1
+ import { n as createAuthUsers } from "../server-CqyzrqTI.js";
2
2
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
3
3
  //#region src/runtime/auth.ts
4
- const authServer = () => import("@vite-hub/auth/server");
4
+ const authServer = () => import("@vite-hub/auth/internal/server");
5
5
  /** The ViteHub Auth user of a request, or null. Generated Comments files pass it as `session` when the app has Auth. */
6
6
  async function commentsAuthSession(event) {
7
7
  const request = getStandardContext(event).req;
@@ -1,6 +1,6 @@
1
- import { n as commentsPageScope } from "../page-B41ozN63.js";
1
+ import { n as commentsPageScope } from "../page-DRz_sDY4.js";
2
2
  import { t as describeCommentContext } from "../context-BqIsmYP1.js";
3
- import { n as installedComments } from "../plugin-PS8PMYus.js";
3
+ import { n as installedComments } from "../plugin-BNFd1zGz.js";
4
4
  //#region src/runtime/console.ts
5
5
  function excerpt(text) {
6
6
  const line = text.replace(/\s+/g, " ").trim();
@@ -54,7 +54,7 @@ async function readCommentsConsoleRecords() {
54
54
  ...describeCommentContext(thread.context ?? null),
55
55
  ...thread.resolvedBy ? [{
56
56
  label: "Resolved by",
57
- value: author(thread.resolvedBy)
57
+ value: `${thread.resolvedActor ? `${thread.resolvedActor.name ?? thread.resolvedActor.id} for ` : ""}${author(thread.resolvedBy)}`
58
58
  }] : []
59
59
  ]
60
60
  };
@@ -1,10 +1,10 @@
1
- import { s as CommentContext } from "../types-CZujrMFd.js";
2
- import { g as CommentsUser } from "../define-B3TF9zzn.js";
3
- import { s as CommentsRequestEvent } from "../types-BIS0hCEl.js";
4
- import { t as Comments } from "../index-DNhy69Wt.js";
5
- import { o as CommentsDatabase } from "../service-CFVm23k7.js";
6
- import { t as CommentsSessionOptions } from "../session-DVx-1Tym.js";
7
- import { t as InstallCommentsOptions } from "../install-W9ghhGoh.js";
1
+ import { s as CommentContext } from "../types-C7LzhgRb.js";
2
+ import { g as CommentsUser } from "../define-CHTWfHPo.js";
3
+ import { s as CommentsRequestEvent } from "../types-C1qzObs2.js";
4
+ import { t as Comments } from "../index-iPGlSAgj.js";
5
+ import { o as CommentsDatabase } from "../service-wC9kx9EX.js";
6
+ import { t as CommentsSessionOptions } from "../session-CKfW6DGE.js";
7
+ import { t as InstallCommentsOptions } from "../install-96NXWnrw.js";
8
8
  //#region src/runtime/github-login.d.ts
9
9
  /** The Server Env names of the OAuth client that people sign in to Comments with: a GitHub App's, or an OAuth App's. */
10
10
  export declare const githubLoginEnv: {
@@ -16,7 +16,7 @@ interface CommentsGitHubLogin {
16
16
  configured(): boolean;
17
17
  /** The person signed in with GitHub, with what they may do in the repository. Null without a session. */
18
18
  user(event: CommentsRequestEvent): Promise<CommentsUser | null>;
19
- /** The sign-in, callback, and sign-out routes under `/api/_vitehub/comments/auth/`. */
19
+ /** The sign-in, callback, and sign-out routes under `/_vitehub/comments/auth/`. */
20
20
  handle(request: Request & CommentsRequestEvent, path: string): Promise<Response>;
21
21
  }
22
22
  /**
@@ -96,7 +96,7 @@ interface CommentsHandlerOptions extends CommentsSessionOptions {
96
96
  components?: Readonly<Record<string, readonly string[]>>;
97
97
  }
98
98
  /**
99
- * The Comments API at `/api/_vitehub/comments/**`, as a Fetchable: mount it as a Nitro or H3 route, or call
99
+ * The Comments API at `/_vitehub/comments/**`, as a Fetchable: mount it as a Nitro or H3 route, or call
100
100
  * `fetch(request)`. The overlay calls it; every route checks the `authorize` policy of `defineComments()` for the user of
101
101
  * the request, and inline edits also check `content.can()`.
102
102
  */
@@ -112,7 +112,7 @@ interface CommentsPluginOptions extends CommentsSessionOptions {
112
112
  /** The Database of `defineComments({ database })`, or undefined when the app has none. The first Comments call reads it. */
113
113
  database: () => CommentsDatabase | undefined | Promise<CommentsDatabase | undefined>;
114
114
  /**
115
- * Path of the overlay script below the app base, such as `/api/_vitehub/comments/assets/overlay.js`. The page tools
115
+ * Path of the overlay script below the app base, such as `/_vitehub/comments/assets/overlay.js`. The page tools
116
116
  * loader imports it for people that may read comments.
117
117
  */
118
118
  overlay: string | false;
@@ -202,9 +202,20 @@ interface ViteHubMcpInputSchema {
202
202
  required?: string[];
203
203
  additionalProperties?: boolean;
204
204
  }
205
- /** What a tool call returns: text for the Agent, and the same data as JSON. */
205
+ /** An image that the Agent sees, such as a screenshot attached to a comment. */
206
+ interface ViteHubMcpImage {
207
+ /** The bytes, Base64-encoded. */
208
+ data: string;
209
+ /** Such as `image/png`. */
210
+ mimeType: string;
211
+ }
212
+ /**
213
+ * What a tool call returns: text for the Agent, the images that it refers to, and the same data as JSON.
214
+ * `mcpToolResult()` turns it into the MCP result, with one `image` block for each image after the text.
215
+ */
206
216
  interface ViteHubMcpToolResult {
207
217
  text: string;
218
+ images?: ViteHubMcpImage[];
208
219
  structured?: Record<string, unknown>;
209
220
  isError?: boolean;
210
221
  }
@@ -258,6 +269,22 @@ interface CommentsMcpToolsOptions {
258
269
  */
259
270
  export declare function commentsMcpTools(comments: Comments, options?: CommentsMcpToolsOptions): ViteHubMcpTool[];
260
271
  //#endregion
272
+ //#region ../internal/src/runtime/mcp-server.d.ts
273
+ type ToolResultContent = ({
274
+ type: "text";
275
+ text: string;
276
+ } | {
277
+ type: "image";
278
+ data: string;
279
+ mimeType: string;
280
+ })[];
281
+ /** The MCP result of a `ViteHubMcpTool` call: a text block, then one image block for each image. */
282
+ export declare function mcpToolResult(result: ViteHubMcpToolResult): {
283
+ content: ToolResultContent;
284
+ structuredContent?: Record<string, unknown>;
285
+ isError: boolean;
286
+ };
287
+ //#endregion
261
288
  //#region ../internal/src/runtime/page-tools.d.ts
262
289
  /**
263
290
  * The route of `GET /_vitehub/page/session`: a Fetchable (https://fetchable.org). Nitro 3 binds each Request to its
@@ -1,15 +1,16 @@
1
- import { t as commentsErrorDiagnostics } from "../errors-C6qptPoG.js";
2
- import { i as commentsRoute, n as commentsPageScope, o as normalizeCommentPage } from "../page-B41ozN63.js";
3
- import { a as commentThreadSummary, c as hiddenThreadsNote, n as commentAnchorSchema, o as commentThreadsText, r as commentInputSchemas, s as describeCommentThread, t as commentActions } from "../operations-DMMIfYPW.js";
1
+ import "../client-files-CJZl5Kc4.js";
2
+ import { t as commentsErrorDiagnostics } from "../errors-BHsVXlpd.js";
3
+ import { i as commentsRoute, n as commentsPageScope, o as normalizeCommentPage } from "../page-DRz_sDY4.js";
4
+ import { a as commentThreadSummary, c as hiddenThreadsNote, n as commentAnchorSchema, o as commentThreadsText, r as commentInputSchemas, s as describeCommentThread, t as commentActions } from "../operations-9tskoLsk.js";
4
5
  import { t as invariant } from "../invariant-D8_xBqmZ.js";
5
- import { a as deniedError, d as mentionedPeople, n as can, r as contextSchema } from "../service-GHhhyQj4.js";
6
+ import { h as readAttachment, i as contextSchema, n as base64, o as deniedError, p as mentionedPeople, r as can } from "../service-C8ZgFWvy.js";
6
7
  import { i as text, n as guestFromHeaders, t as authorOf } from "../identity-CBOzgxSf.js";
7
- import { c as validateCommentsDefinition, o as deniedForMissingPolicy } from "../define-43mMR39K.js";
8
+ import { c as validateCommentsDefinition, o as deniedForMissingPolicy } from "../define-CX_Yr_hz.js";
8
9
  import { a as runWithActiveCloudflareEnv, i as getActiveCloudflareBinding, r as rememberGitHubToken, t as forgetGitHubToken } from "../tokens-DSbwkVSy.js";
9
- import { r as resolveCommentsRuntime } from "../installed-B-PfERBU.js";
10
+ import { a as runtimeOf, r as resolveCommentsRuntime } from "../installed-g6nDr5ac.js";
10
11
  import { t as commentsErrors } from "../errors-4gelGVmK.js";
11
- import { a as viteHubPageSessionHandler, n as resolveCommentsPage, o as forwardedRequestOrigin, t as resolveCommentsIdentity } from "../session-EkudzUmm.js";
12
- import { n as installedComments, t as defineCommentsPlugin } from "../plugin-PS8PMYus.js";
12
+ import { a as viteHubPageSessionHandler, n as resolveCommentsPage, o as forwardedRequestOrigin, t as resolveCommentsIdentity } from "../session-ByjMyTak.js";
13
+ import { n as installedComments, t as defineCommentsPlugin } from "../plugin-BNFd1zGz.js";
13
14
  import { getStandardContext, installRequestStandardContext } from "@vite-hub/runtime/internal/h3";
14
15
  import * as v from "valibot";
15
16
  import { defineGrant } from "@vite-hub/runtime/internal/grant";
@@ -30,7 +31,8 @@ const createBody = v.object({
30
31
  const replyBody = v.object({
31
32
  body: commentInputSchemas.reply.entries.body,
32
33
  mentions: commentInputSchemas.reply.entries.mentions,
33
- attachments: commentInputSchemas.reply.entries.attachments
34
+ attachments: commentInputSchemas.reply.entries.attachments,
35
+ requestId: commentInputSchemas.reply.entries.requestId
34
36
  });
35
37
  const editBody = v.object({
36
38
  body: commentInputSchemas.edit.entries.body,
@@ -170,7 +172,7 @@ function leaseHolder(error) {
170
172
  return typeof name === "string" && name ? name : "Someone";
171
173
  }
172
174
  /**
173
- * The Comments API at `/api/_vitehub/comments/**`, as a Fetchable: mount it as a Nitro or H3 route, or call
175
+ * The Comments API at `/_vitehub/comments/**`, as a Fetchable: mount it as a Nitro or H3 route, or call
174
176
  * `fetch(request)`. The overlay calls it; every route checks the `authorize` policy of `defineComments()` for the user of
175
177
  * the request, and inline edits also check `content.can()`.
176
178
  */
@@ -483,7 +485,7 @@ function createCommentsHandler(options) {
483
485
  } };
484
486
  async function route(request) {
485
487
  const url = new URL(request.url);
486
- const path = url.pathname.slice(url.pathname.indexOf("/api/_vitehub/comments") + 22).replace(/\/+$/, "") || "/";
488
+ const path = url.pathname.slice(url.pathname.indexOf("/_vitehub/comments") + 18).replace(/\/+$/, "") || "/";
487
489
  const parts = path.split("/").filter(Boolean);
488
490
  const method = request.method;
489
491
  const page = url.searchParams.get("page");
@@ -551,6 +553,7 @@ function createCommentsHandler(options) {
551
553
  if (method === "POST" && action === "comments" && !messageId) {
552
554
  const parsed = v.safeParse(replyBody, await readJson(request));
553
555
  if (!parsed.success) return invalid(parsed.issues);
556
+ if (request.headers.has("x-vitehub-comments-outbox-account") && !("requestId" in parsed.output && parsed.output.requestId)) return failure$1(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "Queued replies need server support for requestId." }));
554
557
  return await act(request, "write", (who) => commentActions.reply({
555
558
  ...parsed.output,
556
559
  threadId
@@ -676,6 +679,49 @@ function spend(grant, action, threadId) {
676
679
  const allowed = toolGrant.consume(grant);
677
680
  invariant(allowed.action === action && allowed.threadId === threadId, "each Comments tool spends the grant that it issued for the same action and thread");
678
681
  }
682
+ /** The bytes of images that one `comments_get_thread` answer carries, before Base64. */
683
+ const maximumThreadImageBytes = 4194304;
684
+ /**
685
+ * The image attachments of a thread, in message order, for a reader who may read it, until they reach
686
+ * `maximumThreadImageBytes`. `notes` says which files the Agent does not see, and why.
687
+ */
688
+ async function threadImages(comments, thread, user) {
689
+ const runtime = await runtimeOf(comments);
690
+ if (!runtime) return {
691
+ images: [],
692
+ notes: [`Could not read the attachments: ${commentsErrors.COMMENTS_NOT_INSTALLED().why}`]
693
+ };
694
+ const images = [];
695
+ const notes = [];
696
+ let bytes = 0;
697
+ for (const key of thread.messages.flatMap((message) => message.attachments)) try {
698
+ const file = await readAttachment(runtime, key, {
699
+ thread,
700
+ user
701
+ });
702
+ if (!file.inline) continue;
703
+ if (bytes + file.size > maximumThreadImageBytes) {
704
+ notes.push(`Not shown: ${key}, because the images of one answer stay under ${maximumThreadImageBytes / 1024 / 1024} MB.`);
705
+ continue;
706
+ }
707
+ images.push({
708
+ data: base64(new Uint8Array(await file.data.arrayBuffer())),
709
+ mimeType: file.type
710
+ });
711
+ bytes += file.size;
712
+ } catch (error) {
713
+ if (commentsErrorDiagnostics.COMMENTS_R0020.is(error)) notes.push(`Could not read ${key}: The file is missing or unavailable.`);
714
+ else if (commentsErrorDiagnostics.COMMENTS_R0014.is(error) || commentsErrorDiagnostics.COMMENTS_R0021.is(error)) notes.push(`Could not read ${key}: The app has no attachment reader.`);
715
+ else {
716
+ console.warn(`[vitehub] Comments could not read attachment ${JSON.stringify(key)}:`, error);
717
+ notes.push(`Could not read ${key}: The file could not be loaded.`);
718
+ }
719
+ }
720
+ return {
721
+ images,
722
+ notes
723
+ };
724
+ }
679
725
  /**
680
726
  * The Comments tools for an app's own MCP server. Each call resolves the Comments identity and checks `authorize`,
681
727
  * as the overlay does. The server supplies the checked `context.user`. ViteHub MCP offers the comment operations instead.
@@ -817,7 +863,7 @@ function commentsMcpTools(comments, options = {}) {
817
863
  {
818
864
  name: "comments_get_thread",
819
865
  title: "Read a ViteHub Comments thread",
820
- description: "ViteHub Comments: read one thread that people left with the Comments toolbar: its page, the element and Vue components with their source files, the browser and build, and every comment with its time. Use it to find the code to change.",
866
+ description: "ViteHub Comments: read one thread that people left with the Comments toolbar: its page, the element and Vue components with their source files, the browser and build, every comment with its time, and the images attached to it. Use it to find the code to change.",
821
867
  section: "comments",
822
868
  annotations: { readOnlyHint: true },
823
869
  inputSchema: {
@@ -830,11 +876,14 @@ function commentsMcpTools(comments, options = {}) {
830
876
  additionalProperties: false
831
877
  },
832
878
  async call(input, context) {
833
- const found = await threadFor(input, await identityFor(context), "read");
879
+ const identity = await identityFor(context);
880
+ const found = await threadFor(input, identity, "read");
834
881
  if (!("thread" in found)) return found;
835
882
  const { thread } = found;
883
+ const { images, notes } = await threadImages(comments, thread, identity.user);
836
884
  return {
837
- text: describeCommentThread(thread),
885
+ text: [describeCommentThread(thread), ...notes].join("\n"),
886
+ ...images.length ? { images } : {},
838
887
  structured: { thread: { ...thread } }
839
888
  };
840
889
  }
@@ -920,6 +969,25 @@ function commentsMcpTools(comments, options = {}) {
920
969
  }
921
970
  ];
922
971
  }
972
+ //#endregion
973
+ //#region ../internal/src/runtime/mcp-server.ts
974
+ /** The MCP result of a `ViteHubMcpTool` call: a text block, then one image block for each image. */
975
+ function mcpToolResult(result) {
976
+ const content = [{
977
+ type: "text",
978
+ text: result.text
979
+ }];
980
+ for (const image of result.images ?? []) content.push({
981
+ type: "image",
982
+ data: image.data,
983
+ mimeType: image.mimeType
984
+ });
985
+ return {
986
+ content,
987
+ ...result.structured ? { structuredContent: result.structured } : {},
988
+ isError: result.isError === true
989
+ };
990
+ }
923
991
  new TextEncoder();
924
992
  /** HKDF salt for every ViteHub-derived secret. A different salt than Nuxt's keeps both derivations apart for one shared root. */
925
993
  const viteHubSecretSalt = "vitehub";
@@ -1110,4 +1178,4 @@ function createCommentsGitHubLogin(options = {}) {
1110
1178
  };
1111
1179
  }
1112
1180
  //#endregion
1113
- export { commentsDefinitionOf, commentsMcpTools, createCommentsGitHubLogin, createCommentsHandler, defineCommentsPlugin, githubLoginEnv, installedComments, selectCommentsDatabase, viteHubPageSessionHandler };
1181
+ export { commentsDefinitionOf, commentsMcpTools, createCommentsGitHubLogin, createCommentsHandler, defineCommentsPlugin, githubLoginEnv, installedComments, mcpToolResult, selectCommentsDatabase, viteHubPageSessionHandler };
@@ -1,4 +1,4 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
1
+ import { t as commentsErrorDiagnostics } from "./errors-BHsVXlpd.js";
2
2
  //#region src/operations-core/server.ts
3
3
  const key = Symbol.for("vitehub.comments.runtime");
4
4
  const scope = globalThis;
package/dist/server.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { d as CommentsPeople, x as validateCommentsDefinition } from "./define-B3TF9zzn.js";
2
- import { a as maximumCommentBodyLength, c as CommentsTables, i as CommentsRuntime, l as createCommentsStore, n as CommentsAttachmentStore, o as CommentsDatabase, r as CommentsForgeHooks, s as CommentsStore } from "./service-CFVm23k7.js";
3
- import { a as commentsOperations, i as commentInputSchemas, n as commentActions, r as commentAnchorSchema, t as CommentsCaller } from "./operations-GLeOqgMt.js";
4
- import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-HBcWtg0T.js";
5
- import { n as installComments, t as InstallCommentsOptions } from "./install-W9ghhGoh.js";
1
+ import { d as CommentsPeople, x as validateCommentsDefinition } from "./define-CHTWfHPo.js";
2
+ import { a as maximumCommentBodyLength, c as CommentsTables, i as CommentsRuntime, l as createCommentsStore, n as CommentsAttachmentStore, o as CommentsDatabase, r as CommentsForgeHooks, s as CommentsStore } from "./service-wC9kx9EX.js";
3
+ import { a as commentsOperations, i as commentInputSchemas, n as commentActions, r as commentAnchorSchema, t as CommentsCaller } from "./operations-D93EV10O.js";
4
+ import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-BZ1QNkCC.js";
5
+ import { n as installComments, t as InstallCommentsOptions } from "./install-96NXWnrw.js";
6
6
  //#region src/operations-core/server.d.ts
7
7
  /** Where mentions find people. The same shape as `defineComments({ people })`. */
8
8
  export type CommentsUsers = CommentsPeople;
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
- import { r as createCommentsStore, t as installComments } from "./install-BcMPgPk_.js";
2
- import { i as commentsOperations, n as commentAnchorSchema, r as commentInputSchemas, t as commentActions } from "./operations-DMMIfYPW.js";
3
- import { t as createRpcTransport } from "./rpc-RKPAusHp.js";
4
- import { u as maximumCommentBodyLength } from "./service-GHhhyQj4.js";
5
- import { c as validateCommentsDefinition } from "./define-43mMR39K.js";
6
- import { i as installCommentsRuntime, n as createAuthUsers, r as hasCommentsRuntime, t as commentsRuntime } from "./server-D8k-0GXe.js";
1
+ import { r as createCommentsStore, t as installComments } from "./install-jRKmuLHK.js";
2
+ import { i as commentsOperations, n as commentAnchorSchema, r as commentInputSchemas, t as commentActions } from "./operations-9tskoLsk.js";
3
+ import { t as createRpcTransport } from "./rpc-BQqYx8kb.js";
4
+ import { f as maximumCommentBodyLength } from "./service-C8ZgFWvy.js";
5
+ import { c as validateCommentsDefinition } from "./define-CX_Yr_hz.js";
6
+ import { i as installCommentsRuntime, n as createAuthUsers, r as hasCommentsRuntime, t as commentsRuntime } from "./server-CqyzrqTI.js";
7
7
  export { commentActions, commentAnchorSchema, commentInputSchemas, commentsOperations, commentsRuntime, createAuthUsers, createCommentsStore, createRpcTransport, hasCommentsRuntime, installComments, installCommentsRuntime, maximumCommentBodyLength, validateCommentsDefinition };
@@ -1,8 +1,9 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
1
+ import { t as replyMessageId } from "./reply-id-P_bSuEng.js";
2
+ import { t as commentsErrorDiagnostics } from "./errors-BHsVXlpd.js";
2
3
  import { t as foldName } from "./fold-name-B7Zb3-MF.js";
3
4
  import { t as isPagePath } from "./path--zk6PEMz.js";
4
5
  import { r as guestIdPrefix } from "./identity-CBOzgxSf.js";
5
- import { i as defaultPolicy, o as deniedForMissingPolicy, t as builtinCommentSubjects } from "./define-43mMR39K.js";
6
+ import { i as defaultPolicy, o as deniedForMissingPolicy, t as builtinCommentSubjects } from "./define-CX_Yr_hz.js";
6
7
  import * as v from "valibot";
7
8
  //#region ../internal/src/runtime/client-rate-limit.ts
8
9
  const windowPattern = /^(\d+)(ms|s|m|h|d)$/;
@@ -299,7 +300,7 @@ const contextSchema = v.object({
299
300
  }))
300
301
  });
301
302
  const revisionSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
302
- /** The retry key of `comments.create`, such as `crypto.randomUUID()`. */
303
+ /** The retry key of `comments.create` and `comments.reply`, such as `crypto.randomUUID()`. */
303
304
  const requestIdSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(200));
304
305
  const attachmentKey = v.pipe(v.string(), v.minLength(1), v.maxLength(500));
305
306
  function invalid(issues, field) {
@@ -423,8 +424,24 @@ async function createThread(runtime, input, options = {}) {
423
424
  runtime.forge?.changed(created.id);
424
425
  return created;
425
426
  }
427
+ /** The message that an earlier reply with this `requestId` stored in the thread. A retry gets it back before the reply checks. */
428
+ async function earlierReply(thread, requestId) {
429
+ if (requestId === void 0) return void 0;
430
+ const id = await replyMessageId(thread.id, check(requestIdSchema, requestId, "requestId"));
431
+ return thread.messages.find((message) => message.id === id);
432
+ }
433
+ /** Only the author of the first call gets its message back. */
434
+ function retriedReply(thread, message, author) {
435
+ if (message.author.id !== personOf(author).id) throw fail(commentsErrorDiagnostics.COMMENTS_R0022(), 409);
436
+ return {
437
+ message,
438
+ thread
439
+ };
440
+ }
426
441
  /** Adds a message to a thread. The caller checked access. */
427
442
  async function replyToThread(runtime, thread, input, options = {}) {
443
+ const earlier = await earlierReply(thread, input.requestId);
444
+ if (earlier) return retriedReply(thread, earlier, input.author);
428
445
  if (thread.status === "resolved" && !options.allowResolved) throw fail(commentsErrorDiagnostics.COMMENTS_R0016(), 409);
429
446
  const attachments = attachmentsOf(input.attachments);
430
447
  const body = cleanBody(runtime, {
@@ -442,7 +459,7 @@ async function replyToThread(runtime, thread, input, options = {}) {
442
459
  user,
443
460
  ...options.gate ? { gate: options.gate } : {}
444
461
  });
445
- const id = newId("message");
462
+ const id = input.requestId === void 0 ? newId("message") : await replyMessageId(thread.id, input.requestId);
446
463
  let next;
447
464
  try {
448
465
  next = await runtime.store.addMessage(thread.id, {
@@ -455,6 +472,12 @@ async function replyToThread(runtime, thread, input, options = {}) {
455
472
  ...input.actor ? { actor: input.actor } : {}
456
473
  }, { allowResolved: options.allowResolved === true });
457
474
  } catch (error) {
475
+ if (error instanceof Error && Reflect.get(error, "code") === "COMMENTS_R0022") {
476
+ const stored = await runtime.store.getById(thread.id);
477
+ const winner = stored?.messages.find((message) => message.id === id);
478
+ if (stored && winner) return retriedReply(stored, winner, input.author);
479
+ throw fail(error, 409);
480
+ }
458
481
  if (error instanceof Error && Reflect.get(error, "code") === "COMMENTS_R0016") throw fail(error, 409);
459
482
  if (error instanceof Error && Reflect.get(error, "code") === "COMMENTS_R0002") throw fail(error, 404);
460
483
  throw error;
@@ -569,6 +592,12 @@ async function attachmentThread(runtime, key, readable) {
569
592
  } while (cursor);
570
593
  throw fail(commentsErrorDiagnostics.COMMENTS_R0020({ key }), 404);
571
594
  }
595
+ /** The Base64 text of the bytes of an attachment, for the operations and the MCP tools. */
596
+ function base64(bytes) {
597
+ let binary = "";
598
+ for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
599
+ return btoa(binary);
600
+ }
572
601
  /**
573
602
  * Reads the file of `key` with `readAttachment`, else from the Blob store, for a reader who may read `thread`. A
574
603
  * stored type that Comments does not attach, such as SVG from an app's own hook, answers as a download.
@@ -606,4 +635,4 @@ async function readAttachment(runtime, key, context) {
606
635
  };
607
636
  }
608
637
  //#endregion
609
- export { createClientRateLimit as S, scopeOf as _, deniedError as a, clientAddressKey as b, fail as c, mentionedPeople as d, personOf as f, retried as g, requestIdSchema as h, createThread as i, maximumAttachmentBytes as l, replyToThread as m, can as n, earlierThread as o, readAttachment as p, contextSchema as r, editMessage as s, attachmentThread as t, maximumCommentBodyLength as u, storeAttachment as v, clientRateLimitIssue as x, suggest as y };
638
+ export { clientAddressKey as C, suggest as S, createClientRateLimit as T, requestIdSchema as _, createThread as a, scopeOf as b, earlierThread as c, maximumAttachmentBytes as d, maximumCommentBodyLength as f, replyToThread as g, readAttachment as h, contextSchema as i, editMessage as l, personOf as m, base64 as n, deniedError as o, mentionedPeople as p, can as r, earlierReply as s, attachmentThread as t, fail as u, retried as v, clientRateLimitIssue as w, storeAttachment as x, retriedReply as y };