@vite-hub/comments 0.6.1 → 0.7.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 (49) hide show
  1. package/README.md +6 -4
  2. package/dist/{client-diagnostics-D987sEK7.js → client-diagnostics-DoXqdnBd.js} +8 -0
  3. package/dist/client.d.ts +48 -3
  4. package/dist/client.js +231 -150
  5. package/dist/{database-Cguz3hZL.js → database-BuSNVwTx.js} +1 -1
  6. package/dist/database.js +1 -1
  7. package/dist/{define-C2tnAtBU.js → define-BqPcuDhf.js} +1 -1
  8. package/dist/{errors-ByCRdInk.js → errors-CBvIpwbo.js} +1 -1
  9. package/dist/hosted/hosted-comments/frame.js +1 -1
  10. package/dist/hosted/hosted-comments/tools.js +371 -0
  11. package/dist/hosted/hosted-comments.js +1 -19
  12. package/dist/index.js +4 -4
  13. package/dist/{install-D6hXZaSN.js → install-CqBWFmU7.js} +21 -15
  14. package/dist/{installed-bPUnazFf.js → installed-wUYjqk_k.js} +1 -1
  15. package/dist/{operations-8hqTi0DH.d.ts → operations-DFLer1fR.d.ts} +1 -0
  16. package/dist/{operations-BkkrI8a3.d.ts → operations-Qt8ASQqW.d.ts} +1 -1
  17. package/dist/{operations-B1ALn4VS.js → operations-kMPw-Cyb.js} +6 -7
  18. package/dist/operations.d.ts +1 -1
  19. package/dist/operations.js +2 -2
  20. package/dist/overlay/client-CrnKCZXc.js +4 -0
  21. package/dist/overlay/overlay.js +62 -35
  22. package/dist/page/loader.js +25 -23
  23. package/dist/{page-tools-shared-fvmJQCrP.js → page-tools-shared-BNw-aWEH.js} +2 -5
  24. package/dist/{plugin-l4sPt5-n.js → plugin-ChOHe7vq.js} +7 -7
  25. package/dist/realtime.d.ts +4 -1
  26. package/dist/realtime.js +1 -1
  27. package/dist/{request-origin-YPzfE2eh.js → request-origin-B-CPVAVk.js} +6 -1
  28. package/dist/{rpc-BYmbVkr8.js → rpc-kkxzQ3Qy.js} +1 -1
  29. package/dist/rpc.js +1 -1
  30. package/dist/runtime/auth.js +1 -1
  31. package/dist/runtime/console.js +1 -1
  32. package/dist/runtime/index.d.ts +1 -0
  33. package/dist/runtime/index.js +13 -13
  34. package/dist/{server-DvSehkPP.js → server-8o9u8leM.js} +1 -1
  35. package/dist/server.d.ts +1 -1
  36. package/dist/server.js +6 -6
  37. package/dist/{service-BIGe1Hpo.js → service-XT2A8YEF.js} +2 -2
  38. package/dist/{session-CCRLR9bf.js → session-DGdFKWDB.js} +7 -6
  39. package/dist/testing.js +1 -1
  40. package/dist/vite.d.ts +1 -1
  41. package/dist/vite.js +8 -4
  42. package/package.json +9 -8
  43. package/dist/hosted/hosted-comments/client-Czl2zu9P.js +0 -4
  44. package/dist/hosted/hosted-comments/dist-DyVmH21U.js +0 -14
  45. package/dist/hosted/hosted-comments/overlay-DpS0P-nd.js +0 -186
  46. package/dist/hosted/hosted-comments/protocol-DuB0Zhs-.js +0 -1
  47. package/dist/hosted/hosted-comments/rest-transport-CKZG_jZ4.js +0 -1
  48. package/dist/hosted/hosted-comments/tools-D8xg-kDW.js +0 -126
  49. package/dist/overlay/client-C7ftI-CB.js +0 -4
package/README.md CHANGED
@@ -76,7 +76,7 @@ export const comments = defineComments({
76
76
 
77
77
  Console `comments:read` access allows reading threads and joining presence. Writes also require full `comments` access and the Comments policy.
78
78
 
79
- Press `C` and click the page to start a thread, or press `B` to draw on the page with a marker, a pen, arrows, or text labels and comment with a picture of it. Press `E` to edit text that `contentField()` marks:
79
+ With the pill open, press `C` and click the page to start a thread, or press `B` to draw on the page with a marker, a pen, arrows, or text labels and comment with a picture of it. Press `E` to edit text that `contentField()` marks:
80
80
 
81
81
  ```vue
82
82
  <script setup lang="ts">
@@ -93,7 +93,7 @@ An edit reads the draft, changes one string field, and saves the document with `
93
93
 
94
94
  ### Add Hosted Comments
95
95
 
96
- Register your site in the Console with **Hosted Comments only**, then copy the script into your page HTML. For a connected app, copy it from **Settings** > **Connection** > **Hosted Comments**. The Console signs reviewers in and stores their page threads. Send shows a comment at once and sends it in the background, with one outbox for each project. Confirming an unlink permanently deletes that project's hosted threads and replies.
96
+ Register your site in the Console with **Hosted Comments only**, then copy the script into your page HTML. For a connected app, copy it from **Settings** > **Connection** > **Hosted Comments**, and set `comments: { overlay: false }`. This turns off the app's overlay but keeps its Comments API. When the app's Comments start, Hosted Comments stay off or stop after you send or discard any draft. The browser console shows `COMMENTS_HOSTED_CONFLICT`. The hosted overlay draws in `<vitehub-hosted-comments>`, so it never takes the element of the app's overlay. The Console signs reviewers in and stores their page threads. Send shows a comment at once and sends it in the background, with one outbox for each project. Confirming an unlink permanently deletes that project's hosted threads and replies.
97
97
 
98
98
  ## Server API
99
99
 
@@ -118,7 +118,7 @@ A failure in `onComment`, `onMention`, or the pull request sync never fails the
118
118
 
119
119
  ## Send to an agent
120
120
 
121
- Each open thread has **Open in T3 Code** and **Copy**, and the list of open threads has **Open in T3 Code** and **Copy open**. Both give a prompt with the page URL, the text and replies of each thread, the element, and the URLs of its files, for every person who may read the comments. For a Console team member whose MCP access may read the threads, the prompt also names the linked app, its team, and the steps of the ViteHub MCP. It includes resolution steps only with Console MCP write access. `/session` supplies `agent: { mcp, project, resolve }`, and `repository`, the GitHub `owner/name` that the T3 Code link opens: `forge.repository`, else the repository of the build. A Hosted Comments script tag gives it with `data-vitehub-repo`. For one click without a paste, use `send`:
121
+ Each open thread has **Open in T3 Code** and **Copy**, and the list of open threads has **Copy prompt** and **Open in T3 Code** in one row under the title. **Copy** and **Open in T3 Code** give a prompt with the page URL, the text and replies of each thread, the element, and the URLs of its files, for every person who may read the comments. For a Console team member whose MCP access may read the threads, the prompt also names the linked app, its team, and the steps of the ViteHub MCP. It includes resolution steps only with Console MCP write access. `/session` supplies `agent: { mcp, project, resolve }`, and `repository`, the GitHub `owner/name` that the T3 Code link opens: `forge.repository`, else the repository of the build. A Hosted Comments script tag gives it with `data-vitehub-repo`. The pill shows **Copy prompt** too, in both modes, when the page has open threads. In the pill and in the list, **Copy prompt** copies the same text. For a Console team member, it is a short prompt that names the page, the app (its Console name, else its domain), and the ViteHub MCP calls that read and resolve the page's threads. Other people get the full text. <kbd>Shift</kbd> <kbd>C</kbd> hides or shows the pins, as the eye does. Build it with `commentsPagePrompt({ url, threads, agent })`. For one click without a paste, use `send`:
122
122
 
123
123
  `defineComments({ send: true })` adds **Send N** to the comment pill: one click hands the open threads of the page that wait for an answer to the person's own agent, such as a T3 Code thread. The first press copies a setup prompt; the agent creates a T3 webhook task and pairs it with the one-use code, and the pill asks once to allow it. Each send is a signed `POST` with the thread ids and a read token for 24 hours, through the member endpoints of `@vite-hub/webhooks`. `send: { grant: false }` leaves the token out, for an app that reads through its own MCP server, and `payload` adds fields, and `prompt` changes the setup prompt. Each member has their own count, and Allow sends only the threads the member saw. The `comments_get_send` MCP tool reads a send, and `comments.listSends(user)` and `comments.readSend(user, id)` read sends on the server. Reopening a thread can restore a done inbox send or let the member send it to a webhook agent again. Send needs a ViteHub app with a SQLite Database. See [Send comments to your agent](https://vitehub.dev/docs/comments/send).
124
124
 
@@ -138,7 +138,7 @@ Each open thread has **Open in T3 Code** and **Copy**, and the list of open thre
138
138
  | Import | Purpose |
139
139
  | --- | --- |
140
140
  | `@vite-hub/comments` | `defineComments()` and types. `installComments()` is in `@vite-hub/comments/server`. |
141
- | `@vite-hub/comments/client` | Framework-free client, transport types, `createAnchor()`, `resolveAnchor()`, `commentsAgentPrompt()`, the text of **Copy**, `commentsT3CodeLink()`, the link of **Open in T3 Code**, and `createCommentSend()`, the state of the Send segment that hands a member's waiting comments to their agent. |
141
+ | `@vite-hub/comments/client` | Framework-free client, transport types, `createAnchor()`, `resolveAnchor()`, `commentsAgentPrompt()`, the text of **Copy**, `commentsPagePrompt()`, the text of **Copy prompt** in the pill, `commentsT3CodeLink()`, the link of **Open in T3 Code**, and `createCommentSend()`, the state of the Send segment that hands a member's waiting comments to their agent. |
142
142
  | `@vite-hub/comments/testing` | In-memory client transport for tests and examples. |
143
143
  | `@vite-hub/comments/anchor` | DOM anchoring: `createAnchor()`, `placeAnchor()`, `selectorOf()`, `labelOf()`. |
144
144
  | `@vite-hub/comments/database` | `commentsSchema`, the Drizzle tables, and `commentsTables`, the statements that create them. |
@@ -247,6 +247,8 @@ client.threads; // The cached threads, ordered by number.
247
247
  client.onChange(() => console.log(`${client.threads.length} threads`));
248
248
  ```
249
249
 
250
+ Without `transport`, the client uses the Comments API of the app, with the guest that `saveCommentsGuest(name)` saved in this browser. In Vue, `useComments({ subject })` from `@vite-hub/ui/headless` and `<CommentLayer :subject>` use that client and learn the user from `GET /session`.
251
+
250
252
  To retry a create safely, give it a `requestId`, such as `crypto.randomUUID()`, and keep it for that draft. A second create with the same `requestId` in the same scope returns the first thread and creates no new thread. Only the author of the first thread gets it back, for the same subject, and only when that author may still read it. Anything else fails: the Operations and `POST /threads` answer `409` with `COMMENTS_R0022`, and the server API `comments.create()` returns `COMMENTS_INVALID_INPUT` with the reason. Make a new `requestId` for each new comment.
251
253
 
252
254
  A reply takes a `requestId` too. A second reply with the same `requestId` in the same thread returns the thread with the first message, adds nothing, and runs no hooks. Another author with that key gets the same `409`.
@@ -1,6 +1,10 @@
1
1
  import { Diagnostic, defineDiagnostics } from "nostics";
2
2
  // src/client-diagnostics.ts
3
3
  const commentsClientCodes = {
4
+ COMMENTS_HOSTED_CONFLICT: {
5
+ why: "This page runs the app's own Comments, so the Hosted Comments script does not start its overlay.",
6
+ fix: "Remove the Hosted Comments script, or keep it and set `comments: { overlay: false }` to turn off the app's overlay. See https://vitehub.dev/docs/comments/configure#add-hosted-comments"
7
+ },
4
8
  COMMENTS_OUTBOX_ACCOUNT_CHANGED: {
5
9
  why: "The current author is not the author of this queued comment.",
6
10
  fix: "Sign in as the original author and retry the outbox."
@@ -13,6 +17,10 @@ const commentsClientCodes = {
13
17
  why: "The server may already have this comment, so the draft cannot change.",
14
18
  fix: "Wait for delivery to finish, then edit or delete the server copy."
15
19
  },
20
+ COMMENTS_OVERLAY_ELEMENT_TAKEN: {
21
+ why: ({ name }) => `Another script defined the <${name}> element, so this Comments overlay cannot start.`,
22
+ fix: "Load one Comments overlay script on the page. Remove the other script that defines the element."
23
+ },
16
24
  COMMENTS_R0001: {
17
25
  why: ({ target }) => `createAnchor() found nothing to anchor to for ${target}.`,
18
26
  fix: "Pass an element, a non-empty selection, or a point that is over an element of the page."
package/dist/client.d.ts CHANGED
@@ -137,10 +137,12 @@ interface CommentsAgentPromptThread {
137
137
  /** The ViteHub MCP of a Console member, and the linked app that the agent checks before it reads the threads. */
138
138
  interface CommentsAgentAccess {
139
139
  mcp: string;
140
+ /** `name` is the app's name in the Console, such as `Acme Docs`. */
140
141
  project: {
141
142
  id: string;
142
143
  teamId: string;
143
144
  url: string;
145
+ name?: string;
144
146
  };
145
147
  /** `true` when the member's MCP access may resolve the threads. */
146
148
  resolve: boolean;
@@ -166,6 +168,12 @@ export declare function commentsAgentPrompt(input: CommentsAgentPromptInput): st
166
168
  * the last option is the thread IDs and instructions. Returns `undefined` if none of these fit.
167
169
  */
168
170
  export declare function commentsT3CodeLink(input: CommentsAgentPromptInput, repository?: string): string | undefined;
171
+ /**
172
+ * The prompt of **Copy prompt** in the pill, for the open threads of one page. With `agent`, it is three lines: the page,
173
+ * the app in the Console to read the threads from, and what to do with them. Without it, the agent cannot read the
174
+ * threads, so the prompt is `commentsAgentPrompt()` with their text.
175
+ */
176
+ export declare function commentsPagePrompt(input: CommentsAgentPromptInput): string;
169
177
  /** A point in client (viewport) coordinates, such as `event.clientX` and `event.clientY`. */
170
178
  interface AnchorPoint {
171
179
  x: number;
@@ -437,6 +445,10 @@ export declare const commentsErrorDiagnostics: import("nostics").Diagnostics<{
437
445
  }) => string;
438
446
  readonly fix: "Start a thread on a page in this project.";
439
447
  };
448
+ readonly COMMENTS_HOSTED_CONFLICT: {
449
+ why: string;
450
+ fix: string;
451
+ };
440
452
  readonly COMMENTS_OUTBOX_ACCOUNT_CHANGED: {
441
453
  why: string;
442
454
  fix: string;
@@ -449,6 +461,12 @@ export declare const commentsErrorDiagnostics: import("nostics").Diagnostics<{
449
461
  why: string;
450
462
  fix: string;
451
463
  };
464
+ readonly COMMENTS_OVERLAY_ELEMENT_TAKEN: {
465
+ why: ({ name }: {
466
+ name: string;
467
+ }) => string;
468
+ fix: string;
469
+ };
452
470
  readonly COMMENTS_R0001: {
453
471
  why: ({ target }: {
454
472
  target: string;
@@ -736,6 +754,32 @@ interface CommentSendTransportOptions extends Pick<RestTransportOptions, "base"
736
754
  export declare function createCommentSendTransport(options?: CommentSendTransportOptions): CommentSendTransport;
737
755
  /** Lower case without accents, so `jose` finds `José`. Mention suggestions match names this way, in the browser and on the server. */
738
756
  export declare function foldName(text: string): string;
757
+ /** What the Comments API session lets the person do on the page. */
758
+ interface CommentsPageCan {
759
+ comment: boolean;
760
+ resolve: boolean;
761
+ delete?: boolean;
762
+ /** `false` keeps every message as it was sent. */
763
+ change?: false;
764
+ }
765
+ /**
766
+ * Whether the Comments API lets `user` do `action`, from the permissions of the page session and the ones that the API
767
+ * sent with the thread. A guest never edits or deletes, because the server does not take a guest id as proof. The
768
+ * server still decides.
769
+ */
770
+ export declare function commentsApiCan(user: CommentUser | undefined, page: CommentsPageCan | undefined, action: "reply" | "resolve" | "edit" | "delete", { thread, message }: {
771
+ thread: CommentThread;
772
+ message?: CommentMessage;
773
+ }): boolean;
774
+ /** The app base, such as `/portal`, that Vite `base` or Nuxt `app.baseURL` sets. The Comments API of the app runs below it. */
775
+ export declare function appCommentsBase(): string;
776
+ /** The guest name and id that this browser saved, the same one that the overlay uses. */
777
+ export declare function readCommentsGuest(): CommentsGuest | undefined;
778
+ /** Saves the name that a guest typed. The id stays when the guest saved a name before. */
779
+ export declare function saveCommentsGuest(name: string): CommentsGuest;
780
+ /** Calls `listener` each time `saveCommentsGuest()` saves a guest on this page. Returns a function that stops it. */
781
+ export declare function onCommentsGuestSaved(listener: (guest: CommentsGuest) => void): () => void;
782
+ export declare function commentsGuestUser(guest: CommentsGuest): CommentUser;
739
783
  /**
740
784
  * The id of the message that a reply with `requestId` stores in a thread. Every retry gets the same id, so the primary
741
785
  * key of the messages refuses a second message, and the client's outbox finds the server copy of its waiting reply.
@@ -744,7 +788,8 @@ export declare function foldName(text: string): string;
744
788
  export declare function replyMessageId(threadId: string, requestId: string): Promise<string>;
745
789
  export type CommentsClientStatus = "idle" | "loading" | "ready" | "error";
746
790
  export interface CommentsClientOptions {
747
- transport: CommentsTransport;
791
+ /** Default: the Comments API of this app, as the signed-in user, or as the guest that `saveCommentsGuest()` saved. */
792
+ transport?: CommentsTransport;
748
793
  /** The signed-in user. The UI uses it for the "mine" filter and to know which messages the user may edit. */
749
794
  user?: CommentUser;
750
795
  /** What `refresh()` lists. For example `{ page: "/pricing" }`. Without an explicit limit, loads all pages. */
@@ -796,5 +841,5 @@ export declare function createCommentsClient(options: CommentsClientOptions & {
796
841
  }): CommentsClient & {
797
842
  readonly outbox: CommentsOutbox;
798
843
  };
799
- export declare function createCommentsClient(options: CommentsClientOptions): CommentsClient;
800
- export type { AnchorPoint, AnchorPosition, AnchorRect, AnchorTarget, AreaAnchor, CommentActor, CommentAnchor, CommentAttachment, CommentBuild, CommentComponent, CommentContext, CommentCreateInput, CommentDeleteInput, CommentDelivery, CommentDeliveryError, CommentEditInput, CommentEvent, CommentFiles, CommentForgeLink, CommentGetInput, CommentListCursor, CommentListQuery, CommentMessage, CommentMetadata, CommentReplyInput, CommentSendAgent, CommentSendClient, CommentSendCopy, CommentSendEvent, CommentSendLogo, CommentSendOptions, CommentSendPairing, CommentSendPairingCheck, CommentSendResult, CommentSendState, CommentSendStatus, CommentSendTransport, CommentSendTransportOptions, CommentStatus, CommentStatusInput, CommentSubject, CommentThread, CommentUploadInput, CommentUser, CommentUsersInput, CommentsAgentAccess, CommentsAgentPromptInput, CommentsAgentPromptThread, CommentsClientFiles, CommentsGuest, CommentsOutbox, CommentsOutboxEntry, CommentsOutboxEnvironment, CommentsOutboxMessage, CommentsOutboxOptions, CommentsOutboxStore, CommentsRestAnswer, CommentsRestRequest, CommentsTransport, CreateAnchorOptions, DetachedAnchor, ElementAnchor, ImageAnchor, PageAnchor, ResolvedAnchor, RestCommentThread, RestTransport, RestTransportOptions, TextAnchor };
844
+ export declare function createCommentsClient(options?: CommentsClientOptions): CommentsClient;
845
+ export type { AnchorPoint, AnchorPosition, AnchorRect, AnchorTarget, AreaAnchor, CommentActor, CommentAnchor, CommentAttachment, CommentBuild, CommentComponent, CommentContext, CommentCreateInput, CommentDeleteInput, CommentDelivery, CommentDeliveryError, CommentEditInput, CommentEvent, CommentFiles, CommentForgeLink, CommentGetInput, CommentListCursor, CommentListQuery, CommentMessage, CommentMetadata, CommentReplyInput, CommentSendAgent, CommentSendClient, CommentSendCopy, CommentSendEvent, CommentSendLogo, CommentSendOptions, CommentSendPairing, CommentSendPairingCheck, CommentSendResult, CommentSendState, CommentSendStatus, CommentSendTransport, CommentSendTransportOptions, CommentStatus, CommentStatusInput, CommentSubject, CommentThread, CommentUploadInput, CommentUser, CommentUsersInput, CommentsAgentAccess, CommentsAgentPromptInput, CommentsAgentPromptThread, CommentsClientFiles, CommentsGuest, CommentsOutbox, CommentsOutboxEntry, CommentsOutboxEnvironment, CommentsOutboxMessage, CommentsOutboxOptions, CommentsOutboxStore, CommentsPageCan, CommentsRestAnswer, CommentsRestRequest, CommentsTransport, CreateAnchorOptions, DetachedAnchor, ElementAnchor, ImageAnchor, PageAnchor, ResolvedAnchor, RestCommentThread, RestTransport, RestTransportOptions, TextAnchor };
package/dist/client.js CHANGED
@@ -1,9 +1,9 @@
1
- import { i as commentsUnansweredError, r as commentsClientDiagnostics, t as commentsAnswerError } from "./client-diagnostics-D987sEK7.js";
1
+ import { i as commentsUnansweredError, r as commentsClientDiagnostics, t as commentsAnswerError } from "./client-diagnostics-DoXqdnBd.js";
2
2
  import { i as withCommentFiles, n as outboxAccountHeader, r as retryAfterOf, t as failedCommentPreparation } from "./client-files-lC6X7XyS.js";
3
3
  import { t as replyMessageId } from "./reply-id-Cm9FGOBs.js";
4
- import { t as commentsErrorDiagnostics } from "./errors-ByCRdInk.js";
5
4
  import { o as commentsRoute } from "./page-2NzFladc.js";
6
5
  import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
6
+ import { t as commentsErrorDiagnostics } from "./errors-CBvIpwbo.js";
7
7
  import { t as foldName } from "./fold-name-g-xg0mQk.js";
8
8
  // ../internal/src/browser-environment.ts
9
9
  /** The real browser: window events, Web Locks, and a BroadcastChannel, each only when the browser has it. */
@@ -1036,6 +1036,211 @@ function createOutbox(options, host) {
1036
1036
  }
1037
1037
  };
1038
1038
  }
1039
+ // src/api-can.ts
1040
+ /**
1041
+ * Whether the Comments API lets `user` do `action`, from the permissions of the page session and the ones that the API
1042
+ * sent with the thread. A guest never edits or deletes, because the server does not take a guest id as proof. The
1043
+ * server still decides.
1044
+ */
1045
+ function commentsApiCan(user, page, action, { thread, message }) {
1046
+ if (!user) return false;
1047
+ const allowed = thread.can ?? {
1048
+ comment: Boolean(page?.comment),
1049
+ resolve: Boolean(page?.resolve),
1050
+ delete: Boolean(page?.delete)
1051
+ };
1052
+ if (action === "reply") return thread.status === "open" && allowed.comment;
1053
+ if (action === "resolve") return allowed.resolve;
1054
+ const own = (entry) => !user.guest && !entry.author.guest && entry.author.id === user.id;
1055
+ if (!message || page?.change === false) return false;
1056
+ if (action === "edit") return own(message);
1057
+ return (thread.messages[0]?.id === message.id ? thread.messages.every(own) : own(message)) ? allowed.comment : allowed.delete === true && !user.guest;
1058
+ }
1059
+ /** The app base, such as `/portal`, that Vite `base` or Nuxt `app.baseURL` sets. The Comments API of the app runs below it. */
1060
+ function appCommentsBase() {
1061
+ const base = typeof __VITEHUB_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_APP_BASE_URL__;
1062
+ return base.startsWith("/") && !base.startsWith("//") ? base.replace(/\/+$/, "") : "";
1063
+ }
1064
+ // src/guest.ts
1065
+ const guestKey = "vitehub-comments-guest";
1066
+ /** The guest name and id that this browser saved, the same one that the overlay uses. */
1067
+ function readCommentsGuest() {
1068
+ try {
1069
+ const value = JSON.parse(localStorage.getItem(guestKey) ?? "null");
1070
+ if (value && typeof value === "object" && "id" in value && "name" in value && typeof value.id === "string" && typeof value.name === "string") return {
1071
+ id: value.id,
1072
+ name: value.name
1073
+ };
1074
+ } catch {}
1075
+ }
1076
+ const savedListeners = /* @__PURE__ */ new Set();
1077
+ /** Saves the name that a guest typed. The id stays when the guest saved a name before. */
1078
+ function saveCommentsGuest(name) {
1079
+ const guest = {
1080
+ id: readCommentsGuest()?.id ?? crypto.randomUUID(),
1081
+ name
1082
+ };
1083
+ localStorage.setItem(guestKey, JSON.stringify(guest));
1084
+ for (const listener of savedListeners) listener(guest);
1085
+ return guest;
1086
+ }
1087
+ /** Calls `listener` each time `saveCommentsGuest()` saves a guest on this page. Returns a function that stops it. */
1088
+ function onCommentsGuestSaved(listener) {
1089
+ savedListeners.add(listener);
1090
+ return () => savedListeners.delete(listener);
1091
+ }
1092
+ function commentsGuestUser(guest) {
1093
+ return {
1094
+ id: `guest:${guest.id}`,
1095
+ name: guest.name,
1096
+ guest: true
1097
+ };
1098
+ }
1099
+ // src/rest-transport.ts
1100
+ /** The URL of an attachment key below the Comments API, such as `/_vitehub/comments/attachments/comments/<id>/shot.png`. */
1101
+ function commentAttachmentUrl(key, base = "") {
1102
+ return `${base.replace(/\/+$/, "")}${commentsRoute}/attachments/${key.split("/").map((part) => encodeURIComponent(part)).join("/")}`;
1103
+ }
1104
+ /**
1105
+ * Requests to the Comments API at `<base>/_vitehub/comments`, with the guest headers and the session cookie. A
1106
+ * failure throws a diagnostic with the `code`, `why`, and `fix` of the error object of the answer, and its `status`.
1107
+ */
1108
+ function createCommentsRestRequest(options = {}) {
1109
+ const route = options.route ?? `${(options.base ?? "").replace(/\/+$/, "")}/_vitehub/comments`;
1110
+ return async (path, init = {}) => {
1111
+ const send = options.fetch ?? globalThis.fetch;
1112
+ const headers = new Headers(typeof options.headers === "function" ? await options.headers() : options.headers);
1113
+ for (const [name, value] of new Headers(init.headers)) headers.set(name, value);
1114
+ if (init.body !== void 0 && !headers.has("content-type")) headers.set("content-type", "application/json");
1115
+ const guest = typeof options.guest === "function" ? options.guest() : options.guest;
1116
+ if (guest) {
1117
+ headers.set("x-vitehub-comments-guest-id", guest.id);
1118
+ headers.set("x-vitehub-comments-guest-name", encodeURIComponent(guest.name));
1119
+ }
1120
+ let response;
1121
+ try {
1122
+ response = await send(`${route}${path}`, {
1123
+ ...init,
1124
+ headers,
1125
+ credentials: options.credentials ?? "same-origin",
1126
+ cache: "no-store"
1127
+ });
1128
+ } catch (cause) {
1129
+ throw commentsUnansweredError(0, cause);
1130
+ }
1131
+ const value = await response.json().catch(() => void 0);
1132
+ const retryAfter = retryAfterOf(response);
1133
+ if (isRecordOrFunction(value) && isRecordOrFunction(value.error)) {
1134
+ const { code, why, fix } = value.error;
1135
+ if (typeof code !== "string" || typeof why !== "string") throw commentsUnansweredError(response.status, void 0, retryAfter);
1136
+ throw commentsAnswerError({
1137
+ code,
1138
+ why,
1139
+ ...typeof fix === "string" ? { fix } : {},
1140
+ ...retryAfter === void 0 ? {} : { retryAfter },
1141
+ status: response.status
1142
+ });
1143
+ }
1144
+ if (isRecordOrFunction(value) && "data" in value) {
1145
+ const answer = {
1146
+ data: value.data,
1147
+ people: Array.isArray(value.people) ? value.people : [],
1148
+ ...isRecordOrFunction(value.thread) ? { thread: value.thread } : {}
1149
+ };
1150
+ options.onAnswer?.(answer);
1151
+ return answer;
1152
+ }
1153
+ throw commentsUnansweredError(response.status, void 0, retryAfter);
1154
+ };
1155
+ }
1156
+ function listSearch(query) {
1157
+ const params = new URLSearchParams();
1158
+ if (query.page !== void 0) params.set("page", query.page);
1159
+ if (query.subject) {
1160
+ params.set("subjectKind", query.subject.kind);
1161
+ params.set("subjectId", query.subject.id);
1162
+ } else if (query.subjectKind) params.set("subjectKind", query.subjectKind);
1163
+ if (query.status) params.set("status", query.status);
1164
+ if (query.mine !== void 0) params.set("mine", String(query.mine));
1165
+ if (query.mentions !== void 0) params.set("mentions", String(query.mentions));
1166
+ if (query.revision) params.set("revision", String(query.revision.lte));
1167
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
1168
+ if (query.before) {
1169
+ params.set("beforeId", query.before.id);
1170
+ params.set("beforeUpdatedAt", String(query.before.updatedAt));
1171
+ }
1172
+ return params;
1173
+ }
1174
+ const thread = (id) => `/threads/${encodeURIComponent(id)}`;
1175
+ const post = (body, account) => ({
1176
+ method: "POST",
1177
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
1178
+ ...account === void 0 ? {} : { headers: { [outboxAccountHeader]: encodeURIComponent(account) } }
1179
+ });
1180
+ /**
1181
+ * A transport over the Comments API at `<base>/_vitehub/comments`: the routes that the overlay uses. The server
1182
+ * runs the `authorize` policy of `server/comments.ts` for the user of the request: the app session, or a guest that
1183
+ * `guest` names. Guests and share-link readers can use it. It has no
1184
+ * `subscribe`: the client refreshes when the window gets focus.
1185
+ */
1186
+ function createRestTransport(options = {}) {
1187
+ const request = createCommentsRestRequest(options);
1188
+ const base = (options.base ?? "").replace(/\/+$/, "");
1189
+ const upload = async (input, account) => (await request("/attachments", post(input, account))).data;
1190
+ return {
1191
+ async list(query) {
1192
+ return (await request(`/threads?${listSearch(query)}`)).data;
1193
+ },
1194
+ async get(input) {
1195
+ const path = "threadId" in input ? thread(input.threadId) : `/scopes/${encodeURIComponent(input.scope)}/threads/${input.n}`;
1196
+ return (await request(path)).data;
1197
+ },
1198
+ async create({ files, outbox, ...input }) {
1199
+ const body = await withCommentFiles(input, {
1200
+ files,
1201
+ outbox
1202
+ }, input.subject, (data) => upload(data, outbox?.account));
1203
+ return (await request("/threads", post(body, outbox?.account))).data;
1204
+ },
1205
+ async reply({ threadId, subject, files, outbox, ...input }) {
1206
+ const body = await withCommentFiles(input, {
1207
+ files,
1208
+ outbox
1209
+ }, subject, (data) => upload(data, outbox?.account));
1210
+ const answer = await request(`${thread(threadId)}/comments`, post(body, outbox?.account));
1211
+ if (!answer.thread) throw commentsUnansweredError(200);
1212
+ return answer.thread;
1213
+ },
1214
+ async edit({ threadId, messageId, ...input }) {
1215
+ return (await request(`${thread(threadId)}/comments/${encodeURIComponent(messageId)}`, {
1216
+ method: "PATCH",
1217
+ body: JSON.stringify(input)
1218
+ })).data;
1219
+ },
1220
+ async delete({ threadId, messageId }) {
1221
+ const path = messageId === void 0 ? thread(threadId) : `${thread(threadId)}/comments/${encodeURIComponent(messageId)}`;
1222
+ return (await request(path, { method: "DELETE" })).data;
1223
+ },
1224
+ async resolve({ threadId }) {
1225
+ return (await request(`${thread(threadId)}/resolve`, post())).data;
1226
+ },
1227
+ async reopen({ threadId }) {
1228
+ return (await request(`${thread(threadId)}/reopen`, post())).data;
1229
+ },
1230
+ async users({ query, limit, threadId, subject }) {
1231
+ const params = new URLSearchParams({ q: query });
1232
+ if (limit !== void 0) params.set("limit", String(limit));
1233
+ if (threadId !== void 0) params.set("thread", threadId);
1234
+ else if (subject) {
1235
+ params.set("subjectKind", subject.kind);
1236
+ params.set("subjectId", subject.id);
1237
+ }
1238
+ return (await request(`/people?${params}`)).data;
1239
+ },
1240
+ upload: (input) => upload(input),
1241
+ attachmentUrl: (key) => commentAttachmentUrl(key, base)
1242
+ };
1243
+ }
1039
1244
  // src/agent-prompt.ts
1040
1245
  /** The longest link that `commentsT3CodeLink()` makes. */
1041
1246
  const t3CodeLinkLimit = 8e3;
@@ -1126,6 +1331,24 @@ function commentsT3CodeLink(input, repository) {
1126
1331
  if (href.length <= 8e3) return href;
1127
1332
  }
1128
1333
  }
1334
+ /**
1335
+ * The prompt of **Copy prompt** in the pill, for the open threads of one page. With `agent`, it is three lines: the page,
1336
+ * the app in the Console to read the threads from, and what to do with them. Without it, the agent cannot read the
1337
+ * threads, so the prompt is `commentsAgentPrompt()` with their text.
1338
+ */
1339
+ function commentsPagePrompt(input) {
1340
+ const { agent, threads, url } = input;
1341
+ if (!agent) return commentsAgentPrompt(input);
1342
+ const page = new URL(url);
1343
+ const count = threads.length === 1 ? "a comment" : `${threads.length} comments`;
1344
+ const app = agent.project.name ? `"${agent.project.name}" (${new URL(agent.project.url).host})` : new URL(agent.project.url).host;
1345
+ const ids = threads.map((thread) => thread.id);
1346
+ return [
1347
+ `I left ${count} on ${page.href}`,
1348
+ `In the ViteHub Console, open app ${app} through the ViteHub MCP (${agent.mcp}): find it with list_apps (id: ${agent.project.id}, team ${agent.project.teamId}; if it is missing, ask me to switch team), then call read_operation with the app id, operation "comments.get", and input { threadId } for each ID in ${JSON.stringify(ids)}.`,
1349
+ agent.resolve ? "Fix each comment, then resolve it with run_operation, the app id, operation \"comments.resolve\", and input { threadId, reply }. Say what you changed in the reply." : "Fix each comment and tell me what you changed."
1350
+ ].join("\n");
1351
+ }
1129
1352
  // src/client-anchor.ts
1130
1353
  const defaultContext = 32;
1131
1354
  const clamp = (value) => Math.min(1e3, Math.max(0, value));
@@ -1901,151 +2124,6 @@ function createCommentSend(transport, options = {}) {
1901
2124
  }
1902
2125
  };
1903
2126
  }
1904
- // src/rest-transport.ts
1905
- /** The URL of an attachment key below the Comments API, such as `/_vitehub/comments/attachments/comments/<id>/shot.png`. */
1906
- function commentAttachmentUrl(key, base = "") {
1907
- return `${base.replace(/\/+$/, "")}${commentsRoute}/attachments/${key.split("/").map((part) => encodeURIComponent(part)).join("/")}`;
1908
- }
1909
- /**
1910
- * Requests to the Comments API at `<base>/_vitehub/comments`, with the guest headers and the session cookie. A
1911
- * failure throws a diagnostic with the `code`, `why`, and `fix` of the error object of the answer, and its `status`.
1912
- */
1913
- function createCommentsRestRequest(options = {}) {
1914
- const route = options.route ?? `${(options.base ?? "").replace(/\/+$/, "")}/_vitehub/comments`;
1915
- return async (path, init = {}) => {
1916
- const send = options.fetch ?? globalThis.fetch;
1917
- const headers = new Headers(typeof options.headers === "function" ? await options.headers() : options.headers);
1918
- for (const [name, value] of new Headers(init.headers)) headers.set(name, value);
1919
- if (init.body !== void 0 && !headers.has("content-type")) headers.set("content-type", "application/json");
1920
- const guest = typeof options.guest === "function" ? options.guest() : options.guest;
1921
- if (guest) {
1922
- headers.set("x-vitehub-comments-guest-id", guest.id);
1923
- headers.set("x-vitehub-comments-guest-name", encodeURIComponent(guest.name));
1924
- }
1925
- let response;
1926
- try {
1927
- response = await send(`${route}${path}`, {
1928
- ...init,
1929
- headers,
1930
- credentials: options.credentials ?? "same-origin",
1931
- cache: "no-store"
1932
- });
1933
- } catch (cause) {
1934
- throw commentsUnansweredError(0, cause);
1935
- }
1936
- const value = await response.json().catch(() => void 0);
1937
- const retryAfter = retryAfterOf(response);
1938
- if (isRecordOrFunction(value) && isRecordOrFunction(value.error)) {
1939
- const { code, why, fix } = value.error;
1940
- if (typeof code !== "string" || typeof why !== "string") throw commentsUnansweredError(response.status, void 0, retryAfter);
1941
- throw commentsAnswerError({
1942
- code,
1943
- why,
1944
- ...typeof fix === "string" ? { fix } : {},
1945
- ...retryAfter === void 0 ? {} : { retryAfter },
1946
- status: response.status
1947
- });
1948
- }
1949
- if (isRecordOrFunction(value) && "data" in value) {
1950
- const answer = {
1951
- data: value.data,
1952
- people: Array.isArray(value.people) ? value.people : [],
1953
- ...isRecordOrFunction(value.thread) ? { thread: value.thread } : {}
1954
- };
1955
- options.onAnswer?.(answer);
1956
- return answer;
1957
- }
1958
- throw commentsUnansweredError(response.status, void 0, retryAfter);
1959
- };
1960
- }
1961
- function listSearch(query) {
1962
- const params = new URLSearchParams();
1963
- if (query.page !== void 0) params.set("page", query.page);
1964
- if (query.subject) {
1965
- params.set("subjectKind", query.subject.kind);
1966
- params.set("subjectId", query.subject.id);
1967
- } else if (query.subjectKind) params.set("subjectKind", query.subjectKind);
1968
- if (query.status) params.set("status", query.status);
1969
- if (query.mine !== void 0) params.set("mine", String(query.mine));
1970
- if (query.mentions !== void 0) params.set("mentions", String(query.mentions));
1971
- if (query.revision) params.set("revision", String(query.revision.lte));
1972
- if (query.limit !== void 0) params.set("limit", String(query.limit));
1973
- if (query.before) {
1974
- params.set("beforeId", query.before.id);
1975
- params.set("beforeUpdatedAt", String(query.before.updatedAt));
1976
- }
1977
- return params;
1978
- }
1979
- const thread = (id) => `/threads/${encodeURIComponent(id)}`;
1980
- const post = (body, account) => ({
1981
- method: "POST",
1982
- ...body === void 0 ? {} : { body: JSON.stringify(body) },
1983
- ...account === void 0 ? {} : { headers: { [outboxAccountHeader]: encodeURIComponent(account) } }
1984
- });
1985
- /**
1986
- * A transport over the Comments API at `<base>/_vitehub/comments`: the routes that the overlay uses. The server
1987
- * runs the `authorize` policy of `server/comments.ts` for the user of the request: the app session, or a guest that
1988
- * `guest` names. Guests and share-link readers can use it. It has no
1989
- * `subscribe`: the client refreshes when the window gets focus.
1990
- */
1991
- function createRestTransport(options = {}) {
1992
- const request = createCommentsRestRequest(options);
1993
- const base = (options.base ?? "").replace(/\/+$/, "");
1994
- const upload = async (input, account) => (await request("/attachments", post(input, account))).data;
1995
- return {
1996
- async list(query) {
1997
- return (await request(`/threads?${listSearch(query)}`)).data;
1998
- },
1999
- async get(input) {
2000
- const path = "threadId" in input ? thread(input.threadId) : `/scopes/${encodeURIComponent(input.scope)}/threads/${input.n}`;
2001
- return (await request(path)).data;
2002
- },
2003
- async create({ files, outbox, ...input }) {
2004
- const body = await withCommentFiles(input, {
2005
- files,
2006
- outbox
2007
- }, input.subject, (data) => upload(data, outbox?.account));
2008
- return (await request("/threads", post(body, outbox?.account))).data;
2009
- },
2010
- async reply({ threadId, subject, files, outbox, ...input }) {
2011
- const body = await withCommentFiles(input, {
2012
- files,
2013
- outbox
2014
- }, subject, (data) => upload(data, outbox?.account));
2015
- const answer = await request(`${thread(threadId)}/comments`, post(body, outbox?.account));
2016
- if (!answer.thread) throw commentsUnansweredError(200);
2017
- return answer.thread;
2018
- },
2019
- async edit({ threadId, messageId, ...input }) {
2020
- return (await request(`${thread(threadId)}/comments/${encodeURIComponent(messageId)}`, {
2021
- method: "PATCH",
2022
- body: JSON.stringify(input)
2023
- })).data;
2024
- },
2025
- async delete({ threadId, messageId }) {
2026
- const path = messageId === void 0 ? thread(threadId) : `${thread(threadId)}/comments/${encodeURIComponent(messageId)}`;
2027
- return (await request(path, { method: "DELETE" })).data;
2028
- },
2029
- async resolve({ threadId }) {
2030
- return (await request(`${thread(threadId)}/resolve`, post())).data;
2031
- },
2032
- async reopen({ threadId }) {
2033
- return (await request(`${thread(threadId)}/reopen`, post())).data;
2034
- },
2035
- async users({ query, limit, threadId, subject }) {
2036
- const params = new URLSearchParams({ q: query });
2037
- if (limit !== void 0) params.set("limit", String(limit));
2038
- if (threadId !== void 0) params.set("thread", threadId);
2039
- else if (subject) {
2040
- params.set("subjectKind", subject.kind);
2041
- params.set("subjectId", subject.id);
2042
- }
2043
- return (await request(`/people?${params}`)).data;
2044
- },
2045
- upload: (input) => upload(input),
2046
- attachmentUrl: (key) => commentAttachmentUrl(key, base)
2047
- };
2048
- }
2049
2127
  // src/send-transport.ts
2050
2128
  /**
2051
2129
  * The transport of `createCommentSend()` over the Send routes of Comments, `<base>/_vitehub/comments/send/**`. The
@@ -2106,8 +2184,11 @@ async function filesArrived({ files, deferredFiles, ...input }) {
2106
2184
  ...files ? { files: await files } : {}
2107
2185
  };
2108
2186
  }
2109
- function createCommentsClient(options) {
2110
- const { transport } = options;
2187
+ function createCommentsClient(options = {}) {
2188
+ const transport = options.transport ?? createRestTransport({
2189
+ base: appCommentsBase(),
2190
+ guest: readCommentsGuest
2191
+ });
2111
2192
  const listeners = /* @__PURE__ */ new Set();
2112
2193
  const byId = /* @__PURE__ */ new Map();
2113
2194
  let listed = /* @__PURE__ */ new Set();
@@ -2349,4 +2430,4 @@ function createCommentsClient(options) {
2349
2430
  }
2350
2431
  };
2351
2432
  }
2352
- export { anchorRange, commentAttachmentUrl, commentsAgentPrompt, commentsErrorDiagnostics, commentsT3CodeLink, createAnchor, createCommentSend, createCommentSendTransport, createCommentsClient, createCommentsRestRequest, createIndexedDBOutboxStore, createMemoryOutboxStore, createRestTransport, foldName, replyMessageId, resolveAnchor, selectorFor, t3CodeLinkLimit };
2433
+ export { anchorRange, appCommentsBase, commentAttachmentUrl, commentsAgentPrompt, commentsApiCan, commentsErrorDiagnostics, commentsGuestUser, commentsPagePrompt, commentsT3CodeLink, createAnchor, createCommentSend, createCommentSendTransport, createCommentsClient, createCommentsRestRequest, createIndexedDBOutboxStore, createMemoryOutboxStore, createRestTransport, foldName, onCommentsGuestSaved, readCommentsGuest, replyMessageId, resolveAnchor, saveCommentsGuest, selectorFor, t3CodeLinkLimit };
@@ -1,4 +1,4 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-ByCRdInk.js";
1
+ import { t as commentsErrorDiagnostics } from "./errors-CBvIpwbo.js";
2
2
  import { sql } from "drizzle-orm";
3
3
  import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
4
4
  // src/operations-core/database.ts
package/dist/database.js CHANGED
@@ -1 +1 @@
1
- export { u as commentCounters, d as commentForge, f as commentMessages, t as commentSends, n as commentSendsSchema, r as commentSendsTables, p as commentThreads, i as commentsMigrationSql, m as commentsSchema, o as commentsSchemaState, h as commentsSqliteTables, l as commentsTables, s as liveThreadsBackup, c as migrateComments } from "./database-Cguz3hZL.js";
1
+ export { u as commentCounters, d as commentForge, f as commentMessages, t as commentSends, n as commentSendsSchema, r as commentSendsTables, p as commentThreads, i as commentsMigrationSql, m as commentsSchema, o as commentsSchemaState, h as commentsSqliteTables, l as commentsTables, s as liveThreadsBackup, c as migrateComments } from "./database-BuSNVwTx.js";
@@ -1,4 +1,4 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-ByCRdInk.js";
1
+ import { t as commentsErrorDiagnostics } from "./errors-CBvIpwbo.js";
2
2
  // src/operations-core/define.ts
3
3
  const marker = Symbol.for("vitehub.comments.definition");
4
4
  /** Marks a definition, so the build can check what `server/comments.ts` exports. */
@@ -1,4 +1,4 @@
1
- import { n as commentsClientCodes } from "./client-diagnostics-D987sEK7.js";
1
+ import { n as commentsClientCodes } from "./client-diagnostics-DoXqdnBd.js";
2
2
  import { defineDiagnostics } from "nostics";
3
3
  // src/operations-core/errors.ts
4
4
  const commentsErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({