@vite-hub/comments 0.1.0 → 0.3.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 (87) hide show
  1. package/README.md +79 -31
  2. package/dist/anchor.d.ts +7 -4
  3. package/dist/anchor.js +10 -5
  4. package/dist/client-diagnostics-CcFpkbAk.js +40 -0
  5. package/dist/client.d.ts +78 -3
  6. package/dist/client.js +198 -13
  7. package/dist/{console-BIz9t2cO.d.ts → console-h4KlhIik.d.ts} +97 -8
  8. package/dist/context-BqIsmYP1.js +61 -0
  9. package/dist/database/postgres.d.ts +738 -347
  10. package/dist/database/postgres.js +28 -7
  11. package/dist/{database-Cb2xjC1V.d.ts → database-CA1aHKN7.d.ts} +675 -276
  12. package/dist/database.d.ts +6 -98
  13. package/dist/database.js +2 -3
  14. package/dist/define-43mMR39K.js +89 -0
  15. package/dist/define-B3TF9zzn.d.ts +204 -0
  16. package/dist/errors-4gelGVmK.js +57 -0
  17. package/dist/errors-C6qptPoG.js +135 -0
  18. package/dist/errors-CyQyKAvy.d.ts +185 -0
  19. package/dist/fold-name-B7Zb3-MF.js +7 -0
  20. package/dist/{identity-3qtVC4rF.js → identity-CBOzgxSf.js} +7 -2
  21. package/dist/index-DNhy69Wt.d.ts +83 -0
  22. package/dist/index.d.ts +7 -7
  23. package/dist/index.js +196 -5
  24. package/dist/install-BcMPgPk_.js +1154 -0
  25. package/dist/install-W9ghhGoh.d.ts +36 -0
  26. package/dist/installed-B-PfERBU.js +30 -0
  27. package/dist/invariant-D8_xBqmZ.js +22 -0
  28. package/dist/migrate-B0k_0swk.d.ts +54 -0
  29. package/dist/migrate-BDQ8xqUs.js +289 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/{operations-0B0QTVWX.d.ts → operations-D4A1Fcgf.d.ts} +37 -15
  32. package/dist/operations-DMMIfYPW.js +1159 -0
  33. package/dist/operations-GLeOqgMt.d.ts +257 -0
  34. package/dist/operations.d.ts +3 -7
  35. package/dist/operations.js +3 -2
  36. package/dist/overlay/client-DmsSMOzi.js +4 -0
  37. package/dist/overlay/dist-BoHMOFax.js +14 -0
  38. package/dist/overlay/dist-yIZmvSaU.js +1 -0
  39. package/dist/overlay/overlay.js +183 -177
  40. package/dist/page/loader.js +138 -18
  41. package/dist/{page-BuroSMXO.js → page-B41ozN63.js} +8 -6
  42. package/dist/{page-BtXADR6d.d.ts → page-DtbMOEMd.d.ts} +6 -5
  43. package/dist/page-tools-shared-NHUjKI8E.js +117 -0
  44. package/dist/path--zk6PEMz.js +18 -0
  45. package/dist/plugin-PS8PMYus.js +74 -0
  46. package/dist/realtime.d.ts +6 -12
  47. package/dist/realtime.js +23 -24
  48. package/dist/rpc-HBcWtg0T.d.ts +17 -0
  49. package/dist/rpc-RKPAusHp.js +153 -0
  50. package/dist/rpc.d.ts +2 -29
  51. package/dist/rpc.js +2 -75
  52. package/dist/runtime/auth.d.ts +5 -3
  53. package/dist/runtime/auth.js +8 -5
  54. package/dist/runtime/console.d.ts +1 -1
  55. package/dist/runtime/console.js +26 -21
  56. package/dist/runtime/index.d.ts +108 -60
  57. package/dist/runtime/index.js +684 -236
  58. package/dist/{server-BomGg3Gb.js → server-D8k-0GXe.js} +16 -7
  59. package/dist/server.d.ts +14 -88
  60. package/dist/server.js +7 -326
  61. package/dist/service-CFVm23k7.d.ts +158 -0
  62. package/dist/service-GHhhyQj4.js +609 -0
  63. package/dist/session-DVx-1Tym.d.ts +14 -0
  64. package/dist/session-EkudzUmm.js +503 -0
  65. package/dist/testing.d.ts +1 -1
  66. package/dist/testing.js +14 -2
  67. package/dist/tokens-DSbwkVSy.js +58 -0
  68. package/dist/types-BIS0hCEl.d.ts +124 -0
  69. package/dist/types-CZujrMFd.d.ts +322 -0
  70. package/dist/vite.d.ts +91 -87
  71. package/dist/vite.js +535 -796
  72. package/package.json +24 -27
  73. package/dist/database-BSnVrwHn.js +0 -60
  74. package/dist/database-C-ktS9Do.js +0 -95
  75. package/dist/define-BzW2Ychn.d.ts +0 -46
  76. package/dist/define-Cbhl6QVJ.js +0 -32
  77. package/dist/errors-BAQYcy3_.d.ts +0 -89
  78. package/dist/errors-DeD6wTCl.js +0 -77
  79. package/dist/h3-v1-request-DDGXJ9E7.js +0 -166
  80. package/dist/index-DklG2Etf.d.ts +0 -111
  81. package/dist/operations-NZG5dB8y.js +0 -732
  82. package/dist/page-tools-shared-D-amu6sx.js +0 -53
  83. package/dist/plugin-QElKQYkA.js +0 -725
  84. package/dist/request-DVc3M_AG.js +0 -14
  85. package/dist/src-CRTwnaEG.js +0 -1362
  86. package/dist/types-Cj8K7Vx7.d.ts +0 -176
  87. package/dist/types-Un2dcJWD.d.ts +0 -288
@@ -1,35 +1,48 @@
1
- import { _ as commentsErrors, a as rememberGitHubToken, c as getCloudflareEnv, d as anchorSchema, f as bodySchema, g as pageSchema, h as mentionsSchema, i as forgetGitHubToken, l as resolveWaitUntil, m as describeIssue, p as contextSchema, s as getActiveCloudflareBinding, u as runWithActiveCloudflareEnv } from "../src-CRTwnaEG.js";
2
- import { i as commentsRoute, n as commentsPageScope, o as normalizeCommentPage } from "../page-BuroSMXO.js";
3
- import { n as guestFromHeaders, r as text, t as authorOf } from "../identity-3qtVC4rF.js";
4
- import { t as requestOf } from "../request-DVc3M_AG.js";
5
- import { a as viteHubPageSessionHandler, i as resolveCommentsUser, n as installedComments, o as forwardedRequestOrigin, r as commentsMcpTools, t as defineCommentsPlugin } from "../plugin-QElKQYkA.js";
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";
4
+ 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 { 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 { 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 { 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";
13
+ import { getStandardContext, installRequestStandardContext } from "@vite-hub/runtime/internal/h3";
6
14
  import * as v from "valibot";
7
- import { createAuthForRequest } from "@vite-hub/auth/server";
8
15
  import { defineGrant } from "@vite-hub/runtime/internal/grant";
9
- import { defineEventHandler } from "h3";
10
16
  import { hkdfSync } from "node:crypto";
11
17
  import { defineAuth } from "@vite-hub/auth";
12
18
  import { stateless } from "@vite-hub/auth/presets";
13
19
  //#region src/runtime/handler.ts
14
- /** Issued by `access()` after `authorize` allows an action, for that action on that thread. Each write needs one. */
15
- const actionGrant = defineGrant("vitehub.comments.action", (input) => Object.freeze({ ...input }));
16
- /** Spends a grant for one of `actions` on `threadId`. A grant for another action or thread is a bug, so it throws. */
17
- function spend(grant, actions, threadId) {
18
- const allowed = actionGrant.consume(grant);
19
- if (!actions.includes(allowed.action) || allowed.threadId !== threadId) throw new TypeError(`[vitehub] A Comments write for ${actions.join(" or ")} ran with the grant of ${allowed.action}.`);
20
- }
21
20
  const fieldEditGrant = defineGrant("vitehub.comments.field-edit", (input) => input);
21
+ const pageSchema = v.pipe(v.string(), v.startsWith("/", "A page starts with `/`."), v.maxLength(1024));
22
+ /** `POST /threads`: the input of `comments.create`, or a `page` instead of the subject, and the page context of the overlay. */
22
23
  const createBody = v.object({
23
- page: pageSchema,
24
- anchor: anchorSchema,
25
- context: v.optional(contextSchema),
26
- body: bodySchema,
27
- mentions: mentionsSchema
24
+ ...commentInputSchemas.create.entries,
25
+ subject: v.optional(commentInputSchemas.create.entries.subject),
26
+ page: v.optional(pageSchema),
27
+ anchor: v.optional(commentAnchorSchema),
28
+ context: v.optional(contextSchema)
28
29
  });
29
30
  const replyBody = v.object({
30
- body: bodySchema,
31
- mentions: mentionsSchema
31
+ body: commentInputSchemas.reply.entries.body,
32
+ mentions: commentInputSchemas.reply.entries.mentions,
33
+ attachments: commentInputSchemas.reply.entries.attachments
34
+ });
35
+ const editBody = v.object({
36
+ body: commentInputSchemas.edit.entries.body,
37
+ mentions: commentInputSchemas.edit.entries.mentions
32
38
  });
39
+ /** The first issue as one sentence, for `COMMENTS_INVALID_INPUT`. */
40
+ function describeIssue(issues) {
41
+ const issue = issues[0];
42
+ if (!issue) return "unknown issue.";
43
+ const path = issue.path?.map((item) => String(item.key)).join(".");
44
+ return path ? `${path}: ${issue.message}` : issue.message;
45
+ }
33
46
  const fieldBody = v.object({
34
47
  field: v.pipe(v.string(), v.maxLength(512)),
35
48
  value: v.pipe(v.string(), v.maxLength(2e4)),
@@ -40,6 +53,7 @@ function status(code) {
40
53
  case "COMMENTS_NOT_FOUND":
41
54
  case "COMMENTS_CONTENT_MISSING": return 404;
42
55
  case "COMMENTS_FORBIDDEN":
56
+ case "COMMENTS_POLICY_MISSING":
43
57
  case "COMMENTS_FIELD_FORBIDDEN": return 403;
44
58
  case "COMMENTS_RESOLVED":
45
59
  case "COMMENTS_FIELD_CONFLICT": return 409;
@@ -58,11 +72,67 @@ function json(value, init = {}) {
58
72
  headers
59
73
  });
60
74
  }
61
- function failure(error) {
75
+ function failure$1(error) {
62
76
  return json({ error }, { status: status(error.code) });
63
77
  }
78
+ /** A thrown Comments diagnostic, such as `COMMENTS_R0019` for tables that need a migration, as the API's error object. */
79
+ function diagnosticResponse(error) {
80
+ const code = Reflect.get(Object(error), "code");
81
+ const status = Reflect.get(Object(error), "status");
82
+ if (!(error instanceof Error) || typeof code !== "string" || !code.startsWith("COMMENTS_") || typeof status !== "number") throw error;
83
+ const fix = Reflect.get(error, "fix");
84
+ const retryAfter = Reflect.get(error, "retryAfter");
85
+ return json({ error: {
86
+ code,
87
+ why: Reflect.get(error, "why") ?? error.message,
88
+ ...typeof fix === "string" ? { fix } : {}
89
+ } }, {
90
+ status,
91
+ ...typeof retryAfter === "number" ? { headers: { "retry-after": String(Math.ceil(retryAfter)) } } : {}
92
+ });
93
+ }
94
+ /** The REST code of a diagnostic of the comment actions. Codes without one, such as `COMMENTS_R0019`, stay as they are. */
95
+ const restCodes = {
96
+ COMMENTS_R0002: "COMMENTS_NOT_FOUND",
97
+ COMMENTS_R0003: "COMMENTS_NOT_FOUND",
98
+ COMMENTS_R0004: "COMMENTS_FORBIDDEN",
99
+ COMMENTS_R0005: "COMMENTS_INVALID_INPUT",
100
+ COMMENTS_R0006: "COMMENTS_POLICY_MISSING",
101
+ COMMENTS_R0007: "COMMENTS_INVALID_INPUT",
102
+ COMMENTS_R0008: "COMMENTS_INVALID_INPUT",
103
+ COMMENTS_R0009: "COMMENTS_FORBIDDEN",
104
+ COMMENTS_R0012: "COMMENTS_FORBIDDEN",
105
+ COMMENTS_R0016: "COMMENTS_RESOLVED",
106
+ COMMENTS_R0017: "COMMENTS_INVALID_INPUT",
107
+ COMMENTS_R0018: "COMMENTS_INVALID_INPUT"
108
+ };
109
+ /** A failure of a comment action as the API's error object: the REST code, and the status of the diagnostic. */
110
+ function actionFailure(error, action) {
111
+ const code = Reflect.get(Object(error), "code");
112
+ const mapped = typeof code === "string" ? restCodes[code] : void 0;
113
+ if (!(error instanceof Error) || !mapped) return diagnosticResponse(error);
114
+ const why = String(Reflect.get(error, "why") ?? error.message);
115
+ const result = mapped === "COMMENTS_FORBIDDEN" ? commentsErrors.COMMENTS_FORBIDDEN({ action }) : mapped === "COMMENTS_POLICY_MISSING" ? commentsErrors.COMMENTS_POLICY_MISSING() : mapped === "COMMENTS_RESOLVED" ? commentsErrors.COMMENTS_RESOLVED() : mapped === "COMMENTS_NOT_FOUND" ? commentsErrors.COMMENTS_NOT_FOUND({ id: why }) : commentsErrors.COMMENTS_INVALID_INPUT({ issue: why });
116
+ const statusOf = Reflect.get(error, "status");
117
+ return json({ error: mapped === "COMMENTS_NOT_FOUND" ? {
118
+ ...result,
119
+ why
120
+ } : result }, { status: mapped === "COMMENTS_INVALID_INPUT" && typeof statusOf === "number" ? statusOf : status(mapped) });
121
+ }
122
+ /** Response headers for a stored file: its checked type, a file name, and no way for the browser to run it. */
123
+ function attachmentHeaders(file) {
124
+ return new Headers({
125
+ "cache-control": "private, max-age=300",
126
+ "content-disposition": `${file.inline ? "inline" : "attachment"}; filename*=UTF-8''${encodeURIComponent(file.name)}`,
127
+ "content-length": String(file.size),
128
+ "content-security-policy": "default-src 'none'; sandbox",
129
+ "content-type": file.type === "text/plain" ? "text/plain; charset=utf-8" : file.type,
130
+ "cross-origin-resource-policy": "same-origin",
131
+ "x-content-type-options": "nosniff"
132
+ });
133
+ }
64
134
  function respond([error, data]) {
65
- return error ? failure(error) : json({ data: data ?? null });
135
+ return error ? failure$1(error) : json({ data: data ?? null });
66
136
  }
67
137
  function sameOrigin(request) {
68
138
  const origin = request.headers.get("origin");
@@ -100,60 +170,62 @@ function leaseHolder(error) {
100
170
  return typeof name === "string" && name ? name : "Someone";
101
171
  }
102
172
  /**
103
- * The Comments API at `/api/_vitehub/comments/**`. The overlay calls it; every route checks the `authorize` policy of
104
- * `defineComments()` for the user of the request, and inline edits also check `content.can()`.
173
+ * The Comments API at `/api/_vitehub/comments/**`, as a Fetchable: mount it as a Nitro or H3 route, or call
174
+ * `fetch(request)`. The overlay calls it; every route checks the `authorize` policy of `defineComments()` for the user of
175
+ * the request, and inline edits also check `content.can()`.
105
176
  */
106
177
  function createCommentsHandler(options) {
107
178
  const { comments } = options;
108
- async function resolveUser(event, action = "read") {
109
- return resolveCommentsUser(comments, event, {
110
- ...options,
111
- session: async (request) => await options.session?.(request) ?? await options.githubLogin?.user(request)
112
- }, action);
179
+ /** The user of the request. See `resolveCommentsIdentity()`. */
180
+ async function identityOf(request) {
181
+ return resolveCommentsIdentity(comments, request, options);
113
182
  }
114
- async function access(event, action, thread) {
115
- const user = await resolveUser(event, action);
116
- if (user === false || !await comments.can({
183
+ async function access(request, action, thread, subject) {
184
+ const { user, gate } = await identityOf(request);
185
+ if (!await comments.can({
117
186
  user,
118
187
  action,
119
- thread
120
- })) return [commentsErrors.COMMENTS_FORBIDDEN({ action }), void 0];
188
+ ...thread ? { thread } : {},
189
+ ...subject ? { subject } : {}
190
+ }, gate)) return [deniedForMissingPolicy(comments.options, user, {
191
+ ...gate,
192
+ development: (await resolveCommentsRuntime(comments))?.development === true
193
+ }) ? commentsErrors.COMMENTS_POLICY_MISSING() : commentsErrors.COMMENTS_FORBIDDEN({ action }), void 0];
121
194
  return [void 0, {
122
195
  user,
123
- author: user ? authorOf(user) : guestFromHeaders(requestOf(event).headers),
124
- grant: actionGrant.issue({
125
- action,
126
- threadId: thread?.id
127
- })
196
+ gate,
197
+ author: user ? authorOf(user) : guestFromHeaders(request.headers)
128
198
  }];
129
199
  }
130
- /** The writes of this API. Each one needs the grant of the `access()` check that allowed it. */
131
- const writes = {
132
- create: (grant, input) => {
133
- spend(grant, ["comment"]);
134
- return comments.create(input);
135
- },
136
- reply: (grant, threadId, input) => {
137
- spend(grant, ["comment"], threadId);
138
- return comments.reply(threadId, input);
139
- },
140
- resolve: (grant, threadId, by) => {
141
- spend(grant, ["resolve"], threadId);
142
- return comments.resolve(threadId, { by });
143
- },
144
- reopen: (grant, threadId) => {
145
- spend(grant, ["resolve"], threadId);
146
- return comments.reopen(threadId);
147
- },
148
- remove: (grant, threadId) => {
149
- spend(grant, ["resolve"], threadId);
150
- return comments.remove(threadId);
151
- },
152
- removeComment: (grant, threadId, commentId) => {
153
- spend(grant, ["comment", "resolve"], threadId);
154
- return comments.removeComment(commentId);
200
+ /** The caller of a comment action: the user of the request. */
201
+ async function callerOf(request) {
202
+ const runtime = await resolveCommentsRuntime(comments);
203
+ if (!runtime) return { denied: failure$1(commentsErrors.COMMENTS_NOT_INSTALLED()) };
204
+ const identity = await identityOf(request);
205
+ const waitUntil = request["~standard"].waitUntil;
206
+ return { who: {
207
+ gate: {
208
+ ...identity.gate,
209
+ development: runtime.development === true
210
+ },
211
+ request,
212
+ runtime,
213
+ user: identity.user,
214
+ ...waitUntil ? { waitUntil } : {}
215
+ } };
216
+ }
217
+ /** Runs a comment action for the request, and answers its diagnostics as the API's error objects. */
218
+ async function act(request, action, run, answer) {
219
+ const called = await callerOf(request);
220
+ if ("denied" in called) return called.denied;
221
+ let value;
222
+ try {
223
+ value = await run(called.who);
224
+ } catch (error) {
225
+ return actionFailure(error, action);
155
226
  }
156
- };
227
+ return await answer(value, called.who);
228
+ }
157
229
  /** Adds the build, and the source files of each component, to the context that the overlay read. */
158
230
  function completeContext(context) {
159
231
  const named = context.components?.map((component) => {
@@ -172,28 +244,30 @@ function createCommentsHandler(options) {
172
244
  ...options.build && Object.values(options.build).some(Boolean) ? { build: options.build } : {}
173
245
  };
174
246
  }
175
- async function readJson(event) {
247
+ async function readJson(request) {
176
248
  try {
177
- return await requestOf(event).json();
249
+ return await request.json();
178
250
  } catch {
179
251
  return;
180
252
  }
181
253
  }
182
254
  function invalid(issues) {
183
- return failure(commentsErrors.COMMENTS_INVALID_INPUT({ issue: describeIssue(issues) }));
255
+ return failure$1(commentsErrors.COMMENTS_INVALID_INPUT({ issue: describeIssue(issues) }));
184
256
  }
185
- /** Who the overlay's person is and what they may do. The page tools session decides whether the overlay loads. */
186
- async function session(event) {
187
- const user = await resolveUser(event);
188
- const [read, comment, resolve] = await Promise.all([
257
+ /** Who the overlay's person is, what they may do, and the subject of the page. The page tools session decides whether the overlay loads. */
258
+ async function session(request, subject, revision) {
259
+ const identity = await identityOf(request);
260
+ const { user } = identity;
261
+ const [read, comment, resolve, remove] = await Promise.all([
189
262
  "read",
190
- "comment",
191
- "resolve"
192
- ].map((action) => can(event, user, action)));
263
+ "write",
264
+ "resolve",
265
+ "delete"
266
+ ].map((action) => can$1(identity, action, void 0, subject)));
193
267
  const github = options.githubLogin?.configured() ? options.githubLogin : void 0;
194
- const pathname = new URL(requestOf(event).url).pathname;
268
+ const pathname = new URL(request.url).pathname;
195
269
  const route = pathname.slice(0, pathname.indexOf(commentsRoute) + commentsRoute.length);
196
- const signIn = user !== false && !user && !comments.options.identify && github ? {
270
+ const signIn = !user && !comments.options.identify && github ? {
197
271
  provider: "github",
198
272
  url: `${route}/auth/github`
199
273
  } : void 0;
@@ -204,51 +278,127 @@ function createCommentsHandler(options) {
204
278
  can: {
205
279
  read,
206
280
  comment,
207
- resolve
281
+ resolve,
282
+ delete: remove
208
283
  },
209
284
  ...signIn ? { signIn } : {},
210
285
  ...signOut ? { signOut } : {},
211
286
  realtime: options.realtime,
212
- content: Boolean(options.content)
287
+ ...options.presence === false ? { presence: false } : {},
288
+ content: Boolean(options.content),
289
+ ...subject ? { subject } : {},
290
+ ...revision === void 0 ? {} : { revision }
213
291
  } });
214
292
  }
215
- async function can(event, user, action, thread) {
216
- if (user === false) return false;
217
- if (action !== "read" && await options.consoleSession?.(event, action).catch(() => false) === false) return false;
293
+ async function can$1(identity, action, thread, subject) {
218
294
  return comments.can({
219
- user,
295
+ user: identity.user,
220
296
  action,
221
- thread
222
- });
297
+ ...thread ? { thread } : {},
298
+ ...subject ? { subject } : {}
299
+ }, identity.gate);
223
300
  }
224
- async function permissions(event, user, thread) {
225
- const [comment, resolve] = await Promise.all(["comment", "resolve"].map((action) => can(event, user, action, thread)));
301
+ async function permissions(who, thread) {
302
+ const [comment, resolve, remove] = await Promise.all([
303
+ "write",
304
+ "resolve",
305
+ "delete"
306
+ ].map((action) => can$1(who, action, thread)));
226
307
  return {
227
308
  ...thread,
228
309
  can: {
229
310
  comment,
230
- resolve
311
+ resolve,
312
+ delete: remove
231
313
  }
232
314
  };
233
315
  }
234
- async function respondThread(event, user, [error, thread]) {
235
- return error ? failure(error) : json({ data: await permissions(event, user, thread) });
316
+ /** The people that the threads mention, so a UI shows their names. */
317
+ async function people(who, threads) {
318
+ return await mentionedPeople(who.runtime, who.user, threads, who.gate);
236
319
  }
237
- /** A page thread. Threads of other scopes belong to the app's own UI, so this API does not show or change them. */
238
- async function thread(id) {
239
- const [error, found] = await comments.get(id);
240
- if (error) return [error, void 0];
241
- return found.scope === "pages" ? [void 0, found] : [commentsErrors.COMMENTS_NOT_FOUND({ id }), void 0];
320
+ /** A thread with what the reader may do with it, and the people that it mentions. */
321
+ async function threadResponse(who, thread, extra = {}) {
322
+ if (!thread) return json({
323
+ data: null,
324
+ ...extra
325
+ });
326
+ return json({
327
+ data: await permissions(who, thread),
328
+ people: await people(who, [thread]),
329
+ ...extra
330
+ });
331
+ }
332
+ /** Lists check `read` on the filter first, so a person who may not read gets `403`, not an empty list. */
333
+ async function mayRead(who, subject) {
334
+ if (!await can(who.runtime, {
335
+ action: "read",
336
+ user: who.user,
337
+ ...subject ? { subject } : {}
338
+ }, who.gate)) throw deniedError(who.runtime, "read", who.user, who.gate);
339
+ }
340
+ /** The list query of `GET /threads`: the filters of `comments.list` as search parameters. */
341
+ /** `page`: the subject that `page` of `defineComments()` gives for the `?page=` path, as the overlay sees it. */
342
+ function listQuery(url, page) {
343
+ const params = url.searchParams;
344
+ const number = (name) => params.has(name) ? Number(params.get(name)) : void 0;
345
+ const flag = (name) => params.has(name) ? params.get(name) === "true" || params.get(name) === "1" : void 0;
346
+ const kind = params.get("subjectKind");
347
+ const subjectId = params.get("subjectId");
348
+ const state = params.get("status");
349
+ const lte = number("revision");
350
+ const beforeId = params.get("beforeId");
351
+ const beforeUpdatedAt = number("beforeUpdatedAt");
352
+ const parsed = v.safeParse(commentInputSchemas.list, {
353
+ ...page ? { subject: page } : kind && subjectId ? { subject: {
354
+ kind,
355
+ id: subjectId
356
+ } } : kind ? { subjectKind: kind } : {},
357
+ ...state === "open" || state === "resolved" ? { status: state } : {},
358
+ ...lte === void 0 ? {} : { revision: { lte } },
359
+ ...number("limit") === void 0 ? {} : { limit: number("limit") },
360
+ ...beforeId && beforeUpdatedAt !== void 0 ? { before: {
361
+ id: beforeId,
362
+ updatedAt: beforeUpdatedAt
363
+ } } : {},
364
+ ...flag("mine") === void 0 ? {} : { mine: flag("mine") },
365
+ ...flag("mentions") === void 0 ? {} : { mentions: flag("mentions") }
366
+ });
367
+ return parsed.success ? [void 0, parsed.output] : [commentsErrors.COMMENTS_INVALID_INPUT({ issue: describeIssue(parsed.issues) }), void 0];
368
+ }
369
+ /**
370
+ * Checks the page context that the overlay read: same origin, and a thread on the subject of that page. Keeps only
371
+ * the origin and the path, and gives the revision of the page subject.
372
+ */
373
+ async function checkContext(request, context, subject) {
374
+ const origin = forwardedRequestOrigin(request);
375
+ let submitted;
376
+ try {
377
+ submitted = new URL(context.url);
378
+ } catch {
379
+ return [commentsErrors.COMMENTS_INVALID_INPUT({ issue: "context.url: Expected an absolute page URL." }), void 0];
380
+ }
381
+ if (submitted.origin !== origin) return [commentsErrors.COMMENTS_INVALID_INPUT({ issue: "context.url: Must match the request origin and thread page." }), void 0];
382
+ const page = normalizeCommentPage(submitted.pathname);
383
+ const expected = await resolveCommentsPage(comments, request, request, page);
384
+ if (expected.subject.kind !== subject.kind || expected.subject.id !== subject.id) return [commentsErrors.COMMENTS_INVALID_INPUT({ issue: `context.url: The page ${page} maps to the subject ${expected.subject.kind}:${expected.subject.id}, not ${subject.kind}:${subject.id}.` }), void 0];
385
+ return [void 0, {
386
+ context: completeContext({
387
+ ...context,
388
+ url: `${origin}${page}`
389
+ }),
390
+ ...expected.revision === void 0 ? {} : { revision: expected.revision }
391
+ }];
242
392
  }
243
- async function fieldTarget(event, address) {
393
+ async function fieldTarget(request, address, subject) {
244
394
  if (!options.content) return [commentsErrors.COMMENTS_CONTENT_MISSING(), void 0];
245
- const [denied, allowed] = await access(event, "comment");
395
+ const [denied, allowed] = await access(request, "write", void 0, subject);
246
396
  if (denied) return [denied, void 0];
247
397
  const parsed = options.content.parseField(address);
248
398
  const collection = parsed && options.content.runtime.collections().find((candidate) => candidate.name === parsed.collection);
249
399
  const id = collection?.kind === "singleton" ? collection.id : parsed?.id;
250
400
  if (!parsed || !collection || !id) return [commentsErrors.COMMENTS_FIELD_INVALID({ field: address }), void 0];
251
- if (!allowed.author) return [commentsErrors.COMMENTS_FORBIDDEN({ action: "comment" }), void 0];
401
+ if (!allowed.author) return [commentsErrors.COMMENTS_FORBIDDEN({ action: "write" }), void 0];
252
402
  if (!await options.content.runtime.can({
253
403
  user: allowed.user ?? void 0,
254
404
  collection: collection.name,
@@ -266,9 +416,9 @@ function createCommentsHandler(options) {
266
416
  user: allowed.user
267
417
  }];
268
418
  }
269
- async function readField(event, address) {
270
- const [error, target] = await fieldTarget(event, address);
271
- if (error) return failure(error);
419
+ async function readField(request, address, subject) {
420
+ const [error, target] = await fieldTarget(request, address, subject);
421
+ if (error) return failure$1(error);
272
422
  const value = readPath(target.document.data, target.path);
273
423
  return json({ data: {
274
424
  field: address,
@@ -279,13 +429,13 @@ function createCommentsHandler(options) {
279
429
  id: target.id
280
430
  } });
281
431
  }
282
- async function saveField(event) {
283
- const parsed = v.safeParse(fieldBody, await readJson(event));
432
+ async function saveField(request, subject) {
433
+ const parsed = v.safeParse(fieldBody, await readJson(request));
284
434
  if (!parsed.success) return invalid(parsed.issues);
285
- const [error, target] = await fieldTarget(event, parsed.output.field);
286
- if (error) return failure(error);
287
- if (typeof readPath(target.document.data, target.path) !== "string") return failure(commentsErrors.COMMENTS_FIELD_NOT_EDITABLE({ field: parsed.output.field }));
288
- if (target.document.digest !== parsed.output.ifDigest) return failure(commentsErrors.COMMENTS_FIELD_CONFLICT({ field: parsed.output.field }));
435
+ const [error, target] = await fieldTarget(request, parsed.output.field, subject);
436
+ if (error) return failure$1(error);
437
+ if (typeof readPath(target.document.data, target.path) !== "string") return failure$1(commentsErrors.COMMENTS_FIELD_NOT_EDITABLE({ field: parsed.output.field }));
438
+ if (target.document.digest !== parsed.output.ifDigest) return failure$1(commentsErrors.COMMENTS_FIELD_CONFLICT({ field: parsed.output.field }));
289
439
  return await writeField(fieldEditGrant.issue({
290
440
  collection: target.collection,
291
441
  id: target.id,
@@ -305,7 +455,7 @@ function createCommentsHandler(options) {
305
455
  message: `Edit ${target.path.join(".")} on the page`,
306
456
  metadata: {
307
457
  source: "comments",
308
- author: user.name
458
+ author: user.name ?? user.id
309
459
  }
310
460
  });
311
461
  return json({ data: {
@@ -315,125 +465,147 @@ function createCommentsHandler(options) {
315
465
  } });
316
466
  } catch (cause) {
317
467
  const code = errorCode(cause);
318
- if (code === "WORKSPACE_CONFLICT") return failure(commentsErrors.COMMENTS_FIELD_CONFLICT({ field }));
319
- if (code === "CONTENT_LEASE_HELD") return failure(commentsErrors.COMMENTS_FIELD_LOCKED({ holder: leaseHolder(cause) }));
468
+ if (code === "WORKSPACE_CONFLICT") return failure$1(commentsErrors.COMMENTS_FIELD_CONFLICT({ field }));
469
+ if (code === "CONTENT_LEASE_HELD") return failure$1(commentsErrors.COMMENTS_FIELD_LOCKED({ holder: leaseHolder(cause) }));
320
470
  throw cause;
321
471
  }
322
472
  }
323
- async function handle(event) {
324
- const request = requestOf(event);
325
- const response = await route(event, request);
326
- if (request.method !== "GET" && comments.options.forge) resolveWaitUntil(event, { preferHost: true })?.(comments.flush());
473
+ async function handle(request) {
474
+ const response = await route(request).catch(diagnosticResponse);
475
+ if (request.method !== "GET" && comments.options.forge) request["~standard"].waitUntil?.(comments.flush());
327
476
  return response;
328
477
  }
329
- return defineEventHandler((event) => {
330
- const env = getCloudflareEnv(event, { fallback: false });
331
- return env ? runWithActiveCloudflareEnv(env, () => handle(event)) : handle(event);
332
- });
333
- async function route(event, request) {
478
+ return { async fetch(input) {
479
+ installRequestStandardContext(input);
480
+ const request = input;
481
+ const env = request["~standard"].runtime?.cloudflare?.env;
482
+ return env ? await runWithActiveCloudflareEnv(env, () => handle(request)) : await handle(request);
483
+ } };
484
+ async function route(request) {
334
485
  const url = new URL(request.url);
335
486
  const path = url.pathname.slice(url.pathname.indexOf("/api/_vitehub/comments") + 22).replace(/\/+$/, "") || "/";
336
487
  const parts = path.split("/").filter(Boolean);
337
488
  const method = request.method;
489
+ const page = url.searchParams.get("page");
490
+ const subjectKind = url.searchParams.get("subjectKind");
491
+ const subjectId = url.searchParams.get("subjectId");
492
+ const pageOf = async () => page ? await resolveCommentsPage(comments, request, request, page) : subjectKind && subjectId ? { subject: {
493
+ kind: subjectKind,
494
+ id: subjectId
495
+ } } : void 0;
496
+ const subjectOf = async () => (await pageOf())?.subject;
338
497
  if (method !== "GET" && !sameOrigin(request)) return json({ error: {
339
498
  code: "COMMENTS_FORBIDDEN",
340
499
  why: "Comments requests must come from the site's own pages."
341
500
  } }, { status: 403 });
342
- if (method === "GET" && path === "/session") return await session(event);
343
- if (path.startsWith("/auth/") && options.githubLogin) return await options.githubLogin.handle(event, path);
501
+ if (method === "GET" && path === "/session") {
502
+ const current = await pageOf();
503
+ return await session(request, current?.subject, current?.revision);
504
+ }
505
+ if (path.startsWith("/auth/") && options.githubLogin) return await options.githubLogin.handle(request, path);
344
506
  if (path === "/threads") {
345
507
  if (method === "GET") {
346
- const [denied, allowed] = await access(event, "read");
347
- if (denied) return failure(denied);
348
- const page = url.searchParams.get("page");
349
- const state = url.searchParams.get("status");
350
- const [error, threads] = await comments.list({
351
- scope: commentsPageScope,
352
- page: page ? normalizeCommentPage(page) : void 0,
353
- status: state === "open" || state === "resolved" ? state : void 0
354
- });
355
- return error ? failure(error) : json({ data: await Promise.all(threads.map((thread) => permissions(event, allowed.user, thread))) });
508
+ const [invalidQuery, query] = listQuery(url, page ? await subjectOf() : void 0);
509
+ if (invalidQuery) return failure$1(invalidQuery);
510
+ return await act(request, "read", async (who) => {
511
+ await mayRead(who, query.subject);
512
+ return await commentActions.list(query, who);
513
+ }, async (threads, who) => json({
514
+ data: await Promise.all(threads.map((thread) => permissions(who, thread))),
515
+ people: await people(who, threads)
516
+ }));
356
517
  }
357
518
  if (method === "POST") {
358
- const parsed = v.safeParse(createBody, await readJson(event));
519
+ const parsed = v.safeParse(createBody, await readJson(request));
359
520
  if (!parsed.success) return invalid(parsed.issues);
360
- const [denied, allowed] = await access(event, "comment");
361
- if (denied) return failure(denied);
362
- if (!allowed.author) return failure(commentsErrors.COMMENTS_FORBIDDEN({ action: "comment" }));
363
- const { context, ...input } = parsed.output;
364
- if (context) {
365
- const origin = forwardedRequestOrigin(request);
366
- const page = normalizeCommentPage(input.page);
367
- let submitted;
368
- try {
369
- submitted = new URL(context.url);
370
- } catch {
371
- return failure(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "context.url: Expected an absolute page URL." }));
372
- }
373
- if (submitted.origin !== origin || normalizeCommentPage(submitted.pathname) !== page) return failure(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "context.url: Must match the request origin and thread page." }));
374
- context.url = `${origin}${page}`;
375
- }
376
- return await respondThread(event, allowed.user, await writes.create(allowed.grant, {
521
+ const { page, subject: given, context, anchor, ...input } = parsed.output;
522
+ const mappedPage = given || page === void 0 ? void 0 : await resolveCommentsPage(comments, request, request, page);
523
+ const target = given ?? mappedPage?.subject;
524
+ if (!target) return failure$1(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "subject: Give a subject, or a page." }));
525
+ const [badContext, checked] = context ? await checkContext(request, context, target) : [void 0, void 0];
526
+ if (badContext) return failure$1(badContext);
527
+ const mapped = checked?.revision ?? mappedPage?.revision;
528
+ const revision = mapped === void 0 ? input.revision : input.revision !== void 0 && input.revision <= mapped ? input.revision : mapped;
529
+ return await act(request, "write", (who) => commentActions.create({
377
530
  ...input,
378
- ...context ? { context: completeContext(context) } : {},
379
- author: allowed.author
380
- }));
531
+ anchor: anchor ?? { kind: "page" },
532
+ subject: target,
533
+ ...checked ? { context: checked.context } : {},
534
+ ...revision === void 0 ? {} : { revision }
535
+ }, who), (thread, who) => threadResponse(who, thread));
381
536
  }
382
537
  }
538
+ if (parts[0] === "scopes" && parts[1] && parts[2] === "threads" && parts[3] && !parts[4] && method === "GET") {
539
+ const parsed = v.safeParse(commentInputSchemas.get, {
540
+ scope: decodeURIComponent(parts[1]),
541
+ n: Number(parts[3])
542
+ });
543
+ if (!parsed.success) return invalid(parsed.issues);
544
+ return await act(request, "read", (who) => commentActions.get(parsed.output, who), (thread, who) => threadResponse(who, thread));
545
+ }
383
546
  if (parts[0] === "threads" && parts[1]) {
384
- const id = decodeURIComponent(parts[1]);
385
- const [missing, current] = await thread(id);
386
- if (missing) return failure(missing);
547
+ const threadId = decodeURIComponent(parts[1]);
387
548
  const action = parts[2];
388
- if (method === "POST" && action === "comments") {
389
- const parsed = v.safeParse(replyBody, await readJson(event));
549
+ const messageId = parts[3] ? decodeURIComponent(parts[3]) : void 0;
550
+ if (method === "GET" && !action) return await act(request, "read", (who) => commentActions.get({ id: threadId }, who), (thread, who) => threadResponse(who, thread));
551
+ if (method === "POST" && action === "comments" && !messageId) {
552
+ const parsed = v.safeParse(replyBody, await readJson(request));
390
553
  if (!parsed.success) return invalid(parsed.issues);
391
- const [denied, allowed] = await access(event, "comment", current);
392
- if (denied) return failure(denied);
393
- if (!allowed.author) return failure(commentsErrors.COMMENTS_FORBIDDEN({ action: "comment" }));
394
- return respond(await writes.reply(allowed.grant, id, {
554
+ return await act(request, "write", (who) => commentActions.reply({
395
555
  ...parsed.output,
396
- author: allowed.author
397
- }));
398
- }
399
- if (method === "POST" && (action === "resolve" || action === "reopen")) {
400
- const [denied, allowed] = await access(event, "resolve", current);
401
- if (denied) return failure(denied);
402
- if (action === "reopen") return await respondThread(event, allowed.user, await writes.reopen(allowed.grant, id));
403
- return await respondThread(event, allowed.user, await writes.resolve(allowed.grant, id, allowed.author ?? {
404
- id: "anonymous",
405
- name: "Someone"
556
+ threadId
557
+ }, who), async ({ message, thread }, who) => json({
558
+ data: message,
559
+ thread: await permissions(who, thread),
560
+ people: await people(who, [thread])
406
561
  }));
407
562
  }
408
- if (method === "DELETE" && action === "comments" && parts[3]) {
409
- const commentId = decodeURIComponent(parts[3]);
410
- const comment = current.comments.find((candidate) => candidate.id === commentId);
411
- if (!comment) return failure(commentsErrors.COMMENTS_NOT_FOUND({ id: commentId }));
412
- const [denied, allowed] = await access(event, "comment", current);
413
- if (!denied && allowed.user && !allowed.user.guest && !comment.author.guest && comment.author.id === allowed.user.id) return respond(await writes.removeComment(allowed.grant, id, commentId));
414
- const [cannot, resolver] = await access(event, "resolve", current);
415
- if (cannot) return failure(cannot);
416
- if (!resolver.user || resolver.user.guest) return failure(commentsErrors.COMMENTS_FORBIDDEN({ action: "resolve" }));
417
- return respond(await writes.removeComment(resolver.grant, id, commentId));
418
- }
419
- if (method === "DELETE" && !action) {
420
- const [denied, allowed] = await access(event, "resolve", current);
421
- if (denied) return failure(denied);
422
- if (!allowed.user || allowed.user.guest) return failure(commentsErrors.COMMENTS_FORBIDDEN({ action: "resolve" }));
423
- return respond(await writes.remove(allowed.grant, id));
563
+ if (method === "PATCH" && action === "comments" && messageId) {
564
+ const parsed = v.safeParse(editBody, await readJson(request));
565
+ if (!parsed.success) return invalid(parsed.issues);
566
+ return await act(request, "write", (who) => commentActions.edit({
567
+ ...parsed.output,
568
+ threadId,
569
+ messageId
570
+ }, who), (thread, who) => threadResponse(who, thread));
424
571
  }
572
+ if (method === "POST" && (action === "resolve" || action === "reopen") && !messageId) return await act(request, "resolve", (who) => commentActions.setStatus({ threadId }, who, action === "resolve" ? "resolved" : "open"), (thread, who) => threadResponse(who, thread));
573
+ if (method === "DELETE" && (action === "comments" ? messageId : !action)) return await act(request, "delete", (who) => commentActions.delete({
574
+ threadId,
575
+ ...messageId ? { messageId } : {}
576
+ }, who), (thread, who) => threadResponse(who, thread));
577
+ }
578
+ if (path === "/attachments" && method === "POST") {
579
+ const parsed = v.safeParse(commentInputSchemas.upload, await readJson(request));
580
+ if (!parsed.success) return invalid(parsed.issues);
581
+ return await act(request, "write", (who) => commentActions.upload(parsed.output, who), (attachment) => json({ data: attachment }));
582
+ }
583
+ if (parts[0] === "attachments" && parts.length > 1 && method === "GET") {
584
+ const key = parts.slice(1).map((part) => decodeURIComponent(part)).join("/");
585
+ return await act(request, "read", (who) => commentActions.attachment({ key }, who), (file) => new Response(file.data.stream(), { headers: attachmentHeaders(file) }));
425
586
  }
426
587
  if (method === "GET" && path === "/people") {
427
- const [denied, allowed] = await access(event, "read");
428
- if (denied) return failure(denied);
588
+ const threadId = url.searchParams.get("thread");
589
+ const [missing, current] = threadId ? await comments.get(threadId) : [void 0, void 0];
590
+ if (missing) return failure$1(missing);
591
+ const target = current?.subject ?? await subjectOf();
592
+ const [denied, allowed] = await access(request, "read", current, target);
593
+ if (denied) return failure$1(denied);
594
+ const limit = Number(url.searchParams.get("limit") ?? 20);
429
595
  return respond(await comments.people({
430
596
  query: url.searchParams.get("q") ?? "",
431
- user: allowed.user
597
+ user: allowed.user,
598
+ gate: allowed.gate,
599
+ ...Number.isFinite(limit) ? { limit } : {},
600
+ ...current ? { thread: current } : {},
601
+ ...target ? { subject: target } : {}
432
602
  }));
433
603
  }
434
604
  if (path === "/fields") {
435
- if (method === "GET") return await readField(event, url.searchParams.get("field") ?? "");
436
- if (method === "POST") return await saveField(event);
605
+ const subject = page ? await subjectOf() : void 0;
606
+ if (!subject) return failure$1(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "page: Give the current page for a field edit." }));
607
+ if (method === "GET") return await readField(request, url.searchParams.get("field") ?? "", subject);
608
+ if (method === "POST") return await saveField(request, subject);
437
609
  }
438
610
  return json({ error: {
439
611
  code: "COMMENTS_NOT_FOUND",
@@ -442,44 +614,321 @@ function createCommentsHandler(options) {
442
614
  }
443
615
  }
444
616
  //#endregion
445
- //#region src/runtime/console-session.ts
617
+ //#region src/runtime/database.ts
446
618
  /**
447
- * The user of a request from the Console access rules: the person must be allowed to use the Console `comments`
448
- * section. People that the Console does not allow get `false`, which denies access before Comments guest policies.
449
- * A Console without accounts, such as `console: { auth: false }` or the dev server, stays anonymous to policies.
450
- * Guest authors name themselves in the overlay; their browser display data never becomes a policy user.
619
+ * The Database that `defineComments({ database })` names, else `default`, else the only one. The plugin calls it when
620
+ * the server starts. On Cloudflare that is before any request, so a D1 Database can't connect yet: its db throws until
621
+ * a request brings the binding. An app without a default Database uses a placeholder that throws
622
+ * `DATABASE_DISABLED` or `DATABASE_NOT_FOUND`. The store reads the db per query, by which time the binding is there.
451
623
  */
452
- function commentsConsoleSession(access) {
453
- return async (event, action = "read") => {
454
- if (!await access.authorize({
455
- event,
456
- kind: action === "read" ? "read" : "write"
457
- })) return false;
458
- const user = await access.user({ event });
459
- const id = text(user?.id) ?? text(user?.email);
460
- if (user && id) return {
461
- ...user,
462
- id
463
- };
464
- const person = await access.identify({ event });
465
- const openGuest = person && !person.email && /^guest-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i.test(person.id);
466
- if (person && !openGuest) return { ...person };
467
- return null;
624
+ function selectCommentsDatabase(databases, name) {
625
+ if (name) return databases[name]?.db;
626
+ const fallback = databases.default?.db;
627
+ if (fallback && !isPlaceholder(fallback)) return fallback;
628
+ const names = Object.keys(databases).filter((key) => key !== "default");
629
+ return names.length === 1 ? databases[names[0]]?.db : void 0;
630
+ }
631
+ function isPlaceholder(db) {
632
+ try {
633
+ Reflect.get(db, "select");
634
+ return false;
635
+ } catch (error) {
636
+ const code = error?.code;
637
+ return code === "DATABASE_DISABLED" || code === "DATABASE_NOT_FOUND";
638
+ }
639
+ }
640
+ //#endregion
641
+ //#region src/runtime/definition.ts
642
+ /**
643
+ * The Comments definition of `server/comments.ts`: its `comments` export, else its default export. Both forms run the
644
+ * same surfaces. The generated files call it, so a file without `defineComments()` fails with `COMMENTS_B0002`.
645
+ */
646
+ function commentsDefinitionOf(module, file) {
647
+ return validateCommentsDefinition(module.comments ?? module.default, file);
648
+ }
649
+ //#endregion
650
+ //#region src/runtime/mcp.ts
651
+ /** A user supplied by an app's own MCP server. Missing identities remain anonymous. */
652
+ function commentsUser(user) {
653
+ const id = text(user?.id) ?? text(user?.email);
654
+ return user && id ? {
655
+ ...user,
656
+ id
657
+ } : null;
658
+ }
659
+ function guestFor(context) {
660
+ return context.event ? guestFromHeaders(context.event["~standard"].req.headers) : void 0;
661
+ }
662
+ function failure(why) {
663
+ return {
664
+ text: why,
665
+ isError: true
468
666
  };
469
667
  }
668
+ /** The catalog's COMMENTS_FORBIDDEN, as the overlay API answers it. */
669
+ function forbidden(action) {
670
+ const error = commentsErrors.COMMENTS_FORBIDDEN({ action });
671
+ return failure(`${error.why} ${error.fix}`);
672
+ }
673
+ /** Issued after `authorize` allows a tool's action on a thread. The reply and resolve writes need it. */
674
+ const toolGrant = defineGrant("vitehub.comments.mcp-action", (input) => Object.freeze({ ...input }));
675
+ function spend(grant, action, threadId) {
676
+ const allowed = toolGrant.consume(grant);
677
+ invariant(allowed.action === action && allowed.threadId === threadId, "each Comments tool spends the grant that it issued for the same action and thread");
678
+ }
679
+ /**
680
+ * The Comments tools for an app's own MCP server. Each call resolves the Comments identity and checks `authorize`,
681
+ * as the overlay does. The server supplies the checked `context.user`. ViteHub MCP offers the comment operations instead.
682
+ * With `identify` and a request event, `identify` names the user, as in the overlay API. Otherwise the tools use the
683
+ * checked `context.user`. Replies and resolves show that user as the author.
684
+ */
685
+ function commentsMcpTools(comments, options = {}) {
686
+ const admitted = options.console === true;
687
+ async function identityFor(context) {
688
+ const { identify } = comments.options;
689
+ if (identify && context.event) {
690
+ const event = context.event;
691
+ getStandardContext(event);
692
+ return {
693
+ user: await identify({ event }) ?? null,
694
+ gate: {}
695
+ };
696
+ }
697
+ return {
698
+ user: commentsUser(context.user),
699
+ gate: options.console && !identify ? { console: true } : {}
700
+ };
701
+ }
702
+ async function threadFor(input, { user, gate }, action) {
703
+ const id = text(input.id);
704
+ if (!id) return failure("Give the thread id from comments_list_threads.");
705
+ const [error, thread] = await comments.get(id);
706
+ if (error) return failure(error.why);
707
+ if (thread.subject.kind !== "page") return failure(`No thread ${id} on the app's pages.`);
708
+ if (!await comments.can({
709
+ user,
710
+ action,
711
+ thread,
712
+ console: admitted
713
+ }, gate)) return forbidden(action);
714
+ return {
715
+ thread,
716
+ grant: toolGrant.issue({
717
+ action,
718
+ threadId: thread.id
719
+ })
720
+ };
721
+ }
722
+ return [
723
+ {
724
+ name: "comments_list_threads",
725
+ title: "List ViteHub Comments threads",
726
+ description: "ViteHub Comments: threads people left with the Comments toolbar on the app's pages, newest activity first. Each line has the page, what the comment points at, the time, the first comment, and the Vue component. Says how many threads `authorize` hid. Read one with comments_get_thread. After you change the code, reply with comments_reply and resolve it with comments_resolve_thread.",
727
+ section: "comments",
728
+ annotations: { readOnlyHint: true },
729
+ inputSchema: {
730
+ type: "object",
731
+ properties: {
732
+ page: {
733
+ type: "string",
734
+ description: "Only threads of this page: a path such as /pricing, or a full URL of the page."
735
+ },
736
+ status: {
737
+ type: "string",
738
+ enum: ["open", "resolved"],
739
+ description: "Default: open."
740
+ },
741
+ search: {
742
+ type: "string",
743
+ description: "Only threads whose comments contain this text."
744
+ },
745
+ limit: {
746
+ type: "integer",
747
+ minimum: 1,
748
+ maximum: 100,
749
+ description: "Default 25."
750
+ }
751
+ },
752
+ additionalProperties: false
753
+ },
754
+ async call(input, context) {
755
+ const { user, gate } = await identityFor(context);
756
+ const page = text(input.page);
757
+ const subject = page ? {
758
+ kind: "page",
759
+ id: normalizeCommentPage(page)
760
+ } : void 0;
761
+ if (!await comments.can({
762
+ user,
763
+ action: "read",
764
+ console: admitted,
765
+ ...subject ? { subject } : {}
766
+ }, gate)) return forbidden("read");
767
+ const status = input.status === "resolved" ? "resolved" : "open";
768
+ const search = text(input.search)?.toLowerCase();
769
+ const limit = Math.min(Math.max(Number(input.limit) || 25, 1), 100);
770
+ const found = [];
771
+ let hidden = 0;
772
+ const batchSize = search ? 500 : limit;
773
+ let before;
774
+ while (found.length < limit) {
775
+ const [error, listed] = await comments.list({
776
+ scope: commentsPageScope,
777
+ subjectKind: "page",
778
+ status,
779
+ limit: batchSize,
780
+ ...subject ? { subject } : {},
781
+ ...before ? { before } : {}
782
+ });
783
+ if (error) return failure(error.why);
784
+ for (const thread of listed) {
785
+ if (!await comments.can({
786
+ user,
787
+ action: "read",
788
+ thread,
789
+ console: admitted
790
+ }, gate)) hidden++;
791
+ else if (!search || thread.messages.some((message) => message.body.toLowerCase().includes(search))) found.push(thread);
792
+ if (found.length === limit) break;
793
+ }
794
+ if (listed.length < batchSize) break;
795
+ const last = listed.at(-1);
796
+ before = {
797
+ id: last.id,
798
+ updatedAt: last.updatedAt
799
+ };
800
+ }
801
+ const threads = found.map(commentThreadSummary);
802
+ const note = hiddenThreadsNote(hidden, {
803
+ authorize: Boolean(comments.options.authorize),
804
+ identify: Boolean(comments.options.identify),
805
+ user: user !== null,
806
+ console: admitted
807
+ });
808
+ return {
809
+ text: commentThreadsText(threads, status, note),
810
+ structured: {
811
+ threads: threads.map((thread) => ({ ...thread })),
812
+ hidden
813
+ }
814
+ };
815
+ }
816
+ },
817
+ {
818
+ name: "comments_get_thread",
819
+ 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.",
821
+ section: "comments",
822
+ annotations: { readOnlyHint: true },
823
+ inputSchema: {
824
+ type: "object",
825
+ properties: { id: {
826
+ type: "string",
827
+ description: "The thread id."
828
+ } },
829
+ required: ["id"],
830
+ additionalProperties: false
831
+ },
832
+ async call(input, context) {
833
+ const found = await threadFor(input, await identityFor(context), "read");
834
+ if (!("thread" in found)) return found;
835
+ const { thread } = found;
836
+ return {
837
+ text: describeCommentThread(thread),
838
+ structured: { thread: { ...thread } }
839
+ };
840
+ }
841
+ },
842
+ {
843
+ name: "comments_reply",
844
+ title: "Reply to a ViteHub Comments thread",
845
+ description: "ViteHub Comments: reply to a thread that people left with the Comments toolbar, for example to say what you changed. The reply shows the signed-in Console user as its author.",
846
+ section: "comments",
847
+ inputSchema: {
848
+ type: "object",
849
+ properties: {
850
+ id: {
851
+ type: "string",
852
+ description: "The thread id."
853
+ },
854
+ body: {
855
+ type: "string",
856
+ description: "Markdown, at most 10,000 characters."
857
+ }
858
+ },
859
+ required: ["id", "body"],
860
+ additionalProperties: false
861
+ },
862
+ async call(input, context) {
863
+ const identity = await identityFor(context);
864
+ const found = await threadFor(input, identity, "write");
865
+ if (!("thread" in found)) return found;
866
+ const { thread, grant } = found;
867
+ const author = identity.user ? authorOf(identity.user) : guestFor(context);
868
+ if (!author) return forbidden("write");
869
+ spend(grant, "write", thread.id);
870
+ const [error, message] = await comments.reply(thread.id, {
871
+ body: text(input.body) ?? "",
872
+ author
873
+ });
874
+ if (error) return failure(error.why);
875
+ await comments.flush();
876
+ return {
877
+ text: `Replied to thread ${thread.id}.`,
878
+ structured: { message: { ...message } }
879
+ };
880
+ }
881
+ },
882
+ {
883
+ name: "comments_resolve_thread",
884
+ title: "Resolve or reopen a ViteHub Comments thread",
885
+ description: "ViteHub Comments: resolve a thread that people left with the Comments toolbar after the change it asks for is done, or reopen it. Resolved threads leave the page.",
886
+ section: "comments",
887
+ inputSchema: {
888
+ type: "object",
889
+ properties: {
890
+ id: {
891
+ type: "string",
892
+ description: "The thread id."
893
+ },
894
+ resolved: {
895
+ type: "boolean",
896
+ description: "Default true. False reopens the thread."
897
+ }
898
+ },
899
+ required: ["id"],
900
+ additionalProperties: false
901
+ },
902
+ async call(input, context) {
903
+ const identity = await identityFor(context);
904
+ const found = await threadFor(input, identity, "resolve");
905
+ if (!("thread" in found)) return found;
906
+ const { thread, grant } = found;
907
+ spend(grant, "resolve", thread.id);
908
+ const author = identity.user ? authorOf(identity.user) : guestFor(context) ?? {
909
+ id: "anonymous",
910
+ name: "Someone"
911
+ };
912
+ const [error, updated] = input.resolved === false ? await comments.reopen(thread.id) : await comments.resolve(thread.id, { by: author });
913
+ if (error) return failure(error.why);
914
+ await comments.flush();
915
+ return {
916
+ text: `Thread ${updated.id} is ${updated.status}.`,
917
+ structured: { thread: { ...commentThreadSummary(updated) } }
918
+ };
919
+ }
920
+ }
921
+ ];
922
+ }
470
923
  new TextEncoder();
471
924
  /** HKDF salt for every ViteHub-derived secret. A different salt than Nuxt's keeps both derivations apart for one shared root. */
472
925
  const viteHubSecretSalt = "vitehub";
473
- /**
474
- * Reads the root app secret from an env record: `VITEHUB_SECRET`, then `NUXT_APP_SECRET`, so a Nuxt app needs only one
475
- * secret. Returns `undefined` when neither is a non-empty string.
476
- */
926
+ /** Reads the root app secret, `VITEHUB_SECRET`, from an env record. Returns `undefined` when it is not a non-empty string. */
477
927
  function readViteHubSecret(env) {
478
- for (const name of ["VITEHUB_SECRET", "NUXT_APP_SECRET"]) {
479
- const value = env[name];
480
- if (typeof value === "string" && value) return value;
481
- }
928
+ const value = env.VITEHUB_SECRET;
929
+ return typeof value === "string" && value ? value : void 0;
482
930
  }
931
+ Object.freeze({ prefix: "sha256=" });
483
932
  //#endregion
484
933
  //#region src/runtime/github-login.ts
485
934
  /** The Server Env names of the OAuth client that people sign in to Comments with: a GitHub App's, or an OAuth App's. */
@@ -505,12 +954,9 @@ function serverEnv(name) {
505
954
  * production.
506
955
  */
507
956
  function sessionSecret() {
508
- const root = readViteHubSecret({
509
- VITEHUB_SECRET: serverEnv("VITEHUB_SECRET"),
510
- NUXT_APP_SECRET: serverEnv("NUXT_APP_SECRET")
511
- });
957
+ const root = readViteHubSecret({ VITEHUB_SECRET: serverEnv("VITEHUB_SECRET") });
512
958
  if (!root) return;
513
- if (root.length < 32) throw new TypeError(`[vitehub] VITEHUB_SECRET must be at least 32 characters. Generate one with \`openssl rand -base64 32\`.`);
959
+ if (root.length < 32) throw commentsErrorDiagnostics.COMMENTS_SECRET_TOO_SHORT({ minimum: 32 });
514
960
  const bytes = new Uint8Array(hkdfSync("sha256", root, viteHubSecretSalt, "vitehub:comments:auth", 32));
515
961
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
516
962
  }
@@ -528,7 +974,7 @@ function createCommentsGitHubLogin(options = {}) {
528
974
  const fetcher = options.fetch ?? globalThis.fetch;
529
975
  const instances = /* @__PURE__ */ new Map();
530
976
  const access = /* @__PURE__ */ new Map();
531
- function auth(event, request) {
977
+ async function auth(event, request) {
532
978
  const clientId = serverEnv(githubLoginEnv.clientId);
533
979
  const clientSecret = serverEnv(githubLoginEnv.clientSecret);
534
980
  const secret = sessionSecret();
@@ -553,7 +999,7 @@ function createCommentsGitHubLogin(options = {}) {
553
999
  } },
554
1000
  advanced: { cookiePrefix: "vitehub_comments" }
555
1001
  }));
556
- instance = createAuthForRequest(definition, request, void 0, event);
1002
+ instance = (await import("@vite-hub/auth/internal/server")).createAuthForRequest(definition, request, event);
557
1003
  if (instances.size > 20) instances.clear();
558
1004
  instances.set(key, instance);
559
1005
  }
@@ -567,7 +1013,10 @@ function createCommentsGitHubLogin(options = {}) {
567
1013
  "x-github-api-version": "2022-11-28"
568
1014
  } });
569
1015
  if (response.status === 404) return void 0;
570
- if (!response.ok) throw new Error(`GitHub GET ${path} failed with ${response.status}`);
1016
+ if (!response.ok) throw commentsErrorDiagnostics.COMMENTS_GITHUB_REQUEST_FAILED({
1017
+ path,
1018
+ status: response.status
1019
+ });
571
1020
  return await response.json();
572
1021
  }
573
1022
  /** The GitHub login of a person, and whether they can push to the repository. */
@@ -599,8 +1048,8 @@ function createCommentsGitHubLogin(options = {}) {
599
1048
  configured,
600
1049
  async user(event) {
601
1050
  if (!configured()) return null;
602
- const request = requestOf(event);
603
- const instance = auth(event, request);
1051
+ const request = getStandardContext(event).req;
1052
+ const instance = await auth(event, request);
604
1053
  const user = (await instance.api.getSession({ headers: request.headers }))?.user;
605
1054
  if (!user || typeof user !== "object" || !("id" in user) || typeof user.id !== "string") return null;
606
1055
  const accessToken = await instance.api.getAccessToken({
@@ -618,14 +1067,13 @@ function createCommentsGitHubLogin(options = {}) {
618
1067
  github: githubAccess
619
1068
  };
620
1069
  },
621
- async handle(event, path) {
1070
+ async handle(request, path) {
622
1071
  if (!configured()) return Response.json({ error: {
623
1072
  code: "COMMENTS_SIGN_IN_OFF",
624
1073
  why: "This site has no GitHub sign-in for Comments.",
625
1074
  fix: `Set ${githubLoginEnv.clientId} and ${githubLoginEnv.clientSecret} on the server.`
626
1075
  } }, { status: 404 });
627
- const request = requestOf(event);
628
- const instance = auth(event, request);
1076
+ const instance = await auth(request, request);
629
1077
  const url = new URL(request.url);
630
1078
  if (path === "/auth/github" && request.method === "GET") {
631
1079
  const response = await instance.api.signInSocial({
@@ -662,4 +1110,4 @@ function createCommentsGitHubLogin(options = {}) {
662
1110
  };
663
1111
  }
664
1112
  //#endregion
665
- export { commentsConsoleSession, commentsMcpTools, createCommentsGitHubLogin, createCommentsHandler, defineCommentsPlugin, githubLoginEnv, installedComments, viteHubPageSessionHandler };
1113
+ export { commentsDefinitionOf, commentsMcpTools, createCommentsGitHubLogin, createCommentsHandler, defineCommentsPlugin, githubLoginEnv, installedComments, selectCommentsDatabase, viteHubPageSessionHandler };