@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
package/README.md CHANGED
@@ -22,7 +22,7 @@ A production build connects to `DATABASE_URL`, `TURSO_DATABASE_URL`, or a Cloudf
22
22
 
23
23
  ### Sign in with GitHub
24
24
 
25
- Create a GitHub App, install it on the repository, and list `https://<site>/api/_vitehub/comments/auth/callback/github` as its callback URL. Then set `VITEHUB_GITHUB_CLIENT_ID`, `VITEHUB_GITHUB_CLIENT_SECRET`, and `VITEHUB_SECRET` on the server. People who can push to the repository may comment. The session is an encrypted cookie, so the server stores no users.
25
+ Create a GitHub App, install it on the repository, and list `https://<site>/_vitehub/comments/auth/callback/github` as its callback URL. Then set `VITEHUB_GITHUB_CLIENT_ID`, `VITEHUB_GITHUB_CLIENT_SECRET`, and `VITEHUB_SECRET` on the server. People who can push to the repository may comment. The session is an encrypted cookie, so the server stores no users.
26
26
 
27
27
  ### In a ViteHub app
28
28
 
@@ -41,13 +41,13 @@ export const comments = defineComments({
41
41
 
42
42
  Without the file, `vitehub({ comments: true })` turns Comments on with `defineComments()`, and so does an object such as `{ database: "team" }`. The Console does not turn it on. `comments: false` turns it off. Docs sites of `@vite-hub/docs` on `vite-hub/nuxt` set it by default; `docs: { comments: false }` turns it off.
43
43
 
44
- ViteHub then adds the `vitehub_comment_threads`, `vitehub_comment_messages`, `vitehub_comment_counters`, and `vitehub_comment_forge` tables to the default Database (or the only one, or `defineComments({ database: "name" })`; without a Database Definition, the implicit `default` Database of `@vite-hub/database`), serves `/api/_vitehub/comments/**`, and adds a Comments section to the Console. Apply the tables with `vitehub database generate` and `vitehub database migrate`.
44
+ ViteHub then adds the `vitehub_comment_threads`, `vitehub_comment_messages`, `vitehub_comment_counters`, and `vitehub_comment_forge` tables to the default Database (or the only one, or `defineComments({ database: "name" })`; without a Database Definition, the implicit `default` Database of `@vite-hub/database`), serves `/_vitehub/comments/**`, and adds a Comments section to the Console. Apply the tables with `vitehub database generate` and `vitehub database migrate`.
45
45
 
46
46
  A ViteHub Database with the tables of the earlier live-site model must move them once in a migration: see [Upgrade to one model](https://vitehub.dev/docs/comments/configure#upgrade-to-one-model). Until then every Comments request fails with `COMMENTS_R0019`, whose `fix` names `commentsMigrationSql({ from: "live" })`. `migrateComments(db)` from `@vite-hub/comments/database` moves them in place and keeps the old tables as a backup.
47
47
 
48
48
  Comments is a ViteHub page tool. Open any page with `?vitehub`, or `?vitehub=comments`. The server adds the page tools loader to that page. The loader calls `GET /_vitehub/page/session`, which allows Comments when `authorize` allows `read` or offers GitHub sign-in or account switching, and sets the `vitehub-tools` cookie so later pages open in comment mode too. The loader then draws the ViteHub tools pill at the bottom of the page and imports the overlay. The overlay draws its toolbar in its segment of the pill, and its pins, cursors, and cards in `<vitehub-comments>`. The pill's **×** button turns the page tools off, so the toolbar has no close button of its own. A small ViteHub hexagon then stays at the pill's place, on every page, and pressing it turns them on again. The cookie is a hint, never a credential: every Comments route checks `authorize` again. A request without the hint gets the page with a short inline bootstrap that loads the loader in the browser only when the hint is there, so prerendered pages that a host serves as static files work too. Opening the Console calls the same session route, so the Console's people see the toolbar on the app's pages. The session route and the loader do not need the Console.
49
49
 
50
- A single page app whose `index.html` Vite serves or builds gets a short inline check in that file. It imports the loader in the browser when the page has the query or the cookie, so a built `index.html` that a host serves as a static file also gets the tools. When the app has a Vite `base` or a Nuxt `app.baseURL`, such as `/docs/`, every path follows it: `/docs/_vitehub/page/session`, `/docs/_vitehub/page/assets/loader.js`, and `/docs/api/_vitehub/comments/**`. The loader and the overlay find the base from their own URL, including the overlay's Realtime presence and live update connections.
50
+ A single page app whose `index.html` Vite serves or builds gets a short inline check in that file. It imports the loader in the browser when the page has the query or the cookie, so a built `index.html` that a host serves as a static file also gets the tools. When the app has a Vite `base` or a Nuxt `app.baseURL`, such as `/docs/`, every path follows it: `/docs/_vitehub/page/session`, `/docs/_vitehub/page/assets/loader.js`, and `/docs/_vitehub/comments/**`. The loader and the overlay find the base from their own URL, including the overlay's Realtime presence and live update connections.
51
51
 
52
52
  Custom `identify` names the user of every surface, and `authorize` decides; Comments then reads neither the Auth session nor the Console's access. Without `identify`, when the app has the Console, its Comments section controls access, and opening the Console enables the toolbar on the app's pages. Otherwise Comments reads the Auth session.
53
53
 
@@ -129,23 +129,23 @@ On a preview, `forge: { provider: "github" }` posts each thread to the pull requ
129
129
  | `@vite-hub/comments/anchor` | DOM anchoring: `createAnchor()`, `placeAnchor()`, `selectorOf()`, `labelOf()`. |
130
130
  | `@vite-hub/comments/database` | `commentsSchema`, the Drizzle tables, and `commentsTables`, the statements that create them. |
131
131
  | `@vite-hub/comments/realtime` | `commentsRealtime()`, the presence room Realtime Definition. |
132
- | `@vite-hub/comments/runtime` | `createCommentsHandler()` and `defineCommentsPlugin()` for a manual Nitro setup; `commentsMcpTools()` for an app's own MCP server. |
132
+ | `@vite-hub/comments/runtime` | `createCommentsHandler()` and `defineCommentsPlugin()` for a manual Nitro setup; `commentsMcpTools()` and `mcpToolResult()` for an app's own MCP server. |
133
133
  | `@vite-hub/comments/vite` | `comments()`, the plugin for apps without `vite-hub`, and `hubComments()`, the integration that `vitehub()` adds. |
134
134
  | `@vite-hub/comments/runtime/connect` | `connectDatabase()` of `@vite-hub/database/connect`, for the files that `comments()` generates. `/node` also opens SQLite files. |
135
135
 
136
136
  Generated files under `.vitehub/nitro/comments` are inspectable build output, not application imports.
137
137
 
138
- `createCommentsHandler(options)` returns a Fetchable, `{ fetch(request) }`. Mount it as a Nitro or H3 route at `/api/_vitehub/comments/**`, or call `handler.fetch(request)` yourself. Every outcome is a `Response`, also the errors. The handler gives the Request to `identify` as `event`, and reads cookies, the Cloudflare bindings, and `waitUntil` from its Standard Context, `request["~standard"]`. In a ViteHub app, Nitro sets it. For a Request from elsewhere, the handler sets it.
138
+ `createCommentsHandler(options)` returns a Fetchable, `{ fetch(request) }`. Mount it as a Nitro or H3 route at `/_vitehub/comments/**`, or call `handler.fetch(request)` yourself. Every outcome is a `Response`, also the errors. The handler gives the Request to `identify` as `event`, and reads cookies, the Cloudflare bindings, and `waitUntil` from its Standard Context, `request["~standard"]`. In a ViteHub app, Nitro sets it. For a Request from elsewhere, the handler sets it.
139
139
 
140
140
  ```ts
141
141
  import { createCommentsHandler } from "@vite-hub/comments/runtime";
142
142
  import { comments } from "./server/comments";
143
143
 
144
144
  const handler = createCommentsHandler({ comments, realtime: false });
145
- const response = await handler.fetch(new Request("https://site.test/api/_vitehub/comments/threads?page=/"));
145
+ const response = await handler.fetch(new Request("https://site.test/_vitehub/comments/threads?page=/"));
146
146
  ```
147
147
 
148
- `commentsMcpTools(comments)` returns tools with `call(input, { user })`, where your server authenticates `user` or passes `null` for an anonymous caller. With a request `event`, such as the Request or an H3 event, a configured Comments `identify` or session reader takes precedence over `user`. The `page` filter of `comments_list_threads` and of `comments.threads` takes a path such as `/pricing` or a full URL of the page. When `authorize` hides threads from the caller, the list says how many and why, and its structured output has a `hidden` count. See [Fix comments with an Agent](https://vitehub.dev/docs/comments/configure#fix-comments-with-an-agent).
148
+ `commentsMcpTools(comments)` returns tools with `call(input, { user })`, where your server authenticates `user` or passes `null` for an anonymous caller. A call returns `{ text, images, structured, isError }`: `comments_get_thread` puts the image attachments of the thread in `images`, up to 4 MB. `mcpToolResult(result)` turns it into the MCP tool result, with one `image` block for each image. With a request `event`, such as the Request or an H3 event, a configured Comments `identify` or session reader takes precedence over `user`. The `page` filter of `comments_list_threads` and of `comments.threads` takes a path such as `/pricing` or a full URL of the page. When `authorize` hides threads from the caller, the list says how many and why, and its structured output has a `hidden` count. See [Fix comments with an Agent](https://vitehub.dev/docs/comments/configure#fix-comments-with-an-agent).
149
149
 
150
150
  ## Learn more
151
151
 
@@ -235,8 +235,16 @@ client.onChange(() => console.log(`${client.threads.length} threads`));
235
235
 
236
236
  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.
237
237
 
238
+ 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`.
239
+
238
240
  `start()` listens to the transport's `subscribe`, such as Realtime. Without `subscribe` it refreshes when the window gets focus. A list that comes back late never undoes a thread that was created, changed, or deleted while it was on its way, and an event that is older than the stored thread is ignored. A transport that lost its connection sends `{ type: "reconnected" }` when it has it again, and the client lists the threads once more.
239
241
 
242
+ ### Outbox
243
+
244
+ `createCommentsClient({ ..., outbox: { account } })` saves each new comment and reply in IndexedDB before it sends. Drafts show with `delivery: { status: "pending" }` and survive a reload. The outbox checks the author on each write and stores progress so another tab can resume. See [Write comments offline](https://vitehub.dev/docs/comments/offline).
245
+
246
+ If a comment write gets no answer, retry it to recover the server copy. A later refusal does not make the draft safe to edit or dismiss. A lost upload or thread lookup answer does not lock the draft on its own.
247
+
240
248
  Without an explicit query `limit`, refresh loads every page. Multi-page refreshes require two matching scans before replacing the cache. If three scans cannot agree because the list keeps changing, refresh raises `COMMENTS_R0015` and preserves the previous cache; refresh again to retry. An explicit `limit` makes one request.
241
249
 
242
250
  ### Transport
@@ -244,14 +252,14 @@ Without an explicit query `limit`, refresh loads every page. Multi-page refreshe
244
252
  A transport is the seam to the server. Each method has the name and the input of one `comments.*` operation.
245
253
 
246
254
  ```ts
247
- import type { CommentCreateInput, CommentDeleteInput, CommentEditInput, CommentEvent, CommentGetInput, CommentListQuery, CommentReplyInput, CommentStatusInput, CommentThread, CommentUser, CommentUsersInput } from "@vite-hub/comments"
255
+ import type { CommentCreateInput, CommentDeleteInput, CommentEditInput, CommentEvent, CommentFiles, CommentGetInput, CommentListQuery, CommentReplyInput, CommentStatusInput, CommentThread, CommentUser, CommentUsersInput } from "@vite-hub/comments"
248
256
 
249
257
  interface CommentsTransport {
250
258
  supportsAttachments?: boolean; // Defaults to true for custom transports.
251
259
  list(query: CommentListQuery): Promise<CommentThread[]>;
252
260
  get(input: CommentGetInput): Promise<CommentThread | null>; // { id } or { scope, n }
253
- create(input: CommentCreateInput): Promise<CommentThread>;
254
- reply(input: CommentReplyInput): Promise<CommentThread>;
261
+ create(input: CommentCreateInput & CommentFiles): Promise<CommentThread>; // `files` to store before the comment
262
+ reply(input: CommentReplyInput & CommentFiles): Promise<CommentThread>; // and `subject` of the thread, for the upload
255
263
  edit(input: CommentEditInput): Promise<CommentThread>;
256
264
  delete(input: CommentDeleteInput): Promise<CommentThread | null>;
257
265
  resolve(input: CommentStatusInput): Promise<CommentThread>;
@@ -263,6 +271,8 @@ interface CommentsTransport {
263
271
 
264
272
  A mutation returns the thread as it is afterwards. `delete` returns `null` when the thread is gone.
265
273
 
274
+ Queued `create` and `reply` get `requestId`, the remaining `files`, and `outbox`. Check `outbox.account` against the current author on every server write, including file uploads. Await `outbox.uploaded(key)` for each stored file, add the keys to `attachments`, and return the first thread for a repeated `requestId` on the same target. `createRestTransport()` and `createRpcTransport()` do this. A thrown error with `status` tells the outbox whether to wait, and `retryAfter` in milliseconds tells it how long.
275
+
266
276
  Transports accept attachment keys by default, including the shipped `createRpcTransport()`. Custom transports that reject attachment keys should set `supportsAttachments: false` to disable file controls in comment surfaces.
267
277
 
268
278
  `createMemoryTransport()` keeps threads in memory. Use it in tests and docs examples:
package/dist/anchor.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { D as ElementAnchor } from "./types-CZujrMFd.js";
2
- import "./types-BIS0hCEl.js";
1
+ import { A as ElementAnchor } from "./types-C7LzhgRb.js";
2
+ import "./types-C1qzObs2.js";
3
3
  //#region src/anchor.d.ts
4
4
  /** The anchor of a pin that the overlay drops: an element anchor with every hint that `placeAnchor()` uses. */
5
5
  export type PinAnchor = ElementAnchor & Required<Pick<ElementAnchor, "label" | "page" | "viewport">>;
@@ -1,6 +1,14 @@
1
1
  import { Diagnostic, defineDiagnostics } from "nostics";
2
2
  //#region src/client-diagnostics.ts
3
3
  const commentsClientCodes = {
4
+ COMMENTS_OUTBOX_ACCOUNT_CHANGED: {
5
+ why: "The current author is not the author of this queued comment.",
6
+ fix: "Sign in as the original author and retry the outbox."
7
+ },
8
+ COMMENTS_OUTBOX_SENDING: {
9
+ why: "The server may already have this comment, so the draft cannot change.",
10
+ fix: "Wait for delivery to finish, then edit or delete the server copy."
11
+ },
4
12
  COMMENTS_R0001: {
5
13
  why: ({ target }) => `createAnchor() found nothing to anchor to for ${target}.`,
6
14
  fix: "Pass an element, a non-empty selection, or a point that is over an element of the page."
@@ -18,9 +26,12 @@ const commentsClientDiagnostics = /*#__PURE__*/ defineDiagnostics({
18
26
  docsBase: "https://vitehub.dev/docs/comments/diagnostics",
19
27
  codes: commentsClientCodes
20
28
  });
21
- /** A failure that the server answered: a diagnostic with its code, why, and fix, and the HTTP status of the answer. */
29
+ /**
30
+ * A failure that the server answered: a diagnostic with its code, why, and fix, the HTTP status of the answer, and the
31
+ * wait that its `Retry-After` asks for, in milliseconds.
32
+ */
22
33
  function commentsAnswerError(failure) {
23
- const { code, details, fix, status, why } = failure;
34
+ const { code, details, fix, retryAfter, status, why } = failure;
24
35
  const docs = code.startsWith("COMMENTS_") ? `https://vitehub.dev/docs/comments/diagnostics/${code.toLowerCase()}` : void 0;
25
36
  return Object.assign(new Diagnostic({
26
37
  code,
@@ -29,12 +40,16 @@ function commentsAnswerError(failure) {
29
40
  ...docs ? { docs } : {}
30
41
  }), {
31
42
  status,
32
- ...details ? { details } : {}
43
+ ...details ? { details } : {},
44
+ ...retryAfter === void 0 ? {} : { retryAfter }
33
45
  });
34
46
  }
35
47
  /** `COMMENTS_R0013`: the request got no usable answer. `status` is 0 when it got no answer at all. */
36
- function commentsUnansweredError(status, cause) {
37
- return Object.assign(commentsClientDiagnostics.COMMENTS_R0013(cause === void 0 ? {} : { cause }), { status });
48
+ function commentsUnansweredError(status, cause, retryAfter) {
49
+ return Object.assign(commentsClientDiagnostics.COMMENTS_R0013(cause === void 0 ? {} : { cause }), {
50
+ status,
51
+ ...retryAfter === void 0 ? {} : { retryAfter }
52
+ });
38
53
  }
39
54
  //#endregion
40
55
  export { commentsUnansweredError as i, commentsClientCodes as n, commentsClientDiagnostics as r, commentsAnswerError as t };
@@ -0,0 +1,53 @@
1
+ //#region src/client-files.ts
2
+ const outboxAccountHeader = "x-vitehub-comments-outbox-account";
3
+ const failedCommentPreparation = /* @__PURE__ */ new WeakMap();
4
+ /** The file as Base64, the form that `comments.upload` takes. */
5
+ async function base64(file) {
6
+ const bytes = new Uint8Array(await file.arrayBuffer());
7
+ let binary = "";
8
+ for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
9
+ return btoa(binary);
10
+ }
11
+ /** A `File` keeps its name. A plain `Blob` gets `file` and the extension of its media type, such as `file.png`. */
12
+ function fileName(file) {
13
+ if (file instanceof File && file.name) return file.name;
14
+ const extension = /^[a-z]+\/([a-z0-9]+)/i.exec(file.type)?.[1];
15
+ return extension ? `file.${extension}` : "file";
16
+ }
17
+ /** Stores each file with `upload`, in order, and returns the keys for `attachments`. */
18
+ async function uploadFiles(files, subject, upload, uploaded) {
19
+ const keys = [];
20
+ for (const file of files) {
21
+ const stored = await upload({
22
+ name: fileName(file),
23
+ type: file.type || "application/octet-stream",
24
+ data: await base64(file),
25
+ ...subject ? { subject } : {}
26
+ });
27
+ await uploaded?.(stored.key);
28
+ keys.push(stored.key);
29
+ }
30
+ return keys;
31
+ }
32
+ async function withCommentFiles(input, { files, outbox }, subject, upload) {
33
+ if (!files?.length) return input;
34
+ try {
35
+ return {
36
+ ...input,
37
+ attachments: [...input.attachments ?? [], ...await uploadFiles(files, subject, upload, outbox?.uploaded)]
38
+ };
39
+ } catch (cause) {
40
+ if (outbox) failedCommentPreparation.set(outbox, { cause });
41
+ throw cause;
42
+ }
43
+ }
44
+ /** The `Retry-After` of an answer in milliseconds: seconds, or an HTTP date. */
45
+ function retryAfterOf(response, now = Date.now()) {
46
+ const value = response.headers.get("retry-after")?.trim();
47
+ if (!value) return void 0;
48
+ if (/^\d+$/.test(value)) return Number(value) * 1e3;
49
+ const date = Date.parse(value);
50
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - now);
51
+ }
52
+ //#endregion
53
+ export { withCommentFiles as i, outboxAccountHeader as n, retryAfterOf as r, failedCommentPreparation as t };
package/dist/client.d.ts CHANGED
@@ -1,5 +1,120 @@
1
- import { A as TextAnchor, C as CommentUploadInput, D as ElementAnchor, E as CommentsTransport, O as ImageAnchor, S as CommentThread, T as CommentUsersInput, _ as CommentMetadata, a as CommentBuild, b as CommentStatusInput, c as CommentCreateInput, d as CommentEvent, f as CommentForgeLink, g as CommentMessage, h as CommentListQuery, i as CommentAttachment, k as PageAnchor, l as CommentDeleteInput, m as CommentListCursor, n as CommentActor, o as CommentComponent, p as CommentGetInput, r as CommentAnchor, s as CommentContext, t as AreaAnchor, u as CommentEditInput, v as CommentReplyInput, w as CommentUser, x as CommentSubject, y as CommentStatus } from "./types-CZujrMFd.js";
2
- import { t as commentsErrorDiagnostics } from "./errors-CyQyKAvy.js";
1
+ import { A as ElementAnchor, C as CommentStatusInput, D as CommentUser, E as CommentUploadInput, M as PageAnchor, N as TextAnchor, O as CommentUsersInput, S as CommentStatus, T as CommentThread, _ as CommentListCursor, a as CommentBuild, b as CommentMetadata, c as CommentCreateInput, d as CommentDeliveryError, f as CommentEditInput, g as CommentGetInput, h as CommentForgeLink, i as CommentAttachment, j as ImageAnchor, k as CommentsTransport, l as CommentDeleteInput, m as CommentFiles, n as CommentActor, o as CommentComponent, p as CommentEvent, r as CommentAnchor, s as CommentContext, t as AreaAnchor, u as CommentDelivery, v as CommentListQuery, w as CommentSubject, x as CommentReplyInput, y as CommentMessage } from "./types-C7LzhgRb.js";
2
+ import { t as commentsErrorDiagnostics } from "./errors-BEChnUo7.js";
3
+ //#region ../internal/src/browser-environment.d.ts
4
+ /** A page event that a client store reacts to. */
5
+ type BrowserEvent = "online" | "offline" | "visible" | "hidden";
6
+ /** What a client store needs from the browser: page events, one sender across tabs, and messages between tabs. Tests pass a fake one. */
7
+ interface BrowserEnvironment<Message> {
8
+ listen: (listener: (event: BrowserEvent) => void) => () => void;
9
+ isVisible: () => boolean;
10
+ isOnline: () => boolean;
11
+ /** Runs `task` while this tab holds the lock `name`, so one tab at a time sends. */
12
+ lock: <T>(name: string, task: () => Promise<T>) => Promise<T>;
13
+ /**
14
+ * Runs `task` once this tab is the leader for `name`, so one tab of the browser does it at a time. The tab stays the
15
+ * leader until `task` ends. The returned function gives up: it aborts the signal of `task`, or stops waiting.
16
+ */
17
+ lead: (name: string, task: (signal: AbortSignal) => Promise<void>) => () => void;
18
+ post: (message: Message) => void;
19
+ receive: (listener: (message: Message) => void) => () => void;
20
+ /** Runs `task` after `ms`. Returns a function that cancels it. */
21
+ schedule: (task: () => void, ms: number) => () => void;
22
+ random: () => number;
23
+ }
24
+ //#endregion
25
+ //#region src/client-outbox.d.ts
26
+ /** A message between the tabs of one browser. */
27
+ type CommentsOutboxMessage = {
28
+ type: "change";
29
+ account: string;
30
+ } | {
31
+ type: "sent";
32
+ account: string;
33
+ id: string;
34
+ kind: "create" | "reply";
35
+ key: string;
36
+ thread: CommentThread;
37
+ };
38
+ /** What the outbox needs from the browser: online and visible events, Web Locks, and a BroadcastChannel. Tests pass a fake one. */
39
+ type CommentsOutboxEnvironment = BrowserEnvironment<CommentsOutboxMessage>;
40
+ interface CommentsOutboxEntryBase {
41
+ /** The local thread or message id. Use it for outbox actions. */
42
+ id: string;
43
+ /** The retry key that the server gets. */
44
+ requestId: string;
45
+ account: string;
46
+ files: Blob[];
47
+ /** Milliseconds since the epoch. */
48
+ createdAt: number;
49
+ /** The place in the queue. */
50
+ order: number;
51
+ /** `sending` while one tab sends it. `failed` when the server refused it: it waits for `retry` or a safe `edit` or `dismiss`. */
52
+ status: "pending" | "sending" | "failed";
53
+ /** Why the last try did not go out. */
54
+ error?: CommentDeliveryError;
55
+ uncertain?: boolean;
56
+ claim?: string;
57
+ attempts?: number;
58
+ retryAt?: number;
59
+ held?: boolean;
60
+ uploaded?: string[];
61
+ }
62
+ /** A comment or reply that the outbox holds. */
63
+ type CommentsOutboxEntry = CommentsOutboxEntryBase & ({
64
+ kind: "create";
65
+ input: Omit<CommentCreateInput, "requestId">;
66
+ } | {
67
+ kind: "reply";
68
+ input: Omit<CommentReplyInput, "requestId">;
69
+ subject?: CommentSubject;
70
+ });
71
+ /** Where the outbox keeps its entries. The default is IndexedDB, else memory. */
72
+ interface CommentsOutboxStore {
73
+ /** `false` when the entries live only in this page, and a reload loses them. */
74
+ readonly persisted: boolean;
75
+ /** The entries of `account`, in queue order. */
76
+ list: (account: string) => Promise<CommentsOutboxEntry[]>;
77
+ /** Read and change one account's entries in one transaction. Replace entries rather than mutating them. */
78
+ update: <T>(account: string, change: (entries: Map<string, CommentsOutboxEntry>) => T) => Promise<T>;
79
+ }
80
+ interface CommentsOutboxOptions {
81
+ /**
82
+ * Who writes, such as the user id or a guest id. Entries of another account stay stored and do not send, so a
83
+ * comment never goes out as somebody else.
84
+ */
85
+ account: string;
86
+ /** Default: the `vitehub-comments` IndexedDB database, else memory with `persisted: false`. */
87
+ store?: CommentsOutboxStore;
88
+ /** Default: the browser. */
89
+ environment?: CommentsOutboxEnvironment;
90
+ }
91
+ /** The outbox of a client. `onChange` of the client tells every change. */
92
+ interface CommentsOutbox {
93
+ /** Every entry of the account, in queue order. */
94
+ readonly entries: readonly CommentsOutboxEntry[];
95
+ /** The entries that wait to go out or are going out. */
96
+ readonly queued: readonly CommentsOutboxEntry[];
97
+ /** The entries that the server refused. */
98
+ readonly failures: readonly CommentsOutboxEntry[];
99
+ /** `false` when IndexedDB is not available, so a reload loses the entries. */
100
+ readonly persisted: boolean;
101
+ /** Sends the entry again now. Without `id`, resumes pending entries, such as after a sign-in. */
102
+ retry: (id?: string) => Promise<void>;
103
+ /** Removes a draft and its waiting replies. `false` if it is gone or the server may already have it. */
104
+ dismiss: (id: string) => Promise<boolean>;
105
+ /** Changes a draft and requeues a refused entry. `false` if it is gone or the server may already have it. */
106
+ edit: (id: string, body: string, mentions?: string[]) => Promise<boolean>;
107
+ /** Removes every entry of the account, such as at sign-out. */
108
+ clear: () => Promise<void>;
109
+ }
110
+ /** An outbox store in memory. Entries live as long as the store object. Pass one store to two clients to test a reload. */
111
+ export declare function createMemoryOutboxStore(): CommentsOutboxStore;
112
+ /**
113
+ * The default store: the `drafts` object store of the `vitehub-comments` IndexedDB database. When IndexedDB is missing or
114
+ * does not open, as in some private windows, it keeps the entries in memory and `persisted` is `false`.
115
+ */
116
+ export declare function createIndexedDBOutboxStore(): CommentsOutboxStore;
117
+ //#endregion
3
118
  //#region src/client-anchor.d.ts
4
119
  /** A point in client (viewport) coordinates, such as `event.clientX` and `event.clientY`. */
5
120
  interface AnchorPoint {
@@ -71,6 +186,14 @@ export declare function resolveAnchor(anchor: CommentAnchor, root?: ParentNode):
71
186
  /** Lower case without accents, so `jose` finds `José`. Mention suggestions match names this way, in the browser and on the server. */
72
187
  export declare function foldName(text: string): string;
73
188
  //#endregion
189
+ //#region src/reply-id.d.ts
190
+ /**
191
+ * The id of the message that a reply with `requestId` stores in a thread. Every retry gets the same id, so the primary
192
+ * key of the messages refuses a second message, and the client's outbox finds the server copy of its waiting reply.
193
+ * The server and the browser client both import it, so it has no other import.
194
+ */
195
+ export declare function replyMessageId(threadId: string, requestId: string): Promise<string>;
196
+ //#endregion
74
197
  //#region src/rest-transport.d.ts
75
198
  /** A guest that named itself in the browser. The server keeps the name as display data only. */
76
199
  interface CommentsGuest {
@@ -80,7 +203,7 @@ interface CommentsGuest {
80
203
  interface RestTransportOptions {
81
204
  /**
82
205
  * The app origin and mount, such as `https://app.example.com` or `/portal`. The routes are
83
- * `<base>/api/_vitehub/comments/**`. Default: the page origin.
206
+ * `<base>/_vitehub/comments/**`. Default: the page origin.
84
207
  */
85
208
  base?: string;
86
209
  /**
@@ -114,10 +237,10 @@ interface CommentsRestAnswer<T> {
114
237
  }
115
238
  /** The request function of the Comments API that the overlay and `createRestTransport()` share. */
116
239
  type CommentsRestRequest = <T>(path: string, init?: RequestInit) => Promise<CommentsRestAnswer<T>>;
117
- /** The URL of an attachment key below the Comments API, such as `/api/_vitehub/comments/attachments/comments/<id>/shot.png`. */
240
+ /** The URL of an attachment key below the Comments API, such as `/_vitehub/comments/attachments/comments/<id>/shot.png`. */
118
241
  export declare function commentAttachmentUrl(key: string, base?: string): string;
119
242
  /**
120
- * Requests to the Comments API at `<base>/api/_vitehub/comments`, with the guest headers and the session cookie. A
243
+ * Requests to the Comments API at `<base>/_vitehub/comments`, with the guest headers and the session cookie. A
121
244
  * failure throws a diagnostic with the `code`, `why`, and `fix` of the error object of the answer, and its `status`.
122
245
  */
123
246
  export declare function createCommentsRestRequest(options?: RestTransportOptions & {
@@ -130,7 +253,7 @@ interface RestTransport extends CommentsTransport {
130
253
  attachmentUrl: (key: string) => string;
131
254
  }
132
255
  /**
133
- * A transport over the Comments API at `<base>/api/_vitehub/comments`: the routes that the overlay uses. The server
256
+ * A transport over the Comments API at `<base>/_vitehub/comments`: the routes that the overlay uses. The server
134
257
  * runs the `authorize` policy of `server/comments.ts` for the user of the request: the app session, or a guest that
135
258
  * `guest` names. Guests and share-link readers can use it. It has no
136
259
  * `subscribe`: the client refreshes when the window gets focus.
@@ -147,6 +270,11 @@ export interface CommentsClientOptions {
147
270
  query?: CommentListQuery;
148
271
  /** Refresh when the window gets focus and the transport cannot push updates. Default `true`. */
149
272
  refreshOnFocus?: boolean;
273
+ /**
274
+ * Saves each new comment and reply before it sends, so it shows at once, survives a reload, and goes out once when
275
+ * the network is back. Off by default: `create` and `reply` wait for the server.
276
+ */
277
+ outbox?: CommentsOutboxOptions;
150
278
  }
151
279
  export interface CommentsClient {
152
280
  readonly transport: CommentsTransport;
@@ -158,8 +286,10 @@ export interface CommentsClient {
158
286
  query: CommentListQuery;
159
287
  refresh: () => Promise<readonly CommentThread[]>;
160
288
  get: (input: CommentGetInput) => Promise<CommentThread | null>;
161
- create: (input: CommentCreateInput) => Promise<CommentThread>;
162
- reply: (input: CommentReplyInput) => Promise<CommentThread>;
289
+ /** With an outbox, returns the waiting thread once it is saved, with a local `id` and `delivery`. */
290
+ create: (input: CommentCreateInput & CommentFiles) => Promise<CommentThread>;
291
+ /** With an outbox, returns a thread view with the waiting reply once it is saved. */
292
+ reply: (input: CommentReplyInput & CommentFiles) => Promise<CommentThread>;
163
293
  edit: (input: CommentEditInput) => Promise<CommentThread>;
164
294
  delete: (input: CommentDeleteInput) => Promise<CommentThread | null>;
165
295
  resolve: (input: CommentStatusInput) => Promise<CommentThread>;
@@ -167,10 +297,21 @@ export interface CommentsClient {
167
297
  users: (input: CommentUsersInput) => Promise<CommentUser[]>;
168
298
  /** Calls `listener` after every change of `threads`, `status`, or `error`. Returns a function that stops it. */
169
299
  onChange: (listener: () => void) => () => void;
170
- /** Loads the threads, then keeps them fresh: pushed events when the transport has `subscribe`, else a refresh on window focus. Returns a function that stops it. */
300
+ /**
301
+ * Loads the threads, then keeps them fresh: pushed events when the transport has `subscribe`, else a refresh on window
302
+ * focus. With an outbox, it also sends what an earlier page saved, and tries again when the page is back online.
303
+ * Returns a function that stops it.
304
+ */
171
305
  start: () => () => void;
306
+ /** The saved comments and replies that have not gone out. Only with the `outbox` option. */
307
+ readonly outbox: CommentsOutbox | undefined;
172
308
  }
173
309
  /** A cache and a change signal over a transport. It has no framework in it. */
310
+ export declare function createCommentsClient(options: CommentsClientOptions & {
311
+ outbox: CommentsOutboxOptions;
312
+ }): CommentsClient & {
313
+ readonly outbox: CommentsOutbox;
314
+ };
174
315
  export declare function createCommentsClient(options: CommentsClientOptions): CommentsClient;
175
316
  //#endregion
176
- export { type AnchorPoint, type AnchorPosition, type AnchorRect, type AnchorTarget, type AreaAnchor, type CommentActor, type CommentAnchor, type CommentAttachment, type CommentBuild, type CommentComponent, type CommentContext, type CommentCreateInput, type CommentDeleteInput, type CommentEditInput, type CommentEvent, type CommentForgeLink, type CommentGetInput, type CommentListCursor, type CommentListQuery, type CommentMessage, type CommentMetadata, type CommentReplyInput, type CommentStatus, type CommentStatusInput, type CommentSubject, type CommentThread, type CommentUploadInput, type CommentUser, type CommentUsersInput, type CommentsGuest, type CommentsRestAnswer, type CommentsRestRequest, type CommentsTransport, type CreateAnchorOptions, type DetachedAnchor, type ElementAnchor, type ImageAnchor, type PageAnchor, type ResolvedAnchor, type RestCommentThread, type RestTransport, type RestTransportOptions, type TextAnchor, commentsErrorDiagnostics };
317
+ export { type AnchorPoint, type AnchorPosition, type AnchorRect, type AnchorTarget, type AreaAnchor, type CommentActor, type CommentAnchor, type CommentAttachment, type CommentBuild, type CommentComponent, type CommentContext, type CommentCreateInput, type CommentDeleteInput, type CommentDelivery, type CommentDeliveryError, type CommentEditInput, type CommentEvent, type CommentFiles, type CommentForgeLink, type CommentGetInput, type CommentListCursor, type CommentListQuery, type CommentMessage, type CommentMetadata, type CommentReplyInput, type CommentStatus, type CommentStatusInput, type CommentSubject, type CommentThread, type CommentUploadInput, type CommentUser, type CommentUsersInput, type CommentsGuest, type CommentsOutbox, type CommentsOutboxEntry, type CommentsOutboxEnvironment, type CommentsOutboxMessage, type CommentsOutboxOptions, type CommentsOutboxStore, type CommentsRestAnswer, type CommentsRestRequest, type CommentsTransport, type CreateAnchorOptions, type DetachedAnchor, type ElementAnchor, type ImageAnchor, type PageAnchor, type ResolvedAnchor, type RestCommentThread, type RestTransport, type RestTransportOptions, type TextAnchor, commentsErrorDiagnostics };