context-drop 0.0.0-stage → 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/MIT-LICENSE +21 -0
- package/README.md +710 -2
- package/app/assets/javascripts/context_drop/context_drop.js +9949 -0
- package/dist/app/javascript/context_drop/api-client.d.ts +53 -0
- package/dist/app/javascript/context_drop/api-client.js +470 -0
- package/dist/app/javascript/context_drop/element-picker.d.ts +111 -0
- package/dist/app/javascript/context_drop/element-picker.js +1428 -0
- package/dist/app/javascript/context_drop/icons.d.ts +34 -0
- package/dist/app/javascript/context_drop/icons.js +34 -0
- package/dist/app/javascript/context_drop/index.d.ts +7 -0
- package/dist/app/javascript/context_drop/index.js +9 -0
- package/dist/app/javascript/context_drop/markdown.d.ts +7 -0
- package/dist/app/javascript/context_drop/markdown.js +129 -0
- package/dist/app/javascript/context_drop/sanitizer.d.ts +38 -0
- package/dist/app/javascript/context_drop/sanitizer.js +769 -0
- package/dist/app/javascript/context_drop/screenshot.d.ts +21 -0
- package/dist/app/javascript/context_drop/screenshot.js +245 -0
- package/dist/app/javascript/context_drop/styles.d.ts +1 -0
- package/dist/app/javascript/context_drop/styles.js +2196 -0
- package/dist/app/javascript/context_drop/types.d.ts +316 -0
- package/dist/app/javascript/context_drop/types.js +1 -0
- package/dist/app/javascript/context_drop/widget.d.ts +206 -0
- package/dist/app/javascript/context_drop/widget.js +3752 -0
- package/dist/src/cli.d.ts +3 -0
- package/dist/src/cli.js +207 -0
- package/dist/src/index.d.ts +5 -0
- package/dist/src/index.js +5 -0
- package/dist/src/mcp/dispatcher.d.ts +42 -0
- package/dist/src/mcp/dispatcher.js +895 -0
- package/dist/src/mcp/environment-router.d.ts +38 -0
- package/dist/src/mcp/environment-router.js +174 -0
- package/dist/src/mcp/index.d.ts +24 -0
- package/dist/src/mcp/index.js +75 -0
- package/dist/src/mcp/remote-client.d.ts +25 -0
- package/dist/src/mcp/remote-client.js +98 -0
- package/dist/src/next/index.d.ts +13 -0
- package/dist/src/next/index.js +25 -0
- package/dist/src/next/server.d.ts +1 -0
- package/dist/src/next/server.js +1 -0
- package/dist/src/react/index.d.ts +104 -0
- package/dist/src/react/index.js +144 -0
- package/dist/src/server/handler.d.ts +48 -0
- package/dist/src/server/handler.js +1180 -0
- package/dist/src/server/index.d.ts +8 -0
- package/dist/src/server/index.js +8 -0
- package/dist/src/server/sanitizer.d.ts +15 -0
- package/dist/src/server/sanitizer.js +201 -0
- package/dist/src/server/storage/local.d.ts +22 -0
- package/dist/src/server/storage/local.js +827 -0
- package/dist/src/server/storage/memory.d.ts +8 -0
- package/dist/src/server/storage/memory.js +387 -0
- package/dist/src/server/storage/postgres.d.ts +27 -0
- package/dist/src/server/storage/postgres.js +629 -0
- package/dist/src/server/types.d.ts +227 -0
- package/dist/src/server/types.js +7 -0
- package/dist/src/server/upload-validator.d.ts +16 -0
- package/dist/src/server/upload-validator.js +196 -0
- package/dist/src/widget/index.d.ts +1 -0
- package/dist/src/widget/index.js +1 -0
- package/package.json +99 -4
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { hasAuthenticatedSubmitter, toFeedbackSummary } from "./memory.js";
|
|
3
|
+
function resolvePgSecret(explicit) {
|
|
4
|
+
const raw = explicit ||
|
|
5
|
+
process.env.CONTEXT_DROP_SECRET ||
|
|
6
|
+
process.env.NEXTAUTH_SECRET ||
|
|
7
|
+
process.env.AUTH_SECRET ||
|
|
8
|
+
"context-drop-default-pg-blob-secret";
|
|
9
|
+
return crypto.createHash("sha256").update(raw).digest();
|
|
10
|
+
}
|
|
11
|
+
function toIsoString(val) {
|
|
12
|
+
if (val instanceof Date)
|
|
13
|
+
return val.toISOString();
|
|
14
|
+
if (typeof val === "string") {
|
|
15
|
+
const parsed = Date.parse(val);
|
|
16
|
+
return Number.isNaN(parsed) ? val : new Date(parsed).toISOString();
|
|
17
|
+
}
|
|
18
|
+
return new Date().toISOString();
|
|
19
|
+
}
|
|
20
|
+
function parseJsonColumn(val, fallback) {
|
|
21
|
+
if (val === null || val === undefined)
|
|
22
|
+
return fallback;
|
|
23
|
+
if (typeof val === "object")
|
|
24
|
+
return val;
|
|
25
|
+
if (typeof val === "string") {
|
|
26
|
+
try {
|
|
27
|
+
return JSON.parse(val);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return fallback;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return fallback;
|
|
34
|
+
}
|
|
35
|
+
function toUint8Array(val) {
|
|
36
|
+
if (!val)
|
|
37
|
+
return null;
|
|
38
|
+
if (val instanceof Uint8Array)
|
|
39
|
+
return new Uint8Array(val);
|
|
40
|
+
if (Buffer.isBuffer(val))
|
|
41
|
+
return new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
export function createPostgresStorageAdapter(options) {
|
|
45
|
+
const { pool, autoMigrate = true, blobStore } = options;
|
|
46
|
+
const secretKey = resolvePgSecret(options.secret);
|
|
47
|
+
let migratedPromise = null;
|
|
48
|
+
function signId(rawId) {
|
|
49
|
+
const sig = crypto.createHmac("sha256", secretKey).update(rawId).digest("hex");
|
|
50
|
+
return `${rawId}.${sig}`;
|
|
51
|
+
}
|
|
52
|
+
function verifySignedId(token) {
|
|
53
|
+
const dotIdx = token.lastIndexOf(".");
|
|
54
|
+
if (dotIdx <= 0)
|
|
55
|
+
return null;
|
|
56
|
+
const rawId = token.slice(0, dotIdx);
|
|
57
|
+
const provided = token.slice(dotIdx + 1);
|
|
58
|
+
const expected = crypto.createHmac("sha256", secretKey).update(rawId).digest("hex");
|
|
59
|
+
if (provided.length !== expected.length)
|
|
60
|
+
return null;
|
|
61
|
+
if (!crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(expected))) {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
return rawId;
|
|
65
|
+
}
|
|
66
|
+
async function ensureMigrated() {
|
|
67
|
+
if (!autoMigrate)
|
|
68
|
+
return;
|
|
69
|
+
if (!migratedPromise) {
|
|
70
|
+
migratedPromise = (async () => {
|
|
71
|
+
await pool.query(`
|
|
72
|
+
CREATE TABLE IF NOT EXISTS context_drop_pending_blobs (
|
|
73
|
+
id TEXT PRIMARY KEY,
|
|
74
|
+
filename TEXT NOT NULL,
|
|
75
|
+
content_type TEXT NOT NULL,
|
|
76
|
+
byte_size INTEGER NOT NULL,
|
|
77
|
+
dimensions_json JSONB,
|
|
78
|
+
blob_key TEXT,
|
|
79
|
+
data BYTEA,
|
|
80
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
81
|
+
);
|
|
82
|
+
`);
|
|
83
|
+
await pool.query(`
|
|
84
|
+
CREATE TABLE IF NOT EXISTS context_drop_feedbacks (
|
|
85
|
+
id BIGSERIAL PRIMARY KEY,
|
|
86
|
+
environment TEXT NOT NULL DEFAULT 'production',
|
|
87
|
+
status TEXT NOT NULL DEFAULT 'new',
|
|
88
|
+
message TEXT,
|
|
89
|
+
page_url TEXT NOT NULL,
|
|
90
|
+
user_agent TEXT,
|
|
91
|
+
session_id TEXT,
|
|
92
|
+
submitter JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
93
|
+
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
94
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
95
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
96
|
+
deleted_at TIMESTAMPTZ
|
|
97
|
+
);
|
|
98
|
+
`);
|
|
99
|
+
await pool.query(`
|
|
100
|
+
ALTER TABLE context_drop_feedbacks
|
|
101
|
+
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
|
|
102
|
+
`);
|
|
103
|
+
await pool.query(`
|
|
104
|
+
CREATE INDEX IF NOT EXISTS idx_context_drop_feedbacks_env_status
|
|
105
|
+
ON context_drop_feedbacks (environment, status, created_at DESC);
|
|
106
|
+
`);
|
|
107
|
+
await pool.query(`
|
|
108
|
+
CREATE TABLE IF NOT EXISTS context_drop_element_references (
|
|
109
|
+
id BIGSERIAL PRIMARY KEY,
|
|
110
|
+
feedback_id BIGINT NOT NULL REFERENCES context_drop_feedbacks(id) ON DELETE CASCADE,
|
|
111
|
+
client_ref TEXT,
|
|
112
|
+
tag_name TEXT NOT NULL,
|
|
113
|
+
selector TEXT NOT NULL,
|
|
114
|
+
dom_path TEXT,
|
|
115
|
+
text_content TEXT,
|
|
116
|
+
attributes_snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
117
|
+
bounding_rect JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
118
|
+
viewport JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
119
|
+
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
120
|
+
captured_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
121
|
+
);
|
|
122
|
+
`);
|
|
123
|
+
await pool.query(`
|
|
124
|
+
CREATE TABLE IF NOT EXISTS context_drop_attachments (
|
|
125
|
+
id BIGSERIAL PRIMARY KEY,
|
|
126
|
+
feedback_id BIGINT NOT NULL REFERENCES context_drop_feedbacks(id) ON DELETE CASCADE,
|
|
127
|
+
element_reference_id BIGINT REFERENCES context_drop_element_references(id) ON DELETE SET NULL,
|
|
128
|
+
attachment_type TEXT NOT NULL,
|
|
129
|
+
filename TEXT,
|
|
130
|
+
content_type TEXT,
|
|
131
|
+
byte_size INTEGER,
|
|
132
|
+
blob_key TEXT,
|
|
133
|
+
data BYTEA,
|
|
134
|
+
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
135
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
136
|
+
);
|
|
137
|
+
`);
|
|
138
|
+
})();
|
|
139
|
+
}
|
|
140
|
+
await migratedPromise;
|
|
141
|
+
}
|
|
142
|
+
async function hydrateFeedbackRow(row) {
|
|
143
|
+
const fbId = Number(row["id"]);
|
|
144
|
+
const [elRes, attRes] = await Promise.all([
|
|
145
|
+
pool.query(`SELECT id, feedback_id, client_ref, tag_name, selector, dom_path, text_content,
|
|
146
|
+
attributes_snapshot, bounding_rect, viewport, metadata, captured_at
|
|
147
|
+
FROM context_drop_element_references
|
|
148
|
+
WHERE feedback_id = $1
|
|
149
|
+
ORDER BY id ASC`, [fbId]),
|
|
150
|
+
pool.query(`SELECT id, feedback_id, element_reference_id, attachment_type, filename,
|
|
151
|
+
content_type, byte_size, blob_key, metadata, created_at
|
|
152
|
+
FROM context_drop_attachments
|
|
153
|
+
WHERE feedback_id = $1
|
|
154
|
+
ORDER BY id ASC`, [fbId])
|
|
155
|
+
]);
|
|
156
|
+
const elements = elRes.rows.map((el) => ({
|
|
157
|
+
id: Number(el["id"]),
|
|
158
|
+
feedback_id: fbId,
|
|
159
|
+
client_ref: el["client_ref"] ?? null,
|
|
160
|
+
tag_name: String(el["tag_name"]),
|
|
161
|
+
selector: String(el["selector"]),
|
|
162
|
+
dom_path: el["dom_path"] ?? null,
|
|
163
|
+
text_content: el["text_content"] ?? null,
|
|
164
|
+
attributes_snapshot: parseJsonColumn(el["attributes_snapshot"], {}),
|
|
165
|
+
bounding_rect: parseJsonColumn(el["bounding_rect"], {}),
|
|
166
|
+
viewport: parseJsonColumn(el["viewport"], {}),
|
|
167
|
+
metadata: parseJsonColumn(el["metadata"], {}),
|
|
168
|
+
captured_at: toIsoString(el["captured_at"])
|
|
169
|
+
}));
|
|
170
|
+
const attachments = attRes.rows.map((att) => ({
|
|
171
|
+
id: Number(att["id"]),
|
|
172
|
+
feedback_id: fbId,
|
|
173
|
+
element_reference_id: att["element_reference_id"] !== null && att["element_reference_id"] !== undefined
|
|
174
|
+
? Number(att["element_reference_id"])
|
|
175
|
+
: null,
|
|
176
|
+
attachment_type: att["attachment_type"] === "screenshot" ? "screenshot" : "image",
|
|
177
|
+
filename: att["filename"] ?? null,
|
|
178
|
+
content_type: att["content_type"] ?? null,
|
|
179
|
+
byte_size: att["byte_size"] !== null && att["byte_size"] !== undefined
|
|
180
|
+
? Number(att["byte_size"])
|
|
181
|
+
: null,
|
|
182
|
+
blob_key: att["blob_key"] ?? null,
|
|
183
|
+
metadata: parseJsonColumn(att["metadata"], {}),
|
|
184
|
+
created_at: toIsoString(att["created_at"])
|
|
185
|
+
}));
|
|
186
|
+
return {
|
|
187
|
+
id: fbId,
|
|
188
|
+
environment: String(row["environment"] ?? "production"),
|
|
189
|
+
status: String(row["status"] ?? "new"),
|
|
190
|
+
message: row["message"] ?? null,
|
|
191
|
+
page_url: String(row["page_url"] ?? ""),
|
|
192
|
+
user_agent: row["user_agent"] ?? null,
|
|
193
|
+
session_id: row["session_id"] ?? null,
|
|
194
|
+
submitter: parseJsonColumn(row["submitter"], {}),
|
|
195
|
+
metadata: parseJsonColumn(row["metadata"], {}),
|
|
196
|
+
element_references: elements,
|
|
197
|
+
attachments,
|
|
198
|
+
created_at: toIsoString(row["created_at"]),
|
|
199
|
+
updated_at: toIsoString(row["updated_at"]),
|
|
200
|
+
deleted_at: row["deleted_at"] ? toIsoString(row["deleted_at"]) : null
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
getOwnershipSecret() {
|
|
205
|
+
return secretKey;
|
|
206
|
+
},
|
|
207
|
+
async savePendingBlob(blob) {
|
|
208
|
+
await ensureMigrated();
|
|
209
|
+
const rawId = crypto.randomUUID();
|
|
210
|
+
let blobKey = null;
|
|
211
|
+
let inlineBytes = null;
|
|
212
|
+
if (blobStore) {
|
|
213
|
+
const stored = await blobStore.putBlob({
|
|
214
|
+
key: `pending_${rawId}`,
|
|
215
|
+
data: blob.data,
|
|
216
|
+
contentType: blob.content_type,
|
|
217
|
+
filename: blob.filename
|
|
218
|
+
});
|
|
219
|
+
blobKey = stored.key;
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
inlineBytes = Buffer.from(blob.data);
|
|
223
|
+
}
|
|
224
|
+
await pool.query(`INSERT INTO context_drop_pending_blobs
|
|
225
|
+
(id, filename, content_type, byte_size, dimensions_json, blob_key, data)
|
|
226
|
+
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)`, [
|
|
227
|
+
rawId,
|
|
228
|
+
blob.filename,
|
|
229
|
+
blob.content_type,
|
|
230
|
+
blob.byte_size,
|
|
231
|
+
blob.dimensions ? JSON.stringify(blob.dimensions) : null,
|
|
232
|
+
blobKey,
|
|
233
|
+
inlineBytes
|
|
234
|
+
]);
|
|
235
|
+
return { signed_blob_id: signId(rawId) };
|
|
236
|
+
},
|
|
237
|
+
async consumePendingBlob(signedBlobId) {
|
|
238
|
+
await ensureMigrated();
|
|
239
|
+
const rawId = verifySignedId(signedBlobId);
|
|
240
|
+
if (!rawId)
|
|
241
|
+
return null;
|
|
242
|
+
const res = await pool.query(`DELETE FROM context_drop_pending_blobs
|
|
243
|
+
WHERE id = $1
|
|
244
|
+
RETURNING filename, content_type, byte_size, dimensions_json, blob_key, data`, [rawId]);
|
|
245
|
+
const row = res.rows[0];
|
|
246
|
+
if (!row)
|
|
247
|
+
return null;
|
|
248
|
+
let bytes = null;
|
|
249
|
+
const blobKey = row["blob_key"] ?? null;
|
|
250
|
+
if (blobKey && blobStore) {
|
|
251
|
+
bytes = await blobStore.getBlob(blobKey);
|
|
252
|
+
if (blobStore.deleteBlob) {
|
|
253
|
+
await blobStore.deleteBlob(blobKey);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
bytes = toUint8Array(row["data"]);
|
|
258
|
+
}
|
|
259
|
+
if (!bytes)
|
|
260
|
+
return null;
|
|
261
|
+
return {
|
|
262
|
+
data: bytes,
|
|
263
|
+
filename: String(row["filename"]),
|
|
264
|
+
content_type: String(row["content_type"]),
|
|
265
|
+
byte_size: Number(row["byte_size"]),
|
|
266
|
+
dimensions: parseJsonColumn(row["dimensions_json"], null)
|
|
267
|
+
};
|
|
268
|
+
},
|
|
269
|
+
async createFeedback(input) {
|
|
270
|
+
await ensureMigrated();
|
|
271
|
+
const fbRes = await pool.query(`INSERT INTO context_drop_feedbacks
|
|
272
|
+
(environment, status, message, page_url, user_agent, session_id, submitter, metadata)
|
|
273
|
+
VALUES ($1, 'new', $2, $3, $4, $5, $6::jsonb, $7::jsonb)
|
|
274
|
+
RETURNING *`, [
|
|
275
|
+
input.environment,
|
|
276
|
+
input.message,
|
|
277
|
+
input.page_url,
|
|
278
|
+
input.user_agent,
|
|
279
|
+
input.session_id,
|
|
280
|
+
JSON.stringify(input.submitter || {}),
|
|
281
|
+
JSON.stringify(input.metadata || {})
|
|
282
|
+
]);
|
|
283
|
+
const fbRow = fbRes.rows[0];
|
|
284
|
+
const fbId = Number(fbRow["id"]);
|
|
285
|
+
const elIdByRef = new Map();
|
|
286
|
+
for (let idx = 0; idx < input.element_references.length; idx++) {
|
|
287
|
+
const el = input.element_references[idx];
|
|
288
|
+
const elRes = await pool.query(`INSERT INTO context_drop_element_references
|
|
289
|
+
(feedback_id, client_ref, tag_name, selector, dom_path, text_content,
|
|
290
|
+
attributes_snapshot, bounding_rect, viewport, metadata, captured_at)
|
|
291
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8::jsonb, $9::jsonb, $10::jsonb, $11::timestamptz)
|
|
292
|
+
RETURNING id`, [
|
|
293
|
+
fbId,
|
|
294
|
+
el.client_ref,
|
|
295
|
+
el.tag_name,
|
|
296
|
+
el.selector,
|
|
297
|
+
el.dom_path,
|
|
298
|
+
el.text_content,
|
|
299
|
+
JSON.stringify(el.attributes_snapshot || {}),
|
|
300
|
+
JSON.stringify(el.bounding_rect || {}),
|
|
301
|
+
JSON.stringify(el.viewport || {}),
|
|
302
|
+
JSON.stringify(el.metadata || {}),
|
|
303
|
+
el.captured_at
|
|
304
|
+
]);
|
|
305
|
+
const elId = Number(elRes.rows[0]["id"]);
|
|
306
|
+
elIdByRef.set(el.client_ref || String(idx), elId);
|
|
307
|
+
}
|
|
308
|
+
for (const att of input.attachments) {
|
|
309
|
+
const linkedElId = att.element_client_ref
|
|
310
|
+
? elIdByRef.get(att.element_client_ref) ?? null
|
|
311
|
+
: null;
|
|
312
|
+
let blobKey = null;
|
|
313
|
+
let inlineBytes = null;
|
|
314
|
+
if (att.data) {
|
|
315
|
+
if (blobStore) {
|
|
316
|
+
const saved = await blobStore.putBlob({
|
|
317
|
+
key: `att_${fbId}_${crypto.randomUUID()}`,
|
|
318
|
+
data: att.data,
|
|
319
|
+
contentType: att.content_type || "image/png",
|
|
320
|
+
filename: att.filename || "attachment.png"
|
|
321
|
+
});
|
|
322
|
+
blobKey = saved.key;
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
inlineBytes = Buffer.from(att.data);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
await pool.query(`INSERT INTO context_drop_attachments
|
|
329
|
+
(feedback_id, element_reference_id, attachment_type, filename, content_type, byte_size, blob_key, data, metadata)
|
|
330
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb)`, [
|
|
331
|
+
fbId,
|
|
332
|
+
linkedElId,
|
|
333
|
+
att.attachment_type,
|
|
334
|
+
att.filename,
|
|
335
|
+
att.content_type,
|
|
336
|
+
att.byte_size,
|
|
337
|
+
blobKey,
|
|
338
|
+
inlineBytes,
|
|
339
|
+
JSON.stringify(att.metadata || {})
|
|
340
|
+
]);
|
|
341
|
+
}
|
|
342
|
+
return hydrateFeedbackRow(fbRow);
|
|
343
|
+
},
|
|
344
|
+
async listFeedbacks(filter) {
|
|
345
|
+
await ensureMigrated();
|
|
346
|
+
const limit = Math.max(1, Math.min(100, filter.limit ?? 20));
|
|
347
|
+
const offset = Math.max(0, filter.offset ?? 0);
|
|
348
|
+
const clauses = [];
|
|
349
|
+
const values = [];
|
|
350
|
+
if (!filter.include_deleted) {
|
|
351
|
+
clauses.push("f.deleted_at IS NULL");
|
|
352
|
+
}
|
|
353
|
+
if (filter.environment && filter.environment.trim().length > 0) {
|
|
354
|
+
values.push(filter.environment.trim().toLowerCase());
|
|
355
|
+
clauses.push(`LOWER(f.environment) = $${values.length}`);
|
|
356
|
+
}
|
|
357
|
+
if (filter.status) {
|
|
358
|
+
values.push(filter.status);
|
|
359
|
+
clauses.push(`f.status = $${values.length}`);
|
|
360
|
+
}
|
|
361
|
+
if (filter.page_url && filter.page_url.trim().length > 0) {
|
|
362
|
+
values.push(`%${filter.page_url.trim()}%`);
|
|
363
|
+
clauses.push(`f.page_url ILIKE $${values.length}`);
|
|
364
|
+
}
|
|
365
|
+
if (filter.query && filter.query.trim().length > 0) {
|
|
366
|
+
values.push(`%${filter.query.trim()}%`);
|
|
367
|
+
const p = `$${values.length}`;
|
|
368
|
+
clauses.push(`(f.message ILIKE ${p} OR EXISTS (
|
|
369
|
+
SELECT 1 FROM context_drop_element_references e
|
|
370
|
+
WHERE e.feedback_id = f.id
|
|
371
|
+
AND (e.selector ILIKE ${p} OR e.dom_path ILIKE ${p} OR e.text_content ILIKE ${p})
|
|
372
|
+
))`);
|
|
373
|
+
}
|
|
374
|
+
const whereSql = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
375
|
+
const countRes = await pool.query(`SELECT COUNT(*)::int AS total FROM context_drop_feedbacks f ${whereSql}`, values);
|
|
376
|
+
const total = Number(countRes.rows[0]?.["total"] ?? 0);
|
|
377
|
+
const pageValues = [...values, limit, offset];
|
|
378
|
+
const rowsRes = await pool.query(`SELECT f.* FROM context_drop_feedbacks f ${whereSql}
|
|
379
|
+
ORDER BY f.created_at DESC, f.id DESC
|
|
380
|
+
LIMIT $${pageValues.length - 1} OFFSET $${pageValues.length}`, pageValues);
|
|
381
|
+
const hydrated = await Promise.all(rowsRes.rows.map(hydrateFeedbackRow));
|
|
382
|
+
return {
|
|
383
|
+
total,
|
|
384
|
+
records: hydrated.map(toFeedbackSummary)
|
|
385
|
+
};
|
|
386
|
+
},
|
|
387
|
+
async listOwnFeedbacks(query) {
|
|
388
|
+
await ensureMigrated();
|
|
389
|
+
const limit = Math.max(1, Math.min(50, query.limit ?? 20));
|
|
390
|
+
const ownershipClauses = [];
|
|
391
|
+
const values = [];
|
|
392
|
+
if (hasAuthenticatedSubmitter(query.submitter)) {
|
|
393
|
+
values.push(String(query.submitter?.type || "User").trim());
|
|
394
|
+
const typeParam = `$${values.length}`;
|
|
395
|
+
values.push(String(query.submitter?.id).trim());
|
|
396
|
+
const idParam = `$${values.length}`;
|
|
397
|
+
ownershipClauses.push(`(COALESCE(NULLIF(f.submitter->>'type', ''), 'User') = ${typeParam} AND f.submitter->>'id' = ${idParam})`);
|
|
398
|
+
}
|
|
399
|
+
if (query.session_id && query.session_id.trim().length > 0) {
|
|
400
|
+
values.push(query.session_id.trim());
|
|
401
|
+
const sidParam = `$${values.length}`;
|
|
402
|
+
ownershipClauses.push(`((f.submitter->>'id' IS NULL OR f.submitter->>'id' = '') AND f.session_id = ${sidParam})`);
|
|
403
|
+
}
|
|
404
|
+
const numericTokenIds = (query.token_ids ?? [])
|
|
405
|
+
.map((t) => Number(t))
|
|
406
|
+
.filter((n) => Number.isInteger(n) && n > 0);
|
|
407
|
+
if (numericTokenIds.length > 0) {
|
|
408
|
+
values.push(numericTokenIds);
|
|
409
|
+
const idsParam = `$${values.length}`;
|
|
410
|
+
ownershipClauses.push(`((f.submitter->>'id' IS NULL OR f.submitter->>'id' = '') AND f.id = ANY(${idsParam}::bigint[]))`);
|
|
411
|
+
}
|
|
412
|
+
if (ownershipClauses.length === 0) {
|
|
413
|
+
return { total: 0, records: [] };
|
|
414
|
+
}
|
|
415
|
+
const whereSql = `WHERE f.deleted_at IS NULL AND (${ownershipClauses.join(" OR ")})`;
|
|
416
|
+
const countRes = await pool.query(`SELECT COUNT(*)::int AS total FROM context_drop_feedbacks f ${whereSql}`, values);
|
|
417
|
+
const total = Number(countRes.rows[0]?.["total"] ?? 0);
|
|
418
|
+
const pageValues = [...values, limit];
|
|
419
|
+
const rowsRes = await pool.query(`SELECT f.* FROM context_drop_feedbacks f ${whereSql}
|
|
420
|
+
ORDER BY f.created_at DESC, f.id DESC
|
|
421
|
+
LIMIT $${pageValues.length}`, pageValues);
|
|
422
|
+
const hydrated = await Promise.all(rowsRes.rows.map(hydrateFeedbackRow));
|
|
423
|
+
return {
|
|
424
|
+
total,
|
|
425
|
+
records: hydrated
|
|
426
|
+
};
|
|
427
|
+
},
|
|
428
|
+
async getFeedback(id) {
|
|
429
|
+
await ensureMigrated();
|
|
430
|
+
const res = await pool.query("SELECT * FROM context_drop_feedbacks WHERE id = $1", [
|
|
431
|
+
Number(id)
|
|
432
|
+
]);
|
|
433
|
+
const row = res.rows[0];
|
|
434
|
+
if (!row)
|
|
435
|
+
return null;
|
|
436
|
+
return hydrateFeedbackRow(row);
|
|
437
|
+
},
|
|
438
|
+
async updateFeedback(id, input) {
|
|
439
|
+
await ensureMigrated();
|
|
440
|
+
const fbId = Number(id);
|
|
441
|
+
const existing = await this.getFeedback(fbId);
|
|
442
|
+
if (!existing || existing.deleted_at)
|
|
443
|
+
return null;
|
|
444
|
+
const nextMessage = input.message !== undefined ? input.message : existing.message;
|
|
445
|
+
const nextMetadata = input.metadata !== undefined ? input.metadata : existing.metadata;
|
|
446
|
+
await pool.query(`UPDATE context_drop_feedbacks
|
|
447
|
+
SET message = $1, metadata = $2::jsonb, updated_at = NOW()
|
|
448
|
+
WHERE id = $3`, [nextMessage, JSON.stringify(nextMetadata || {}), fbId]);
|
|
449
|
+
const elIdByRef = new Map();
|
|
450
|
+
if (input.element_references !== undefined) {
|
|
451
|
+
await pool.query("DELETE FROM context_drop_element_references WHERE feedback_id = $1", [fbId]);
|
|
452
|
+
for (let idx = 0; idx < input.element_references.length; idx++) {
|
|
453
|
+
const el = input.element_references[idx];
|
|
454
|
+
const elRes = await pool.query(`INSERT INTO context_drop_element_references
|
|
455
|
+
(feedback_id, client_ref, tag_name, selector, dom_path, text_content,
|
|
456
|
+
attributes_snapshot, bounding_rect, viewport, metadata, captured_at)
|
|
457
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8::jsonb, $9::jsonb, $10::jsonb, $11::timestamptz)
|
|
458
|
+
RETURNING id`, [
|
|
459
|
+
fbId,
|
|
460
|
+
el.client_ref,
|
|
461
|
+
el.tag_name,
|
|
462
|
+
el.selector,
|
|
463
|
+
el.dom_path,
|
|
464
|
+
el.text_content,
|
|
465
|
+
JSON.stringify(el.attributes_snapshot || {}),
|
|
466
|
+
JSON.stringify(el.bounding_rect || {}),
|
|
467
|
+
JSON.stringify(el.viewport || {}),
|
|
468
|
+
JSON.stringify(el.metadata || {}),
|
|
469
|
+
el.captured_at
|
|
470
|
+
]);
|
|
471
|
+
elIdByRef.set(el.client_ref || String(idx), Number(elRes.rows[0]["id"]));
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
else {
|
|
475
|
+
existing.element_references.forEach((el, idx) => {
|
|
476
|
+
elIdByRef.set(el.client_ref || String(idx), Number(el.id));
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
if (input.attachments !== undefined) {
|
|
480
|
+
const retainedIds = new Set();
|
|
481
|
+
const prevById = new Map();
|
|
482
|
+
for (const a of existing.attachments) {
|
|
483
|
+
prevById.set(String(a.id), a);
|
|
484
|
+
}
|
|
485
|
+
for (const spec of input.attachments) {
|
|
486
|
+
if (spec.kind === "retain") {
|
|
487
|
+
const prev = prevById.get(String(spec.existing_id));
|
|
488
|
+
if (!prev)
|
|
489
|
+
continue;
|
|
490
|
+
retainedIds.add(Number(prev.id));
|
|
491
|
+
const linkedElId = spec.element_client_ref !== undefined
|
|
492
|
+
? spec.element_client_ref
|
|
493
|
+
? elIdByRef.get(spec.element_client_ref) ?? null
|
|
494
|
+
: null
|
|
495
|
+
: input.element_references === undefined && prev.element_reference_id !== null
|
|
496
|
+
? Number(prev.element_reference_id)
|
|
497
|
+
: null;
|
|
498
|
+
const nextAttMeta = spec.update_metadata && spec.metadata ? spec.metadata : prev.metadata;
|
|
499
|
+
await pool.query(`UPDATE context_drop_attachments
|
|
500
|
+
SET element_reference_id = $1, metadata = $2::jsonb
|
|
501
|
+
WHERE id = $3`, [linkedElId, JSON.stringify(nextAttMeta || {}), Number(prev.id)]);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
for (const prev of existing.attachments) {
|
|
505
|
+
if (!retainedIds.has(Number(prev.id))) {
|
|
506
|
+
await pool.query("DELETE FROM context_drop_attachments WHERE id = $1", [
|
|
507
|
+
Number(prev.id)
|
|
508
|
+
]);
|
|
509
|
+
if (prev.blob_key && blobStore?.deleteBlob) {
|
|
510
|
+
await blobStore.deleteBlob(prev.blob_key);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
for (const spec of input.attachments) {
|
|
515
|
+
if (spec.kind !== "create")
|
|
516
|
+
continue;
|
|
517
|
+
const linkedElId = spec.element_client_ref
|
|
518
|
+
? elIdByRef.get(spec.element_client_ref) ?? null
|
|
519
|
+
: null;
|
|
520
|
+
let blobKey = null;
|
|
521
|
+
let inlineBytes = null;
|
|
522
|
+
if (spec.data) {
|
|
523
|
+
if (blobStore) {
|
|
524
|
+
const saved = await blobStore.putBlob({
|
|
525
|
+
key: `att_${fbId}_${crypto.randomUUID()}`,
|
|
526
|
+
data: spec.data,
|
|
527
|
+
contentType: spec.content_type || "image/png",
|
|
528
|
+
filename: spec.filename || "attachment.png"
|
|
529
|
+
});
|
|
530
|
+
blobKey = saved.key;
|
|
531
|
+
}
|
|
532
|
+
else {
|
|
533
|
+
inlineBytes = Buffer.from(spec.data);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
await pool.query(`INSERT INTO context_drop_attachments
|
|
537
|
+
(feedback_id, element_reference_id, attachment_type, filename, content_type, byte_size, blob_key, data, metadata)
|
|
538
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb)`, [
|
|
539
|
+
fbId,
|
|
540
|
+
linkedElId,
|
|
541
|
+
spec.attachment_type,
|
|
542
|
+
spec.filename,
|
|
543
|
+
spec.content_type,
|
|
544
|
+
spec.byte_size,
|
|
545
|
+
blobKey,
|
|
546
|
+
inlineBytes,
|
|
547
|
+
JSON.stringify(spec.metadata || {})
|
|
548
|
+
]);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return this.getFeedback(fbId);
|
|
552
|
+
},
|
|
553
|
+
async softDeleteFeedback(id) {
|
|
554
|
+
await ensureMigrated();
|
|
555
|
+
const fbId = Number(id);
|
|
556
|
+
const existing = await this.getFeedback(fbId);
|
|
557
|
+
if (!existing || existing.deleted_at)
|
|
558
|
+
return null;
|
|
559
|
+
const res = await pool.query(`UPDATE context_drop_feedbacks
|
|
560
|
+
SET deleted_at = NOW(), updated_at = NOW()
|
|
561
|
+
WHERE id = $1 AND deleted_at IS NULL
|
|
562
|
+
RETURNING *`, [fbId]);
|
|
563
|
+
const row = res.rows[0];
|
|
564
|
+
if (!row)
|
|
565
|
+
return null;
|
|
566
|
+
return hydrateFeedbackRow(row);
|
|
567
|
+
},
|
|
568
|
+
async getAttachment(attachmentId) {
|
|
569
|
+
await ensureMigrated();
|
|
570
|
+
const res = await pool.query(`SELECT a.*, e.selector AS element_selector
|
|
571
|
+
FROM context_drop_attachments a
|
|
572
|
+
LEFT JOIN context_drop_element_references e ON e.id = a.element_reference_id
|
|
573
|
+
WHERE a.id = $1`, [Number(attachmentId)]);
|
|
574
|
+
const row = res.rows[0];
|
|
575
|
+
if (!row)
|
|
576
|
+
return null;
|
|
577
|
+
const blobKey = row["blob_key"] ?? null;
|
|
578
|
+
let bytes = null;
|
|
579
|
+
if (blobKey && blobStore) {
|
|
580
|
+
bytes = await blobStore.getBlob(blobKey);
|
|
581
|
+
}
|
|
582
|
+
else {
|
|
583
|
+
bytes = toUint8Array(row["data"]);
|
|
584
|
+
}
|
|
585
|
+
const attachment = {
|
|
586
|
+
id: Number(row["id"]),
|
|
587
|
+
feedback_id: Number(row["feedback_id"]),
|
|
588
|
+
element_reference_id: row["element_reference_id"] !== null && row["element_reference_id"] !== undefined
|
|
589
|
+
? Number(row["element_reference_id"])
|
|
590
|
+
: null,
|
|
591
|
+
attachment_type: row["attachment_type"] === "screenshot" ? "screenshot" : "image",
|
|
592
|
+
filename: row["filename"] ?? null,
|
|
593
|
+
content_type: row["content_type"] ?? null,
|
|
594
|
+
byte_size: row["byte_size"] !== null && row["byte_size"] !== undefined
|
|
595
|
+
? Number(row["byte_size"])
|
|
596
|
+
: null,
|
|
597
|
+
blob_key: blobKey,
|
|
598
|
+
metadata: parseJsonColumn(row["metadata"], {}),
|
|
599
|
+
created_at: toIsoString(row["created_at"])
|
|
600
|
+
};
|
|
601
|
+
return {
|
|
602
|
+
attachment,
|
|
603
|
+
element_selector: row["element_selector"] ?? null,
|
|
604
|
+
data: bytes
|
|
605
|
+
};
|
|
606
|
+
},
|
|
607
|
+
async getAttachmentBytes(attachmentId) {
|
|
608
|
+
const res = await this.getAttachment(attachmentId);
|
|
609
|
+
return res?.data ?? null;
|
|
610
|
+
},
|
|
611
|
+
async updateFeedbackStatus(id, status) {
|
|
612
|
+
await ensureMigrated();
|
|
613
|
+
const existing = await this.getFeedback(id);
|
|
614
|
+
if (!existing || existing.deleted_at)
|
|
615
|
+
return null;
|
|
616
|
+
const res = await pool.query(`UPDATE context_drop_feedbacks
|
|
617
|
+
SET status = $1, updated_at = NOW()
|
|
618
|
+
WHERE id = $2
|
|
619
|
+
RETURNING *`, [status, Number(id)]);
|
|
620
|
+
const row = res.rows[0];
|
|
621
|
+
if (!row)
|
|
622
|
+
return null;
|
|
623
|
+
return {
|
|
624
|
+
previous_status: existing.status,
|
|
625
|
+
feedback: await hydrateFeedbackRow(row)
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
}
|