@matija2209/payload-plugin-admin-feedback 1.0.3 → 1.1.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/dist/index.js CHANGED
@@ -1,6 +1,22 @@
1
1
  import { definePlugin, headersWithCors } from 'payload';
2
+ import { timingSafeEqual, createHmac } from 'crypto';
2
3
 
3
4
  // src/index.ts
5
+ var DELETE_TOKEN_TTL_MS = 60 * 60 * 1e3;
6
+ var sign = (secret, value) => createHmac("sha256", secret).update(`admin-feedback-delete:${value}`).digest("base64url");
7
+ var createDeleteToken = (secret, mediaId, userId, now = Date.now()) => {
8
+ const expiresAt = now + DELETE_TOKEN_TTL_MS;
9
+ return `${expiresAt}.${sign(secret, `${mediaId}.${userId}.${expiresAt}`)}`;
10
+ };
11
+ var verifyDeleteToken = (secret, token, mediaId, userId, now = Date.now()) => {
12
+ if (!token) return false;
13
+ const [expiresRaw, signature] = token.split(".");
14
+ const expiresAt = Number(expiresRaw);
15
+ if (!signature || !Number.isFinite(expiresAt) || expiresAt < now) return false;
16
+ const expected = Buffer.from(sign(secret, `${mediaId}.${userId}.${expiresAt}`));
17
+ const actual = Buffer.from(signature);
18
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
19
+ };
4
20
  var trim = (value) => {
5
21
  if (typeof value !== "string") {
6
22
  return null;
@@ -12,36 +28,10 @@ var corsHeaders = (req, init) => headersWithCors({
12
28
  headers: new Headers(init),
13
29
  req
14
30
  });
15
- var getCreatorId = (createdBy) => {
16
- if (!createdBy) {
17
- return null;
18
- }
19
- if (typeof createdBy === "object" && createdBy !== null && "id" in createdBy) {
20
- const value = createdBy.id;
21
- return value !== void 0 && value !== null ? String(value) : null;
22
- }
23
- if (typeof createdBy === "number" || typeof createdBy === "string") {
24
- return String(createdBy);
25
- }
26
- return null;
27
- };
28
- var getRelationId = (value) => {
29
- if (!value) {
30
- return null;
31
- }
32
- if (typeof value === "object" && value !== null && "id" in value) {
33
- const relationId = value.id;
34
- return relationId !== void 0 && relationId !== null ? String(relationId) : null;
35
- }
36
- if (typeof value === "number" || typeof value === "string") {
37
- return String(value);
38
- }
39
- return null;
40
- };
41
31
 
42
- // src/collections/admin-feedback/endpoints/deleteFeedback.ts
43
- var createDeleteFeedbackEndpoint = (mediaCollectionSlug) => ({
44
- path: "/delete/:id",
32
+ // src/endpoints/deleteUpload.ts
33
+ var createDeleteUploadEndpoint = (mediaCollectionSlug) => ({
34
+ path: "/upload/:id",
45
35
  method: "delete",
46
36
  handler: async (req) => {
47
37
  try {
@@ -52,88 +42,71 @@ var createDeleteFeedbackEndpoint = (mediaCollectionSlug) => ({
52
42
  );
53
43
  }
54
44
  const id = req.routeParams?.id;
55
- if (!id) {
45
+ if (typeof id !== "string" && typeof id !== "number") {
56
46
  return Response.json(
57
- { success: false, error: "Missing feedback ID." },
47
+ { success: false, error: "Missing media ID." },
58
48
  { status: 400, headers: corsHeaders(req) }
59
49
  );
60
50
  }
61
- const existing = await req.payload.findByID({
62
- collection: "admin-feedback",
63
- id
64
- });
65
- if (String(req.user.id) !== getCreatorId(existing.createdBy)) {
51
+ const token = req.headers.get("x-feedback-delete-token");
52
+ if (!verifyDeleteToken(req.payload.secret, token, id, req.user.id)) {
66
53
  return Response.json(
67
- { success: false, error: "You can only delete your own feedback." },
54
+ { success: false, error: "Forbidden" },
68
55
  { status: 403, headers: corsHeaders(req) }
69
56
  );
70
57
  }
71
- const screenshotId = getRelationId(existing.screenshot);
72
- if (screenshotId) {
73
- try {
74
- await req.payload.delete({
75
- collection: mediaCollectionSlug,
76
- id: screenshotId
77
- });
78
- } catch (error) {
79
- req.payload.logger.warn(
80
- `Failed to delete feedback screenshot ${screenshotId}: ${error instanceof Error ? error.message : "unknown error"}`
81
- );
82
- }
83
- }
84
- await req.payload.delete({
58
+ const attached = await req.payload.count({
85
59
  collection: "admin-feedback",
86
- id
60
+ where: { screenshot: { equals: id } },
61
+ overrideAccess: true
87
62
  });
88
- return Response.json({ success: true }, { headers: corsHeaders(req) });
89
- } catch (error) {
90
- return Response.json(
91
- { success: false, error: error instanceof Error ? error.message : "Unknown error" },
92
- { status: 500, headers: corsHeaders(req) }
93
- );
94
- }
95
- }
96
- });
97
-
98
- // src/collections/admin-feedback/endpoints/deleteUpload.ts
99
- var createDeleteUploadEndpoint = (mediaCollectionSlug) => ({
100
- path: "/upload/:id",
101
- method: "delete",
102
- handler: async (req) => {
103
- try {
104
- if (!req.user) {
105
- return Response.json(
106
- { success: false, error: "Unauthorized" },
107
- { status: 401, headers: corsHeaders(req) }
108
- );
109
- }
110
- const id = req.routeParams?.id;
111
- if (!id) {
63
+ if (attached.totalDocs > 0) {
112
64
  return Response.json(
113
- { success: false, error: "Missing media ID." },
114
- { status: 400, headers: corsHeaders(req) }
65
+ { success: false, error: "This screenshot is already part of a report." },
66
+ { status: 409, headers: corsHeaders(req) }
115
67
  );
116
68
  }
117
69
  await req.payload.delete({
118
70
  collection: mediaCollectionSlug,
119
- id
71
+ id,
72
+ overrideAccess: true
120
73
  });
121
74
  return Response.json({ success: true }, { headers: corsHeaders(req) });
122
75
  } catch (error) {
76
+ req.payload.logger.error({ err: error, msg: "admin-feedback: delete upload failed" });
123
77
  return Response.json(
124
- { success: false, error: error instanceof Error ? error.message : "Unknown error" },
78
+ { success: false, error: "Could not remove the image." },
125
79
  { status: 500, headers: corsHeaders(req) }
126
80
  );
127
81
  }
128
82
  }
129
83
  });
130
84
 
131
- // src/collections/admin-feedback/endpoints/submit.ts
132
- var createSubmitEndpoint = () => ({
85
+ // src/endpoints/access.ts
86
+ var canCreateFeedback = async (req, options) => {
87
+ const create = options.access.create;
88
+ if (!create) return Boolean(req.user);
89
+ const result = await create({ req });
90
+ return Boolean(result);
91
+ };
92
+
93
+ // src/endpoints/submit.ts
94
+ var toId = (value) => {
95
+ if (typeof value === "number" && Number.isFinite(value)) return value;
96
+ if (typeof value === "string" && value.trim()) return value.trim();
97
+ return void 0;
98
+ };
99
+ var createSubmitEndpoint = (options) => ({
133
100
  path: "/submit",
134
101
  method: "post",
135
102
  handler: async (req) => {
136
103
  try {
104
+ if (!await canCreateFeedback(req, options)) {
105
+ return Response.json(
106
+ { success: false, error: req.user ? "Forbidden" : "Unauthorized" },
107
+ { status: req.user ? 403 : 401, headers: corsHeaders(req) }
108
+ );
109
+ }
137
110
  const body = await req.json();
138
111
  const message = trim(body?.message);
139
112
  if (!message) {
@@ -144,100 +117,108 @@ var createSubmitEndpoint = () => ({
144
117
  }
145
118
  const doc = await req.payload.create({
146
119
  collection: "admin-feedback",
120
+ req,
147
121
  data: {
148
122
  message,
149
123
  pagePath: trim(body?.pagePath) || "/",
150
124
  selector: trim(body?.selector) || void 0,
151
125
  selectedText: trim(body?.selectedText) || void 0,
152
- screenshot: body?.screenshotId || void 0,
153
- createdBy: req.user?.id,
126
+ screenshot: toId(body?.screenshotId),
154
127
  meta: {
155
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
156
128
  userAgent: trim(body?.meta?.userAgent),
157
129
  locale: trim(body?.meta?.locale),
158
130
  viewport: trim(body?.meta?.viewport)
159
131
  }
160
132
  }
161
133
  });
162
- return Response.json({ success: true, id: doc.id }, { headers: corsHeaders(req) });
134
+ return Response.json(
135
+ { success: true, id: doc.id },
136
+ { headers: corsHeaders(req) }
137
+ );
163
138
  } catch (error) {
139
+ req.payload.logger.error({ err: error, msg: "admin-feedback: submit failed" });
164
140
  return Response.json(
165
- { success: false, error: error instanceof Error ? error.message : "Unknown error" },
141
+ { success: false, error: "Could not save the report." },
166
142
  { status: 500, headers: corsHeaders(req) }
167
143
  );
168
144
  }
169
145
  }
170
146
  });
171
147
 
172
- // src/collections/admin-feedback/endpoints/updateFeedback.ts
173
- var createUpdateFeedbackEndpoint = () => ({
174
- path: "/update/:id",
175
- method: "patch",
176
- handler: async (req) => {
148
+ // src/tenant/extractTenantSlug.ts
149
+ var extractTenantSlugFromPathname = (pathname, pathMarkers) => {
150
+ if (pathMarkers.length === 0) {
151
+ return null;
152
+ }
153
+ const segments = pathname.split("?")[0].split("/").filter(Boolean);
154
+ for (const marker of pathMarkers) {
155
+ const markerIndex = segments.indexOf(marker);
156
+ if (markerIndex > 0) {
157
+ return segments[markerIndex - 1] ?? null;
158
+ }
159
+ }
160
+ return null;
161
+ };
162
+
163
+ // src/tenant/resolveUploadTenant.ts
164
+ var resolveFeedbackUploadTenantId = async (req, options, tenantSlugFromForm) => {
165
+ const tenantConfig = options.tenant;
166
+ if (!tenantConfig?.enabled) {
167
+ return null;
168
+ }
169
+ let tenantSlug = tenantSlugFromForm;
170
+ if (!tenantSlug && tenantConfig.pathMarkers?.length) {
177
171
  try {
178
- if (!req.user) {
179
- return Response.json(
180
- { success: false, error: "Unauthorized" },
181
- { status: 401, headers: corsHeaders(req) }
182
- );
183
- }
184
- const id = req.routeParams?.id;
185
- if (!id) {
186
- return Response.json(
187
- { success: false, error: "Missing feedback ID." },
188
- { status: 400, headers: corsHeaders(req) }
189
- );
190
- }
191
- const existing = await req.payload.findByID({
192
- collection: "admin-feedback",
193
- id
194
- });
195
- if (String(req.user.id) !== getCreatorId(existing.createdBy)) {
196
- return Response.json(
197
- { success: false, error: "You can only edit your own feedback." },
198
- { status: 403, headers: corsHeaders(req) }
199
- );
200
- }
201
- const body = await req.json();
202
- const updateData = {};
203
- const newMessage = trim(body?.message);
204
- if (newMessage) {
205
- updateData.message = newMessage;
206
- }
207
- if (body && "screenshotId" in body) {
208
- updateData.screenshot = body.screenshotId || null;
209
- }
210
- const updated = await req.payload.update({
211
- collection: "admin-feedback",
212
- id: existing.id,
213
- data: updateData
214
- });
215
- return Response.json({ success: true, doc: updated }, { headers: corsHeaders(req) });
216
- } catch (error) {
217
- return Response.json(
218
- { success: false, error: error instanceof Error ? error.message : "Unknown error" },
219
- { status: 500, headers: corsHeaders(req) }
220
- );
172
+ const url = new URL(req.url || "", `http://${req.headers.get("host") || "localhost"}`);
173
+ tenantSlug = extractTenantSlugFromPathname(url.pathname, tenantConfig.pathMarkers);
174
+ } catch {
175
+ tenantSlug = null;
221
176
  }
222
177
  }
223
- });
178
+ const collectionSlug = tenantConfig.collectionSlug || "tenants";
179
+ if (tenantSlug) {
180
+ const found = await req.payload.find({
181
+ collection: collectionSlug,
182
+ where: { slug: { equals: tenantSlug } },
183
+ limit: 1,
184
+ overrideAccess: true
185
+ });
186
+ const doc = found.docs[0];
187
+ if (doc?.id != null) {
188
+ return Number(doc.id);
189
+ }
190
+ }
191
+ if (tenantConfig.resolveTenantId) {
192
+ return tenantConfig.resolveTenantId({ req, tenantSlug: tenantSlug ?? null });
193
+ }
194
+ return null;
195
+ };
224
196
 
225
- // src/collections/admin-feedback/endpoints/upload.ts
226
- var createUploadEndpoint = (mediaCollectionSlug) => ({
197
+ // src/endpoints/upload.ts
198
+ var createUploadEndpoint = (mediaCollectionSlug, options) => ({
227
199
  path: "/upload",
228
200
  method: "post",
229
201
  handler: async (req) => {
230
202
  try {
231
- if (!req.user) {
203
+ if (!options.allowScreenshotUpload) {
232
204
  return Response.json(
233
- { success: false, error: "Unauthorized" },
234
- { status: 401, headers: corsHeaders(req) }
205
+ { success: false, error: "Uploads are disabled." },
206
+ { status: 404, headers: corsHeaders(req) }
207
+ );
208
+ }
209
+ if (!req.user || !await canCreateFeedback(req, options)) {
210
+ return Response.json(
211
+ { success: false, error: req.user ? "Forbidden" : "Unauthorized" },
212
+ { status: req.user ? 403 : 401, headers: corsHeaders(req) }
235
213
  );
236
214
  }
237
215
  const formData = await req.formData();
238
216
  const file = formData.get("file");
239
217
  const altRaw = formData.get("alt");
218
+ const tenantSlugKey = options.tenant?.formDataSlugKey || "tenant";
219
+ const tenantSlugRaw = formData.get(tenantSlugKey);
240
220
  const alt = typeof altRaw === "string" ? altRaw.trim() : "";
221
+ const tenantSlugFromForm = typeof tenantSlugRaw === "string" ? tenantSlugRaw.trim() : "";
241
222
  if (!(file instanceof File)) {
242
223
  return Response.json(
243
224
  { success: false, error: "Missing file." },
@@ -250,11 +231,39 @@ var createUploadEndpoint = (mediaCollectionSlug) => ({
250
231
  { status: 400, headers: corsHeaders(req) }
251
232
  );
252
233
  }
234
+ if (file.size > options.screenshot.maxFileSizeBytes) {
235
+ return Response.json(
236
+ { success: false, error: "File is too large." },
237
+ { status: 413, headers: corsHeaders(req) }
238
+ );
239
+ }
240
+ if (!options.screenshot.allowedMimeTypes.includes(file.type)) {
241
+ return Response.json(
242
+ { success: false, error: "This file type is not allowed." },
243
+ { status: 415, headers: corsHeaders(req) }
244
+ );
245
+ }
246
+ const mediaData = {
247
+ alt: alt || file.name
248
+ };
249
+ if (options.tenant?.enabled) {
250
+ const tenantId = await resolveFeedbackUploadTenantId(
251
+ req,
252
+ options,
253
+ tenantSlugFromForm || null
254
+ );
255
+ if (typeof tenantId !== "number") {
256
+ return Response.json(
257
+ { success: false, error: "Tenant context required." },
258
+ { status: 400, headers: corsHeaders(req) }
259
+ );
260
+ }
261
+ mediaData[options.tenant.fieldName || "tenant"] = tenantId;
262
+ }
253
263
  const media = await req.payload.create({
254
264
  collection: mediaCollectionSlug,
255
- data: {
256
- alt: alt || file.name
257
- },
265
+ overrideAccess: true,
266
+ data: mediaData,
258
267
  file: {
259
268
  data: Buffer.from(await file.arrayBuffer()),
260
269
  mimetype: file.type || "application/octet-stream",
@@ -263,28 +272,38 @@ var createUploadEndpoint = (mediaCollectionSlug) => ({
263
272
  }
264
273
  });
265
274
  return Response.json(
266
- { success: true, mediaId: Number(media.id) },
275
+ {
276
+ success: true,
277
+ mediaId: Number(media.id),
278
+ deleteToken: createDeleteToken(req.payload.secret, media.id, req.user.id)
279
+ },
267
280
  { headers: corsHeaders(req) }
268
281
  );
269
282
  } catch (error) {
283
+ req.payload.logger.error({ err: error, msg: "admin-feedback: upload failed" });
270
284
  return Response.json(
271
- { success: false, error: error instanceof Error ? error.message : "Unknown error" },
285
+ { success: false, error: "Could not upload the image." },
272
286
  { status: 500, headers: corsHeaders(req) }
273
287
  );
274
288
  }
275
289
  }
276
290
  });
277
291
 
278
- // src/collections/admin-feedback/endpoints/index.ts
279
- var createAdminFeedbackEndpoints = (mediaCollectionSlug) => [
280
- createSubmitEndpoint(),
281
- createUploadEndpoint(mediaCollectionSlug),
282
- createDeleteUploadEndpoint(mediaCollectionSlug),
283
- createUpdateFeedbackEndpoint(),
284
- createDeleteFeedbackEndpoint(mediaCollectionSlug)
285
- ];
292
+ // src/server/escapeHtml.ts
293
+ var HTML_ESCAPES = {
294
+ "&": "&amp;",
295
+ "<": "&lt;",
296
+ ">": "&gt;",
297
+ '"': "&quot;",
298
+ "'": "&#39;"
299
+ };
300
+ var escapeHtml = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char);
286
301
 
287
302
  // src/server/sendFeedbackEmail.ts
303
+ var toAbsoluteUrl = (base, url) => {
304
+ if (/^https?:\/\//i.test(url)) return url;
305
+ return `${base.replace(/\/+$/, "")}/${url.replace(/^\/+/, "")}`;
306
+ };
288
307
  async function sendFeedbackEmail(payload, options, data) {
289
308
  if (!options.emailTo) {
290
309
  return;
@@ -294,7 +313,7 @@ async function sendFeedbackEmail(payload, options, data) {
294
313
  const createdBy = data.createdByName || data.createdByEmail || "Unknown";
295
314
  let formattedDate = "Unknown";
296
315
  try {
297
- formattedDate = data.createdAt ? new Date(data.createdAt).toLocaleString("sl-SI", {
316
+ formattedDate = data.createdAt ? new Date(data.createdAt).toLocaleString(options.emailDateLocale || "sl-SI", {
298
317
  day: "numeric",
299
318
  month: "long",
300
319
  year: "numeric",
@@ -304,17 +323,18 @@ async function sendFeedbackEmail(payload, options, data) {
304
323
  } catch (e) {
305
324
  formattedDate = data.createdAt || "Unknown";
306
325
  }
307
- const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL || "http://localhost:34572";
308
- const adminUrl = data.id ? `${serverUrl}/admin/collections/admin-feedback/${data.id}` : null;
326
+ const serverUrl = options.adminBaseUrl || payload.config.serverURL || process.env.NEXT_PUBLIC_SERVER_URL || "http://localhost:3000";
327
+ const adminUrl = data.id ? toAbsoluteUrl(serverUrl, `${options.adminRoute}/collections/admin-feedback/${encodeURIComponent(String(data.id))}`) : null;
328
+ const screenshotUrl = data.screenshotUrl && data.screenshotUrl !== "-" ? toAbsoluteUrl(serverUrl, data.screenshotUrl) : null;
309
329
  const from = options.fromAddress ? `${options.fromName || options.fromLabel || "Admin Feedback"} <${options.fromAddress}>` : void 0;
310
- const screenshotHtml = data.screenshotUrl && data.screenshotUrl !== "-" ? `
330
+ const screenshotHtml = screenshotUrl ? `
311
331
  <div style="margin-top: 24px;">
312
332
  <p style="margin: 0 0 8px 0; font-size: 13px; text-transform: uppercase; letter-spacing: 0.05em; color: #8b8b8b; font-weight: 600;">Screenshot Preview</p>
313
333
  <div style="border-radius: 12px; overflow: hidden; border: 1px solid #d6e3e7; background: #00455a;">
314
- <img src="${data.screenshotUrl}" alt="Feedback Screenshot" style="width: 100%; height: auto; display: block;" />
334
+ <img src="${escapeHtml(screenshotUrl)}" alt="Feedback Screenshot" style="width: 100%; height: auto; display: block;" />
315
335
  </div>
316
336
  <p style="margin: 8px 0 0 0; font-size: 12px; color: #8b8b8b;">
317
- Full URL: <a href="${data.screenshotUrl}" style="color: #00455a; text-decoration: none;">${data.screenshotUrl}</a>
337
+ Full URL: <a href="${escapeHtml(screenshotUrl)}" style="color: #00455a; text-decoration: none;">${escapeHtml(screenshotUrl)}</a>
318
338
  </p>
319
339
  </div>
320
340
  ` : "";
@@ -341,42 +361,42 @@ async function sendFeedbackEmail(payload, options, data) {
341
361
  <div class="container">
342
362
  <div class="header">
343
363
  <h1>New Admin Feedback</h1>
344
- <p style="margin: 8px 0 0 0; opacity: 0.8; font-size: 14px;">[${sourceLabel}] Received via Feedback Widget</p>
364
+ <p style="margin: 8px 0 0 0; opacity: 0.8; font-size: 14px;">[${escapeHtml(sourceLabel)}] Received via Feedback Widget</p>
345
365
  </div>
346
366
  <div class="content">
347
367
  <div class="section">
348
368
  <p class="label">Message</p>
349
369
  <div class="message-box">
350
- <p class="value" style="white-space: pre-wrap;">${data.message}</p>
370
+ <p class="value" style="white-space: pre-wrap;">${escapeHtml(data.message)}</p>
351
371
  </div>
352
372
  </div>
353
373
 
354
374
  <div style="display: flex; flex-wrap: wrap; gap: 20px; border-top: 1px solid #e3edef; padding-top: 24px;">
355
375
  <div style="flex: 1; min-width: 200px; margin-bottom: 16px;">
356
376
  <p class="label">Page Path</p>
357
- <p class="value" style="word-break: break-all;">${data.pagePath}</p>
377
+ <p class="value" style="word-break: break-all;">${escapeHtml(data.pagePath)}</p>
358
378
  </div>
359
379
  <div style="flex: 1; min-width: 200px; margin-bottom: 16px;">
360
380
  <p class="label">Created By</p>
361
- <p class="value">${createdBy}</p>
381
+ <p class="value">${escapeHtml(createdBy)}</p>
362
382
  </div>
363
383
  </div>
364
384
 
365
385
  <div style="display: flex; flex-wrap: wrap; gap: 20px;">
366
386
  <div style="flex: 1; min-width: 200px; margin-bottom: 16px;">
367
387
  <p class="label">Selector</p>
368
- <p class="value" style="font-family: monospace; font-size: 13px;">${data.selector || "-"}</p>
388
+ <p class="value" style="font-family: monospace; font-size: 13px;">${escapeHtml(data.selector || "-")}</p>
369
389
  </div>
370
390
  <div style="flex: 1; min-width: 200px; margin-bottom: 16px;">
371
391
  <p class="label">Created At</p>
372
- <p class="value">${formattedDate}</p>
392
+ <p class="value">${escapeHtml(formattedDate)}</p>
373
393
  </div>
374
394
  </div>
375
395
 
376
396
  ${data.selectedText && data.selectedText !== "-" ? `
377
397
  <div class="section">
378
398
  <p class="label">Selected Text</p>
379
- <p class="value" style="font-style: italic; color: #555;">"${data.selectedText}"</p>
399
+ <p class="value" style="font-style: italic; color: #555;">"${escapeHtml(data.selectedText)}"</p>
380
400
  </div>
381
401
  ` : ""}
382
402
 
@@ -384,7 +404,7 @@ async function sendFeedbackEmail(payload, options, data) {
384
404
 
385
405
  ${adminUrl ? `
386
406
  <div style="text-align: center; margin-top: 32px;">
387
- <a href="${adminUrl}" class="button">View in Admin Panel</a>
407
+ <a href="${escapeHtml(adminUrl)}" class="button">View in Admin Panel</a>
388
408
  </div>
389
409
  ` : ""}
390
410
  </div>
@@ -406,7 +426,7 @@ async function sendFeedbackEmail(payload, options, data) {
406
426
  await payload.sendEmail(emailMessage);
407
427
  }
408
428
 
409
- // src/collections/admin-feedback/hooks/afterChange.ts
429
+ // src/hooks/afterChange.ts
410
430
  var createAfterChangeHook = (options) => {
411
431
  return async ({ doc, operation, req }) => {
412
432
  if (operation !== "create") {
@@ -436,39 +456,38 @@ var createAfterChangeHook = (options) => {
436
456
  };
437
457
  };
438
458
 
439
- // src/collections/admin-feedback/hooks/beforeChange.ts
440
- var normalizeFeedbackBeforeChange = ({ data, req, operation }) => {
441
- if (!data) {
442
- return data;
443
- }
444
- const nextData = { ...data };
445
- const message = trim(nextData.message);
446
- const pagePath = trim(nextData.pagePath);
447
- nextData.message = message || "";
448
- nextData.pagePath = pagePath || "/";
449
- nextData.selector = trim(nextData.selector);
450
- nextData.selectedText = trim(nextData.selectedText);
451
- const existingMeta = typeof nextData.meta === "object" && nextData.meta !== null ? nextData.meta : {};
452
- nextData.meta = {
453
- ...existingMeta,
454
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
455
- userAgent: trim(existingMeta.userAgent),
456
- locale: trim(existingMeta.locale),
457
- viewport: trim(existingMeta.viewport)
459
+ // src/hooks/beforeChange.ts
460
+ var createBeforeChangeHook = () => {
461
+ return ({ data, req, operation, originalDoc }) => {
462
+ if (!data) {
463
+ return data;
464
+ }
465
+ const nextData = { ...data };
466
+ const message = trim(nextData.message);
467
+ const pagePath = trim(nextData.pagePath);
468
+ nextData.message = message || "";
469
+ nextData.pagePath = pagePath || "/";
470
+ nextData.selector = trim(nextData.selector);
471
+ nextData.selectedText = trim(nextData.selectedText);
472
+ const existingMeta = typeof nextData.meta === "object" && nextData.meta !== null ? nextData.meta : {};
473
+ nextData.meta = {
474
+ ...existingMeta,
475
+ createdAt: operation === "create" || typeof existingMeta.createdAt !== "string" ? (/* @__PURE__ */ new Date()).toISOString() : existingMeta.createdAt,
476
+ userAgent: trim(existingMeta.userAgent),
477
+ locale: trim(existingMeta.locale),
478
+ viewport: trim(existingMeta.viewport)
479
+ };
480
+ if (operation === "create") {
481
+ nextData.createdBy = req.user?.id ?? null;
482
+ } else {
483
+ const original = originalDoc?.createdBy;
484
+ nextData.createdBy = original && typeof original === "object" ? original.id ?? null : original ?? null;
485
+ }
486
+ return nextData;
458
487
  };
459
- if (operation === "create" && req.user && !nextData.createdBy) {
460
- nextData.createdBy = req.user.id;
461
- }
462
- return nextData;
463
488
  };
464
489
 
465
- // src/collections/admin-feedback/hooks/index.ts
466
- var createAdminFeedbackHooks = (options) => ({
467
- beforeChange: [normalizeFeedbackBeforeChange],
468
- afterChange: [createAfterChangeHook(options)]
469
- });
470
-
471
- // src/collections/admin-feedback/index.ts
490
+ // src/collections/AdminFeedback.ts
472
491
  var createAdminFeedbackCollection = (options, mediaCollectionSlug) => {
473
492
  return {
474
493
  slug: "admin-feedback",
@@ -481,14 +500,16 @@ var createAdminFeedbackCollection = (options, mediaCollectionSlug) => {
481
500
  useAsTitle: "message",
482
501
  defaultColumns: ["createdAt", "pagePath", "status"]
483
502
  },
484
- access: {
485
- read: ({ req }) => Boolean(req.user),
486
- create: () => true,
487
- update: ({ req }) => Boolean(req.user),
488
- delete: ({ req }) => Boolean(req.user)
503
+ access: options.access,
504
+ endpoints: [
505
+ createSubmitEndpoint(options),
506
+ createUploadEndpoint(mediaCollectionSlug, options),
507
+ createDeleteUploadEndpoint(mediaCollectionSlug)
508
+ ],
509
+ hooks: {
510
+ beforeChange: [createBeforeChangeHook()],
511
+ afterChange: [createAfterChangeHook(options)]
489
512
  },
490
- endpoints: createAdminFeedbackEndpoints(mediaCollectionSlug),
491
- hooks: createAdminFeedbackHooks(options),
492
513
  fields: [
493
514
  {
494
515
  name: "message",
@@ -568,6 +589,14 @@ var pathMatchesAllowlist = (pathname, patterns) => {
568
589
  var PLUGIN_SLUG = "payload-plugin-admin-feedback";
569
590
  var DEFAULT_MEDIA_COLLECTION_SLUG = "media";
570
591
  var DEFAULT_ORDER = 10;
592
+ var CLIENT_EXPORT = "@matija2209/payload-plugin-admin-feedback/client";
593
+ var signedIn = ({ req }) => Boolean(req.user);
594
+ var DEFAULT_ACCESS = {
595
+ create: signedIn,
596
+ read: signedIn,
597
+ update: signedIn,
598
+ delete: signedIn
599
+ };
571
600
  var isUploadCollection = (collection) => Boolean(collection.upload);
572
601
  var getCollectionLabel = (slug) => `Collection "${slug}"`;
573
602
  var resolveMediaCollectionSlug = (config, options) => {
@@ -597,13 +626,15 @@ var resolveMediaCollectionSlug = (config, options) => {
597
626
  }
598
627
  return targetCollection.slug;
599
628
  };
600
- var resolveOptions = (pluginOptions) => ({
629
+ var resolveOptions = (pluginOptions, config) => ({
601
630
  enabled: true,
602
631
  allowScreenshotUpload: true,
603
632
  maxMessageLength: 3e3,
604
633
  mediaCollectionSlug: DEFAULT_MEDIA_COLLECTION_SLUG,
605
634
  strictMediaCollection: true,
606
635
  ...pluginOptions,
636
+ access: { ...DEFAULT_ACCESS, ...pluginOptions.access },
637
+ adminRoute: config.routes?.admin || "/admin",
607
638
  frontend: {
608
639
  enabled: true,
609
640
  include: [],
@@ -621,7 +652,7 @@ var adminFeedbackPlugin = definePlugin({
621
652
  slug: PLUGIN_SLUG,
622
653
  order: DEFAULT_ORDER,
623
654
  plugin: ({ config, ...pluginOptions }) => {
624
- const options = resolveOptions(pluginOptions);
655
+ const options = resolveOptions(pluginOptions, config);
625
656
  if (!options.enabled) {
626
657
  return config;
627
658
  }
@@ -632,12 +663,37 @@ var adminFeedbackPlugin = definePlugin({
632
663
  config.email = pluginOptions.email;
633
664
  }
634
665
  const resolvedMediaCollectionSlug = resolveMediaCollectionSlug(config, options);
635
- const feedbackCollection = createAdminFeedbackCollection(options, resolvedMediaCollectionSlug);
666
+ const generatedCollection = createAdminFeedbackCollection(options, resolvedMediaCollectionSlug);
667
+ const feedbackCollection = options.collectionOverrides ? options.collectionOverrides(generatedCollection) : generatedCollection;
668
+ const adminWidget = options.adminWidget;
669
+ const admin = adminWidget?.enabled ? {
670
+ ...config.admin,
671
+ components: {
672
+ ...config.admin?.components,
673
+ providers: [
674
+ ...config.admin?.components?.providers || [],
675
+ {
676
+ path: `${CLIENT_EXPORT}#AdminFeedbackProvider`,
677
+ clientProps: {
678
+ collectionSlug: feedbackCollection.slug,
679
+ title: adminWidget.title,
680
+ submitLabel: adminWidget.submitLabel,
681
+ uploadLabel: adminWidget.uploadLabel,
682
+ allowScreenshotUpload: options.allowScreenshotUpload,
683
+ screenshotMaxFileSizeBytes: options.screenshot.maxFileSizeBytes,
684
+ screenshotAllowedMimeTypes: options.screenshot.allowedMimeTypes,
685
+ capturePolicy: options.screenshot.capturePolicy
686
+ }
687
+ }
688
+ ]
689
+ }
690
+ } : config.admin;
636
691
  return {
637
692
  ...config,
693
+ admin,
638
694
  collections: [...config.collections || [], feedbackCollection]
639
695
  };
640
696
  }
641
697
  });
642
698
 
643
- export { adminFeedbackPlugin, pathMatchesAllowlist };
699
+ export { adminFeedbackPlugin, extractTenantSlugFromPathname, pathMatchesAllowlist };