context-drop 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/MIT-LICENSE +21 -0
  2. package/README.md +709 -2
  3. package/app/assets/javascripts/context_drop/context_drop.js +8936 -0
  4. package/dist/app/javascript/context_drop/api-client.d.ts +41 -0
  5. package/dist/app/javascript/context_drop/api-client.js +279 -0
  6. package/dist/app/javascript/context_drop/element-picker.d.ts +111 -0
  7. package/dist/app/javascript/context_drop/element-picker.js +1428 -0
  8. package/dist/app/javascript/context_drop/icons.d.ts +32 -0
  9. package/dist/app/javascript/context_drop/icons.js +32 -0
  10. package/dist/app/javascript/context_drop/index.d.ts +7 -0
  11. package/dist/app/javascript/context_drop/index.js +9 -0
  12. package/dist/app/javascript/context_drop/markdown.d.ts +7 -0
  13. package/dist/app/javascript/context_drop/markdown.js +129 -0
  14. package/dist/app/javascript/context_drop/sanitizer.d.ts +38 -0
  15. package/dist/app/javascript/context_drop/sanitizer.js +769 -0
  16. package/dist/app/javascript/context_drop/screenshot.d.ts +21 -0
  17. package/dist/app/javascript/context_drop/screenshot.js +245 -0
  18. package/dist/app/javascript/context_drop/styles.d.ts +1 -0
  19. package/dist/app/javascript/context_drop/styles.js +2015 -0
  20. package/dist/app/javascript/context_drop/types.d.ts +239 -0
  21. package/dist/app/javascript/context_drop/types.js +1 -0
  22. package/dist/app/javascript/context_drop/widget.d.ts +188 -0
  23. package/dist/app/javascript/context_drop/widget.js +3227 -0
  24. package/dist/src/cli.d.ts +3 -0
  25. package/dist/src/cli.js +207 -0
  26. package/dist/src/index.d.ts +5 -0
  27. package/dist/src/index.js +5 -0
  28. package/dist/src/mcp/dispatcher.d.ts +42 -0
  29. package/dist/src/mcp/dispatcher.js +869 -0
  30. package/dist/src/mcp/environment-router.d.ts +38 -0
  31. package/dist/src/mcp/environment-router.js +174 -0
  32. package/dist/src/mcp/index.d.ts +24 -0
  33. package/dist/src/mcp/index.js +75 -0
  34. package/dist/src/mcp/remote-client.d.ts +25 -0
  35. package/dist/src/mcp/remote-client.js +98 -0
  36. package/dist/src/next/index.d.ts +13 -0
  37. package/dist/src/next/index.js +25 -0
  38. package/dist/src/next/server.d.ts +1 -0
  39. package/dist/src/next/server.js +1 -0
  40. package/dist/src/react/index.d.ts +90 -0
  41. package/dist/src/react/index.js +124 -0
  42. package/dist/src/server/handler.d.ts +42 -0
  43. package/dist/src/server/handler.js +677 -0
  44. package/dist/src/server/index.d.ts +8 -0
  45. package/dist/src/server/index.js +8 -0
  46. package/dist/src/server/sanitizer.d.ts +15 -0
  47. package/dist/src/server/sanitizer.js +201 -0
  48. package/dist/src/server/storage/local.d.ts +22 -0
  49. package/dist/src/server/storage/local.js +574 -0
  50. package/dist/src/server/storage/memory.d.ts +5 -0
  51. package/dist/src/server/storage/memory.js +221 -0
  52. package/dist/src/server/storage/postgres.d.ts +27 -0
  53. package/dist/src/server/storage/postgres.js +446 -0
  54. package/dist/src/server/types.d.ts +190 -0
  55. package/dist/src/server/types.js +7 -0
  56. package/dist/src/server/upload-validator.d.ts +16 -0
  57. package/dist/src/server/upload-validator.js +196 -0
  58. package/dist/src/widget/index.d.ts +1 -0
  59. package/dist/src/widget/index.js +1 -0
  60. package/package.json +99 -4
@@ -0,0 +1,221 @@
1
+ import crypto from "node:crypto";
2
+ export function formatSubmitterLabel(submitter) {
3
+ if (!submitter)
4
+ return "Anonymous";
5
+ if (submitter.label && String(submitter.label).trim().length > 0) {
6
+ return String(submitter.label).trim();
7
+ }
8
+ if (submitter.type && submitter.id !== undefined && submitter.id !== null) {
9
+ return `${submitter.type}#${submitter.id}`;
10
+ }
11
+ if (submitter.id !== undefined && submitter.id !== null) {
12
+ return `User#${submitter.id}`;
13
+ }
14
+ return "Anonymous";
15
+ }
16
+ export function toFeedbackSummary(record) {
17
+ return {
18
+ id: record.id,
19
+ qualified_id: `${record.environment}:${record.id}`,
20
+ environment: record.environment,
21
+ status: record.status,
22
+ message: record.message,
23
+ page_url: record.page_url,
24
+ submitter: formatSubmitterLabel(record.submitter),
25
+ attachments_count: record.attachments.length,
26
+ element_references_count: record.element_references.length,
27
+ element_selectors: record.element_references.map((el) => el.selector),
28
+ created_at: record.created_at
29
+ };
30
+ }
31
+ export function matchesFeedbackFilter(record, filter) {
32
+ if (filter.environment && filter.environment.trim().length > 0) {
33
+ if (record.environment.toLowerCase() !== filter.environment.trim().toLowerCase()) {
34
+ return false;
35
+ }
36
+ }
37
+ if (filter.status && record.status !== filter.status) {
38
+ return false;
39
+ }
40
+ if (filter.page_url && filter.page_url.trim().length > 0) {
41
+ const needle = filter.page_url.trim().toLowerCase();
42
+ if (!record.page_url.toLowerCase().includes(needle)) {
43
+ return false;
44
+ }
45
+ }
46
+ if (filter.query && filter.query.trim().length > 0) {
47
+ const q = filter.query.trim().toLowerCase();
48
+ const inMessage = (record.message ?? "").toLowerCase().includes(q);
49
+ const inElements = record.element_references.some((el) => el.selector.toLowerCase().includes(q) ||
50
+ (el.dom_path ?? "").toLowerCase().includes(q) ||
51
+ (el.text_content ?? "").toLowerCase().includes(q));
52
+ if (!inMessage && !inElements) {
53
+ return false;
54
+ }
55
+ }
56
+ return true;
57
+ }
58
+ export function createMemoryStorageAdapter() {
59
+ let nextFeedbackId = 1;
60
+ let nextElementId = 1;
61
+ let nextAttachmentId = 1;
62
+ const secret = crypto.randomBytes(32);
63
+ const pendingBlobs = new Map();
64
+ const attachmentBlobs = new Map();
65
+ const feedbacks = new Map();
66
+ function signId(rawId) {
67
+ const sig = crypto.createHmac("sha256", secret).update(rawId).digest("hex");
68
+ return `${rawId}.${sig}`;
69
+ }
70
+ function verifySignedId(token) {
71
+ const dotIdx = token.lastIndexOf(".");
72
+ if (dotIdx <= 0)
73
+ return null;
74
+ const rawId = token.slice(0, dotIdx);
75
+ const provided = token.slice(dotIdx + 1);
76
+ const expected = crypto.createHmac("sha256", secret).update(rawId).digest("hex");
77
+ if (provided.length !== expected.length)
78
+ return null;
79
+ if (!crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(expected))) {
80
+ return null;
81
+ }
82
+ return rawId;
83
+ }
84
+ return {
85
+ async savePendingBlob(blob) {
86
+ const rawId = crypto.randomUUID();
87
+ pendingBlobs.set(rawId, {
88
+ ...blob,
89
+ data: new Uint8Array(blob.data)
90
+ });
91
+ return { signed_blob_id: signId(rawId) };
92
+ },
93
+ async consumePendingBlob(signedBlobId) {
94
+ const rawId = verifySignedId(signedBlobId);
95
+ if (!rawId)
96
+ return null;
97
+ const blob = pendingBlobs.get(rawId) ?? null;
98
+ if (blob) {
99
+ pendingBlobs.delete(rawId);
100
+ }
101
+ return blob;
102
+ },
103
+ async createFeedback(input) {
104
+ const id = nextFeedbackId++;
105
+ const now = new Date().toISOString();
106
+ const elementsByClientRef = new Map();
107
+ const storedElements = input.element_references.map((el, idx) => {
108
+ const elRecord = {
109
+ id: nextElementId++,
110
+ feedback_id: id,
111
+ client_ref: el.client_ref,
112
+ tag_name: el.tag_name,
113
+ selector: el.selector,
114
+ dom_path: el.dom_path,
115
+ text_content: el.text_content,
116
+ attributes_snapshot: { ...el.attributes_snapshot },
117
+ bounding_rect: { ...el.bounding_rect },
118
+ viewport: { ...el.viewport },
119
+ metadata: { ...el.metadata },
120
+ captured_at: el.captured_at
121
+ };
122
+ const refKey = el.client_ref || String(idx);
123
+ elementsByClientRef.set(refKey, elRecord);
124
+ return elRecord;
125
+ });
126
+ const storedAttachments = input.attachments.map((att) => {
127
+ const attId = nextAttachmentId++;
128
+ const linkedEl = att.element_client_ref
129
+ ? elementsByClientRef.get(att.element_client_ref) ?? null
130
+ : null;
131
+ const blobKey = att.data ? `att_${attId}` : null;
132
+ if (blobKey && att.data) {
133
+ attachmentBlobs.set(blobKey, new Uint8Array(att.data));
134
+ }
135
+ return {
136
+ id: attId,
137
+ feedback_id: id,
138
+ element_reference_id: linkedEl ? linkedEl.id : null,
139
+ attachment_type: att.attachment_type,
140
+ filename: att.filename,
141
+ content_type: att.content_type,
142
+ byte_size: att.byte_size,
143
+ blob_key: blobKey,
144
+ metadata: { ...att.metadata },
145
+ created_at: now
146
+ };
147
+ });
148
+ const record = {
149
+ id,
150
+ environment: input.environment,
151
+ status: "new",
152
+ message: input.message,
153
+ page_url: input.page_url,
154
+ user_agent: input.user_agent,
155
+ session_id: input.session_id,
156
+ submitter: { ...input.submitter },
157
+ metadata: { ...input.metadata },
158
+ element_references: storedElements,
159
+ attachments: storedAttachments,
160
+ created_at: now,
161
+ updated_at: now
162
+ };
163
+ feedbacks.set(id, record);
164
+ return structuredClone(record);
165
+ },
166
+ async listFeedbacks(filter) {
167
+ const limit = Math.max(1, Math.min(100, filter.limit ?? 20));
168
+ const offset = Math.max(0, filter.offset ?? 0);
169
+ const matching = Array.from(feedbacks.values())
170
+ .filter((fb) => matchesFeedbackFilter(fb, filter))
171
+ .sort((a, b) => {
172
+ const dt = Date.parse(b.created_at) - Date.parse(a.created_at);
173
+ return dt !== 0 ? dt : Number(b.id) - Number(a.id);
174
+ });
175
+ return {
176
+ total: matching.length,
177
+ records: matching.slice(offset, offset + limit).map(toFeedbackSummary)
178
+ };
179
+ },
180
+ async getFeedback(id) {
181
+ const numId = Number(id);
182
+ const found = feedbacks.get(numId);
183
+ return found ? structuredClone(found) : null;
184
+ },
185
+ async getAttachment(attachmentId) {
186
+ const numAttId = Number(attachmentId);
187
+ for (const fb of feedbacks.values()) {
188
+ const att = fb.attachments.find((a) => Number(a.id) === numAttId);
189
+ if (att) {
190
+ const linkedEl = att.element_reference_id !== null
191
+ ? fb.element_references.find((e) => e.id === att.element_reference_id)
192
+ : undefined;
193
+ const bytes = att.blob_key ? attachmentBlobs.get(att.blob_key) ?? null : null;
194
+ return {
195
+ attachment: structuredClone(att),
196
+ element_selector: linkedEl?.selector ?? null,
197
+ data: bytes ? new Uint8Array(bytes) : null
198
+ };
199
+ }
200
+ }
201
+ return null;
202
+ },
203
+ async getAttachmentBytes(attachmentId) {
204
+ const res = await this.getAttachment(attachmentId);
205
+ return res?.data ?? null;
206
+ },
207
+ async updateFeedbackStatus(id, status) {
208
+ const numId = Number(id);
209
+ const existing = feedbacks.get(numId);
210
+ if (!existing)
211
+ return null;
212
+ const previous_status = existing.status;
213
+ existing.status = status;
214
+ existing.updated_at = new Date().toISOString();
215
+ return {
216
+ previous_status,
217
+ feedback: structuredClone(existing)
218
+ };
219
+ }
220
+ };
221
+ }
@@ -0,0 +1,27 @@
1
+ import type { BlobStorageAdapter, StorageAdapter } from "../types.js";
2
+ export interface PostgresQueryResult<Row = Record<string, unknown>> {
3
+ rows: Row[];
4
+ }
5
+ export interface PostgresQueryable {
6
+ query(text: string, values?: unknown[]): Promise<PostgresQueryResult>;
7
+ }
8
+ export interface PostgresStorageAdapterOptions {
9
+ /**
10
+ * Any PostgreSQL client or pool exposing `query(sql, values)` (`pg.Pool`, `@vercel/postgres`, `@neondatabase/serverless`, etc.).
11
+ */
12
+ pool: PostgresQueryable;
13
+ /**
14
+ * Automatically create `context_drop_*` tables on first query if they don't exist (default `true`).
15
+ */
16
+ autoMigrate?: boolean;
17
+ /**
18
+ * Optional HMAC secret for signing pending upload blob IDs (`process.env.CONTEXT_DROP_SECRET` used if omitted).
19
+ */
20
+ secret?: string;
21
+ /**
22
+ * Optional external blob store (e.g. S3, R2, Vercel Blob, Supabase Storage).
23
+ * When omitted, binary attachments are stored directly in PostgreSQL `BYTEA`.
24
+ */
25
+ blobStore?: BlobStorageAdapter;
26
+ }
27
+ export declare function createPostgresStorageAdapter(options: PostgresStorageAdapterOptions): StorageAdapter;
@@ -0,0 +1,446 @@
1
+ import crypto from "node:crypto";
2
+ import { 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
+ );
97
+ `);
98
+ await pool.query(`
99
+ CREATE INDEX IF NOT EXISTS idx_context_drop_feedbacks_env_status
100
+ ON context_drop_feedbacks (environment, status, created_at DESC);
101
+ `);
102
+ await pool.query(`
103
+ CREATE TABLE IF NOT EXISTS context_drop_element_references (
104
+ id BIGSERIAL PRIMARY KEY,
105
+ feedback_id BIGINT NOT NULL REFERENCES context_drop_feedbacks(id) ON DELETE CASCADE,
106
+ client_ref TEXT,
107
+ tag_name TEXT NOT NULL,
108
+ selector TEXT NOT NULL,
109
+ dom_path TEXT,
110
+ text_content TEXT,
111
+ attributes_snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,
112
+ bounding_rect JSONB NOT NULL DEFAULT '{}'::jsonb,
113
+ viewport JSONB NOT NULL DEFAULT '{}'::jsonb,
114
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
115
+ captured_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
116
+ );
117
+ `);
118
+ await pool.query(`
119
+ CREATE TABLE IF NOT EXISTS context_drop_attachments (
120
+ id BIGSERIAL PRIMARY KEY,
121
+ feedback_id BIGINT NOT NULL REFERENCES context_drop_feedbacks(id) ON DELETE CASCADE,
122
+ element_reference_id BIGINT REFERENCES context_drop_element_references(id) ON DELETE SET NULL,
123
+ attachment_type TEXT NOT NULL,
124
+ filename TEXT,
125
+ content_type TEXT,
126
+ byte_size INTEGER,
127
+ blob_key TEXT,
128
+ data BYTEA,
129
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
130
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
131
+ );
132
+ `);
133
+ })();
134
+ }
135
+ await migratedPromise;
136
+ }
137
+ async function hydrateFeedbackRow(row) {
138
+ const fbId = Number(row["id"]);
139
+ const [elRes, attRes] = await Promise.all([
140
+ pool.query(`SELECT id, feedback_id, client_ref, tag_name, selector, dom_path, text_content,
141
+ attributes_snapshot, bounding_rect, viewport, metadata, captured_at
142
+ FROM context_drop_element_references
143
+ WHERE feedback_id = $1
144
+ ORDER BY id ASC`, [fbId]),
145
+ pool.query(`SELECT id, feedback_id, element_reference_id, attachment_type, filename,
146
+ content_type, byte_size, blob_key, metadata, created_at
147
+ FROM context_drop_attachments
148
+ WHERE feedback_id = $1
149
+ ORDER BY id ASC`, [fbId])
150
+ ]);
151
+ const elements = elRes.rows.map((el) => ({
152
+ id: Number(el["id"]),
153
+ feedback_id: fbId,
154
+ client_ref: el["client_ref"] ?? null,
155
+ tag_name: String(el["tag_name"]),
156
+ selector: String(el["selector"]),
157
+ dom_path: el["dom_path"] ?? null,
158
+ text_content: el["text_content"] ?? null,
159
+ attributes_snapshot: parseJsonColumn(el["attributes_snapshot"], {}),
160
+ bounding_rect: parseJsonColumn(el["bounding_rect"], {}),
161
+ viewport: parseJsonColumn(el["viewport"], {}),
162
+ metadata: parseJsonColumn(el["metadata"], {}),
163
+ captured_at: toIsoString(el["captured_at"])
164
+ }));
165
+ const attachments = attRes.rows.map((att) => ({
166
+ id: Number(att["id"]),
167
+ feedback_id: fbId,
168
+ element_reference_id: att["element_reference_id"] !== null && att["element_reference_id"] !== undefined
169
+ ? Number(att["element_reference_id"])
170
+ : null,
171
+ attachment_type: att["attachment_type"] === "screenshot" ? "screenshot" : "image",
172
+ filename: att["filename"] ?? null,
173
+ content_type: att["content_type"] ?? null,
174
+ byte_size: att["byte_size"] !== null && att["byte_size"] !== undefined
175
+ ? Number(att["byte_size"])
176
+ : null,
177
+ blob_key: att["blob_key"] ?? null,
178
+ metadata: parseJsonColumn(att["metadata"], {}),
179
+ created_at: toIsoString(att["created_at"])
180
+ }));
181
+ return {
182
+ id: fbId,
183
+ environment: String(row["environment"] ?? "production"),
184
+ status: String(row["status"] ?? "new"),
185
+ message: row["message"] ?? null,
186
+ page_url: String(row["page_url"] ?? ""),
187
+ user_agent: row["user_agent"] ?? null,
188
+ session_id: row["session_id"] ?? null,
189
+ submitter: parseJsonColumn(row["submitter"], {}),
190
+ metadata: parseJsonColumn(row["metadata"], {}),
191
+ element_references: elements,
192
+ attachments,
193
+ created_at: toIsoString(row["created_at"]),
194
+ updated_at: toIsoString(row["updated_at"])
195
+ };
196
+ }
197
+ return {
198
+ async savePendingBlob(blob) {
199
+ await ensureMigrated();
200
+ const rawId = crypto.randomUUID();
201
+ let blobKey = null;
202
+ let inlineBytes = null;
203
+ if (blobStore) {
204
+ const stored = await blobStore.putBlob({
205
+ key: `pending_${rawId}`,
206
+ data: blob.data,
207
+ contentType: blob.content_type,
208
+ filename: blob.filename
209
+ });
210
+ blobKey = stored.key;
211
+ }
212
+ else {
213
+ inlineBytes = Buffer.from(blob.data);
214
+ }
215
+ await pool.query(`INSERT INTO context_drop_pending_blobs
216
+ (id, filename, content_type, byte_size, dimensions_json, blob_key, data)
217
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)`, [
218
+ rawId,
219
+ blob.filename,
220
+ blob.content_type,
221
+ blob.byte_size,
222
+ blob.dimensions ? JSON.stringify(blob.dimensions) : null,
223
+ blobKey,
224
+ inlineBytes
225
+ ]);
226
+ return { signed_blob_id: signId(rawId) };
227
+ },
228
+ async consumePendingBlob(signedBlobId) {
229
+ await ensureMigrated();
230
+ const rawId = verifySignedId(signedBlobId);
231
+ if (!rawId)
232
+ return null;
233
+ const res = await pool.query(`DELETE FROM context_drop_pending_blobs
234
+ WHERE id = $1
235
+ RETURNING filename, content_type, byte_size, dimensions_json, blob_key, data`, [rawId]);
236
+ const row = res.rows[0];
237
+ if (!row)
238
+ return null;
239
+ let bytes = null;
240
+ const blobKey = row["blob_key"] ?? null;
241
+ if (blobKey && blobStore) {
242
+ bytes = await blobStore.getBlob(blobKey);
243
+ if (blobStore.deleteBlob) {
244
+ await blobStore.deleteBlob(blobKey);
245
+ }
246
+ }
247
+ else {
248
+ bytes = toUint8Array(row["data"]);
249
+ }
250
+ if (!bytes)
251
+ return null;
252
+ return {
253
+ data: bytes,
254
+ filename: String(row["filename"]),
255
+ content_type: String(row["content_type"]),
256
+ byte_size: Number(row["byte_size"]),
257
+ dimensions: parseJsonColumn(row["dimensions_json"], null)
258
+ };
259
+ },
260
+ async createFeedback(input) {
261
+ await ensureMigrated();
262
+ const fbRes = await pool.query(`INSERT INTO context_drop_feedbacks
263
+ (environment, status, message, page_url, user_agent, session_id, submitter, metadata)
264
+ VALUES ($1, 'new', $2, $3, $4, $5, $6::jsonb, $7::jsonb)
265
+ RETURNING *`, [
266
+ input.environment,
267
+ input.message,
268
+ input.page_url,
269
+ input.user_agent,
270
+ input.session_id,
271
+ JSON.stringify(input.submitter || {}),
272
+ JSON.stringify(input.metadata || {})
273
+ ]);
274
+ const fbRow = fbRes.rows[0];
275
+ const fbId = Number(fbRow["id"]);
276
+ const elIdByRef = new Map();
277
+ for (let idx = 0; idx < input.element_references.length; idx++) {
278
+ const el = input.element_references[idx];
279
+ const elRes = await pool.query(`INSERT INTO context_drop_element_references
280
+ (feedback_id, client_ref, tag_name, selector, dom_path, text_content,
281
+ attributes_snapshot, bounding_rect, viewport, metadata, captured_at)
282
+ VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8::jsonb, $9::jsonb, $10::jsonb, $11::timestamptz)
283
+ RETURNING id`, [
284
+ fbId,
285
+ el.client_ref,
286
+ el.tag_name,
287
+ el.selector,
288
+ el.dom_path,
289
+ el.text_content,
290
+ JSON.stringify(el.attributes_snapshot || {}),
291
+ JSON.stringify(el.bounding_rect || {}),
292
+ JSON.stringify(el.viewport || {}),
293
+ JSON.stringify(el.metadata || {}),
294
+ el.captured_at
295
+ ]);
296
+ const elId = Number(elRes.rows[0]["id"]);
297
+ elIdByRef.set(el.client_ref || String(idx), elId);
298
+ }
299
+ for (const att of input.attachments) {
300
+ const linkedElId = att.element_client_ref
301
+ ? elIdByRef.get(att.element_client_ref) ?? null
302
+ : null;
303
+ let blobKey = null;
304
+ let inlineBytes = null;
305
+ if (att.data) {
306
+ if (blobStore) {
307
+ const saved = await blobStore.putBlob({
308
+ key: `att_${fbId}_${crypto.randomUUID()}`,
309
+ data: att.data,
310
+ contentType: att.content_type || "image/png",
311
+ filename: att.filename || "attachment.png"
312
+ });
313
+ blobKey = saved.key;
314
+ }
315
+ else {
316
+ inlineBytes = Buffer.from(att.data);
317
+ }
318
+ }
319
+ await pool.query(`INSERT INTO context_drop_attachments
320
+ (feedback_id, element_reference_id, attachment_type, filename, content_type, byte_size, blob_key, data, metadata)
321
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb)`, [
322
+ fbId,
323
+ linkedElId,
324
+ att.attachment_type,
325
+ att.filename,
326
+ att.content_type,
327
+ att.byte_size,
328
+ blobKey,
329
+ inlineBytes,
330
+ JSON.stringify(att.metadata || {})
331
+ ]);
332
+ }
333
+ return hydrateFeedbackRow(fbRow);
334
+ },
335
+ async listFeedbacks(filter) {
336
+ await ensureMigrated();
337
+ const limit = Math.max(1, Math.min(100, filter.limit ?? 20));
338
+ const offset = Math.max(0, filter.offset ?? 0);
339
+ const clauses = [];
340
+ const values = [];
341
+ if (filter.environment && filter.environment.trim().length > 0) {
342
+ values.push(filter.environment.trim().toLowerCase());
343
+ clauses.push(`LOWER(f.environment) = $${values.length}`);
344
+ }
345
+ if (filter.status) {
346
+ values.push(filter.status);
347
+ clauses.push(`f.status = $${values.length}`);
348
+ }
349
+ if (filter.page_url && filter.page_url.trim().length > 0) {
350
+ values.push(`%${filter.page_url.trim()}%`);
351
+ clauses.push(`f.page_url ILIKE $${values.length}`);
352
+ }
353
+ if (filter.query && filter.query.trim().length > 0) {
354
+ values.push(`%${filter.query.trim()}%`);
355
+ const p = `$${values.length}`;
356
+ clauses.push(`(f.message ILIKE ${p} OR EXISTS (
357
+ SELECT 1 FROM context_drop_element_references e
358
+ WHERE e.feedback_id = f.id
359
+ AND (e.selector ILIKE ${p} OR e.dom_path ILIKE ${p} OR e.text_content ILIKE ${p})
360
+ ))`);
361
+ }
362
+ const whereSql = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
363
+ const countRes = await pool.query(`SELECT COUNT(*)::int AS total FROM context_drop_feedbacks f ${whereSql}`, values);
364
+ const total = Number(countRes.rows[0]?.["total"] ?? 0);
365
+ const pageValues = [...values, limit, offset];
366
+ const rowsRes = await pool.query(`SELECT f.* FROM context_drop_feedbacks f ${whereSql}
367
+ ORDER BY f.created_at DESC, f.id DESC
368
+ LIMIT $${pageValues.length - 1} OFFSET $${pageValues.length}`, pageValues);
369
+ const hydrated = await Promise.all(rowsRes.rows.map(hydrateFeedbackRow));
370
+ return {
371
+ total,
372
+ records: hydrated.map(toFeedbackSummary)
373
+ };
374
+ },
375
+ async getFeedback(id) {
376
+ await ensureMigrated();
377
+ const res = await pool.query("SELECT * FROM context_drop_feedbacks WHERE id = $1", [
378
+ Number(id)
379
+ ]);
380
+ const row = res.rows[0];
381
+ if (!row)
382
+ return null;
383
+ return hydrateFeedbackRow(row);
384
+ },
385
+ async getAttachment(attachmentId) {
386
+ await ensureMigrated();
387
+ const res = await pool.query(`SELECT a.*, e.selector AS element_selector
388
+ FROM context_drop_attachments a
389
+ LEFT JOIN context_drop_element_references e ON e.id = a.element_reference_id
390
+ WHERE a.id = $1`, [Number(attachmentId)]);
391
+ const row = res.rows[0];
392
+ if (!row)
393
+ return null;
394
+ const blobKey = row["blob_key"] ?? null;
395
+ let bytes = null;
396
+ if (blobKey && blobStore) {
397
+ bytes = await blobStore.getBlob(blobKey);
398
+ }
399
+ else {
400
+ bytes = toUint8Array(row["data"]);
401
+ }
402
+ const attachment = {
403
+ id: Number(row["id"]),
404
+ feedback_id: Number(row["feedback_id"]),
405
+ element_reference_id: row["element_reference_id"] !== null && row["element_reference_id"] !== undefined
406
+ ? Number(row["element_reference_id"])
407
+ : null,
408
+ attachment_type: row["attachment_type"] === "screenshot" ? "screenshot" : "image",
409
+ filename: row["filename"] ?? null,
410
+ content_type: row["content_type"] ?? null,
411
+ byte_size: row["byte_size"] !== null && row["byte_size"] !== undefined
412
+ ? Number(row["byte_size"])
413
+ : null,
414
+ blob_key: blobKey,
415
+ metadata: parseJsonColumn(row["metadata"], {}),
416
+ created_at: toIsoString(row["created_at"])
417
+ };
418
+ return {
419
+ attachment,
420
+ element_selector: row["element_selector"] ?? null,
421
+ data: bytes
422
+ };
423
+ },
424
+ async getAttachmentBytes(attachmentId) {
425
+ const res = await this.getAttachment(attachmentId);
426
+ return res?.data ?? null;
427
+ },
428
+ async updateFeedbackStatus(id, status) {
429
+ await ensureMigrated();
430
+ const existing = await this.getFeedback(id);
431
+ if (!existing)
432
+ return null;
433
+ const updatedRes = await pool.query(`UPDATE context_drop_feedbacks
434
+ SET status = $1, updated_at = NOW()
435
+ WHERE id = $2
436
+ RETURNING *`, [status, Number(id)]);
437
+ const row = updatedRes.rows[0];
438
+ if (!row)
439
+ return null;
440
+ return {
441
+ previous_status: existing.status,
442
+ feedback: await hydrateFeedbackRow(row)
443
+ };
444
+ }
445
+ };
446
+ }