context-drop 0.3.0 → 0.3.1

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.
@@ -194,6 +194,13 @@ function parseSubRoute(pathname) {
194
194
  attachmentId: decodeURIComponent(fbAttMatch[2])
195
195
  };
196
196
  }
197
+ const fbCommentsMatch = /\/feedback\/([^/]+)\/comments$/.exec(clean);
198
+ if (fbCommentsMatch) {
199
+ return {
200
+ kind: "feedback_comments",
201
+ feedbackId: decodeURIComponent(fbCommentsMatch[1])
202
+ };
203
+ }
197
204
  const fbItemMatch = /\/feedback\/([^/]+)$/.exec(clean);
198
205
  if (fbItemMatch) {
199
206
  return {
@@ -352,7 +359,28 @@ function serializeOwnFeedback(record, ownershipToken) {
352
359
  metadata: att.metadata ?? {},
353
360
  created_at: att.created_at
354
361
  };
355
- })
362
+ }),
363
+ comments_count: (record.comments ?? []).length,
364
+ comments: (record.comments ?? []).map((comment) => ({
365
+ id: comment.id,
366
+ feedback_id: comment.feedback_id,
367
+ author_label: comment.author_label,
368
+ author_type: comment.author_type ?? null,
369
+ body: comment.body,
370
+ attachments: (comment.attachments ?? []).map((att) => ({
371
+ id: att.id,
372
+ attachment_type: att.attachment_type,
373
+ element_reference_id: null,
374
+ element_reference_ref: null,
375
+ filename: att.filename,
376
+ content_type: att.content_type,
377
+ byte_size: att.byte_size,
378
+ metadata: att.metadata ?? {},
379
+ created_at: att.created_at
380
+ })),
381
+ created_at: comment.created_at,
382
+ updated_at: comment.updated_at
383
+ }))
356
384
  };
357
385
  }
358
386
  function resolveWidgetBundleFilePath() {
@@ -868,6 +896,11 @@ export function createContextDropFetchHandler(config = {}) {
868
896
  const hasMetadataKey = Object.prototype.hasOwnProperty.call(payload, "metadata");
869
897
  const hasElementsKey = Object.prototype.hasOwnProperty.call(payload, "element_references");
870
898
  const hasAttachmentsKey = Object.prototype.hasOwnProperty.call(payload, "attachments");
899
+ const hasStatusKey = Object.prototype.hasOwnProperty.call(payload, "status");
900
+ const requestedStatus = hasStatusKey ? String(payload["status"] ?? "").trim() : undefined;
901
+ if (hasStatusKey && requestedStatus !== "reviewed" && requestedStatus !== "dismissed") {
902
+ return jsonResponse({ error: `Invalid status '${requestedStatus}'` }, 422, corsHeaders);
903
+ }
871
904
  const rawElements = hasElementsKey
872
905
  ? Array.isArray(payload["element_references"])
873
906
  ? payload["element_references"]
@@ -960,6 +993,7 @@ export function createContextDropFetchHandler(config = {}) {
960
993
  }
961
994
  const updated = await storage.updateFeedback(existing.id, {
962
995
  ...(hasMessageKey ? { message: nextMessage } : {}),
996
+ ...(hasStatusKey ? { status: requestedStatus } : {}),
963
997
  ...(nextMetadata !== undefined ? { metadata: nextMetadata } : {}),
964
998
  ...(sanitizedElements !== undefined ? { element_references: sanitizedElements } : {}),
965
999
  ...(preparedAttachmentSpecs !== undefined ? { attachments: preparedAttachmentSpecs } : {})
@@ -997,6 +1031,94 @@ export function createContextDropFetchHandler(config = {}) {
997
1031
  return jsonResponse({ error: err.message || "Failed to update feedback" }, 422, corsHeaders);
998
1032
  }
999
1033
  }
1034
+ if (parsedRoute.kind === "feedback_comments" && method === "POST") {
1035
+ const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
1036
+ if (!originCheck.ok) {
1037
+ return jsonResponse({ error: originCheck.error }, 403, corsHeaders);
1038
+ }
1039
+ const auth = await checkSubmissionAuth(request);
1040
+ if (!auth.ok) {
1041
+ return jsonResponse({ error: auth.error }, auth.status, corsHeaders);
1042
+ }
1043
+ if (!checkRateLimit(request)) {
1044
+ return jsonResponse({ error: "Rate limit exceeded. Please try again later." }, 429, corsHeaders);
1045
+ }
1046
+ const storage = getStorage();
1047
+ const existing = await storage.getFeedback(parsedRoute.feedbackId);
1048
+ if (!existing || existing.deleted_at) {
1049
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
1050
+ }
1051
+ try {
1052
+ const rawJson = (await request.json().catch(() => ({})));
1053
+ const payload = rawJson["comment"] && typeof rawJson["comment"] === "object"
1054
+ ? asRecord(rawJson["comment"])
1055
+ : asRecord(rawJson);
1056
+ const secret = getOwnershipSecret();
1057
+ const rawTokens = combineRequestOwnershipTokens(request, url, payload["ownership_token"] ?? rawJson["ownership_token"]);
1058
+ const tokenIds = extractVerifiedOwnershipIds(rawTokens, secret);
1059
+ if (!matchesOwnFeedback(existing, {
1060
+ submitter: auth.submitter,
1061
+ session_id: extractHashedSessionId(request),
1062
+ token_ids: tokenIds
1063
+ })) {
1064
+ return jsonResponse({ error: "Forbidden" }, 403, corsHeaders);
1065
+ }
1066
+ const rawAttachments = Array.isArray(payload["attachments"]) ? payload["attachments"] : [];
1067
+ const maxAttachments = config.limits?.maxAttachments ?? 10;
1068
+ if (rawAttachments.length > maxAttachments) {
1069
+ return jsonResponse({
1070
+ error: `Attachments count (${rawAttachments.length}) exceeds maximum allowed (${maxAttachments})`
1071
+ }, 422, corsHeaders);
1072
+ }
1073
+ const uploadOpts = getUploadValidationOptions();
1074
+ const preparedAttachments = await Promise.all(rawAttachments.map((rawAtt) => parseNewAttachmentSpec(rawAtt, storage, uploadOpts)));
1075
+ const bodyText = String(payload["body"] ?? "").trim() || null;
1076
+ if (!bodyText && preparedAttachments.length === 0) {
1077
+ return jsonResponse({ error: "Comment must include text or an image attachment" }, 422, corsHeaders);
1078
+ }
1079
+ if (!storage.addComment) {
1080
+ return jsonResponse({ error: "Storage adapter does not support comments" }, 501, corsHeaders);
1081
+ }
1082
+ const authorLabel = auth.submitter?.label ||
1083
+ (auth.submitter?.type && auth.submitter?.id !== undefined && auth.submitter?.id !== null
1084
+ ? `${auth.submitter.type}#${auth.submitter.id}`
1085
+ : "You");
1086
+ const result = await storage.addComment(existing.id, {
1087
+ author_type: auth.submitter?.type ?? "User",
1088
+ author_label: authorLabel,
1089
+ body: bodyText,
1090
+ attachments: preparedAttachments,
1091
+ status: "updated"
1092
+ });
1093
+ if (!result) {
1094
+ return jsonResponse({ error: "Feedback not found" }, 404, corsHeaders);
1095
+ }
1096
+ if (config.onFeedbackUpdated) {
1097
+ try {
1098
+ await config.onFeedbackUpdated(result.feedback);
1099
+ }
1100
+ catch (cbErr) {
1101
+ console.error("[context-drop] onFeedbackUpdated callback error:", cbErr);
1102
+ }
1103
+ }
1104
+ const ownershipToken = findOwnershipTokenFor(rawTokens, result.feedback.id, secret) ??
1105
+ generateOwnershipToken(result.feedback.id, secret);
1106
+ return jsonResponse({
1107
+ id: result.comment.id,
1108
+ feedback_id: result.feedback.id,
1109
+ status: result.feedback.status,
1110
+ comment: result.comment,
1111
+ feedback: serializeOwnFeedback(result.feedback, ownershipToken),
1112
+ created_at: result.comment.created_at
1113
+ }, 201, corsHeaders);
1114
+ }
1115
+ catch (err) {
1116
+ if (err instanceof SensitiveElementError || err instanceof UploadValidationError) {
1117
+ return jsonResponse({ error: err.message }, err.status, corsHeaders);
1118
+ }
1119
+ return jsonResponse({ error: err.message || "Failed to add comment" }, 422, corsHeaders);
1120
+ }
1121
+ }
1000
1122
  if (parsedRoute.kind === "feedback_item" && method === "DELETE") {
1001
1123
  const originCheck = verifyMutationOrigin(request, config.allowedOrigins);
1002
1124
  if (!originCheck.ok) {
@@ -1066,7 +1188,11 @@ export function createContextDropFetchHandler(config = {}) {
1066
1188
  })) {
1067
1189
  return new Response("Forbidden", { status: 403, headers: corsHeaders });
1068
1190
  }
1069
- const attMeta = existing.attachments.find((a) => String(a.id) === String(parsedRoute.attachmentId));
1191
+ const allFeedbackAttachments = [
1192
+ ...existing.attachments,
1193
+ ...(existing.comments ?? []).flatMap((c) => c.attachments ?? [])
1194
+ ];
1195
+ const attMeta = allFeedbackAttachments.find((a) => String(a.id) === String(parsedRoute.attachmentId));
1070
1196
  if (!attMeta) {
1071
1197
  return new Response("Not Found", { status: 404, headers: corsHeaders });
1072
1198
  }
@@ -139,9 +139,20 @@ export function createLocalStorageAdapter(options = {}) {
139
139
  captured_at TEXT NOT NULL
140
140
  );
141
141
 
142
+ CREATE TABLE IF NOT EXISTS context_drop_comments (
143
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
144
+ feedback_id INTEGER NOT NULL REFERENCES context_drop_feedbacks(id) ON DELETE CASCADE,
145
+ author_type TEXT,
146
+ author_label TEXT,
147
+ body TEXT,
148
+ created_at TEXT NOT NULL,
149
+ updated_at TEXT NOT NULL
150
+ );
151
+
142
152
  CREATE TABLE IF NOT EXISTS context_drop_attachments (
143
153
  id INTEGER PRIMARY KEY AUTOINCREMENT,
144
154
  feedback_id INTEGER NOT NULL REFERENCES context_drop_feedbacks(id) ON DELETE CASCADE,
155
+ comment_id INTEGER REFERENCES context_drop_comments(id) ON DELETE CASCADE,
145
156
  element_reference_id INTEGER REFERENCES context_drop_element_references(id) ON DELETE SET NULL,
146
157
  attachment_type TEXT NOT NULL,
147
158
  filename TEXT,
@@ -156,6 +167,11 @@ export function createLocalStorageAdapter(options = {}) {
156
167
  if (!cols.some((c) => String(c["name"]) === "deleted_at")) {
157
168
  sqliteDb.exec("ALTER TABLE context_drop_feedbacks ADD COLUMN deleted_at TEXT;");
158
169
  }
170
+ const attCols = sqliteDb.prepare("PRAGMA table_info(context_drop_attachments)").all();
171
+ if (!attCols.some((c) => String(c["name"]) === "comment_id")) {
172
+ sqliteDb.exec("ALTER TABLE context_drop_attachments ADD COLUMN comment_id INTEGER REFERENCES context_drop_comments(id) ON DELETE CASCADE;");
173
+ }
174
+ sqliteDb.exec("UPDATE context_drop_feedbacks SET status = 'fixed' WHERE status = 'resolved';");
159
175
  const hydrateFeedbackRow = (row) => {
160
176
  const fbId = Number(row["id"]);
161
177
  const elRows = sqliteDb
@@ -164,6 +180,9 @@ export function createLocalStorageAdapter(options = {}) {
164
180
  const attRows = sqliteDb
165
181
  .prepare("SELECT * FROM context_drop_attachments WHERE feedback_id = ? ORDER BY id ASC")
166
182
  .all(fbId);
183
+ const commentRows = sqliteDb
184
+ .prepare("SELECT * FROM context_drop_comments WHERE feedback_id = ? ORDER BY id ASC")
185
+ .all(fbId);
167
186
  const elements = elRows.map((el) => ({
168
187
  id: Number(el["id"]),
169
188
  feedback_id: fbId,
@@ -178,9 +197,12 @@ export function createLocalStorageAdapter(options = {}) {
178
197
  metadata: JSON.parse(String(el["metadata_json"] || "{}")),
179
198
  captured_at: String(el["captured_at"])
180
199
  }));
181
- const attachments = attRows.map((att) => ({
200
+ const allAttachments = attRows.map((att) => ({
182
201
  id: Number(att["id"]),
183
202
  feedback_id: fbId,
203
+ comment_id: att["comment_id"] !== null && att["comment_id"] !== undefined
204
+ ? Number(att["comment_id"])
205
+ : null,
184
206
  element_reference_id: att["element_reference_id"] !== null && att["element_reference_id"] !== undefined
185
207
  ? Number(att["element_reference_id"])
186
208
  : null,
@@ -194,10 +216,34 @@ export function createLocalStorageAdapter(options = {}) {
194
216
  metadata: JSON.parse(String(att["metadata_json"] || "{}")),
195
217
  created_at: String(att["created_at"])
196
218
  }));
219
+ const attachments = allAttachments.filter((a) => a.comment_id === null || a.comment_id === undefined);
220
+ const attachmentsByComment = new Map();
221
+ for (const a of allAttachments) {
222
+ if (a.comment_id !== null && a.comment_id !== undefined) {
223
+ const list = attachmentsByComment.get(Number(a.comment_id)) ?? [];
224
+ list.push(a);
225
+ attachmentsByComment.set(Number(a.comment_id), list);
226
+ }
227
+ }
228
+ const comments = commentRows.map((c) => {
229
+ const cid = Number(c["id"]);
230
+ return {
231
+ id: cid,
232
+ feedback_id: fbId,
233
+ author_type: c["author_type"] ?? null,
234
+ author_label: String(c["author_label"] || "You"),
235
+ body: c["body"] ?? null,
236
+ attachments: attachmentsByComment.get(cid) ?? [],
237
+ created_at: String(c["created_at"]),
238
+ updated_at: String(c["updated_at"])
239
+ };
240
+ });
241
+ const rawStatus = String(row["status"]);
242
+ const normalizedStatus = (rawStatus === "resolved" ? "fixed" : rawStatus);
197
243
  return {
198
244
  id: fbId,
199
245
  environment: String(row["environment"]),
200
- status: String(row["status"]),
246
+ status: normalizedStatus,
201
247
  message: row["message"] ?? null,
202
248
  page_url: String(row["page_url"]),
203
249
  user_agent: row["user_agent"] ?? null,
@@ -206,6 +252,7 @@ export function createLocalStorageAdapter(options = {}) {
206
252
  metadata: JSON.parse(String(row["metadata_json"] || "{}")),
207
253
  element_references: elements,
208
254
  attachments,
255
+ comments,
209
256
  created_at: String(row["created_at"]),
210
257
  updated_at: String(row["updated_at"]),
211
258
  deleted_at: row["deleted_at"] ?? null
@@ -339,9 +386,14 @@ export function createLocalStorageAdapter(options = {}) {
339
386
  const now = new Date().toISOString();
340
387
  const nextMessage = input.message !== undefined ? input.message : existing.message;
341
388
  const nextMetadata = input.metadata !== undefined ? input.metadata : existing.metadata;
389
+ const contentEdited = input.message !== undefined ||
390
+ input.metadata !== undefined ||
391
+ input.element_references !== undefined ||
392
+ input.attachments !== undefined;
393
+ const nextStatus = input.status ?? (contentEdited ? "updated" : existing.status);
342
394
  sqliteDb
343
- .prepare("UPDATE context_drop_feedbacks SET message = ?, metadata_json = ?, updated_at = ? WHERE id = ?")
344
- .run(nextMessage, JSON.stringify(nextMetadata || {}), now, fbId);
395
+ .prepare("UPDATE context_drop_feedbacks SET message = ?, metadata_json = ?, status = ?, updated_at = ? WHERE id = ?")
396
+ .run(nextMessage, JSON.stringify(nextMetadata || {}), nextStatus, now, fbId);
345
397
  const elIdByRef = new Map();
346
398
  if (input.element_references !== undefined) {
347
399
  sqliteDb
@@ -482,6 +534,48 @@ export function createLocalStorageAdapter(options = {}) {
482
534
  previous_status: existing.status,
483
535
  feedback: updated
484
536
  };
537
+ },
538
+ async addComment(feedbackId, input) {
539
+ const fbId = Number(feedbackId);
540
+ const existing = await this.getFeedback(fbId);
541
+ if (!existing || existing.deleted_at)
542
+ return null;
543
+ const now = new Date().toISOString();
544
+ const commentRes = sqliteDb
545
+ .prepare(`INSERT INTO context_drop_comments (feedback_id, author_type, author_label, body, created_at, updated_at)
546
+ VALUES (?, ?, ?, ?, ?, ?)`)
547
+ .run(fbId, input.author_type ?? "User", input.author_label || "You", input.body, now, now);
548
+ const commentId = Number(commentRes.lastInsertRowid);
549
+ const insertAttStmt = sqliteDb.prepare(`INSERT INTO context_drop_attachments
550
+ (feedback_id, comment_id, element_reference_id, attachment_type, filename, content_type, byte_size, blob_key, metadata_json, created_at)
551
+ VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, ?)`);
552
+ for (const att of input.attachments ?? []) {
553
+ let blobKey = null;
554
+ if (att.data) {
555
+ const saved = await blobStore.putBlob({
556
+ key: `fb_${fbId}_comment_${commentId}_${crypto.randomUUID()}`,
557
+ data: att.data,
558
+ contentType: att.content_type || "image/png",
559
+ filename: att.filename || "image.png"
560
+ });
561
+ blobKey = saved.key;
562
+ }
563
+ insertAttStmt.run(fbId, commentId, att.attachment_type, att.filename, att.content_type, att.byte_size, blobKey, JSON.stringify(att.metadata || {}), now);
564
+ }
565
+ const nextStatus = input.status ?? "updated";
566
+ sqliteDb
567
+ .prepare("UPDATE context_drop_feedbacks SET status = ?, updated_at = ? WHERE id = ?")
568
+ .run(nextStatus, now, fbId);
569
+ const updated = await this.getFeedback(fbId);
570
+ if (!updated)
571
+ return null;
572
+ const createdComment = (updated.comments ?? []).find((c) => Number(c.id) === commentId);
573
+ if (!createdComment)
574
+ return null;
575
+ return {
576
+ comment: createdComment,
577
+ feedback: updated
578
+ };
485
579
  }
486
580
  };
487
581
  }
@@ -676,12 +770,22 @@ export function createLocalStorageAdapter(options = {}) {
676
770
  if (!found || found.deleted_at)
677
771
  return null;
678
772
  const now = new Date().toISOString();
773
+ const contentEdited = input.message !== undefined ||
774
+ input.metadata !== undefined ||
775
+ input.element_references !== undefined ||
776
+ input.attachments !== undefined;
679
777
  if (input.message !== undefined) {
680
778
  found.message = input.message;
681
779
  }
682
780
  if (input.metadata !== undefined) {
683
781
  found.metadata = { ...input.metadata };
684
782
  }
783
+ if (input.status !== undefined) {
784
+ found.status = input.status;
785
+ }
786
+ else if (contentEdited) {
787
+ found.status = "updated";
788
+ }
685
789
  const elementsByRef = new Map();
686
790
  if (input.element_references !== undefined) {
687
791
  found.element_references = input.element_references.map((el, idx) => {
@@ -802,6 +906,17 @@ export function createLocalStorageAdapter(options = {}) {
802
906
  data: bytes
803
907
  };
804
908
  }
909
+ for (const comment of fb.comments ?? []) {
910
+ const commentAtt = comment.attachments.find((a) => String(a.id) === String(attachmentId));
911
+ if (commentAtt) {
912
+ const bytes = commentAtt.blob_key ? await blobStore.getBlob(commentAtt.blob_key) : null;
913
+ return {
914
+ attachment: structuredClone(commentAtt),
915
+ element_selector: null,
916
+ data: bytes
917
+ };
918
+ }
919
+ }
805
920
  }
806
921
  return null;
807
922
  },
@@ -809,6 +924,62 @@ export function createLocalStorageAdapter(options = {}) {
809
924
  const res = await this.getAttachment(attachmentId);
810
925
  return res?.data ?? null;
811
926
  },
927
+ async addComment(feedbackId, input) {
928
+ const state = readJsonStore();
929
+ const found = state.feedbacks.find((fb) => String(fb.id) === String(feedbackId));
930
+ if (!found || found.deleted_at)
931
+ return null;
932
+ const now = new Date().toISOString();
933
+ const commentId = state.nextCommentId ?? 1;
934
+ state.nextCommentId = commentId + 1;
935
+ const commentAttachments = [];
936
+ for (const att of input.attachments ?? []) {
937
+ const attId = state.nextAttachmentId++;
938
+ let blobKey = null;
939
+ if (att.data) {
940
+ const saved = await blobStore.putBlob({
941
+ key: `fb_${found.id}_comment_${commentId}_${attId}_${crypto.randomUUID()}`,
942
+ data: att.data,
943
+ contentType: att.content_type || "image/png",
944
+ filename: att.filename || "image.png"
945
+ });
946
+ blobKey = saved.key;
947
+ }
948
+ commentAttachments.push({
949
+ id: attId,
950
+ feedback_id: found.id,
951
+ comment_id: commentId,
952
+ element_reference_id: null,
953
+ attachment_type: att.attachment_type,
954
+ filename: att.filename,
955
+ content_type: att.content_type,
956
+ byte_size: att.byte_size,
957
+ blob_key: blobKey,
958
+ metadata: { ...att.metadata },
959
+ created_at: now
960
+ });
961
+ }
962
+ const comment = {
963
+ id: commentId,
964
+ feedback_id: found.id,
965
+ author_type: input.author_type ?? "User",
966
+ author_label: input.author_label || "You",
967
+ body: input.body,
968
+ attachments: commentAttachments,
969
+ created_at: now,
970
+ updated_at: now
971
+ };
972
+ if (!found.comments)
973
+ found.comments = [];
974
+ found.comments.push(comment);
975
+ found.status = input.status ?? "updated";
976
+ found.updated_at = now;
977
+ writeJsonStore(state);
978
+ return {
979
+ comment: structuredClone(comment),
980
+ feedback: structuredClone(found)
981
+ };
982
+ },
812
983
  async updateFeedbackStatus(id, status) {
813
984
  const state = readJsonStore();
814
985
  const found = state.feedbacks.find((fb) => String(fb.id) === String(id));
@@ -56,6 +56,7 @@ export function toFeedbackSummary(record) {
56
56
  submitter: formatSubmitterLabel(record.submitter),
57
57
  attachments_count: record.attachments.length,
58
58
  element_references_count: record.element_references.length,
59
+ comments_count: record.comments?.length ?? 0,
59
60
  element_selectors: record.element_references.map((el) => el.selector),
60
61
  created_at: record.created_at
61
62
  };
@@ -99,6 +100,7 @@ export function createMemoryStorageAdapter() {
99
100
  let nextFeedbackId = 1;
100
101
  let nextElementId = 1;
101
102
  let nextAttachmentId = 1;
103
+ let nextCommentId = 1;
102
104
  const secret = crypto.randomBytes(32);
103
105
  const pendingBlobs = new Map();
104
106
  const attachmentBlobs = new Map();
@@ -200,6 +202,7 @@ export function createMemoryStorageAdapter() {
200
202
  metadata: { ...input.metadata },
201
203
  element_references: storedElements,
202
204
  attachments: storedAttachments,
205
+ comments: [],
203
206
  created_at: now,
204
207
  updated_at: now,
205
208
  deleted_at: null
@@ -245,12 +248,22 @@ export function createMemoryStorageAdapter() {
245
248
  if (!existing || existing.deleted_at)
246
249
  return null;
247
250
  const now = new Date().toISOString();
251
+ const contentEdited = input.message !== undefined ||
252
+ input.metadata !== undefined ||
253
+ input.element_references !== undefined ||
254
+ input.attachments !== undefined;
248
255
  if (input.message !== undefined) {
249
256
  existing.message = input.message;
250
257
  }
251
258
  if (input.metadata !== undefined) {
252
259
  existing.metadata = { ...input.metadata };
253
260
  }
261
+ if (input.status !== undefined) {
262
+ existing.status = input.status;
263
+ }
264
+ else if (contentEdited) {
265
+ existing.status = "updated";
266
+ }
254
267
  const elementsByRef = new Map();
255
268
  if (input.element_references !== undefined) {
256
269
  existing.element_references = input.element_references.map((el, idx) => {
@@ -363,6 +376,17 @@ export function createMemoryStorageAdapter() {
363
376
  data: bytes ? new Uint8Array(bytes) : null
364
377
  };
365
378
  }
379
+ for (const comment of fb.comments ?? []) {
380
+ const commentAtt = comment.attachments.find((a) => Number(a.id) === numAttId);
381
+ if (commentAtt) {
382
+ const bytes = commentAtt.blob_key ? attachmentBlobs.get(commentAtt.blob_key) ?? null : null;
383
+ return {
384
+ attachment: structuredClone(commentAtt),
385
+ element_selector: null,
386
+ data: bytes ? new Uint8Array(bytes) : null
387
+ };
388
+ }
389
+ }
366
390
  }
367
391
  return null;
368
392
  },
@@ -370,6 +394,54 @@ export function createMemoryStorageAdapter() {
370
394
  const res = await this.getAttachment(attachmentId);
371
395
  return res?.data ?? null;
372
396
  },
397
+ async addComment(feedbackId, input) {
398
+ const numId = Number(feedbackId);
399
+ const existing = feedbacks.get(numId);
400
+ if (!existing || existing.deleted_at)
401
+ return null;
402
+ const now = new Date().toISOString();
403
+ const commentId = nextCommentId++;
404
+ const commentAttachments = [];
405
+ for (const att of input.attachments ?? []) {
406
+ const attId = nextAttachmentId++;
407
+ const blobKey = att.data ? `att_${attId}` : null;
408
+ if (blobKey && att.data) {
409
+ attachmentBlobs.set(blobKey, new Uint8Array(att.data));
410
+ }
411
+ commentAttachments.push({
412
+ id: attId,
413
+ feedback_id: existing.id,
414
+ comment_id: commentId,
415
+ element_reference_id: null,
416
+ attachment_type: att.attachment_type,
417
+ filename: att.filename,
418
+ content_type: att.content_type,
419
+ byte_size: att.byte_size,
420
+ blob_key: blobKey,
421
+ metadata: { ...att.metadata },
422
+ created_at: now
423
+ });
424
+ }
425
+ const comment = {
426
+ id: commentId,
427
+ feedback_id: existing.id,
428
+ author_type: input.author_type ?? "User",
429
+ author_label: input.author_label || "You",
430
+ body: input.body,
431
+ attachments: commentAttachments,
432
+ created_at: now,
433
+ updated_at: now
434
+ };
435
+ if (!existing.comments)
436
+ existing.comments = [];
437
+ existing.comments.push(comment);
438
+ existing.status = input.status ?? "updated";
439
+ existing.updated_at = now;
440
+ return {
441
+ comment: structuredClone(comment),
442
+ feedback: structuredClone(existing)
443
+ };
444
+ },
373
445
  async updateFeedbackStatus(id, status) {
374
446
  const numId = Number(id);
375
447
  const existing = feedbacks.get(numId);