@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.
- package/README.md +79 -31
- package/dist/anchor.d.ts +7 -4
- package/dist/anchor.js +10 -5
- package/dist/client-diagnostics-CcFpkbAk.js +40 -0
- package/dist/client.d.ts +78 -3
- package/dist/client.js +198 -13
- package/dist/{console-BIz9t2cO.d.ts → console-h4KlhIik.d.ts} +97 -8
- package/dist/context-BqIsmYP1.js +61 -0
- package/dist/database/postgres.d.ts +738 -347
- package/dist/database/postgres.js +28 -7
- package/dist/{database-Cb2xjC1V.d.ts → database-CA1aHKN7.d.ts} +675 -276
- package/dist/database.d.ts +6 -98
- package/dist/database.js +2 -3
- package/dist/define-43mMR39K.js +89 -0
- package/dist/define-B3TF9zzn.d.ts +204 -0
- package/dist/errors-4gelGVmK.js +57 -0
- package/dist/errors-C6qptPoG.js +135 -0
- package/dist/errors-CyQyKAvy.d.ts +185 -0
- package/dist/fold-name-B7Zb3-MF.js +7 -0
- package/dist/{identity-3qtVC4rF.js → identity-CBOzgxSf.js} +7 -2
- package/dist/index-DNhy69Wt.d.ts +83 -0
- package/dist/index.d.ts +7 -7
- package/dist/index.js +196 -5
- package/dist/install-BcMPgPk_.js +1154 -0
- package/dist/install-W9ghhGoh.d.ts +36 -0
- package/dist/installed-B-PfERBU.js +30 -0
- package/dist/invariant-D8_xBqmZ.js +22 -0
- package/dist/migrate-B0k_0swk.d.ts +54 -0
- package/dist/migrate-BDQ8xqUs.js +289 -0
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/{operations-0B0QTVWX.d.ts → operations-D4A1Fcgf.d.ts} +37 -15
- package/dist/operations-DMMIfYPW.js +1159 -0
- package/dist/operations-GLeOqgMt.d.ts +257 -0
- package/dist/operations.d.ts +3 -7
- package/dist/operations.js +3 -2
- package/dist/overlay/client-DmsSMOzi.js +4 -0
- package/dist/overlay/dist-BoHMOFax.js +14 -0
- package/dist/overlay/dist-yIZmvSaU.js +1 -0
- package/dist/overlay/overlay.js +183 -177
- package/dist/page/loader.js +138 -18
- package/dist/{page-BuroSMXO.js → page-B41ozN63.js} +8 -6
- package/dist/{page-BtXADR6d.d.ts → page-DtbMOEMd.d.ts} +6 -5
- package/dist/page-tools-shared-NHUjKI8E.js +117 -0
- package/dist/path--zk6PEMz.js +18 -0
- package/dist/plugin-PS8PMYus.js +74 -0
- package/dist/realtime.d.ts +6 -12
- package/dist/realtime.js +23 -24
- package/dist/rpc-HBcWtg0T.d.ts +17 -0
- package/dist/rpc-RKPAusHp.js +153 -0
- package/dist/rpc.d.ts +2 -29
- package/dist/rpc.js +2 -75
- package/dist/runtime/auth.d.ts +5 -3
- package/dist/runtime/auth.js +8 -5
- package/dist/runtime/console.d.ts +1 -1
- package/dist/runtime/console.js +26 -21
- package/dist/runtime/index.d.ts +108 -60
- package/dist/runtime/index.js +684 -236
- package/dist/{server-BomGg3Gb.js → server-D8k-0GXe.js} +16 -7
- package/dist/server.d.ts +14 -88
- package/dist/server.js +7 -326
- package/dist/service-CFVm23k7.d.ts +158 -0
- package/dist/service-GHhhyQj4.js +609 -0
- package/dist/session-DVx-1Tym.d.ts +14 -0
- package/dist/session-EkudzUmm.js +503 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +14 -2
- package/dist/tokens-DSbwkVSy.js +58 -0
- package/dist/types-BIS0hCEl.d.ts +124 -0
- package/dist/types-CZujrMFd.d.ts +322 -0
- package/dist/vite.d.ts +91 -87
- package/dist/vite.js +535 -796
- package/package.json +24 -27
- package/dist/database-BSnVrwHn.js +0 -60
- package/dist/database-C-ktS9Do.js +0 -95
- package/dist/define-BzW2Ychn.d.ts +0 -46
- package/dist/define-Cbhl6QVJ.js +0 -32
- package/dist/errors-BAQYcy3_.d.ts +0 -89
- package/dist/errors-DeD6wTCl.js +0 -77
- package/dist/h3-v1-request-DDGXJ9E7.js +0 -166
- package/dist/index-DklG2Etf.d.ts +0 -111
- package/dist/operations-NZG5dB8y.js +0 -732
- package/dist/page-tools-shared-D-amu6sx.js +0 -53
- package/dist/plugin-QElKQYkA.js +0 -725
- package/dist/request-DVc3M_AG.js +0 -14
- package/dist/src-CRTwnaEG.js +0 -1362
- package/dist/types-Cj8K7Vx7.d.ts +0 -176
- package/dist/types-Un2dcJWD.d.ts +0 -288
|
@@ -0,0 +1,1154 @@
|
|
|
1
|
+
import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
|
|
2
|
+
import { r as guestIdPrefix } from "./identity-CBOzgxSf.js";
|
|
3
|
+
import { t as describeCommentContext } from "./context-BqIsmYP1.js";
|
|
4
|
+
import { c as commentForge, d as commentsSchema, l as commentMessages, n as commentsSchemaGate, s as commentCounters, u as commentThreads } from "./migrate-BDQ8xqUs.js";
|
|
5
|
+
import { i as installCommentsRuntime } from "./server-D8k-0GXe.js";
|
|
6
|
+
import { i as getActiveCloudflareBinding, n as recentGitHubToken } from "./tokens-DSbwkVSy.js";
|
|
7
|
+
import { n as pendingKey, o as runtimes } from "./installed-B-PfERBU.js";
|
|
8
|
+
import { getStandardContext } from "@vite-hub/runtime/internal/h3";
|
|
9
|
+
import * as v from "valibot";
|
|
10
|
+
import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, like, lt, lte, or, sql } from "drizzle-orm";
|
|
11
|
+
import { forgeEnv, githubAppCredentials, githubInstallationFor, githubInstallationRouting, readForgeEnv, readGitHubAppPrivateKey } from "@vite-hub/forge";
|
|
12
|
+
//#region \0rolldown/runtime.js
|
|
13
|
+
var __defProp = Object.defineProperty;
|
|
14
|
+
var __exportAll = (all, no_symbols) => {
|
|
15
|
+
let target = {};
|
|
16
|
+
for (var name in all) __defProp(target, name, {
|
|
17
|
+
get: all[name],
|
|
18
|
+
enumerable: true
|
|
19
|
+
});
|
|
20
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
21
|
+
return target;
|
|
22
|
+
};
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/operations-core/store.ts
|
|
25
|
+
const chunkSize = 80;
|
|
26
|
+
const allocationAttempts = 12;
|
|
27
|
+
const candidateLimit = 200;
|
|
28
|
+
function chunks(items) {
|
|
29
|
+
const result = [];
|
|
30
|
+
for (let index = 0; index < items.length; index += chunkSize) result.push(items.slice(index, index + chunkSize));
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
function parseJson(value, fallback) {
|
|
34
|
+
if (!value) return fallback;
|
|
35
|
+
try {
|
|
36
|
+
return JSON.parse(value);
|
|
37
|
+
} catch {
|
|
38
|
+
return fallback;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function user(id, name, image) {
|
|
42
|
+
return {
|
|
43
|
+
id,
|
|
44
|
+
...name ? { name } : {},
|
|
45
|
+
...image ? { image } : {},
|
|
46
|
+
...id.startsWith("guest:") ? { guest: true } : {}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function messageOf(row) {
|
|
50
|
+
const actor = parseJson(row.actor, void 0);
|
|
51
|
+
return {
|
|
52
|
+
attachments: parseJson(row.attachments, []),
|
|
53
|
+
author: user(row.authorId, row.authorName, row.authorImage),
|
|
54
|
+
body: row.body,
|
|
55
|
+
createdAt: row.createdAt,
|
|
56
|
+
id: row.id,
|
|
57
|
+
mentions: parseJson(row.mentions, []),
|
|
58
|
+
threadId: row.threadId,
|
|
59
|
+
...actor ? { actor } : {},
|
|
60
|
+
...row.editedAt === null ? {} : { editedAt: row.editedAt }
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function threadOf(row, messages) {
|
|
64
|
+
const actor = parseJson(row.actor, void 0);
|
|
65
|
+
const resolvedBy = parseJson(row.resolvedBy, void 0);
|
|
66
|
+
const metadata = parseJson(row.metadata, void 0);
|
|
67
|
+
const context = parseJson(row.context, void 0);
|
|
68
|
+
return {
|
|
69
|
+
anchor: parseJson(row.anchor, { kind: "page" }),
|
|
70
|
+
author: user(row.authorId, row.authorName, row.authorImage),
|
|
71
|
+
createdAt: row.createdAt,
|
|
72
|
+
id: row.id,
|
|
73
|
+
messages,
|
|
74
|
+
n: row.n,
|
|
75
|
+
scope: row.scope,
|
|
76
|
+
status: row.status,
|
|
77
|
+
subject: {
|
|
78
|
+
id: row.subjectId,
|
|
79
|
+
kind: row.subjectKind
|
|
80
|
+
},
|
|
81
|
+
updatedAt: row.updatedAt,
|
|
82
|
+
...actor ? { actor } : {},
|
|
83
|
+
...resolvedBy ? { resolvedBy } : {},
|
|
84
|
+
...row.resolvedAt === null ? {} : { resolvedAt: row.resolvedAt },
|
|
85
|
+
...metadata ? { metadata } : {},
|
|
86
|
+
...context ? { context } : {},
|
|
87
|
+
...row.revision === null ? {} : { revision: row.revision }
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
const uniqueCodes = /* @__PURE__ */ new Set([
|
|
91
|
+
"23505",
|
|
92
|
+
"SQLITE_CONSTRAINT_PRIMARYKEY",
|
|
93
|
+
"SQLITE_CONSTRAINT_UNIQUE"
|
|
94
|
+
]);
|
|
95
|
+
const uniqueMessage = /UNIQUE constraint failed|duplicate key value violates unique constraint/i;
|
|
96
|
+
/**
|
|
97
|
+
* A unique index refused the insert. Drizzle wraps the driver error in one whose message carries the statement and its
|
|
98
|
+
* parameters, which come from the user. So only codes decide, and a message counts only when it is the driver's own:
|
|
99
|
+
* the error with no cause below it.
|
|
100
|
+
*/
|
|
101
|
+
function isUniqueViolation(error) {
|
|
102
|
+
for (let current = error, depth = 0; current && depth < 5; depth++) {
|
|
103
|
+
const code = Reflect.get(Object(current), "code");
|
|
104
|
+
if (typeof code === "string" && uniqueCodes.has(code)) return true;
|
|
105
|
+
const cause = Reflect.get(Object(current), "cause");
|
|
106
|
+
if (!cause) return uniqueMessage.test(String(Reflect.get(Object(current), "message") ?? ""));
|
|
107
|
+
current = cause;
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
function escapeLike(value) {
|
|
112
|
+
return value.replaceAll(/[%_\\]/g, "\\$&");
|
|
113
|
+
}
|
|
114
|
+
function createCommentsStore(database, tables = {
|
|
115
|
+
commentCounters,
|
|
116
|
+
commentMessages,
|
|
117
|
+
commentThreads
|
|
118
|
+
}) {
|
|
119
|
+
const { commentCounters: counters, commentMessages: messages, commentThreads: threads } = tables;
|
|
120
|
+
const db = database;
|
|
121
|
+
async function attach(rows) {
|
|
122
|
+
const ids = rows.map((row) => row.id);
|
|
123
|
+
const byThread = /* @__PURE__ */ new Map();
|
|
124
|
+
for (const part of chunks(ids)) {
|
|
125
|
+
const found = await db.select().from(messages).where(inArray(messages.threadId, part)).orderBy(asc(messages.createdAt), asc(messages.id));
|
|
126
|
+
for (const row of found) byThread.set(row.threadId, [...byThread.get(row.threadId) ?? [], messageOf(row)]);
|
|
127
|
+
}
|
|
128
|
+
return rows.map((row) => threadOf(row, byThread.get(row.id) ?? []));
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The threads that match, newest activity first, with their messages. On libSQL and D1 one batch reads both, so a
|
|
132
|
+
* read costs one round trip: both statements select the same threads, because the order ends on the unique id and a
|
|
133
|
+
* batch reads one snapshot.
|
|
134
|
+
*/
|
|
135
|
+
async function read(where, limit) {
|
|
136
|
+
const order = [desc(threads.updatedAt), desc(threads.id)];
|
|
137
|
+
const batch = Reflect.get(Object(db), "batch");
|
|
138
|
+
if (typeof batch !== "function") return attach(await db.select().from(threads).where(where).orderBy(...order).limit(limit));
|
|
139
|
+
const [rows, messageRows] = await Reflect.apply(batch, db, [[db.select().from(threads).where(where).orderBy(...order).limit(limit), db.select().from(messages).where(inArray(messages.threadId, db.select({ id: threads.id }).from(threads).where(where).orderBy(...order).limit(limit))).orderBy(asc(messages.createdAt), asc(messages.id))]]);
|
|
140
|
+
const byThread = /* @__PURE__ */ new Map();
|
|
141
|
+
for (const row of messageRows) byThread.set(row.threadId, [...byThread.get(row.threadId) ?? [], messageOf(row)]);
|
|
142
|
+
return rows.map((row) => threadOf(row, byThread.get(row.id) ?? []));
|
|
143
|
+
}
|
|
144
|
+
async function find(id) {
|
|
145
|
+
return (await read(eq(threads.id, id), 1))[0] ?? null;
|
|
146
|
+
}
|
|
147
|
+
async function one(id) {
|
|
148
|
+
const found = await find(id);
|
|
149
|
+
if (!found) throw commentsErrorDiagnostics.COMMENTS_R0002({ id });
|
|
150
|
+
return found;
|
|
151
|
+
}
|
|
152
|
+
const driver = db;
|
|
153
|
+
/**
|
|
154
|
+
* Whether the driver can run several writes as one unit: `batch()` on libSQL and D1, a transaction on Postgres. Read
|
|
155
|
+
* on use: a D1 Database connects only when a request brings its binding.
|
|
156
|
+
*/
|
|
157
|
+
const groups = () => typeof driver.batch === "function" || typeof driver.transaction === "function";
|
|
158
|
+
/**
|
|
159
|
+
* Runs the writes together where the driver can. Otherwise they run in order, and the caller orders them so that a
|
|
160
|
+
* failure leaves nothing visible.
|
|
161
|
+
*/
|
|
162
|
+
async function together(build) {
|
|
163
|
+
if (typeof driver.batch === "function") {
|
|
164
|
+
await driver.batch(build(db));
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (typeof driver.transaction === "function") {
|
|
168
|
+
await driver.transaction(async (target) => {
|
|
169
|
+
for (const statement of build(target)) await statement;
|
|
170
|
+
});
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
for (const statement of build(db)) await statement;
|
|
174
|
+
}
|
|
175
|
+
function touching(target, id, now, values = {}, only) {
|
|
176
|
+
const updatedAt = sql`case when ${threads.updatedAt} >= ${now} then ${threads.updatedAt} + 1 else ${now} end`;
|
|
177
|
+
return target.update(threads).set({
|
|
178
|
+
...values,
|
|
179
|
+
updatedAt,
|
|
180
|
+
...values.status === "resolved" ? { resolvedAt: updatedAt } : {}
|
|
181
|
+
}).where(and(eq(threads.id, id), only));
|
|
182
|
+
}
|
|
183
|
+
function messageRow(threadId, input) {
|
|
184
|
+
return {
|
|
185
|
+
actor: input.actor ? JSON.stringify(input.actor) : null,
|
|
186
|
+
attachments: JSON.stringify(input.attachments),
|
|
187
|
+
authorId: input.author.id,
|
|
188
|
+
authorImage: input.author.image ?? null,
|
|
189
|
+
authorName: input.author.name ?? null,
|
|
190
|
+
body: input.body,
|
|
191
|
+
createdAt: input.now,
|
|
192
|
+
editedAt: null,
|
|
193
|
+
id: input.id,
|
|
194
|
+
mentions: JSON.stringify(input.mentions),
|
|
195
|
+
threadId
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
/** The next number of a scope. The counter only goes up, so a deleted thread never gives its number away. */
|
|
199
|
+
async function claimNumber(scope) {
|
|
200
|
+
const [existing] = await db.select({ next: counters.next }).from(counters).where(eq(counters.scope, scope)).limit(1);
|
|
201
|
+
if (!existing) {
|
|
202
|
+
const [top] = await db.select({ highest: sql`coalesce(max(${threads.n}), 0)` }).from(threads).where(eq(threads.scope, scope));
|
|
203
|
+
await db.insert(counters).values({
|
|
204
|
+
next: Number(top?.highest ?? 0) + 1,
|
|
205
|
+
scope
|
|
206
|
+
}).onConflictDoNothing();
|
|
207
|
+
}
|
|
208
|
+
const [claimed] = await db.update(counters).set({ next: sql`${counters.next} + 1` }).where(eq(counters.scope, scope)).returning({ next: counters.next });
|
|
209
|
+
if (!claimed) throw commentsErrorDiagnostics.COMMENTS_R0011();
|
|
210
|
+
return Number(claimed.next) - 1;
|
|
211
|
+
}
|
|
212
|
+
function candidateAuthors(where) {
|
|
213
|
+
return db.select({
|
|
214
|
+
createdAt: messages.createdAt,
|
|
215
|
+
messageId: messages.id,
|
|
216
|
+
id: messages.authorId,
|
|
217
|
+
image: messages.authorImage,
|
|
218
|
+
name: messages.authorName,
|
|
219
|
+
threadId: messages.threadId
|
|
220
|
+
}).from(messages).innerJoin(threads, eq(threads.id, messages.threadId)).where(and(where, sql`${messages.authorId} not like ${`${guestIdPrefix}%`}`)).orderBy(desc(messages.createdAt), desc(messages.id));
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
async list(query) {
|
|
224
|
+
const subject = query.subject ?? (query.page === void 0 ? void 0 : {
|
|
225
|
+
id: query.page,
|
|
226
|
+
kind: "page"
|
|
227
|
+
});
|
|
228
|
+
const before = query.before;
|
|
229
|
+
const where = [
|
|
230
|
+
...subject ? [eq(threads.subjectKind, subject.kind), eq(threads.subjectId, subject.id)] : [],
|
|
231
|
+
...query.subjectKind === void 0 ? [] : [eq(threads.subjectKind, query.subjectKind)],
|
|
232
|
+
...query.scope === void 0 ? [] : [eq(threads.scope, query.scope)],
|
|
233
|
+
...query.status ? [eq(threads.status, query.status)] : [],
|
|
234
|
+
...query.revision ? [lte(threads.revision, query.revision.lte)] : [],
|
|
235
|
+
...query.mine ? [query.userId ? eq(threads.authorId, query.userId) : sql`1 = 0`] : [],
|
|
236
|
+
...query.mentions ? [query.userId ? sql`exists (select 1 from ${messages} where ${messages.threadId} = ${threads.id} and ${messages.mentions} like ${`%${escapeLike(JSON.stringify(query.userId))}%`} escape '\\')` : sql`1 = 0`] : [],
|
|
237
|
+
...before ? [or(lt(threads.updatedAt, before.updatedAt), and(eq(threads.updatedAt, before.updatedAt), lt(threads.id, before.id)))] : []
|
|
238
|
+
];
|
|
239
|
+
const limit = Math.min(Math.max(Math.trunc(query.limit ?? 200), 1), 500);
|
|
240
|
+
return read(where.length ? and(...where) : void 0, limit);
|
|
241
|
+
},
|
|
242
|
+
getById: find,
|
|
243
|
+
async getByNumber(scope, n) {
|
|
244
|
+
return (await read(and(eq(threads.scope, scope), eq(threads.n, n)), 1))[0] ?? null;
|
|
245
|
+
},
|
|
246
|
+
async getByRequestId(scope, requestId) {
|
|
247
|
+
return (await read(and(eq(threads.scope, scope), eq(threads.requestId, requestId)), 1))[0] ?? null;
|
|
248
|
+
},
|
|
249
|
+
async getByMessage(messageId) {
|
|
250
|
+
const [row] = await db.select({ threadId: messages.threadId }).from(messages).where(eq(messages.id, messageId)).limit(1);
|
|
251
|
+
return row ? find(row.threadId) : null;
|
|
252
|
+
},
|
|
253
|
+
async getByAttachment(key, cursor) {
|
|
254
|
+
const pattern = `%${JSON.stringify(key).replaceAll(/[\\%_]/g, (character) => `\\${character}`)}%`;
|
|
255
|
+
const rows = await db.select({
|
|
256
|
+
id: messages.id,
|
|
257
|
+
threadId: messages.threadId,
|
|
258
|
+
attachments: messages.attachments
|
|
259
|
+
}).from(messages).where(and(sql`${messages.attachments} LIKE ${pattern} ESCAPE '\\'`, cursor === void 0 ? void 0 : gt(messages.id, cursor))).orderBy(asc(messages.id)).limit(candidateLimit);
|
|
260
|
+
const ids = [...new Set(rows.filter((row) => parseJson(row.attachments, []).includes(key)).map((row) => row.threadId))];
|
|
261
|
+
return {
|
|
262
|
+
threads: (await Promise.all(ids.map((id) => find(id)))).filter((thread) => thread !== null),
|
|
263
|
+
...rows.length === candidateLimit ? { cursor: rows.at(-1).id } : {}
|
|
264
|
+
};
|
|
265
|
+
},
|
|
266
|
+
async createThread(input) {
|
|
267
|
+
const requested = async () => input.requestId === void 0 ? void 0 : (await read(and(eq(threads.scope, input.scope), eq(threads.requestId, input.requestId)), 1))[0];
|
|
268
|
+
const earlier = await requested();
|
|
269
|
+
if (earlier) return earlier;
|
|
270
|
+
for (let attempt = 0; attempt < allocationAttempts; attempt++) {
|
|
271
|
+
const n = await claimNumber(input.scope);
|
|
272
|
+
const thread = {
|
|
273
|
+
actor: input.actor ? JSON.stringify(input.actor) : null,
|
|
274
|
+
anchor: JSON.stringify(input.anchor),
|
|
275
|
+
authorId: input.author.id,
|
|
276
|
+
authorImage: input.author.image ?? null,
|
|
277
|
+
authorName: input.author.name ?? null,
|
|
278
|
+
createdAt: input.now,
|
|
279
|
+
id: input.threadId,
|
|
280
|
+
n,
|
|
281
|
+
resolvedAt: null,
|
|
282
|
+
resolvedBy: null,
|
|
283
|
+
scope: input.scope,
|
|
284
|
+
status: "open",
|
|
285
|
+
subjectId: input.subject.id,
|
|
286
|
+
subjectKind: input.subject.kind,
|
|
287
|
+
metadata: input.metadata ? JSON.stringify(input.metadata) : null,
|
|
288
|
+
context: input.context ? JSON.stringify(input.context) : null,
|
|
289
|
+
revision: input.revision ?? null,
|
|
290
|
+
requestId: input.requestId ?? null,
|
|
291
|
+
updatedAt: input.now
|
|
292
|
+
};
|
|
293
|
+
try {
|
|
294
|
+
await together((target) => [target.insert(messages).values(messageRow(input.threadId, input)), target.insert(threads).values(thread)]);
|
|
295
|
+
} catch (error) {
|
|
296
|
+
if (!groups()) await db.delete(messages).where(eq(messages.id, input.id)).catch(() => void 0);
|
|
297
|
+
if (!isUniqueViolation(error)) throw error;
|
|
298
|
+
const winner = await requested();
|
|
299
|
+
if (winner) return winner;
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
return one(input.threadId);
|
|
303
|
+
}
|
|
304
|
+
throw commentsErrorDiagnostics.COMMENTS_R0011();
|
|
305
|
+
},
|
|
306
|
+
async addMessage(threadId, input, { allowResolved = false } = {}) {
|
|
307
|
+
if ((await one(threadId)).status === "resolved" && !allowResolved) throw commentsErrorDiagnostics.COMMENTS_R0016();
|
|
308
|
+
await together((target) => [touching(target, threadId, input.now, {}, allowResolved ? void 0 : eq(threads.status, "open")), target.insert(messages).select(sql`select
|
|
309
|
+
${input.id}, ${threadId}, ${input.body}, ${input.author.id}, ${input.author.name ?? null}, ${input.author.image ?? null},
|
|
310
|
+
${input.actor ? JSON.stringify(input.actor) : null}, ${JSON.stringify(input.mentions)}, ${JSON.stringify(input.attachments)},
|
|
311
|
+
${threads.updatedAt}, null
|
|
312
|
+
from ${threads} where ${threads.id} = ${threadId}${allowResolved ? sql`` : sql` and ${threads.status} = 'open'`}`)]);
|
|
313
|
+
const after = await one(threadId);
|
|
314
|
+
if (!after.messages.some((message) => message.id === input.id)) throw commentsErrorDiagnostics.COMMENTS_R0016();
|
|
315
|
+
return after;
|
|
316
|
+
},
|
|
317
|
+
async editMessage(threadId, messageId, input) {
|
|
318
|
+
if (!(await one(threadId)).messages.some((message) => message.id === messageId)) throw commentsErrorDiagnostics.COMMENTS_R0003({ messageId });
|
|
319
|
+
await together((target) => [target.update(messages).set({
|
|
320
|
+
body: input.body,
|
|
321
|
+
editedAt: input.now,
|
|
322
|
+
mentions: JSON.stringify(input.mentions)
|
|
323
|
+
}).where(and(eq(messages.id, messageId), eq(messages.threadId, threadId))), touching(target, threadId, input.now, {}, sql`exists (select 1 from ${messages} where ${messages.id} = ${messageId} and ${messages.threadId} = ${threadId})`)]);
|
|
324
|
+
const after = await one(threadId);
|
|
325
|
+
if (!after.messages.some((message) => message.id === messageId)) throw commentsErrorDiagnostics.COMMENTS_R0003({ messageId });
|
|
326
|
+
return after;
|
|
327
|
+
},
|
|
328
|
+
async deleteMessage(threadId, messageId, now) {
|
|
329
|
+
await together((target) => [target.delete(messages).where(and(eq(messages.id, messageId), eq(messages.threadId, threadId))), touching(target, threadId, now)]);
|
|
330
|
+
return one(threadId);
|
|
331
|
+
},
|
|
332
|
+
async deleteThread(threadId, ownerId) {
|
|
333
|
+
await together((target) => [
|
|
334
|
+
target.update(threads).set({ id: threadId }).where(eq(threads.id, threadId)),
|
|
335
|
+
target.delete(threads).where(and(eq(threads.id, threadId), ownerId === void 0 ? void 0 : sql`not exists (select 1 from ${messages} where ${messages.threadId} = ${threadId} and ${messages.authorId} <> ${ownerId})`)),
|
|
336
|
+
target.delete(messages).where(and(eq(messages.threadId, threadId), sql`not exists (select 1 from ${threads} where ${threads.id} = ${threadId})`))
|
|
337
|
+
]);
|
|
338
|
+
return await find(threadId) === null;
|
|
339
|
+
},
|
|
340
|
+
async setStatus(threadId, status, by, now) {
|
|
341
|
+
await one(threadId);
|
|
342
|
+
await touching(db, threadId, now, status === "resolved" ? {
|
|
343
|
+
resolvedBy: JSON.stringify(by),
|
|
344
|
+
status
|
|
345
|
+
} : {
|
|
346
|
+
resolvedAt: null,
|
|
347
|
+
resolvedBy: null,
|
|
348
|
+
status
|
|
349
|
+
});
|
|
350
|
+
return one(threadId);
|
|
351
|
+
},
|
|
352
|
+
async deleteScope(scope) {
|
|
353
|
+
const remove = (target) => [target.delete(messages).where(inArray(messages.threadId, target.select({ id: threads.id }).from(threads).where(eq(threads.scope, scope)))), target.delete(threads).where(eq(threads.scope, scope)).returning({ id: threads.id })];
|
|
354
|
+
let removed = [];
|
|
355
|
+
if (typeof driver.batch === "function") removed = (await driver.batch([...remove(db)]))[1];
|
|
356
|
+
else if (typeof driver.transaction === "function") await driver.transaction(async (target) => {
|
|
357
|
+
removed = await target.delete(threads).where(eq(threads.scope, scope)).returning({ id: threads.id });
|
|
358
|
+
for (const part of chunks(removed.map((row) => row.id))) await target.delete(messages).where(inArray(messages.threadId, part));
|
|
359
|
+
});
|
|
360
|
+
else {
|
|
361
|
+
removed = await db.delete(threads).where(eq(threads.scope, scope)).returning({ id: threads.id });
|
|
362
|
+
for (const part of chunks(removed.map((row) => row.id))) await db.delete(messages).where(inArray(messages.threadId, part));
|
|
363
|
+
}
|
|
364
|
+
return removed.map((row) => row.id);
|
|
365
|
+
},
|
|
366
|
+
async knownUsersByIds(ids, canRead) {
|
|
367
|
+
const seen = /* @__PURE__ */ new Map();
|
|
368
|
+
const readable = /* @__PURE__ */ new Map();
|
|
369
|
+
for (const part of chunks([...new Set(ids)])) {
|
|
370
|
+
const rows = await candidateAuthors(inArray(messages.authorId, part));
|
|
371
|
+
for (const row of rows) {
|
|
372
|
+
if (seen.has(row.id)) continue;
|
|
373
|
+
let allowed = readable.get(row.threadId);
|
|
374
|
+
if (!allowed) {
|
|
375
|
+
allowed = (async () => {
|
|
376
|
+
const found = await find(row.threadId);
|
|
377
|
+
return found ? await canRead(found) : false;
|
|
378
|
+
})();
|
|
379
|
+
readable.set(row.threadId, allowed);
|
|
380
|
+
}
|
|
381
|
+
if (await allowed) seen.set(row.id, user(row.id, row.name, row.image));
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return [...seen.values()];
|
|
385
|
+
},
|
|
386
|
+
async knownUsers(query, limit, canRead) {
|
|
387
|
+
const pattern = `%${escapeLike(query.toLowerCase())}%`;
|
|
388
|
+
const matching = sql`lower(coalesce(${messages.authorName}, ${messages.authorId})) like ${pattern} escape '\\'`;
|
|
389
|
+
const seen = /* @__PURE__ */ new Map();
|
|
390
|
+
const readable = /* @__PURE__ */ new Map();
|
|
391
|
+
let before;
|
|
392
|
+
while (seen.size < limit) {
|
|
393
|
+
const rows = await candidateAuthors(and(matching, before ? or(lt(messages.createdAt, before.createdAt), and(eq(messages.createdAt, before.createdAt), lt(messages.id, before.messageId))) : void 0)).limit(candidateLimit);
|
|
394
|
+
for (const row of rows) {
|
|
395
|
+
if (seen.has(row.id)) continue;
|
|
396
|
+
let allowed = readable.get(row.threadId);
|
|
397
|
+
if (!allowed) {
|
|
398
|
+
allowed = (async () => {
|
|
399
|
+
const found = await find(row.threadId);
|
|
400
|
+
return found ? await canRead(found) : false;
|
|
401
|
+
})();
|
|
402
|
+
readable.set(row.threadId, allowed);
|
|
403
|
+
}
|
|
404
|
+
if (await allowed) seen.set(row.id, user(row.id, row.name, row.image));
|
|
405
|
+
if (seen.size >= limit) break;
|
|
406
|
+
}
|
|
407
|
+
if (rows.length < candidateLimit) break;
|
|
408
|
+
before = rows.at(-1);
|
|
409
|
+
}
|
|
410
|
+
return [...seen.values()];
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
//#endregion
|
|
415
|
+
//#region src/forge/github.ts
|
|
416
|
+
/** The HTTP status of a GitHub failure of the pull request sync, or `undefined` for another error. */
|
|
417
|
+
function gitHubFailureStatus(error) {
|
|
418
|
+
if (!(error instanceof Error)) return void 0;
|
|
419
|
+
const code = Reflect.get(error, "code");
|
|
420
|
+
const status = Reflect.get(error, "status");
|
|
421
|
+
return (code === "COMMENTS_GITHUB_SYNC_FAILED" || code === "COMMENTS_GITHUB_CREDENTIALS_MISSING") && typeof status === "number" ? status : void 0;
|
|
422
|
+
}
|
|
423
|
+
const commentResponse = v.object({
|
|
424
|
+
id: v.number(),
|
|
425
|
+
node_id: v.string(),
|
|
426
|
+
html_url: v.string()
|
|
427
|
+
});
|
|
428
|
+
const commentListResponse = v.array(v.object({
|
|
429
|
+
...commentResponse.entries,
|
|
430
|
+
body: v.string()
|
|
431
|
+
}));
|
|
432
|
+
const pullsResponse = v.array(v.object({ number: v.number() }));
|
|
433
|
+
/** A Server Env value from the active Cloudflare bindings, else from `process.env`. */
|
|
434
|
+
function serverEnv(name) {
|
|
435
|
+
return getActiveCloudflareBinding(name) ?? globalThis.process?.env?.[name];
|
|
436
|
+
}
|
|
437
|
+
function createGitHubClient(options = {}) {
|
|
438
|
+
const apiUrl = (options.apiUrl ?? "https://api.github.com").replace(/\/+$/, "");
|
|
439
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
440
|
+
const pullRequests = /* @__PURE__ */ new Map();
|
|
441
|
+
async function request(token, method, path, body) {
|
|
442
|
+
const response = await fetcher(`${apiUrl}${path}`, {
|
|
443
|
+
method,
|
|
444
|
+
headers: {
|
|
445
|
+
"accept": "application/vnd.github+json",
|
|
446
|
+
"authorization": `Bearer ${token}`,
|
|
447
|
+
"user-agent": "vitehub-comments",
|
|
448
|
+
"x-github-api-version": "2022-11-28",
|
|
449
|
+
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
450
|
+
},
|
|
451
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
452
|
+
});
|
|
453
|
+
if (!response.ok) {
|
|
454
|
+
const data = await response.json().catch(() => void 0);
|
|
455
|
+
const message = data && typeof data === "object" && "message" in data && typeof data.message === "string" ? data.message : response.statusText;
|
|
456
|
+
throw Object.assign(commentsErrorDiagnostics.COMMENTS_GITHUB_SYNC_FAILED({
|
|
457
|
+
reason: message,
|
|
458
|
+
request: `${method} ${path.split("?")[0]}`,
|
|
459
|
+
status: response.status
|
|
460
|
+
}), { status: response.status });
|
|
461
|
+
}
|
|
462
|
+
return response.status === 204 ? void 0 : await response.json();
|
|
463
|
+
}
|
|
464
|
+
async function graphql(token, query, variables) {
|
|
465
|
+
const graphqlUrl = apiUrl.endsWith("/api/v3") ? `${apiUrl.slice(0, -2)}graphql` : `${apiUrl}/graphql`;
|
|
466
|
+
const response = await fetcher(graphqlUrl, {
|
|
467
|
+
method: "POST",
|
|
468
|
+
headers: {
|
|
469
|
+
"authorization": `Bearer ${token}`,
|
|
470
|
+
"content-type": "application/json",
|
|
471
|
+
"user-agent": "vitehub-comments"
|
|
472
|
+
},
|
|
473
|
+
body: JSON.stringify({
|
|
474
|
+
query,
|
|
475
|
+
variables
|
|
476
|
+
})
|
|
477
|
+
});
|
|
478
|
+
const data = await response.json().catch(() => void 0);
|
|
479
|
+
const errors = data && typeof data === "object" && "errors" in data && Array.isArray(data.errors) ? data.errors : [];
|
|
480
|
+
if (!response.ok || errors.length) {
|
|
481
|
+
const message = errors[0] && typeof errors[0] === "object" && "message" in errors[0] ? String(errors[0].message) : response.statusText;
|
|
482
|
+
throw Object.assign(commentsErrorDiagnostics.COMMENTS_GITHUB_SYNC_FAILED({
|
|
483
|
+
reason: message,
|
|
484
|
+
request: "GraphQL",
|
|
485
|
+
status: response.status
|
|
486
|
+
}), { status: response.status });
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return {
|
|
490
|
+
async appToken(repository) {
|
|
491
|
+
const env = (name) => serverEnv(name);
|
|
492
|
+
const appId = readForgeEnv(forgeEnv.github.appId, env);
|
|
493
|
+
const privateKey = appId ? await readGitHubAppPrivateKey(readForgeEnv(forgeEnv.github.privateKey, env), readForgeEnv(forgeEnv.github.privateKeyPath, env)) : void 0;
|
|
494
|
+
if (appId && privateKey) {
|
|
495
|
+
const app = githubAppCredentials({
|
|
496
|
+
appId,
|
|
497
|
+
privateKey,
|
|
498
|
+
baseUrl: apiUrl,
|
|
499
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
500
|
+
userAgent: "vitehub-comments"
|
|
501
|
+
});
|
|
502
|
+
const routing = githubInstallationRouting({
|
|
503
|
+
installationId: readForgeEnv(forgeEnv.github.installationId, env),
|
|
504
|
+
appOwner: readForgeEnv(forgeEnv.github.appOwner, env),
|
|
505
|
+
appInstallations: readForgeEnv(forgeEnv.github.appInstallations, env)
|
|
506
|
+
});
|
|
507
|
+
const installation = githubInstallationFor(routing, repository) ?? await app.installation(repository);
|
|
508
|
+
return (await app.installationToken(installation)).token;
|
|
509
|
+
}
|
|
510
|
+
const token = readForgeEnv(forgeEnv.github.token, env);
|
|
511
|
+
if (token) return token;
|
|
512
|
+
throw Object.assign(commentsErrorDiagnostics.COMMENTS_GITHUB_CREDENTIALS_MISSING(), { status: 401 });
|
|
513
|
+
},
|
|
514
|
+
async findPullRequest(repository, branch) {
|
|
515
|
+
const key = `${repository}\0${branch}`;
|
|
516
|
+
const cached = pullRequests.get(key);
|
|
517
|
+
if (cached && cached.until > Date.now()) return cached.number;
|
|
518
|
+
const token = await this.appToken(repository);
|
|
519
|
+
const owner = repository.split("/")[0];
|
|
520
|
+
const number = v.parse(pullsResponse, await request(token, "GET", `/repos/${repository}/pulls?state=open&per_page=1&head=${encodeURIComponent(`${owner}:${branch}`)}`))[0]?.number;
|
|
521
|
+
pullRequests.set(key, {
|
|
522
|
+
number,
|
|
523
|
+
until: Date.now() + (number ? 5 : 1) * 6e4
|
|
524
|
+
});
|
|
525
|
+
return number;
|
|
526
|
+
},
|
|
527
|
+
async findComment(token, repository, pullRequest, marker) {
|
|
528
|
+
for (let page = 1;; page++) {
|
|
529
|
+
const comments = v.parse(commentListResponse, await request(token, "GET", `/repos/${repository}/issues/${pullRequest}/comments?per_page=100&page=${page}`));
|
|
530
|
+
const found = comments.find((comment) => comment.body.trimEnd().endsWith(marker));
|
|
531
|
+
if (found) return {
|
|
532
|
+
id: String(found.id),
|
|
533
|
+
nodeId: found.node_id,
|
|
534
|
+
url: found.html_url,
|
|
535
|
+
body: found.body
|
|
536
|
+
};
|
|
537
|
+
if (comments.length < 100) return;
|
|
538
|
+
}
|
|
539
|
+
},
|
|
540
|
+
async createComment(token, repository, pullRequest, body) {
|
|
541
|
+
const comment = v.parse(commentResponse, await request(token, "POST", `/repos/${repository}/issues/${pullRequest}/comments`, { body }));
|
|
542
|
+
return {
|
|
543
|
+
id: String(comment.id),
|
|
544
|
+
nodeId: comment.node_id,
|
|
545
|
+
url: comment.html_url
|
|
546
|
+
};
|
|
547
|
+
},
|
|
548
|
+
async updateComment(token, repository, id, body) {
|
|
549
|
+
await request(token, "PATCH", `/repos/${repository}/issues/comments/${id}`, { body });
|
|
550
|
+
},
|
|
551
|
+
async deleteComment(token, repository, id) {
|
|
552
|
+
try {
|
|
553
|
+
await request(token, "DELETE", `/repos/${repository}/issues/comments/${id}`);
|
|
554
|
+
} catch (error) {
|
|
555
|
+
if (gitHubFailureStatus(error) !== 404) throw error;
|
|
556
|
+
}
|
|
557
|
+
},
|
|
558
|
+
async minimize(token, nodeId, minimized) {
|
|
559
|
+
await graphql(token, minimized ? "mutation($id: ID!) { minimizeComment(input: { subjectId: $id, classifier: RESOLVED }) { clientMutationId } }" : "mutation($id: ID!) { unminimizeComment(input: { subjectId: $id }) { clientMutationId } }", { id: nodeId });
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
//#endregion
|
|
564
|
+
//#region src/forge/render.ts
|
|
565
|
+
/** The `<!-- -->` marker that ends every comment the sync posts, so people and tools can tell them apart. */
|
|
566
|
+
const forgeMarker = "vitehub-comments";
|
|
567
|
+
const summaryMarker = `<!-- ${forgeMarker} summary -->`;
|
|
568
|
+
function commentMarker(threadId, commentId) {
|
|
569
|
+
return `<!-- ${forgeMarker} thread=${threadId} comment=${commentId} -->`;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Text that GitHub must not link: `@name` notifies a GitHub user, and `#3` links issue 3. Comment mentions and thread
|
|
573
|
+
* numbers belong to the app, so a word joiner breaks both without changing how they read.
|
|
574
|
+
*/
|
|
575
|
+
function unlinked(text) {
|
|
576
|
+
return text.replace(/@(?=[\w-])/g, "@").replace(/#(?=\d)/g, "#");
|
|
577
|
+
}
|
|
578
|
+
/** A thread number as people say it, "#3", that GitHub does not link to issue 3. */
|
|
579
|
+
function number(thread) {
|
|
580
|
+
return `#\u2060${thread.n}`;
|
|
581
|
+
}
|
|
582
|
+
function quote(text) {
|
|
583
|
+
return text.split("\n").map((line) => `> ${line}`).join("\n");
|
|
584
|
+
}
|
|
585
|
+
/** Comment text is plain text in the preview; keep it literal in GitHub Markdown too. */
|
|
586
|
+
function plainText(text) {
|
|
587
|
+
return unlinked(text).replace(/&/g, "&").replace(/[\\`*_{}[\]<>#+=!:|~-]/g, "\\$&").replace(/\b(www)\./gi, "$1\\.").replace(/^(\s*\d+)([.)])(?=\s)/gm, "$1\\$2").replace(/^[ \t]/gm, (char) => char === " " ? "	" : " ");
|
|
588
|
+
}
|
|
589
|
+
/** One line for a Markdown table cell. */
|
|
590
|
+
function cell(text) {
|
|
591
|
+
return plainText(text).replace(/\s+/g, " ").trim();
|
|
592
|
+
}
|
|
593
|
+
/** A code span for a Markdown table cell. GitHub shows `<` in a code span as typed, so only pipes are escaped. */
|
|
594
|
+
function code(text) {
|
|
595
|
+
return `\`${text.replace(/\s+/g, " ").replace(/\|/g, "\\|").replace(/`/g, "'").trim()}\``;
|
|
596
|
+
}
|
|
597
|
+
/** The first sentence of a comment, at most 100 characters. */
|
|
598
|
+
function headline(body) {
|
|
599
|
+
const first = body.trim().split(/(?<=[.!?])\s/, 1)[0] ?? "";
|
|
600
|
+
return first.length > 100 ? `${first.slice(0, 99).trimEnd()}…` : first;
|
|
601
|
+
}
|
|
602
|
+
function authorName(comment) {
|
|
603
|
+
return unlinked(`${comment.author.name ?? comment.author.id}${comment.author.guest ? " (guest)" : ""}`);
|
|
604
|
+
}
|
|
605
|
+
/** The page of a thread: the subject of a page thread. */
|
|
606
|
+
function pageOf(thread) {
|
|
607
|
+
return thread.subject.id;
|
|
608
|
+
}
|
|
609
|
+
/** The page of a thread in comment mode, with its thread open: the Console's **Open on page** link. */
|
|
610
|
+
function previewUrl(thread) {
|
|
611
|
+
if (!thread.context?.url) return;
|
|
612
|
+
try {
|
|
613
|
+
const url = new URL(thread.context.url);
|
|
614
|
+
url.hash = "";
|
|
615
|
+
url.searchParams.set("comment", String(thread.n));
|
|
616
|
+
return url.href;
|
|
617
|
+
} catch {
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
function pageLink(thread) {
|
|
622
|
+
const url = previewUrl(thread);
|
|
623
|
+
return url ? `[\`${pageOf(thread)}\`](${url})` : `\`${pageOf(thread)}\``;
|
|
624
|
+
}
|
|
625
|
+
function where(thread) {
|
|
626
|
+
const element = thread.context?.element;
|
|
627
|
+
const name = element?.name ? ` “${cell(element.name).slice(0, 60)}”` : "";
|
|
628
|
+
return `**${number(thread)}** on ${pageLink(thread)}${element ? ` · \`${element.tag}\`${name}` : ""}`;
|
|
629
|
+
}
|
|
630
|
+
function details(thread) {
|
|
631
|
+
const fields = describeCommentContext(thread.context ?? null);
|
|
632
|
+
if (!fields.length) return "";
|
|
633
|
+
return [
|
|
634
|
+
"<details><summary>What they were looking at</summary>",
|
|
635
|
+
"",
|
|
636
|
+
"| | |",
|
|
637
|
+
"| --- | --- |",
|
|
638
|
+
...fields.map(({ label, value }) => {
|
|
639
|
+
return `| ${label} | ${label === "URL" ? cell(value) : label === "Files" ? value.split(", ").map(code).join("<br>") : code(value)} |`;
|
|
640
|
+
}),
|
|
641
|
+
"",
|
|
642
|
+
"</details>"
|
|
643
|
+
].join("\n");
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* The pull request comment of one comment. `author` posts with the person's own token, so the text is theirs; `app`
|
|
647
|
+
* posts for them, so it names them and quotes them.
|
|
648
|
+
*/
|
|
649
|
+
function renderComment(thread, comment, postedAs) {
|
|
650
|
+
const first = thread.messages[0]?.id === comment.id;
|
|
651
|
+
const body = plainText(comment.body);
|
|
652
|
+
const lines = [];
|
|
653
|
+
if (postedAs === "app") lines.push(first ? `**${plainText(authorName(comment))}** commented on the preview:` : `**${plainText(authorName(comment))}** replied on ${number(thread)}:`, "", quote(body));
|
|
654
|
+
else lines.push(body);
|
|
655
|
+
lines.push("");
|
|
656
|
+
if (first) {
|
|
657
|
+
lines.push(where(thread));
|
|
658
|
+
const context = details(thread);
|
|
659
|
+
if (context) lines.push("", context);
|
|
660
|
+
} else lines.push(`<sub>Reply on ${number(thread)} · ${pageLink(thread)}</sub>`);
|
|
661
|
+
lines.push("", commentMarker(thread.id, comment.id));
|
|
662
|
+
return lines.join("\n");
|
|
663
|
+
}
|
|
664
|
+
/** The summary comment of a pull request: every thread posted to it, by number, with its state. */
|
|
665
|
+
function renderSummary(input) {
|
|
666
|
+
const threads = [...input.threads].sort((a, b) => a.thread.n - b.thread.n);
|
|
667
|
+
const open = threads.filter(({ thread }) => thread.status === "open").length;
|
|
668
|
+
const site = threads.map(({ thread }) => thread.context?.url).find(Boolean);
|
|
669
|
+
let origin;
|
|
670
|
+
try {
|
|
671
|
+
origin = site ? new URL(site) : void 0;
|
|
672
|
+
} catch {}
|
|
673
|
+
const rows = threads.map(({ thread, url, failed }) => {
|
|
674
|
+
const first = thread.messages[0];
|
|
675
|
+
const text = cell(unlinked(headline(first?.body ?? "")));
|
|
676
|
+
const comment = url ? `[${text}](${url})` : text;
|
|
677
|
+
const shown = thread.status === "resolved" ? `~~${comment}~~` : comment;
|
|
678
|
+
const preview = previewUrl(thread);
|
|
679
|
+
const label = preview ? `[${number(thread)}](${preview})` : number(thread);
|
|
680
|
+
const state = thread.status === "resolved" ? "Resolved" : failed ? "Open, not posted yet" : "Open";
|
|
681
|
+
return `| ${label} | ${shown}<br><sub>${code(pageOf(thread))} · ${cell(first ? authorName(first) : unlinked(thread.author.name ?? thread.author.id))}</sub> | ${state} |`;
|
|
682
|
+
});
|
|
683
|
+
return [
|
|
684
|
+
`### ${input.title}`,
|
|
685
|
+
"",
|
|
686
|
+
`**${open} open**, ${threads.length - open} resolved${origin ? ` on [${origin.host}](${origin.origin})` : ""}.`,
|
|
687
|
+
"",
|
|
688
|
+
"| # | Comment | State |",
|
|
689
|
+
"| --- | --- | --- |",
|
|
690
|
+
...rows,
|
|
691
|
+
"",
|
|
692
|
+
"<sub>ViteHub Comments keeps this comment up to date. Each thread is also its own comment below; reply on the page to keep the thread together.</sub>",
|
|
693
|
+
"",
|
|
694
|
+
summaryMarker
|
|
695
|
+
].join("\n");
|
|
696
|
+
}
|
|
697
|
+
//#endregion
|
|
698
|
+
//#region src/forge/sync.ts
|
|
699
|
+
/** How long a row that is being posted stays claimed, so a sync that died does not block the comment for good. */
|
|
700
|
+
const claimTimeout = 6e4;
|
|
701
|
+
/** Change detection only: two FNV-1a passes, as `commentRoom()` hashes pages. */
|
|
702
|
+
function digest(text) {
|
|
703
|
+
let a = 2166136261;
|
|
704
|
+
let b = 1523705862;
|
|
705
|
+
for (let index = 0; index < text.length; index++) {
|
|
706
|
+
const code = text.charCodeAt(index);
|
|
707
|
+
a = Math.imul(a ^ code, 16777619) >>> 0;
|
|
708
|
+
b = Math.imul(b ^ code, 2671213388) >>> 0;
|
|
709
|
+
}
|
|
710
|
+
return `${a.toString(16).padStart(8, "0")}${b.toString(16).padStart(8, "0")}`;
|
|
711
|
+
}
|
|
712
|
+
function message(error) {
|
|
713
|
+
return (error instanceof Error ? error.message : String(error)).slice(0, 500);
|
|
714
|
+
}
|
|
715
|
+
function linkOf(thread, byId) {
|
|
716
|
+
const rows = thread.messages.map((comment) => byId.get(comment.id));
|
|
717
|
+
const first = rows[0];
|
|
718
|
+
const target = first ?? rows.find((row) => row !== void 0);
|
|
719
|
+
if (!target) return null;
|
|
720
|
+
const error = rows.find((row) => row?.error)?.error;
|
|
721
|
+
return {
|
|
722
|
+
repository: target.repository,
|
|
723
|
+
pullRequest: target.pullRequest,
|
|
724
|
+
state: error ? "failed" : rows.some((row) => !row?.remoteId) ? "pending" : "posted",
|
|
725
|
+
...first?.url ? { url: first.url } : {},
|
|
726
|
+
...error ? { error } : {},
|
|
727
|
+
...first?.postedAs ? { postedAs: first.postedAs } : {}
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
function authorizationFailed(error) {
|
|
731
|
+
const status = gitHubFailureStatus(error);
|
|
732
|
+
return status === 401 || status === 403 || status === 404;
|
|
733
|
+
}
|
|
734
|
+
/** Runs tasks with the same key one after another, so two syncs of a thread or a pull request never interleave. */
|
|
735
|
+
function serial() {
|
|
736
|
+
const tails = /* @__PURE__ */ new Map();
|
|
737
|
+
return (key, task) => {
|
|
738
|
+
const run = (tails.get(key) ?? Promise.resolve()).catch(() => {}).then(task);
|
|
739
|
+
tails.set(key, run);
|
|
740
|
+
run.catch(() => {}).finally(() => {
|
|
741
|
+
if (tails.get(key) === run) tails.delete(key);
|
|
742
|
+
});
|
|
743
|
+
return run;
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
function createForgeSync(options, input) {
|
|
747
|
+
const { database } = input;
|
|
748
|
+
const links = input.table ?? commentForge;
|
|
749
|
+
const store = {
|
|
750
|
+
get: async (id) => await input.store.getById(id) ?? void 0,
|
|
751
|
+
threadOf: async (messageId) => (await input.store.getByMessage(messageId))?.id
|
|
752
|
+
};
|
|
753
|
+
const github = input.github ?? createGitHubClient({
|
|
754
|
+
...options.apiUrl ? { apiUrl: options.apiUrl } : {},
|
|
755
|
+
...options.fetch ? { fetch: options.fetch } : {}
|
|
756
|
+
});
|
|
757
|
+
const title = options.title ?? "Preview comments";
|
|
758
|
+
const inOrder = serial();
|
|
759
|
+
async function rowsOfThread(threadId) {
|
|
760
|
+
return await database.select().from(links).where(eq(links.threadId, threadId));
|
|
761
|
+
}
|
|
762
|
+
async function row(id) {
|
|
763
|
+
const [found] = await database.select().from(links).where(eq(links.id, id)).limit(1);
|
|
764
|
+
return found;
|
|
765
|
+
}
|
|
766
|
+
async function save(id, values) {
|
|
767
|
+
await database.update(links).set({
|
|
768
|
+
...values,
|
|
769
|
+
updatedAt: Date.now()
|
|
770
|
+
}).where(eq(links.id, id));
|
|
771
|
+
}
|
|
772
|
+
/** Pending writes are fenced by the claim's timestamp, including retries within the same millisecond. */
|
|
773
|
+
async function savePending(id, claimedAt, values) {
|
|
774
|
+
await database.update(links).set(values).where(and(eq(links.id, id), isNull(links.remoteId), eq(links.updatedAt, claimedAt)));
|
|
775
|
+
}
|
|
776
|
+
/** Claims a create. An expired owner may still finish; recordPosted reconciles its response. */
|
|
777
|
+
async function claim(id, existing, values) {
|
|
778
|
+
const now = Math.max(Date.now(), (existing?.updatedAt ?? 0) + 1);
|
|
779
|
+
if (!existing) return (await database.insert(links).values({
|
|
780
|
+
id,
|
|
781
|
+
...values,
|
|
782
|
+
minimized: false,
|
|
783
|
+
updatedAt: now
|
|
784
|
+
}).onConflictDoNothing().returning({ id: links.id })).length ? now : void 0;
|
|
785
|
+
if (existing.remoteId || !existing.error && existing.updatedAt > Date.now() - claimTimeout) return;
|
|
786
|
+
return (await database.update(links).set({
|
|
787
|
+
error: null,
|
|
788
|
+
updatedAt: now
|
|
789
|
+
}).where(and(eq(links.id, id), isNull(links.remoteId), eq(links.updatedAt, existing.updatedAt))).returning({ id: links.id })).length ? now : void 0;
|
|
790
|
+
}
|
|
791
|
+
/** Retain the remote identity before removing its link, so a failed DELETE can be retried without the thread. */
|
|
792
|
+
async function deletePosted(at, remoteId, token, existing) {
|
|
793
|
+
const id = `cleanup:${at.repository}#${remoteId}`;
|
|
794
|
+
await database.insert(links).values({
|
|
795
|
+
id,
|
|
796
|
+
threadId: null,
|
|
797
|
+
repository: at.repository,
|
|
798
|
+
pullRequest: at.pullRequest,
|
|
799
|
+
remoteId,
|
|
800
|
+
updatedAt: Date.now()
|
|
801
|
+
}).onConflictDoNothing();
|
|
802
|
+
if (existing && existing.id !== id) await database.delete(links).where(and(eq(links.id, existing.id), eq(links.remoteId, remoteId)));
|
|
803
|
+
await github.deleteComment(await token(), at.repository, remoteId);
|
|
804
|
+
await database.delete(links).where(eq(links.id, id));
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* The first saved remote identity wins, even if its POST outlived its lease. A late creator cannot overwrite
|
|
808
|
+
* the winner, and queues deletion of its own extra comment before trying it. Cleanup survives a failed DELETE,
|
|
809
|
+
* even when the original thread and link have already been removed.
|
|
810
|
+
*/
|
|
811
|
+
async function recordPosted(id, at, posted, body, token, postedAs) {
|
|
812
|
+
const [saved] = await database.update(links).set({
|
|
813
|
+
remoteId: posted.id,
|
|
814
|
+
nodeId: posted.nodeId,
|
|
815
|
+
url: posted.url,
|
|
816
|
+
digest: digest(body),
|
|
817
|
+
error: null,
|
|
818
|
+
updatedAt: Date.now(),
|
|
819
|
+
...postedAs ? { postedAs } : {}
|
|
820
|
+
}).where(and(eq(links.id, id), isNull(links.remoteId))).returning();
|
|
821
|
+
if (saved) return saved;
|
|
822
|
+
const current = await row(id);
|
|
823
|
+
if (current?.remoteId !== posted.id) await deletePosted(at, posted.id, token);
|
|
824
|
+
return current;
|
|
825
|
+
}
|
|
826
|
+
/** Cleanup rows are independent of thread membership, so even a deleted thread can retry its remote deletions. */
|
|
827
|
+
async function retryCleanup() {
|
|
828
|
+
const pending = await database.select().from(links).where(like(links.id, "cleanup:%"));
|
|
829
|
+
for (const existing of pending) try {
|
|
830
|
+
await removeLink(existing, () => github.appToken(existing.repository));
|
|
831
|
+
} catch (error) {
|
|
832
|
+
await save(existing.id, { error: message(error) });
|
|
833
|
+
console.warn("[vitehub] Comments could not delete a pull request comment:", error);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
/** A claimed row may have reached GitHub before its creator died or lost the response. Never blindly repost it. */
|
|
837
|
+
async function recover(existing, token) {
|
|
838
|
+
const marker = existing.threadId === null ? summaryMarker : commentMarker(existing.threadId, existing.id);
|
|
839
|
+
const posted = await github.findComment(await token(), existing.repository, existing.pullRequest, marker);
|
|
840
|
+
if (!posted) return;
|
|
841
|
+
return await recordPosted(existing.id, existing, posted, posted.body, token);
|
|
842
|
+
}
|
|
843
|
+
async function removeLink(existing, token) {
|
|
844
|
+
let current = await row(existing.id);
|
|
845
|
+
if (!current) return;
|
|
846
|
+
if (!current.remoteId) {
|
|
847
|
+
const claimedAt = await claim(current.id, current, current);
|
|
848
|
+
if (claimedAt === void 0) return;
|
|
849
|
+
try {
|
|
850
|
+
await recover(current, token);
|
|
851
|
+
} catch (error) {
|
|
852
|
+
await savePending(current.id, claimedAt, { error: message(error) });
|
|
853
|
+
throw error;
|
|
854
|
+
}
|
|
855
|
+
if ((await database.delete(links).where(and(eq(links.id, current.id), isNull(links.remoteId))).returning({ id: links.id })).length) return;
|
|
856
|
+
current = await row(current.id);
|
|
857
|
+
}
|
|
858
|
+
if (current?.remoteId) await deletePosted(current, current.remoteId, token, current);
|
|
859
|
+
}
|
|
860
|
+
async function target(thread) {
|
|
861
|
+
const build = thread.context?.build;
|
|
862
|
+
const repository = options.repository ?? build?.repository;
|
|
863
|
+
if (!repository) return;
|
|
864
|
+
let pullRequest = options.pullRequest ? await options.pullRequest(thread) : build?.pullRequest;
|
|
865
|
+
if (!options.pullRequest && pullRequest === void 0 && build?.branch) pullRequest = await github.findPullRequest(repository, build.branch);
|
|
866
|
+
return pullRequest ? {
|
|
867
|
+
repository,
|
|
868
|
+
pullRequest
|
|
869
|
+
} : void 0;
|
|
870
|
+
}
|
|
871
|
+
/** The person's own GitHub token: `token(author)`, else the token of their GitHub sign-in to Comments. */
|
|
872
|
+
async function authorToken(comment) {
|
|
873
|
+
if (comment.author.guest) return;
|
|
874
|
+
if (!options.token) return recentGitHubToken(comment.author.id);
|
|
875
|
+
try {
|
|
876
|
+
return await options.token(comment.author) || void 0;
|
|
877
|
+
} catch (error) {
|
|
878
|
+
console.warn(`[vitehub] Comments forge token for ${comment.author.id} failed:`, error);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
async function syncComment(thread, comment, existing, at, appToken) {
|
|
883
|
+
if (existing?.remoteId) {
|
|
884
|
+
const body = renderComment(thread, comment, existing.postedAs ?? "app");
|
|
885
|
+
const hash = digest(body);
|
|
886
|
+
try {
|
|
887
|
+
if (existing.digest !== hash) {
|
|
888
|
+
const own = existing.postedAs === "author" ? await authorToken(comment) : void 0;
|
|
889
|
+
try {
|
|
890
|
+
await github.updateComment(own ?? await appToken(), at.repository, existing.remoteId, body);
|
|
891
|
+
} catch (error) {
|
|
892
|
+
if (!own || !authorizationFailed(error)) throw error;
|
|
893
|
+
await github.updateComment(await appToken(), at.repository, existing.remoteId, body);
|
|
894
|
+
}
|
|
895
|
+
await save(comment.id, {
|
|
896
|
+
digest: hash,
|
|
897
|
+
error: null
|
|
898
|
+
});
|
|
899
|
+
} else if (existing.error) await save(comment.id, { error: null });
|
|
900
|
+
} catch (error) {
|
|
901
|
+
await save(comment.id, { error: message(error) });
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
const latest = await store.get(thread.id);
|
|
905
|
+
const edited = latest?.messages.find((item) => item.id === comment.id);
|
|
906
|
+
if (latest && edited && renderComment(latest, edited, existing.postedAs ?? "app") !== body) await syncComment(latest, edited, await row(comment.id), at, appToken);
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
const claimedAt = await claim(comment.id, existing, {
|
|
910
|
+
threadId: thread.id,
|
|
911
|
+
...at
|
|
912
|
+
});
|
|
913
|
+
if (claimedAt === void 0) return;
|
|
914
|
+
try {
|
|
915
|
+
const recovered = existing ? await recover(existing, appToken) : void 0;
|
|
916
|
+
if (recovered?.remoteId) {
|
|
917
|
+
await syncComment(thread, comment, recovered, at, appToken);
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
const own = await authorToken(comment);
|
|
921
|
+
let postedAs = own ? "author" : "app";
|
|
922
|
+
let body = renderComment(thread, comment, postedAs);
|
|
923
|
+
let token = own ?? await appToken();
|
|
924
|
+
let posted;
|
|
925
|
+
try {
|
|
926
|
+
await savePending(comment.id, claimedAt, { postedAs });
|
|
927
|
+
posted = await github.createComment(token, at.repository, at.pullRequest, body);
|
|
928
|
+
} catch (error) {
|
|
929
|
+
if (!own || !authorizationFailed(error)) throw error;
|
|
930
|
+
postedAs = "app";
|
|
931
|
+
body = renderComment(thread, comment, postedAs);
|
|
932
|
+
token = await appToken();
|
|
933
|
+
await savePending(comment.id, claimedAt, { postedAs });
|
|
934
|
+
posted = await github.createComment(token, at.repository, at.pullRequest, body);
|
|
935
|
+
}
|
|
936
|
+
const saved = await recordPosted(comment.id, at, posted, body, async () => token, postedAs);
|
|
937
|
+
const latest = await store.get(thread.id);
|
|
938
|
+
const edited = latest?.messages.find((item) => item.id === comment.id);
|
|
939
|
+
if (saved?.remoteId && latest && edited) await syncComment(latest, edited, saved, at, appToken);
|
|
940
|
+
} catch (error) {
|
|
941
|
+
await savePending(comment.id, claimedAt, { error: message(error) });
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
async function summaryBody(at, extraId) {
|
|
945
|
+
const rows = await database.select().from(links).where(and(eq(links.repository, at.repository), eq(links.pullRequest, at.pullRequest), isNotNull(links.threadId)));
|
|
946
|
+
const ids = new Set(rows.map((item) => item.threadId));
|
|
947
|
+
if (extraId) ids.add(extraId);
|
|
948
|
+
const threads = (await Promise.all([...ids].map((threadId) => store.get(threadId)))).filter((thread) => thread !== void 0);
|
|
949
|
+
if (!threads.length) return;
|
|
950
|
+
const byId = new Map(rows.map((item) => [item.id, item]));
|
|
951
|
+
return renderSummary({
|
|
952
|
+
title,
|
|
953
|
+
threads: threads.map((thread) => {
|
|
954
|
+
const link = linkOf(thread, byId);
|
|
955
|
+
return {
|
|
956
|
+
thread,
|
|
957
|
+
...link?.url ? { url: link.url } : {},
|
|
958
|
+
failed: link?.state !== "posted"
|
|
959
|
+
};
|
|
960
|
+
})
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
async function syncSummary(at, extra) {
|
|
964
|
+
await inOrder(`summary:${at.repository}#${at.pullRequest}`, async () => {
|
|
965
|
+
const id = `summary:${at.repository}#${at.pullRequest}`;
|
|
966
|
+
let appToken;
|
|
967
|
+
const token = async () => appToken ??= await github.appToken(at.repository);
|
|
968
|
+
while (true) {
|
|
969
|
+
const existing = await row(id);
|
|
970
|
+
const body = await summaryBody(at, extra?.id);
|
|
971
|
+
if (body === void 0) {
|
|
972
|
+
if (existing) await removeLink(existing, token);
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
const hash = digest(body);
|
|
976
|
+
if (existing?.remoteId) {
|
|
977
|
+
if (existing.digest === hash) return;
|
|
978
|
+
try {
|
|
979
|
+
await github.updateComment(await token(), at.repository, existing.remoteId, body);
|
|
980
|
+
await save(id, {
|
|
981
|
+
digest: hash,
|
|
982
|
+
error: null
|
|
983
|
+
});
|
|
984
|
+
} catch (error) {
|
|
985
|
+
await save(id, { error: message(error) });
|
|
986
|
+
throw error;
|
|
987
|
+
}
|
|
988
|
+
continue;
|
|
989
|
+
}
|
|
990
|
+
const claimedAt = await claim(id, existing, {
|
|
991
|
+
threadId: null,
|
|
992
|
+
...at
|
|
993
|
+
});
|
|
994
|
+
if (claimedAt === void 0) return;
|
|
995
|
+
try {
|
|
996
|
+
if ((existing ? await recover(existing, token) : void 0)?.remoteId) continue;
|
|
997
|
+
if (!await recordPosted(id, at, await github.createComment(await token(), at.repository, at.pullRequest, body), body, token, "app")) return;
|
|
998
|
+
} catch (error) {
|
|
999
|
+
await savePending(id, claimedAt, { error: message(error) });
|
|
1000
|
+
throw error;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
async function syncThread(threadId) {
|
|
1006
|
+
await retryCleanup();
|
|
1007
|
+
let thread = await store.get(threadId);
|
|
1008
|
+
const rows = await rowsOfThread(threadId);
|
|
1009
|
+
const at = rows[0] ? {
|
|
1010
|
+
repository: rows[0].repository,
|
|
1011
|
+
pullRequest: rows[0].pullRequest
|
|
1012
|
+
} : thread ? await target(thread) : void 0;
|
|
1013
|
+
if (!at) return;
|
|
1014
|
+
let appToken;
|
|
1015
|
+
const token = async () => appToken ??= await github.appToken(at.repository);
|
|
1016
|
+
let delay = 10;
|
|
1017
|
+
try {
|
|
1018
|
+
while (thread && !(await row(`summary:${at.repository}#${at.pullRequest}`))?.remoteId) {
|
|
1019
|
+
await syncSummary(at, thread);
|
|
1020
|
+
if ((await row(`summary:${at.repository}#${at.pullRequest}`))?.remoteId) break;
|
|
1021
|
+
thread = await store.get(threadId);
|
|
1022
|
+
if (!thread) break;
|
|
1023
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
1024
|
+
delay = Math.min(delay * 2, 1e3);
|
|
1025
|
+
}
|
|
1026
|
+
} catch (error) {
|
|
1027
|
+
const first = (await store.get(threadId))?.messages[0];
|
|
1028
|
+
if (first) await database.insert(links).values({
|
|
1029
|
+
id: first.id,
|
|
1030
|
+
threadId,
|
|
1031
|
+
...at,
|
|
1032
|
+
error: message(error),
|
|
1033
|
+
updatedAt: Date.now()
|
|
1034
|
+
}).onConflictDoNothing();
|
|
1035
|
+
console.warn("[vitehub] Comments could not post the pull request summary:", error);
|
|
1036
|
+
return;
|
|
1037
|
+
}
|
|
1038
|
+
thread = await store.get(threadId);
|
|
1039
|
+
const live = new Set(thread?.messages.map((comment) => comment.id) ?? []);
|
|
1040
|
+
for (const gone of rows.filter((item) => !live.has(item.id))) await removeLink(gone, token);
|
|
1041
|
+
if (thread) {
|
|
1042
|
+
for (const comment of thread.messages) {
|
|
1043
|
+
if (await store.threadOf(comment.id) !== threadId) continue;
|
|
1044
|
+
await syncComment(thread, comment, rows.find((item) => item.id === comment.id), at, token);
|
|
1045
|
+
}
|
|
1046
|
+
while (true) {
|
|
1047
|
+
const latest = await store.get(threadId);
|
|
1048
|
+
if (!latest) break;
|
|
1049
|
+
const first = await row(latest.messages[0]?.id ?? "");
|
|
1050
|
+
const resolved = latest.status === "resolved";
|
|
1051
|
+
if (!first?.nodeId || first.minimized === resolved) break;
|
|
1052
|
+
try {
|
|
1053
|
+
await github.minimize(await token(), first.nodeId, resolved);
|
|
1054
|
+
await save(first.id, { minimized: resolved });
|
|
1055
|
+
} catch (error) {
|
|
1056
|
+
await save(first.id, { error: message(error) });
|
|
1057
|
+
console.warn(`[vitehub] Comments could not ${resolved ? "hide" : "show"} the comment of thread ${thread.id}:`, error);
|
|
1058
|
+
break;
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
const latest = await store.get(threadId);
|
|
1063
|
+
const remaining = new Set(latest?.messages.map((comment) => comment.id) ?? []);
|
|
1064
|
+
for (const gone of (await rowsOfThread(threadId)).filter((item) => !remaining.has(item.id))) await removeLink(gone, token);
|
|
1065
|
+
await syncSummary(at);
|
|
1066
|
+
}
|
|
1067
|
+
return {
|
|
1068
|
+
async sync(threadId) {
|
|
1069
|
+
await inOrder(`thread:${threadId}`, () => syncThread(threadId));
|
|
1070
|
+
},
|
|
1071
|
+
async attach(threads) {
|
|
1072
|
+
if (!threads.length) return threads;
|
|
1073
|
+
const rows = await database.select().from(links).where(inArray(links.threadId, threads.map((thread) => thread.id)));
|
|
1074
|
+
const byId = new Map(rows.map((item) => [item.id, item]));
|
|
1075
|
+
return threads.map((thread) => {
|
|
1076
|
+
return {
|
|
1077
|
+
...thread,
|
|
1078
|
+
forge: linkOf(thread, byId)
|
|
1079
|
+
};
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
//#endregion
|
|
1085
|
+
//#region src/install.ts
|
|
1086
|
+
var install_exports = /* @__PURE__ */ __exportAll({ installComments: () => installComments });
|
|
1087
|
+
/** The store, after the tables are ready: each method waits for `ready` first. */
|
|
1088
|
+
function gated(store, ready) {
|
|
1089
|
+
const wrapped = {};
|
|
1090
|
+
for (const key of Object.keys(store)) {
|
|
1091
|
+
const method = store[key];
|
|
1092
|
+
wrapped[key] = async (...args) => {
|
|
1093
|
+
await ready();
|
|
1094
|
+
return method(...args);
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
return wrapped;
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Connects a Comments definition to its Database, for the server API, the overlay API, and the comment operations.
|
|
1101
|
+
* The generated Nitro plugin calls it on the first Comments call; call it yourself only in tests or outside ViteHub.
|
|
1102
|
+
*/
|
|
1103
|
+
function installComments(comments, install) {
|
|
1104
|
+
const tables = install.tables ?? {
|
|
1105
|
+
commentCounters: commentsSchema.vitehubCommentCounters,
|
|
1106
|
+
commentMessages: commentsSchema.vitehubCommentMessages,
|
|
1107
|
+
commentThreads: commentsSchema.vitehubCommentThreads
|
|
1108
|
+
};
|
|
1109
|
+
const store = gated(createCommentsStore(install.database, tables), commentsSchemaGate(install.database, install.schema ?? "app", { dialect: install.dialect ?? "sqlite" }));
|
|
1110
|
+
const pending = Reflect.get(comments, pendingKey);
|
|
1111
|
+
const track = (task) => {
|
|
1112
|
+
if (!pending) return;
|
|
1113
|
+
const tracked = task.catch(() => void 0).finally(() => pending.delete(tracked));
|
|
1114
|
+
pending.add(tracked);
|
|
1115
|
+
};
|
|
1116
|
+
const { identify } = comments.options;
|
|
1117
|
+
const runtime = {
|
|
1118
|
+
background: track,
|
|
1119
|
+
definition: comments.options,
|
|
1120
|
+
...identify ? { identify: async (event) => {
|
|
1121
|
+
const requestEvent = event;
|
|
1122
|
+
getStandardContext(requestEvent);
|
|
1123
|
+
return await identify({ event: requestEvent }) ?? null;
|
|
1124
|
+
} } : {},
|
|
1125
|
+
...install.development === void 0 ? {} : { development: install.development },
|
|
1126
|
+
store,
|
|
1127
|
+
...install.users ? { users: install.users } : {},
|
|
1128
|
+
...install.attachments ? { attachments: install.attachments } : {},
|
|
1129
|
+
...install.rateLimit ? { rateLimit: install.rateLimit } : {}
|
|
1130
|
+
};
|
|
1131
|
+
let sync;
|
|
1132
|
+
if (comments.options.forge) {
|
|
1133
|
+
const forge = createForgeSync(comments.options.forge, {
|
|
1134
|
+
database: install.database,
|
|
1135
|
+
store,
|
|
1136
|
+
...install.tables?.commentForge ? { table: install.tables.commentForge } : {}
|
|
1137
|
+
});
|
|
1138
|
+
sync = forge.sync;
|
|
1139
|
+
runtime.forge = {
|
|
1140
|
+
attach: forge.attach,
|
|
1141
|
+
changed(threadId) {
|
|
1142
|
+
track(forge.sync(threadId).catch((error) => console.error(`[vitehub] Comments could not sync thread ${threadId} to its pull request:`, error)));
|
|
1143
|
+
}
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
runtimes.set(comments, {
|
|
1147
|
+
runtime,
|
|
1148
|
+
...sync ? { sync } : {}
|
|
1149
|
+
});
|
|
1150
|
+
installCommentsRuntime(runtime);
|
|
1151
|
+
return runtime;
|
|
1152
|
+
}
|
|
1153
|
+
//#endregion
|
|
1154
|
+
export { install_exports as n, createCommentsStore as r, installComments as t };
|