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,574 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import path from "node:path";
5
+ import { matchesFeedbackFilter, toFeedbackSummary } from "./memory.js";
6
+ function tryOpenNodeSqlite(dbPath) {
7
+ try {
8
+ const req = createRequire(import.meta.url);
9
+ // Suppress Node experimental SQLite warning when probing built-in module
10
+ const sqliteMod = req("node:sqlite");
11
+ if (sqliteMod && typeof sqliteMod.DatabaseSync === "function") {
12
+ const db = new sqliteMod.DatabaseSync(dbPath);
13
+ db.exec("PRAGMA journal_mode = WAL;");
14
+ db.exec("PRAGMA busy_timeout = 5000;");
15
+ db.exec("PRAGMA foreign_keys = ON;");
16
+ return db;
17
+ }
18
+ }
19
+ catch {
20
+ // Fallback to JSON file store when node:sqlite is unavailable
21
+ }
22
+ return null;
23
+ }
24
+ function createDiskBlobStore(blobsDir) {
25
+ return {
26
+ async putBlob({ key, data }) {
27
+ fs.mkdirSync(blobsDir, { recursive: true });
28
+ const safeKey = key.replace(/[^a-zA-Z0-9._-]/g, "_");
29
+ const targetPath = path.join(blobsDir, safeKey);
30
+ fs.writeFileSync(targetPath, data);
31
+ return { key: safeKey };
32
+ },
33
+ async getBlob(key) {
34
+ const safeKey = key.replace(/[^a-zA-Z0-9._-]/g, "_");
35
+ const targetPath = path.join(blobsDir, safeKey);
36
+ if (!fs.existsSync(targetPath))
37
+ return null;
38
+ const buf = fs.readFileSync(targetPath);
39
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
40
+ },
41
+ async deleteBlob(key) {
42
+ const safeKey = key.replace(/[^a-zA-Z0-9._-]/g, "_");
43
+ const targetPath = path.join(blobsDir, safeKey);
44
+ if (fs.existsSync(targetPath)) {
45
+ fs.unlinkSync(targetPath);
46
+ }
47
+ }
48
+ };
49
+ }
50
+ function resolveOrCreateSecret(storageDir, explicitSecret) {
51
+ const fromEnv = explicitSecret || process.env.CONTEXT_DROP_SECRET;
52
+ if (fromEnv && fromEnv.trim().length > 0) {
53
+ return crypto.createHash("sha256").update(fromEnv.trim()).digest();
54
+ }
55
+ const secretPath = path.join(storageDir, ".blob_secret");
56
+ if (fs.existsSync(secretPath)) {
57
+ return crypto.createHash("sha256").update(fs.readFileSync(secretPath, "utf8").trim()).digest();
58
+ }
59
+ const generated = crypto.randomBytes(32).toString("hex");
60
+ fs.writeFileSync(secretPath, generated, { encoding: "utf8", mode: 0o600 });
61
+ return crypto.createHash("sha256").update(generated).digest();
62
+ }
63
+ export function createLocalStorageAdapter(options = {}) {
64
+ const storageDir = path.resolve(options.dir || process.env.CONTEXT_DROP_STORAGE_DIR || path.join(process.cwd(), ".context-drop"));
65
+ fs.mkdirSync(storageDir, { recursive: true });
66
+ const gitignorePath = path.join(storageDir, ".gitignore");
67
+ if (!fs.existsSync(gitignorePath)) {
68
+ fs.writeFileSync(gitignorePath, "*\n", "utf8");
69
+ }
70
+ const blobsDir = path.join(storageDir, "blobs");
71
+ fs.mkdirSync(blobsDir, { recursive: true });
72
+ const blobStore = options.blobStore ?? createDiskBlobStore(blobsDir);
73
+ const secretKey = resolveOrCreateSecret(storageDir, options.secret);
74
+ function signId(rawId) {
75
+ const sig = crypto.createHmac("sha256", secretKey).update(rawId).digest("hex");
76
+ return `${rawId}.${sig}`;
77
+ }
78
+ function verifySignedId(token) {
79
+ const dotIdx = token.lastIndexOf(".");
80
+ if (dotIdx <= 0)
81
+ return null;
82
+ const rawId = token.slice(0, dotIdx);
83
+ const provided = token.slice(dotIdx + 1);
84
+ const expected = crypto.createHmac("sha256", secretKey).update(rawId).digest("hex");
85
+ if (provided.length !== expected.length)
86
+ return null;
87
+ if (!crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(expected))) {
88
+ return null;
89
+ }
90
+ return rawId;
91
+ }
92
+ const requestedBackend = options.backend ?? "auto";
93
+ const dbPath = path.join(storageDir, "context_drop.sqlite");
94
+ const sqliteDb = requestedBackend === "json" ? null : tryOpenNodeSqlite(dbPath);
95
+ if (requestedBackend === "sqlite" && !sqliteDb) {
96
+ throw new Error("ContextDrop SQLite backend requested, but node:sqlite is unavailable in this Node runtime.");
97
+ }
98
+ if (sqliteDb) {
99
+ sqliteDb.exec(`
100
+ CREATE TABLE IF NOT EXISTS context_drop_pending_blobs (
101
+ id TEXT PRIMARY KEY,
102
+ filename TEXT NOT NULL,
103
+ content_type TEXT NOT NULL,
104
+ byte_size INTEGER NOT NULL,
105
+ dimensions_json TEXT,
106
+ blob_key TEXT NOT NULL,
107
+ created_at TEXT NOT NULL
108
+ );
109
+
110
+ CREATE TABLE IF NOT EXISTS context_drop_feedbacks (
111
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
112
+ environment TEXT NOT NULL,
113
+ status TEXT NOT NULL DEFAULT 'new',
114
+ message TEXT,
115
+ page_url TEXT NOT NULL,
116
+ user_agent TEXT,
117
+ session_id TEXT,
118
+ submitter_json TEXT NOT NULL,
119
+ metadata_json TEXT NOT NULL,
120
+ created_at TEXT NOT NULL,
121
+ updated_at TEXT NOT NULL
122
+ );
123
+
124
+ CREATE INDEX IF NOT EXISTS idx_cd_feedbacks_env_status
125
+ ON context_drop_feedbacks (environment, status, created_at DESC);
126
+
127
+ CREATE TABLE IF NOT EXISTS context_drop_element_references (
128
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
129
+ feedback_id INTEGER NOT NULL REFERENCES context_drop_feedbacks(id) ON DELETE CASCADE,
130
+ client_ref TEXT,
131
+ tag_name TEXT NOT NULL,
132
+ selector TEXT NOT NULL,
133
+ dom_path TEXT,
134
+ text_content TEXT,
135
+ attributes_json TEXT NOT NULL,
136
+ bounding_rect_json TEXT NOT NULL,
137
+ viewport_json TEXT NOT NULL,
138
+ metadata_json TEXT NOT NULL,
139
+ captured_at TEXT NOT NULL
140
+ );
141
+
142
+ CREATE TABLE IF NOT EXISTS context_drop_attachments (
143
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
144
+ feedback_id INTEGER NOT NULL REFERENCES context_drop_feedbacks(id) ON DELETE CASCADE,
145
+ element_reference_id INTEGER REFERENCES context_drop_element_references(id) ON DELETE SET NULL,
146
+ attachment_type TEXT NOT NULL,
147
+ filename TEXT,
148
+ content_type TEXT,
149
+ byte_size INTEGER,
150
+ blob_key TEXT,
151
+ metadata_json TEXT NOT NULL,
152
+ created_at TEXT NOT NULL
153
+ );
154
+ `);
155
+ const hydrateFeedbackRow = (row) => {
156
+ const fbId = Number(row["id"]);
157
+ const elRows = sqliteDb
158
+ .prepare("SELECT * FROM context_drop_element_references WHERE feedback_id = ? ORDER BY id ASC")
159
+ .all(fbId);
160
+ const attRows = sqliteDb
161
+ .prepare("SELECT * FROM context_drop_attachments WHERE feedback_id = ? ORDER BY id ASC")
162
+ .all(fbId);
163
+ const elements = elRows.map((el) => ({
164
+ id: Number(el["id"]),
165
+ feedback_id: fbId,
166
+ client_ref: el["client_ref"] ?? null,
167
+ tag_name: String(el["tag_name"]),
168
+ selector: String(el["selector"]),
169
+ dom_path: el["dom_path"] ?? null,
170
+ text_content: el["text_content"] ?? null,
171
+ attributes_snapshot: JSON.parse(String(el["attributes_json"] || "{}")),
172
+ bounding_rect: JSON.parse(String(el["bounding_rect_json"] || "{}")),
173
+ viewport: JSON.parse(String(el["viewport_json"] || "{}")),
174
+ metadata: JSON.parse(String(el["metadata_json"] || "{}")),
175
+ captured_at: String(el["captured_at"])
176
+ }));
177
+ const attachments = attRows.map((att) => ({
178
+ id: Number(att["id"]),
179
+ feedback_id: fbId,
180
+ element_reference_id: att["element_reference_id"] !== null && att["element_reference_id"] !== undefined
181
+ ? Number(att["element_reference_id"])
182
+ : null,
183
+ attachment_type: (att["attachment_type"] === "screenshot" ? "screenshot" : "image"),
184
+ filename: att["filename"] ?? null,
185
+ content_type: att["content_type"] ?? null,
186
+ byte_size: att["byte_size"] !== null && att["byte_size"] !== undefined
187
+ ? Number(att["byte_size"])
188
+ : null,
189
+ blob_key: att["blob_key"] ?? null,
190
+ metadata: JSON.parse(String(att["metadata_json"] || "{}")),
191
+ created_at: String(att["created_at"])
192
+ }));
193
+ return {
194
+ id: fbId,
195
+ environment: String(row["environment"]),
196
+ status: String(row["status"]),
197
+ message: row["message"] ?? null,
198
+ page_url: String(row["page_url"]),
199
+ user_agent: row["user_agent"] ?? null,
200
+ session_id: row["session_id"] ?? null,
201
+ submitter: JSON.parse(String(row["submitter_json"] || "{}")),
202
+ metadata: JSON.parse(String(row["metadata_json"] || "{}")),
203
+ element_references: elements,
204
+ attachments,
205
+ created_at: String(row["created_at"]),
206
+ updated_at: String(row["updated_at"])
207
+ };
208
+ };
209
+ return {
210
+ async savePendingBlob(blob) {
211
+ const rawId = crypto.randomUUID();
212
+ const stored = await blobStore.putBlob({
213
+ key: `pending_${rawId}`,
214
+ data: blob.data,
215
+ contentType: blob.content_type,
216
+ filename: blob.filename
217
+ });
218
+ sqliteDb
219
+ .prepare(`INSERT INTO context_drop_pending_blobs
220
+ (id, filename, content_type, byte_size, dimensions_json, blob_key, created_at)
221
+ VALUES (?, ?, ?, ?, ?, ?, ?)`)
222
+ .run(rawId, blob.filename, blob.content_type, blob.byte_size, blob.dimensions ? JSON.stringify(blob.dimensions) : null, stored.key, new Date().toISOString());
223
+ return { signed_blob_id: signId(rawId) };
224
+ },
225
+ async consumePendingBlob(signedBlobId) {
226
+ const rawId = verifySignedId(signedBlobId);
227
+ if (!rawId)
228
+ return null;
229
+ const row = sqliteDb
230
+ .prepare("SELECT * FROM context_drop_pending_blobs WHERE id = ?")
231
+ .get(rawId);
232
+ if (!row)
233
+ return null;
234
+ sqliteDb.prepare("DELETE FROM context_drop_pending_blobs WHERE id = ?").run(rawId);
235
+ const blobKey = String(row["blob_key"]);
236
+ const bytes = await blobStore.getBlob(blobKey);
237
+ if (blobStore.deleteBlob) {
238
+ await blobStore.deleteBlob(blobKey);
239
+ }
240
+ if (!bytes)
241
+ return null;
242
+ return {
243
+ data: bytes,
244
+ filename: String(row["filename"]),
245
+ content_type: String(row["content_type"]),
246
+ byte_size: Number(row["byte_size"]),
247
+ dimensions: row["dimensions_json"]
248
+ ? JSON.parse(String(row["dimensions_json"]))
249
+ : null
250
+ };
251
+ },
252
+ async createFeedback(input) {
253
+ const now = new Date().toISOString();
254
+ const fbRes = sqliteDb
255
+ .prepare(`INSERT INTO context_drop_feedbacks
256
+ (environment, status, message, page_url, user_agent, session_id, submitter_json, metadata_json, created_at, updated_at)
257
+ VALUES (?, 'new', ?, ?, ?, ?, ?, ?, ?, ?)`)
258
+ .run(input.environment, input.message, input.page_url, input.user_agent, input.session_id, JSON.stringify(input.submitter || {}), JSON.stringify(input.metadata || {}), now, now);
259
+ const fbId = Number(fbRes.lastInsertRowid);
260
+ const elIdByClientRef = new Map();
261
+ const insertElStmt = sqliteDb.prepare(`INSERT INTO context_drop_element_references
262
+ (feedback_id, client_ref, tag_name, selector, dom_path, text_content, attributes_json, bounding_rect_json, viewport_json, metadata_json, captured_at)
263
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
264
+ input.element_references.forEach((el, idx) => {
265
+ const elRes = insertElStmt.run(fbId, el.client_ref, el.tag_name, el.selector, el.dom_path, el.text_content, JSON.stringify(el.attributes_snapshot || {}), JSON.stringify(el.bounding_rect || {}), JSON.stringify(el.viewport || {}), JSON.stringify(el.metadata || {}), el.captured_at);
266
+ const elId = Number(elRes.lastInsertRowid);
267
+ const key = el.client_ref || String(idx);
268
+ elIdByClientRef.set(key, elId);
269
+ });
270
+ const insertAttStmt = sqliteDb.prepare(`INSERT INTO context_drop_attachments
271
+ (feedback_id, element_reference_id, attachment_type, filename, content_type, byte_size, blob_key, metadata_json, created_at)
272
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
273
+ for (const att of input.attachments) {
274
+ const linkedElId = att.element_client_ref
275
+ ? elIdByClientRef.get(att.element_client_ref) ?? null
276
+ : null;
277
+ let blobKey = null;
278
+ if (att.data) {
279
+ const saved = await blobStore.putBlob({
280
+ key: `att_${fbId}_${crypto.randomUUID()}`,
281
+ data: att.data,
282
+ contentType: att.content_type || "image/png",
283
+ filename: att.filename || "attachment.png"
284
+ });
285
+ blobKey = saved.key;
286
+ }
287
+ insertAttStmt.run(fbId, linkedElId, att.attachment_type, att.filename, att.content_type, att.byte_size, blobKey, JSON.stringify(att.metadata || {}), now);
288
+ }
289
+ const created = await this.getFeedback(fbId);
290
+ if (!created) {
291
+ throw new Error("Failed to load created ContextDrop feedback record");
292
+ }
293
+ return created;
294
+ },
295
+ async listFeedbacks(filter) {
296
+ const limit = Math.max(1, Math.min(100, filter.limit ?? 20));
297
+ const offset = Math.max(0, filter.offset ?? 0);
298
+ const rows = sqliteDb
299
+ .prepare("SELECT * FROM context_drop_feedbacks ORDER BY created_at DESC, id DESC")
300
+ .all();
301
+ const hydrated = rows.map(hydrateFeedbackRow).filter((fb) => matchesFeedbackFilter(fb, filter));
302
+ return {
303
+ total: hydrated.length,
304
+ records: hydrated.slice(offset, offset + limit).map(toFeedbackSummary)
305
+ };
306
+ },
307
+ async getFeedback(id) {
308
+ const row = sqliteDb
309
+ .prepare("SELECT * FROM context_drop_feedbacks WHERE id = ?")
310
+ .get(Number(id));
311
+ if (!row)
312
+ return null;
313
+ return hydrateFeedbackRow(row);
314
+ },
315
+ async getAttachment(attachmentId) {
316
+ const row = sqliteDb
317
+ .prepare(`SELECT a.*, e.selector AS element_selector
318
+ FROM context_drop_attachments a
319
+ LEFT JOIN context_drop_element_references e ON e.id = a.element_reference_id
320
+ WHERE a.id = ?`)
321
+ .get(Number(attachmentId));
322
+ if (!row)
323
+ return null;
324
+ const blobKey = row["blob_key"] ?? null;
325
+ const bytes = blobKey ? await blobStore.getBlob(blobKey) : null;
326
+ const attachment = {
327
+ id: Number(row["id"]),
328
+ feedback_id: Number(row["feedback_id"]),
329
+ element_reference_id: row["element_reference_id"] !== null && row["element_reference_id"] !== undefined
330
+ ? Number(row["element_reference_id"])
331
+ : null,
332
+ attachment_type: row["attachment_type"] === "screenshot" ? "screenshot" : "image",
333
+ filename: row["filename"] ?? null,
334
+ content_type: row["content_type"] ?? null,
335
+ byte_size: row["byte_size"] !== null && row["byte_size"] !== undefined
336
+ ? Number(row["byte_size"])
337
+ : null,
338
+ blob_key: blobKey,
339
+ metadata: JSON.parse(String(row["metadata_json"] || "{}")),
340
+ created_at: String(row["created_at"])
341
+ };
342
+ return {
343
+ attachment,
344
+ element_selector: row["element_selector"] ?? null,
345
+ data: bytes
346
+ };
347
+ },
348
+ async getAttachmentBytes(attachmentId) {
349
+ const res = await this.getAttachment(attachmentId);
350
+ return res?.data ?? null;
351
+ },
352
+ async updateFeedbackStatus(id, status) {
353
+ const existing = await this.getFeedback(id);
354
+ if (!existing)
355
+ return null;
356
+ const now = new Date().toISOString();
357
+ sqliteDb
358
+ .prepare("UPDATE context_drop_feedbacks SET status = ?, updated_at = ? WHERE id = ?")
359
+ .run(status, now, Number(id));
360
+ const updated = await this.getFeedback(id);
361
+ if (!updated)
362
+ return null;
363
+ return {
364
+ previous_status: existing.status,
365
+ feedback: updated
366
+ };
367
+ }
368
+ };
369
+ }
370
+ // Fallback atomic JSON file store
371
+ const jsonFilePath = path.join(storageDir, "feedbacks.json");
372
+ function readJsonStore() {
373
+ if (!fs.existsSync(jsonFilePath)) {
374
+ return {
375
+ nextFeedbackId: 1,
376
+ nextElementId: 1,
377
+ nextAttachmentId: 1,
378
+ pendingBlobs: {},
379
+ feedbacks: []
380
+ };
381
+ }
382
+ try {
383
+ const raw = fs.readFileSync(jsonFilePath, "utf8");
384
+ return JSON.parse(raw);
385
+ }
386
+ catch {
387
+ return {
388
+ nextFeedbackId: 1,
389
+ nextElementId: 1,
390
+ nextAttachmentId: 1,
391
+ pendingBlobs: {},
392
+ feedbacks: []
393
+ };
394
+ }
395
+ }
396
+ function writeJsonStore(state) {
397
+ const tmpPath = `${jsonFilePath}.${process.pid}.${Date.now()}.tmp`;
398
+ fs.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf8");
399
+ fs.renameSync(tmpPath, jsonFilePath);
400
+ }
401
+ return {
402
+ async savePendingBlob(blob) {
403
+ const rawId = crypto.randomUUID();
404
+ const stored = await blobStore.putBlob({
405
+ key: `pending_${rawId}`,
406
+ data: blob.data,
407
+ contentType: blob.content_type,
408
+ filename: blob.filename
409
+ });
410
+ const state = readJsonStore();
411
+ state.pendingBlobs[rawId] = {
412
+ filename: blob.filename,
413
+ content_type: blob.content_type,
414
+ byte_size: blob.byte_size,
415
+ dimensions: blob.dimensions,
416
+ blob_key: stored.key,
417
+ created_at: new Date().toISOString()
418
+ };
419
+ writeJsonStore(state);
420
+ return { signed_blob_id: signId(rawId) };
421
+ },
422
+ async consumePendingBlob(signedBlobId) {
423
+ const rawId = verifySignedId(signedBlobId);
424
+ if (!rawId)
425
+ return null;
426
+ const state = readJsonStore();
427
+ const entry = state.pendingBlobs[rawId];
428
+ if (!entry)
429
+ return null;
430
+ delete state.pendingBlobs[rawId];
431
+ writeJsonStore(state);
432
+ const bytes = await blobStore.getBlob(entry.blob_key);
433
+ if (blobStore.deleteBlob) {
434
+ await blobStore.deleteBlob(entry.blob_key);
435
+ }
436
+ if (!bytes)
437
+ return null;
438
+ return {
439
+ data: bytes,
440
+ filename: entry.filename,
441
+ content_type: entry.content_type,
442
+ byte_size: entry.byte_size,
443
+ dimensions: entry.dimensions
444
+ };
445
+ },
446
+ async createFeedback(input) {
447
+ const state = readJsonStore();
448
+ const id = state.nextFeedbackId++;
449
+ const now = new Date().toISOString();
450
+ const elementsByRef = new Map();
451
+ const storedElements = input.element_references.map((el, idx) => {
452
+ const elRec = {
453
+ id: state.nextElementId++,
454
+ feedback_id: id,
455
+ client_ref: el.client_ref,
456
+ tag_name: el.tag_name,
457
+ selector: el.selector,
458
+ dom_path: el.dom_path,
459
+ text_content: el.text_content,
460
+ attributes_snapshot: { ...el.attributes_snapshot },
461
+ bounding_rect: { ...el.bounding_rect },
462
+ viewport: { ...el.viewport },
463
+ metadata: { ...el.metadata },
464
+ captured_at: el.captured_at
465
+ };
466
+ elementsByRef.set(el.client_ref || String(idx), elRec);
467
+ return elRec;
468
+ });
469
+ const storedAttachments = [];
470
+ for (const att of input.attachments) {
471
+ const attId = state.nextAttachmentId++;
472
+ const linkedEl = att.element_client_ref
473
+ ? elementsByRef.get(att.element_client_ref) ?? null
474
+ : null;
475
+ let blobKey = null;
476
+ if (att.data) {
477
+ const saved = await blobStore.putBlob({
478
+ key: `att_${id}_${attId}_${crypto.randomUUID()}`,
479
+ data: att.data,
480
+ contentType: att.content_type || "image/png",
481
+ filename: att.filename || "attachment.png"
482
+ });
483
+ blobKey = saved.key;
484
+ }
485
+ storedAttachments.push({
486
+ id: attId,
487
+ feedback_id: id,
488
+ element_reference_id: linkedEl ? linkedEl.id : null,
489
+ attachment_type: att.attachment_type,
490
+ filename: att.filename,
491
+ content_type: att.content_type,
492
+ byte_size: att.byte_size,
493
+ blob_key: blobKey,
494
+ metadata: { ...att.metadata },
495
+ created_at: now
496
+ });
497
+ }
498
+ const record = {
499
+ id,
500
+ environment: input.environment,
501
+ status: "new",
502
+ message: input.message,
503
+ page_url: input.page_url,
504
+ user_agent: input.user_agent,
505
+ session_id: input.session_id,
506
+ submitter: { ...input.submitter },
507
+ metadata: { ...input.metadata },
508
+ element_references: storedElements,
509
+ attachments: storedAttachments,
510
+ created_at: now,
511
+ updated_at: now
512
+ };
513
+ state.feedbacks.push(record);
514
+ writeJsonStore(state);
515
+ return structuredClone(record);
516
+ },
517
+ async listFeedbacks(filter) {
518
+ const state = readJsonStore();
519
+ const limit = Math.max(1, Math.min(100, filter.limit ?? 20));
520
+ const offset = Math.max(0, filter.offset ?? 0);
521
+ const matching = state.feedbacks
522
+ .filter((fb) => matchesFeedbackFilter(fb, filter))
523
+ .sort((a, b) => {
524
+ const dt = Date.parse(b.created_at) - Date.parse(a.created_at);
525
+ return dt !== 0 ? dt : Number(b.id) - Number(a.id);
526
+ });
527
+ return {
528
+ total: matching.length,
529
+ records: matching.slice(offset, offset + limit).map(toFeedbackSummary)
530
+ };
531
+ },
532
+ async getFeedback(id) {
533
+ const state = readJsonStore();
534
+ const found = state.feedbacks.find((fb) => String(fb.id) === String(id));
535
+ return found ? structuredClone(found) : null;
536
+ },
537
+ async getAttachment(attachmentId) {
538
+ const state = readJsonStore();
539
+ for (const fb of state.feedbacks) {
540
+ const att = fb.attachments.find((a) => String(a.id) === String(attachmentId));
541
+ if (att) {
542
+ const linkedEl = att.element_reference_id !== null
543
+ ? fb.element_references.find((e) => e.id === att.element_reference_id)
544
+ : undefined;
545
+ const bytes = att.blob_key ? await blobStore.getBlob(att.blob_key) : null;
546
+ return {
547
+ attachment: structuredClone(att),
548
+ element_selector: linkedEl?.selector ?? null,
549
+ data: bytes
550
+ };
551
+ }
552
+ }
553
+ return null;
554
+ },
555
+ async getAttachmentBytes(attachmentId) {
556
+ const res = await this.getAttachment(attachmentId);
557
+ return res?.data ?? null;
558
+ },
559
+ async updateFeedbackStatus(id, status) {
560
+ const state = readJsonStore();
561
+ const found = state.feedbacks.find((fb) => String(fb.id) === String(id));
562
+ if (!found)
563
+ return null;
564
+ const previous_status = found.status;
565
+ found.status = status;
566
+ found.updated_at = new Date().toISOString();
567
+ writeJsonStore(state);
568
+ return {
569
+ previous_status,
570
+ feedback: structuredClone(found)
571
+ };
572
+ }
573
+ };
574
+ }
@@ -0,0 +1,5 @@
1
+ import type { FeedbackQueryFilter, FeedbackSummaryItem, StorageAdapter, StoredFeedbackRecord } from "../types.js";
2
+ export declare function formatSubmitterLabel(submitter: StoredFeedbackRecord["submitter"]): string;
3
+ export declare function toFeedbackSummary(record: StoredFeedbackRecord): FeedbackSummaryItem;
4
+ export declare function matchesFeedbackFilter(record: StoredFeedbackRecord, filter: FeedbackQueryFilter): boolean;
5
+ export declare function createMemoryStorageAdapter(): StorageAdapter;