@vite-hub/comments 0.0.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 (77) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +291 -0
  3. package/dist/anchor.d.ts +43 -0
  4. package/dist/anchor.js +133 -0
  5. package/dist/client-diagnostics-CcFpkbAk.js +40 -0
  6. package/dist/client.d.ts +176 -0
  7. package/dist/client.js +738 -0
  8. package/dist/console-h4KlhIik.d.ts +332 -0
  9. package/dist/context-BqIsmYP1.js +61 -0
  10. package/dist/database/postgres.d.ts +1402 -0
  11. package/dist/database/postgres.js +81 -0
  12. package/dist/database-CA1aHKN7.d.ts +1495 -0
  13. package/dist/database.d.ts +12 -0
  14. package/dist/database.js +2 -0
  15. package/dist/define-43mMR39K.js +89 -0
  16. package/dist/define-B3TF9zzn.d.ts +204 -0
  17. package/dist/errors-4gelGVmK.js +57 -0
  18. package/dist/errors-C6qptPoG.js +135 -0
  19. package/dist/errors-CyQyKAvy.d.ts +185 -0
  20. package/dist/fold-name-B7Zb3-MF.js +7 -0
  21. package/dist/identity-CBOzgxSf.js +39 -0
  22. package/dist/index-DNhy69Wt.d.ts +83 -0
  23. package/dist/index.d.ts +7 -0
  24. package/dist/index.js +196 -0
  25. package/dist/install-BcMPgPk_.js +1154 -0
  26. package/dist/install-W9ghhGoh.d.ts +36 -0
  27. package/dist/installed-B-PfERBU.js +30 -0
  28. package/dist/invariant-D8_xBqmZ.js +22 -0
  29. package/dist/migrate-B0k_0swk.d.ts +54 -0
  30. package/dist/migrate-BDQ8xqUs.js +289 -0
  31. package/dist/object-Da1zyPCR.js +11 -0
  32. package/dist/operations-D4A1Fcgf.d.ts +160 -0
  33. package/dist/operations-DMMIfYPW.js +1159 -0
  34. package/dist/operations-GLeOqgMt.d.ts +257 -0
  35. package/dist/operations.d.ts +3 -0
  36. package/dist/operations.js +3 -0
  37. package/dist/overlay/client-DmsSMOzi.js +4 -0
  38. package/dist/overlay/dist-BoHMOFax.js +14 -0
  39. package/dist/overlay/dist-yIZmvSaU.js +1 -0
  40. package/dist/overlay/overlay.js +201 -0
  41. package/dist/page/loader.js +142 -0
  42. package/dist/page-B41ozN63.js +40 -0
  43. package/dist/page-DtbMOEMd.d.ts +22 -0
  44. package/dist/page-tools-shared-NHUjKI8E.js +117 -0
  45. package/dist/path--zk6PEMz.js +18 -0
  46. package/dist/plugin-PS8PMYus.js +74 -0
  47. package/dist/realtime.d.ts +12 -0
  48. package/dist/realtime.js +47 -0
  49. package/dist/rpc-HBcWtg0T.d.ts +17 -0
  50. package/dist/rpc-RKPAusHp.js +153 -0
  51. package/dist/rpc.d.ts +2 -0
  52. package/dist/rpc.js +2 -0
  53. package/dist/runtime/auth.d.ts +8 -0
  54. package/dist/runtime/auth.js +18 -0
  55. package/dist/runtime/connect/node.d.ts +1 -0
  56. package/dist/runtime/connect/node.js +2 -0
  57. package/dist/runtime/connect.d.ts +1 -0
  58. package/dist/runtime/connect.js +2 -0
  59. package/dist/runtime/console.d.ts +5 -0
  60. package/dist/runtime/console.js +64 -0
  61. package/dist/runtime/index.d.ts +270 -0
  62. package/dist/runtime/index.js +1113 -0
  63. package/dist/server-D8k-0GXe.js +72 -0
  64. package/dist/server.d.ts +20 -0
  65. package/dist/server.js +7 -0
  66. package/dist/service-CFVm23k7.d.ts +158 -0
  67. package/dist/service-GHhhyQj4.js +609 -0
  68. package/dist/session-DVx-1Tym.d.ts +14 -0
  69. package/dist/session-EkudzUmm.js +503 -0
  70. package/dist/testing.d.ts +30 -0
  71. package/dist/testing.js +187 -0
  72. package/dist/tokens-DSbwkVSy.js +58 -0
  73. package/dist/types-BIS0hCEl.d.ts +124 -0
  74. package/dist/types-CZujrMFd.d.ts +322 -0
  75. package/dist/vite.d.ts +308 -0
  76. package/dist/vite.js +1660 -0
  77. package/package.json +153 -4
@@ -0,0 +1,609 @@
1
+ import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
2
+ import { t as foldName } from "./fold-name-B7Zb3-MF.js";
3
+ import { t as isPagePath } from "./path--zk6PEMz.js";
4
+ import { r as guestIdPrefix } from "./identity-CBOzgxSf.js";
5
+ import { i as defaultPolicy, o as deniedForMissingPolicy, t as builtinCommentSubjects } from "./define-43mMR39K.js";
6
+ import * as v from "valibot";
7
+ //#region ../internal/src/runtime/client-rate-limit.ts
8
+ const windowPattern = /^(\d+)(ms|s|m|h|d)$/;
9
+ const units = {
10
+ ms: 1,
11
+ s: 1e3,
12
+ m: 6e4,
13
+ h: 36e5,
14
+ d: 864e5
15
+ };
16
+ /** Why `policy` is not a budget, or `undefined` when it is one. */
17
+ function clientRateLimitIssue(policy) {
18
+ if (!Number.isInteger(policy.limit) || policy.limit < 1) return "`rateLimit.limit` must be a whole number of 1 or more.";
19
+ if (!windowPattern.test(policy.window)) return "`rateLimit.window` must be a duration such as `30s`, `1m`, or `1h`.";
20
+ const duration = windowMs(policy.window);
21
+ if (!Number.isFinite(duration) || duration <= 0 || duration > 864e13) return "`rateLimit.window` must resolve to finite milliseconds greater than zero and at most 8640000000000000.";
22
+ }
23
+ function windowMs(window) {
24
+ const [, amount, unit] = windowPattern.exec(window) ?? [];
25
+ return Number(amount) * (units[unit ?? "m"] ?? 6e4);
26
+ }
27
+ /** An IPv6 address counts as its /64 network, since one host can use any address in it. */
28
+ function addressKey(address) {
29
+ if (!address.includes(":") || address.includes(".")) return address;
30
+ const [head = "", tail = ""] = address.toLowerCase().split("::");
31
+ const left = head ? head.split(":") : [];
32
+ const right = tail ? tail.split(":") : [];
33
+ return `${(address.includes("::") ? [
34
+ ...left,
35
+ ...Array.from({ length: 8 - left.length - right.length }, () => "0"),
36
+ ...right
37
+ ] : left).slice(0, 4).map((group) => group.replace(/^0+(?=.)/, "")).join(":")}::/64`;
38
+ }
39
+ /** The address that a client limit counts: the host's client address, else `cf-connecting-ip` on Cloudflare only. */
40
+ function clientAddressKey(request, context) {
41
+ return addressKey(context?.runtime?.clientAddress ?? (context?.runtime?.cloudflare ? request.headers.get("cf-connecting-ip") : void 0) ?? "unknown");
42
+ }
43
+ /** A fixed window for each key, in this process only. Enough for one Node server; a Worker should use Rate Limit. */
44
+ function memoryClientRateLimit(now = Date.now) {
45
+ const windows = /* @__PURE__ */ new Map();
46
+ let nextSweep = 0;
47
+ return (key, policy) => {
48
+ const time = now();
49
+ if (windows.size > 1e4 && time >= nextSweep) {
50
+ nextSweep = time + 1e3;
51
+ for (const [stale, entry] of windows) if (entry.resetAt <= time) windows.delete(stale);
52
+ }
53
+ const current = windows.get(key);
54
+ const entry = current && current.resetAt > time ? current : {
55
+ count: 0,
56
+ resetAt: time + windowMs(policy.window)
57
+ };
58
+ entry.count += 1;
59
+ windows.set(key, entry);
60
+ return entry.count <= policy.limit ? { allowed: true } : {
61
+ allowed: false,
62
+ retryAfter: (entry.resetAt - time) / 1e3
63
+ };
64
+ };
65
+ }
66
+ /**
67
+ * The rate limit of a public write, such as a form message or a guest comment. It counts `key` in the shared Rate
68
+ * Limit store when the app has one, else in the memory of this process. When the shared store does not answer, it
69
+ * logs the error and counts in memory.
70
+ */
71
+ function createClientRateLimit(options) {
72
+ const memory = memoryClientRateLimit(options.now);
73
+ const { shared, name } = options;
74
+ return async (request, key, policy) => {
75
+ if (shared) {
76
+ const window = policy.window;
77
+ const [error, decision] = await shared(request, name, {
78
+ key,
79
+ limit: policy.limit,
80
+ window
81
+ });
82
+ if (decision && decision.reason !== "unavailable") return decision.allowed || decision.retryAfter === void 0 ? { allowed: decision.allowed } : {
83
+ allowed: false,
84
+ retryAfter: decision.retryAfter
85
+ };
86
+ console.error(`[vitehub] ${options.unavailable}, so it counts it in the memory of this process.`, error ?? decision?.cause);
87
+ }
88
+ return memory(key, policy);
89
+ };
90
+ }
91
+ //#endregion
92
+ //#region src/operations-core/service.ts
93
+ /** Longest message, in characters. */
94
+ const maximumCommentBodyLength = 1e4;
95
+ /** Largest attachment, in bytes. */
96
+ const maximumAttachmentBytes = 5242880;
97
+ /** The media types that `upload` stores. SVG and HTML are left out because a browser runs their scripts. */
98
+ const attachmentTypes = [
99
+ "image/png",
100
+ "image/jpeg",
101
+ "image/gif",
102
+ "image/webp",
103
+ "image/avif",
104
+ "application/pdf",
105
+ "text/plain"
106
+ ];
107
+ /** The media types that a browser may show inline. Every other file downloads. */
108
+ const inlineTypes = [
109
+ "image/png",
110
+ "image/jpeg",
111
+ "image/gif",
112
+ "image/webp",
113
+ "image/avif"
114
+ ];
115
+ /** An error with the HTTP status that the operation RPC answers. */
116
+ function fail(error, status) {
117
+ return Object.assign(error, { status });
118
+ }
119
+ function isGuestId(id) {
120
+ return id.startsWith(guestIdPrefix);
121
+ }
122
+ /**
123
+ * Public identity for stored comments and notifications; policies keep the full user. A guest id gets the `guest:`
124
+ * prefix, so a guest stays a guest in the Database and never owns the messages of a person with the same id.
125
+ */
126
+ function personOf(user) {
127
+ const guest = user.guest === true || isGuestId(user.id);
128
+ return {
129
+ id: guest && !isGuestId(user.id) ? `${guestIdPrefix}${user.id}` : user.id,
130
+ ...user.name ? { name: user.name } : {},
131
+ ...user.image ? { image: user.image } : {},
132
+ ...guest ? { guest: true } : {}
133
+ };
134
+ }
135
+ function subjectDefinition(runtime, kind) {
136
+ return [...builtinCommentSubjects, ...runtime.definition.subjects ?? []].reverse().find((candidate) => candidate.kind === kind);
137
+ }
138
+ function scopeOf(runtime, target) {
139
+ const definition = subjectDefinition(runtime, target.kind);
140
+ if (!definition) throw fail(commentsErrorDiagnostics.COMMENTS_R0008({ kind: target.kind }), 400);
141
+ if (target.kind === "page" && !isPagePath(target.id)) throw fail(commentsErrorDiagnostics.COMMENTS_R0007({ message: "A page subject takes an app path that starts with one \"/\", such as \"/pricing\", without \"?\" or \"#\"." }), 400);
142
+ if (target.kind === "content" && !target.id.includes("/")) throw fail(commentsErrorDiagnostics.COMMENTS_R0007({ message: "A content subject is \"<collection>/<id>\"." }), 400);
143
+ return definition.scope(target.id);
144
+ }
145
+ /**
146
+ * The one access policy of every surface: `authorize`, else `defaultPolicy()`. Only `true` allows. `gate` says what the
147
+ * server checked before, such as the Console's section access; `development` defaults to the runtime's.
148
+ */
149
+ async function can(runtime, context, gate = {}) {
150
+ const { authorize } = runtime.definition;
151
+ const subject = context.subject ?? context.thread?.subject;
152
+ const full = {
153
+ ...context,
154
+ user: context.user ? { ...context.user } : null,
155
+ ...subject ? { subject } : {}
156
+ };
157
+ const checked = {
158
+ ...gate,
159
+ development: gate.development ?? runtime.development === true
160
+ };
161
+ if (authorize) return await authorize(full) === true;
162
+ if (defaultPolicy(full.user, checked, full.action)) return true;
163
+ if (deniedForMissingPolicy(runtime.definition, full.user, checked)) warnMissingPolicy();
164
+ return false;
165
+ }
166
+ let warned = false;
167
+ /** Says once per process, in the server log, that signed-in people wait for an `authorize` policy. */
168
+ function warnMissingPolicy() {
169
+ if (warned) return;
170
+ warned = true;
171
+ const diagnostic = commentsErrorDiagnostics.COMMENTS_R0006();
172
+ globalThis.console.warn(`[vitehub] ${diagnostic.code}: ${diagnostic.why} ${diagnostic.fix}`);
173
+ }
174
+ /** The diagnostic of a denied action: `COMMENTS_R0006` when only the missing `authorize` denied it, else `COMMENTS_R0009`. */
175
+ function deniedError(runtime, action, user, gate = {}) {
176
+ const checked = {
177
+ ...gate,
178
+ development: gate.development ?? runtime.development === true
179
+ };
180
+ if (deniedForMissingPolicy(runtime.definition, user, checked)) return fail(commentsErrorDiagnostics.COMMENTS_R0006(), 403);
181
+ return fail(commentsErrorDiagnostics.COMMENTS_R0009({ action }), 403);
182
+ }
183
+ /** Whether `user` may mention `person`: `canMention`, else whether `person` may read the thread. */
184
+ async function mayMention(runtime, user, found, target) {
185
+ const subject = target.subject ?? target.thread?.subject;
186
+ const person = { ...found };
187
+ const context = {
188
+ person,
189
+ user,
190
+ ...target.thread ? { thread: target.thread } : {},
191
+ ...subject ? { subject } : {}
192
+ };
193
+ try {
194
+ if (runtime.definition.canMention) return await runtime.definition.canMention(context) === true;
195
+ return await can(runtime, {
196
+ action: "read",
197
+ user: { ...person },
198
+ ...target.thread ? { thread: target.thread } : {},
199
+ ...subject ? { subject } : {}
200
+ }, target.gate);
201
+ } catch {
202
+ return false;
203
+ }
204
+ }
205
+ /** Where `@` finds people: `people`, else Auth, else the authors of threads that `reader` may read. */
206
+ function peopleOf(runtime, reader, gate, console) {
207
+ const explicit = runtime.definition.people ?? runtime.users;
208
+ if (explicit) return explicit;
209
+ const readable = (thread) => can(runtime, {
210
+ action: "read",
211
+ thread,
212
+ user: reader,
213
+ ...console ? { console: true } : {}
214
+ }, gate).catch(() => false);
215
+ return {
216
+ byIds: (ids) => runtime.store.knownUsersByIds(ids, readable),
217
+ search: (query, limit) => runtime.store.knownUsers(query, limit, readable)
218
+ };
219
+ }
220
+ /** People that `@` suggests to `user`, without the ones that may not be mentioned in the thread. */
221
+ async function suggest(runtime, input) {
222
+ const found = await peopleOf(runtime, input.user, input.gate, input.console).search(input.query, input.limit * 2);
223
+ const needle = foldName(input.query.trim());
224
+ const people = [];
225
+ for (const person of found) {
226
+ if (people.length >= input.limit) break;
227
+ if (isGuestId(person.id) || needle && !foldName(person.name ?? person.id).includes(needle)) continue;
228
+ if (await mayMention(runtime, input.user, person, input)) people.push(personOf(person));
229
+ }
230
+ return people;
231
+ }
232
+ /** The people that the messages of `threads` mention, so a UI can show their names. */
233
+ async function mentionedPeople(runtime, reader, threads, gate) {
234
+ const ids = [...new Set(threads.flatMap((thread) => thread.messages.flatMap((message) => message.mentions)))];
235
+ if (!ids.length) return [];
236
+ return (await peopleOf(runtime, reader, gate).byIds(ids)).map(personOf);
237
+ }
238
+ function escapeRegExp(value) {
239
+ return value.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
240
+ }
241
+ /** The mentioned ids must be real people that `user` may mention there, and the text must name each one with `@name`. */
242
+ async function checkMentions(runtime, input) {
243
+ const unique = [...new Set(input.ids ?? [])];
244
+ if (!unique.length) return [];
245
+ if (unique.length > 20) throw fail(commentsErrorDiagnostics.COMMENTS_R0007({ message: `A message mentions at most 20 people.` }), 400);
246
+ const found = new Map((await peopleOf(runtime, input.user, input.gate, input.console).byIds(unique)).map((person) => [person.id, person]));
247
+ const people = [];
248
+ for (const mentioned of unique) {
249
+ const person = found.get(mentioned);
250
+ if (!person || isGuestId(person.id)) throw fail(commentsErrorDiagnostics.COMMENTS_R0007({ message: `The mentioned user ${JSON.stringify(mentioned)} does not exist.` }), 400);
251
+ const name = person.name ?? person.id;
252
+ if (!new RegExp(`(^|[^\\p{L}\\p{N}\\p{M}_])@${escapeRegExp(name)}(?=$|[^\\p{L}\\p{N}\\p{M}_])`, "iu").test(input.body)) throw fail(commentsErrorDiagnostics.COMMENTS_R0007({ message: `The text does not name @${name}, but the comment mentions ${name}.` }), 400);
253
+ if (!await mayMention(runtime, input.user, person, input)) throw fail(commentsErrorDiagnostics.COMMENTS_R0007({ message: `${name} may not be mentioned here.` }), 400);
254
+ people.push(personOf(person));
255
+ }
256
+ return people;
257
+ }
258
+ const metadataSchema = v.pipe(v.record(v.pipe(v.string(), v.minLength(1), v.maxLength(64)), v.union([
259
+ v.pipe(v.string(), v.maxLength(4e3)),
260
+ v.number(),
261
+ v.boolean(),
262
+ v.null()
263
+ ])), v.check((value) => Object.keys(value).length <= 50, "Keep at most 50 metadata fields."));
264
+ const short = (max) => v.pipe(v.string(), v.maxLength(max));
265
+ const size = v.pipe(v.number(), v.minValue(0), v.maxValue(1e5));
266
+ /** The page context that the overlay reads. The server checks its URL and adds the build. */
267
+ const contextSchema = v.object({
268
+ url: short(2048),
269
+ title: v.optional(short(256)),
270
+ route: v.optional(short(256)),
271
+ element: v.optional(v.object({
272
+ tag: short(64),
273
+ id: v.optional(short(128)),
274
+ testId: v.optional(short(128)),
275
+ role: v.optional(short(64)),
276
+ name: v.optional(short(120)),
277
+ classes: v.optional(v.pipe(v.array(short(64)), v.maxLength(8)))
278
+ })),
279
+ components: v.optional(v.pipe(v.array(v.object({
280
+ name: short(128),
281
+ files: v.optional(v.pipe(v.array(short(512)), v.maxLength(8)))
282
+ })), v.maxLength(12))),
283
+ environment: v.optional(v.object({
284
+ viewport: v.object({
285
+ width: size,
286
+ height: size
287
+ }),
288
+ devicePixelRatio: v.pipe(v.number(), v.minValue(0), v.maxValue(16)),
289
+ userAgent: short(512),
290
+ language: v.optional(short(64)),
291
+ colorScheme: v.optional(v.picklist(["light", "dark"])),
292
+ timeZone: v.optional(short(64))
293
+ })),
294
+ build: v.optional(v.object({
295
+ commit: v.optional(short(64)),
296
+ branch: v.optional(short(256)),
297
+ repository: v.optional(short(256)),
298
+ pullRequest: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1)))
299
+ }))
300
+ });
301
+ const revisionSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
302
+ /** The retry key of `comments.create`, such as `crypto.randomUUID()`. */
303
+ const requestIdSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(200));
304
+ const attachmentKey = v.pipe(v.string(), v.minLength(1), v.maxLength(500));
305
+ function invalid(issues, field) {
306
+ const issue = issues[0];
307
+ const path = [field, ...issue?.path?.map((item) => String(item.key)) ?? []].join(".");
308
+ return fail(commentsErrorDiagnostics.COMMENTS_R0018({ message: `${path}: ${issue?.message ?? "invalid."}` }), 400);
309
+ }
310
+ function check(schema, value, field) {
311
+ const parsed = v.safeParse(schema, value);
312
+ if (!parsed.success) throw invalid(parsed.issues, field);
313
+ return parsed.output;
314
+ }
315
+ /** The trimmed text. Empty only with attachments, or on a subject that allows it. */
316
+ function cleanBody(runtime, input) {
317
+ if (input.body.length > 1e4) throw fail(commentsErrorDiagnostics.COMMENTS_R0018({ message: `body: Keep a message under ${maximumCommentBodyLength.toLocaleString("en")} characters.` }), 400);
318
+ const trimmed = input.body.trim();
319
+ if (trimmed || input.attachments.length) return trimmed;
320
+ const allowed = subjectDefinition(runtime, input.subject.kind)?.emptyBody;
321
+ if (allowed === true || typeof allowed === "function" && allowed(input.metadata ? { metadata: input.metadata } : {})) return "";
322
+ throw fail(commentsErrorDiagnostics.COMMENTS_R0005(), 400);
323
+ }
324
+ function attachmentsOf(list) {
325
+ const keys = check(v.pipe(v.array(attachmentKey), v.maxLength(10)), list ?? [], "attachments");
326
+ return [...new Set(keys)];
327
+ }
328
+ function newId(prefix) {
329
+ return `${prefix}_${crypto.randomUUID()}`;
330
+ }
331
+ /**
332
+ * Runs `onComment` before the answer and `onMention` after it, for one saved message. A failure is logged and never
333
+ * fails the comment.
334
+ */
335
+ async function announce(runtime, thread, message, mentions, fresh, options) {
336
+ if (!message) return;
337
+ const { onComment, onMention } = runtime.definition;
338
+ if (options.comment && onComment) try {
339
+ await onComment({
340
+ mentions,
341
+ message,
342
+ thread
343
+ });
344
+ } catch (error) {
345
+ globalThis.console.error("[vitehub] Comments onComment failed:", error);
346
+ }
347
+ if (!onMention || !fresh.length) return;
348
+ const link = subjectDefinition(runtime, thread.subject.kind)?.link?.(thread);
349
+ const task = (async () => {
350
+ try {
351
+ await onMention({
352
+ message,
353
+ thread,
354
+ users: fresh,
355
+ ...link ? { link } : {}
356
+ });
357
+ } catch (error) {
358
+ globalThis.console.error("[vitehub] Comments onMention failed:", error);
359
+ }
360
+ })();
361
+ options.waitUntil?.(task);
362
+ runtime.background?.(task);
363
+ }
364
+ /** The thread that an earlier `createThread` with this `requestId` stored. A retry gets it back before the create checks. */
365
+ async function earlierThread(runtime, input) {
366
+ if (input.requestId === void 0) return void 0;
367
+ return await runtime.store.getByRequestId(scopeOf(runtime, input.subject), check(requestIdSchema, input.requestId, "requestId")) ?? void 0;
368
+ }
369
+ /** Only the author of the first call gets its thread back, for the same subject, and only while they may read it. */
370
+ async function retried(thread, input, canRead) {
371
+ if (!(thread.subject.kind === input.subject.kind && thread.subject.id === input.subject.id) || thread.author.id !== personOf(input.author).id || canRead && !await canRead(thread)) throw fail(commentsErrorDiagnostics.COMMENTS_R0022(), 409);
372
+ return thread;
373
+ }
374
+ /** Starts a thread. The caller checked access. */
375
+ async function createThread(runtime, input, options = {}) {
376
+ const earlier = await earlierThread(runtime, input);
377
+ if (earlier) return retried(earlier, input, options.canRead);
378
+ const scope = scopeOf(runtime, input.subject);
379
+ const metadata = input.metadata === void 0 ? void 0 : check(metadataSchema, input.metadata, "metadata");
380
+ const context = input.context === void 0 ? void 0 : check(contextSchema, input.context, "context");
381
+ const revision = input.revision === void 0 ? void 0 : check(revisionSchema, input.revision, "revision");
382
+ const requestId = input.requestId === void 0 ? void 0 : check(requestIdSchema, input.requestId, "requestId");
383
+ const attachments = attachmentsOf(input.attachments);
384
+ const body = cleanBody(runtime, {
385
+ attachments,
386
+ body: input.body,
387
+ subject: input.subject,
388
+ ...metadata ? { metadata } : {}
389
+ });
390
+ const user = options.user === void 0 ? { ...input.author } : options.user;
391
+ const mentioned = await checkMentions(runtime, {
392
+ console: options.console,
393
+ body,
394
+ ids: input.mentions,
395
+ subject: input.subject,
396
+ user,
397
+ ...options.gate ? { gate: options.gate } : {}
398
+ });
399
+ const author = personOf(input.author);
400
+ const threadId = newId("thread");
401
+ const created = await runtime.store.createThread({
402
+ anchor: input.anchor ?? { kind: "page" },
403
+ attachments,
404
+ author,
405
+ body,
406
+ id: newId("message"),
407
+ mentions: mentioned.map((person) => person.id),
408
+ now: Date.now(),
409
+ scope,
410
+ subject: input.subject,
411
+ threadId,
412
+ ...input.actor ? { actor: input.actor } : {},
413
+ ...metadata ? { metadata } : {},
414
+ ...context ? { context } : {},
415
+ ...revision === void 0 ? {} : { revision },
416
+ ...requestId === void 0 ? {} : { requestId }
417
+ });
418
+ if (created.id !== threadId) return retried(created, input, options.canRead);
419
+ await announce(runtime, created, created.messages[0], mentioned, mentioned, {
420
+ comment: true,
421
+ ...options.waitUntil ? { waitUntil: options.waitUntil } : {}
422
+ });
423
+ runtime.forge?.changed(created.id);
424
+ return created;
425
+ }
426
+ /** Adds a message to a thread. The caller checked access. */
427
+ async function replyToThread(runtime, thread, input, options = {}) {
428
+ if (thread.status === "resolved" && !options.allowResolved) throw fail(commentsErrorDiagnostics.COMMENTS_R0016(), 409);
429
+ const attachments = attachmentsOf(input.attachments);
430
+ const body = cleanBody(runtime, {
431
+ attachments,
432
+ body: input.body,
433
+ subject: thread.subject,
434
+ ...thread.metadata ? { metadata: thread.metadata } : {}
435
+ });
436
+ const user = options.user === void 0 ? { ...input.author } : options.user;
437
+ const mentioned = await checkMentions(runtime, {
438
+ console: options.console,
439
+ body,
440
+ ids: input.mentions,
441
+ thread,
442
+ user,
443
+ ...options.gate ? { gate: options.gate } : {}
444
+ });
445
+ const id = newId("message");
446
+ let next;
447
+ try {
448
+ next = await runtime.store.addMessage(thread.id, {
449
+ attachments,
450
+ author: personOf(input.author),
451
+ body,
452
+ id,
453
+ mentions: mentioned.map((person) => person.id),
454
+ now: Date.now(),
455
+ ...input.actor ? { actor: input.actor } : {}
456
+ }, { allowResolved: options.allowResolved === true });
457
+ } catch (error) {
458
+ if (error instanceof Error && Reflect.get(error, "code") === "COMMENTS_R0016") throw fail(error, 409);
459
+ if (error instanceof Error && Reflect.get(error, "code") === "COMMENTS_R0002") throw fail(error, 404);
460
+ throw error;
461
+ }
462
+ const message = next.messages.find((entry) => entry.id === id);
463
+ await announce(runtime, next, message, mentioned, mentioned, {
464
+ comment: true,
465
+ ...options.waitUntil ? { waitUntil: options.waitUntil } : {}
466
+ });
467
+ runtime.forge?.changed(next.id);
468
+ return {
469
+ message,
470
+ thread: next
471
+ };
472
+ }
473
+ /** Changes the text of a message. The caller checked access and authorship. */
474
+ async function editMessage(runtime, thread, messageId, input, options) {
475
+ const target = thread.messages.find((entry) => entry.id === messageId);
476
+ if (!target) throw fail(commentsErrorDiagnostics.COMMENTS_R0003({ messageId }), 404);
477
+ const body = cleanBody(runtime, {
478
+ attachments: target.attachments,
479
+ body: input.body,
480
+ subject: thread.subject,
481
+ ...thread.metadata ? { metadata: thread.metadata } : {}
482
+ });
483
+ const mentioned = await checkMentions(runtime, {
484
+ console: options.console,
485
+ body,
486
+ ids: input.mentions,
487
+ thread,
488
+ user: options.user,
489
+ ...options.gate ? { gate: options.gate } : {}
490
+ });
491
+ const next = await runtime.store.editMessage(thread.id, target.id, {
492
+ body,
493
+ mentions: mentioned.map((person) => person.id),
494
+ now: Date.now()
495
+ });
496
+ const fresh = mentioned.filter((person) => !target.mentions.includes(person.id));
497
+ await announce(runtime, next, next.messages.find((entry) => entry.id === target.id), mentioned, fresh, {
498
+ comment: false,
499
+ ...options.waitUntil ? { waitUntil: options.waitUntil } : {}
500
+ });
501
+ runtime.forge?.changed(next.id);
502
+ return next;
503
+ }
504
+ function safeName(name) {
505
+ return name.normalize("NFKC").replaceAll(/[^\w.-]+/g, "-").replaceAll(/^[-.]+|-+$/g, "").slice(0, 100) || "file";
506
+ }
507
+ function decodeBase64(data) {
508
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(data) || data.length % 4 !== 0) throw fail(commentsErrorDiagnostics.COMMENTS_R0017({ message: "The file data is not Base64." }), 400);
509
+ const binary = atob(data);
510
+ const bytes = new Uint8Array(binary.length);
511
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
512
+ return bytes;
513
+ }
514
+ /** Binds an upload to its exact key and bytes, including after a process restart or an app Blob replacement. */
515
+ async function attachmentRecord(key, data) {
516
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array(data)));
517
+ const sha256 = Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
518
+ return JSON.stringify({
519
+ key,
520
+ sha256
521
+ });
522
+ }
523
+ /** Checks a file and stores it with `storeAttachment`, else in the Blob store. The caller checked access. */
524
+ async function storeAttachment(runtime, input, user) {
525
+ const type = input.type.toLowerCase().split(";", 1)[0].trim();
526
+ if (!attachmentTypes.includes(type)) throw fail(commentsErrorDiagnostics.COMMENTS_R0017({ message: `Comments does not attach files of type ${JSON.stringify(input.type)}.` }), 415);
527
+ if (typeof input.data === "string" && input.data.length > Math.ceil(5242880 / 3) * 4) throw fail(commentsErrorDiagnostics.COMMENTS_R0017({ message: "The file is larger than 5 MB." }), 413);
528
+ const data = typeof input.data === "string" ? decodeBase64(input.data) : input.data;
529
+ if (data.byteLength > 5242880) throw fail(commentsErrorDiagnostics.COMMENTS_R0017({ message: "The file is larger than 5 MB." }), 413);
530
+ if (!data.byteLength) throw fail(commentsErrorDiagnostics.COMMENTS_R0017({ message: "The file is empty." }), 400);
531
+ const name = safeName(input.name);
532
+ const file = {
533
+ data,
534
+ name,
535
+ size: data.byteLength,
536
+ type
537
+ };
538
+ if (input.subject) scopeOf(runtime, input.subject);
539
+ let key;
540
+ if (runtime.definition.storeAttachment) key = check(attachmentKey, await runtime.definition.storeAttachment(file, {
541
+ user,
542
+ ...input.subject ? { subject: input.subject } : {}
543
+ }), "storeAttachment");
544
+ else {
545
+ if (!runtime.attachments) throw fail(commentsErrorDiagnostics.COMMENTS_R0014(), 501);
546
+ const id = crypto.randomUUID();
547
+ key = `comments/${id}/${name}`;
548
+ const [error] = await runtime.attachments.put(key, data, { contentType: type });
549
+ if (error) throw error;
550
+ const record = new TextEncoder().encode(await attachmentRecord(key, data));
551
+ const [recordError] = await runtime.attachments.put(`comments/${id}/.upload.json`, record, { contentType: "application/json" });
552
+ if (recordError) throw recordError;
553
+ }
554
+ return {
555
+ key,
556
+ name,
557
+ size: file.size,
558
+ type
559
+ };
560
+ }
561
+ /** The thread through which `user` may read the file of `key`, else `COMMENTS_R0020` as not found. */
562
+ async function attachmentThread(runtime, key, readable) {
563
+ check(attachmentKey, key, "key");
564
+ let cursor;
565
+ do {
566
+ const page = await runtime.store.getByAttachment(key, cursor);
567
+ for (const thread of page.threads) if (await readable(thread).catch(() => false)) return thread;
568
+ cursor = page.cursor;
569
+ } while (cursor);
570
+ throw fail(commentsErrorDiagnostics.COMMENTS_R0020({ key }), 404);
571
+ }
572
+ /**
573
+ * Reads the file of `key` with `readAttachment`, else from the Blob store, for a reader who may read `thread`. A
574
+ * stored type that Comments does not attach, such as SVG from an app's own hook, answers as a download.
575
+ */
576
+ async function readAttachment(runtime, key, context) {
577
+ const { readAttachment: read, storeAttachment: store } = runtime.definition;
578
+ let data;
579
+ if (read) data = await read(key, {
580
+ thread: context.thread,
581
+ user: context.user ? { ...context.user } : null
582
+ });
583
+ else if (store) throw fail(commentsErrorDiagnostics.COMMENTS_R0021(), 501);
584
+ else if (runtime.attachments?.get) {
585
+ const match = /^comments\/([\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12})\/\w[\w.-]{0,99}$/.exec(key);
586
+ if (!match) throw fail(commentsErrorDiagnostics.COMMENTS_R0020({ key }), 404);
587
+ const [recordError, record] = await runtime.attachments.get(`comments/${match[1]}/.upload.json`);
588
+ if (recordError) throw recordError;
589
+ if (!record || record.size > 1024) throw fail(commentsErrorDiagnostics.COMMENTS_R0020({ key }), 404);
590
+ const [error, found] = await runtime.attachments.get(key);
591
+ if (error) throw error;
592
+ if (!found || found.size > 5242880 || await record.text() !== await attachmentRecord(key, new Uint8Array(await found.arrayBuffer()))) throw fail(commentsErrorDiagnostics.COMMENTS_R0020({ key }), 404);
593
+ data = found;
594
+ } else throw fail(commentsErrorDiagnostics.COMMENTS_R0014(), 501);
595
+ if (!data) throw fail(commentsErrorDiagnostics.COMMENTS_R0020({ key }), 404);
596
+ const stored = data.type.toLowerCase().split(";", 1)[0].trim();
597
+ const type = attachmentTypes.includes(stored) ? stored : "application/octet-stream";
598
+ const name = safeName(data instanceof File && data.name ? data.name : key.split("/").at(-1) ?? "file");
599
+ return {
600
+ data,
601
+ inline: inlineTypes.includes(type),
602
+ key,
603
+ name,
604
+ size: data.size,
605
+ type
606
+ };
607
+ }
608
+ //#endregion
609
+ export { createClientRateLimit as S, scopeOf as _, deniedError as a, clientAddressKey as b, fail as c, mentionedPeople as d, personOf as f, retried as g, requestIdSchema as h, createThread as i, maximumAttachmentBytes as l, replyToThread as m, can as n, earlierThread as o, readAttachment as p, contextSchema as r, editMessage as s, attachmentThread as t, maximumCommentBodyLength as u, storeAttachment as v, clientRateLimitIssue as x, suggest as y };
@@ -0,0 +1,14 @@
1
+ import { g as CommentsUser } from "./define-B3TF9zzn.js";
2
+ import { s as CommentsRequestEvent } from "./types-BIS0hCEl.js";
3
+ import "./index-DNhy69Wt.js";
4
+ //#region src/runtime/session.d.ts
5
+ interface CommentsSessionOptions {
6
+ /** Reads the ViteHub Auth user only when no custom `identify` is configured. */
7
+ session?: (event: CommentsRequestEvent) => Promise<CommentsUser | null | undefined>;
8
+ /** Reads the person signed in with GitHub, in an app without Auth. */
9
+ githubLogin?: {
10
+ user: (event: CommentsRequestEvent) => Promise<CommentsUser | null>;
11
+ };
12
+ }
13
+ //#endregion
14
+ export { CommentsSessionOptions as t };