@matija2209/payload-plugin-admin-feedback 1.0.3 → 1.0.4

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.cjs CHANGED
@@ -14,90 +14,8 @@ var corsHeaders = (req, init) => payload.headersWithCors({
14
14
  headers: new Headers(init),
15
15
  req
16
16
  });
17
- var getCreatorId = (createdBy) => {
18
- if (!createdBy) {
19
- return null;
20
- }
21
- if (typeof createdBy === "object" && createdBy !== null && "id" in createdBy) {
22
- const value = createdBy.id;
23
- return value !== void 0 && value !== null ? String(value) : null;
24
- }
25
- if (typeof createdBy === "number" || typeof createdBy === "string") {
26
- return String(createdBy);
27
- }
28
- return null;
29
- };
30
- var getRelationId = (value) => {
31
- if (!value) {
32
- return null;
33
- }
34
- if (typeof value === "object" && value !== null && "id" in value) {
35
- const relationId = value.id;
36
- return relationId !== void 0 && relationId !== null ? String(relationId) : null;
37
- }
38
- if (typeof value === "number" || typeof value === "string") {
39
- return String(value);
40
- }
41
- return null;
42
- };
43
17
 
44
- // src/collections/admin-feedback/endpoints/deleteFeedback.ts
45
- var createDeleteFeedbackEndpoint = (mediaCollectionSlug) => ({
46
- path: "/delete/:id",
47
- method: "delete",
48
- handler: async (req) => {
49
- try {
50
- if (!req.user) {
51
- return Response.json(
52
- { success: false, error: "Unauthorized" },
53
- { status: 401, headers: corsHeaders(req) }
54
- );
55
- }
56
- const id = req.routeParams?.id;
57
- if (!id) {
58
- return Response.json(
59
- { success: false, error: "Missing feedback ID." },
60
- { status: 400, headers: corsHeaders(req) }
61
- );
62
- }
63
- const existing = await req.payload.findByID({
64
- collection: "admin-feedback",
65
- id
66
- });
67
- if (String(req.user.id) !== getCreatorId(existing.createdBy)) {
68
- return Response.json(
69
- { success: false, error: "You can only delete your own feedback." },
70
- { status: 403, headers: corsHeaders(req) }
71
- );
72
- }
73
- const screenshotId = getRelationId(existing.screenshot);
74
- if (screenshotId) {
75
- try {
76
- await req.payload.delete({
77
- collection: mediaCollectionSlug,
78
- id: screenshotId
79
- });
80
- } catch (error) {
81
- req.payload.logger.warn(
82
- `Failed to delete feedback screenshot ${screenshotId}: ${error instanceof Error ? error.message : "unknown error"}`
83
- );
84
- }
85
- }
86
- await req.payload.delete({
87
- collection: "admin-feedback",
88
- id
89
- });
90
- return Response.json({ success: true }, { headers: corsHeaders(req) });
91
- } catch (error) {
92
- return Response.json(
93
- { success: false, error: error instanceof Error ? error.message : "Unknown error" },
94
- { status: 500, headers: corsHeaders(req) }
95
- );
96
- }
97
- }
98
- });
99
-
100
- // src/collections/admin-feedback/endpoints/deleteUpload.ts
18
+ // src/endpoints/deleteUpload.ts
101
19
  var createDeleteUploadEndpoint = (mediaCollectionSlug) => ({
102
20
  path: "/upload/:id",
103
21
  method: "delete",
@@ -120,7 +38,10 @@ var createDeleteUploadEndpoint = (mediaCollectionSlug) => ({
120
38
  collection: mediaCollectionSlug,
121
39
  id
122
40
  });
123
- return Response.json({ success: true }, { headers: corsHeaders(req) });
41
+ return Response.json(
42
+ { success: true },
43
+ { headers: corsHeaders(req) }
44
+ );
124
45
  } catch (error) {
125
46
  return Response.json(
126
47
  { success: false, error: error instanceof Error ? error.message : "Unknown error" },
@@ -130,7 +51,7 @@ var createDeleteUploadEndpoint = (mediaCollectionSlug) => ({
130
51
  }
131
52
  });
132
53
 
133
- // src/collections/admin-feedback/endpoints/submit.ts
54
+ // src/endpoints/submit.ts
134
55
  var createSubmitEndpoint = () => ({
135
56
  path: "/submit",
136
57
  method: "post",
@@ -161,7 +82,10 @@ var createSubmitEndpoint = () => ({
161
82
  }
162
83
  }
163
84
  });
164
- return Response.json({ success: true, id: doc.id }, { headers: corsHeaders(req) });
85
+ return Response.json(
86
+ { success: true, id: doc.id },
87
+ { headers: corsHeaders(req) }
88
+ );
165
89
  } catch (error) {
166
90
  return Response.json(
167
91
  { success: false, error: error instanceof Error ? error.message : "Unknown error" },
@@ -171,61 +95,57 @@ var createSubmitEndpoint = () => ({
171
95
  }
172
96
  });
173
97
 
174
- // src/collections/admin-feedback/endpoints/updateFeedback.ts
175
- var createUpdateFeedbackEndpoint = () => ({
176
- path: "/update/:id",
177
- method: "patch",
178
- handler: async (req) => {
98
+ // src/tenant/extractTenantSlug.ts
99
+ var extractTenantSlugFromPathname = (pathname, pathMarkers) => {
100
+ if (pathMarkers.length === 0) {
101
+ return null;
102
+ }
103
+ const segments = pathname.split("?")[0].split("/").filter(Boolean);
104
+ for (const marker of pathMarkers) {
105
+ const markerIndex = segments.indexOf(marker);
106
+ if (markerIndex > 0) {
107
+ return segments[markerIndex - 1] ?? null;
108
+ }
109
+ }
110
+ return null;
111
+ };
112
+
113
+ // src/tenant/resolveUploadTenant.ts
114
+ var resolveFeedbackUploadTenantId = async (req, options, tenantSlugFromForm) => {
115
+ const tenantConfig = options.tenant;
116
+ if (!tenantConfig?.enabled) {
117
+ return null;
118
+ }
119
+ let tenantSlug = tenantSlugFromForm;
120
+ if (!tenantSlug && tenantConfig.pathMarkers?.length) {
179
121
  try {
180
- if (!req.user) {
181
- return Response.json(
182
- { success: false, error: "Unauthorized" },
183
- { status: 401, headers: corsHeaders(req) }
184
- );
185
- }
186
- const id = req.routeParams?.id;
187
- if (!id) {
188
- return Response.json(
189
- { success: false, error: "Missing feedback ID." },
190
- { status: 400, headers: corsHeaders(req) }
191
- );
192
- }
193
- const existing = await req.payload.findByID({
194
- collection: "admin-feedback",
195
- id
196
- });
197
- if (String(req.user.id) !== getCreatorId(existing.createdBy)) {
198
- return Response.json(
199
- { success: false, error: "You can only edit your own feedback." },
200
- { status: 403, headers: corsHeaders(req) }
201
- );
202
- }
203
- const body = await req.json();
204
- const updateData = {};
205
- const newMessage = trim(body?.message);
206
- if (newMessage) {
207
- updateData.message = newMessage;
208
- }
209
- if (body && "screenshotId" in body) {
210
- updateData.screenshot = body.screenshotId || null;
211
- }
212
- const updated = await req.payload.update({
213
- collection: "admin-feedback",
214
- id: existing.id,
215
- data: updateData
216
- });
217
- return Response.json({ success: true, doc: updated }, { headers: corsHeaders(req) });
218
- } catch (error) {
219
- return Response.json(
220
- { success: false, error: error instanceof Error ? error.message : "Unknown error" },
221
- { status: 500, headers: corsHeaders(req) }
222
- );
122
+ const url = new URL(req.url || "", `http://${req.headers.get("host") || "localhost"}`);
123
+ tenantSlug = extractTenantSlugFromPathname(url.pathname, tenantConfig.pathMarkers);
124
+ } catch {
125
+ tenantSlug = null;
223
126
  }
224
127
  }
225
- });
128
+ const collectionSlug = tenantConfig.collectionSlug || "tenants";
129
+ if (tenantSlug) {
130
+ const found = await req.payload.find({
131
+ collection: collectionSlug,
132
+ where: { slug: { equals: tenantSlug } },
133
+ limit: 1,
134
+ overrideAccess: true
135
+ });
136
+ const doc = found.docs[0];
137
+ if (doc?.id != null) {
138
+ return Number(doc.id);
139
+ }
140
+ }
141
+ if (tenantConfig.resolveTenantId) {
142
+ return tenantConfig.resolveTenantId({ req, tenantSlug: tenantSlug ?? null });
143
+ }
144
+ return null;
145
+ };
226
146
 
227
- // src/collections/admin-feedback/endpoints/upload.ts
228
- var createUploadEndpoint = (mediaCollectionSlug) => ({
147
+ // src/endpoints/upload.ts
148
+ var createUploadEndpoint = (mediaCollectionSlug, options) => ({
229
149
  path: "/upload",
230
150
  method: "post",
231
151
  handler: async (req) => {
@@ -239,7 +159,10 @@ var createUploadEndpoint = (mediaCollectionSlug) => ({
239
159
  const formData = await req.formData();
240
160
  const file = formData.get("file");
241
161
  const altRaw = formData.get("alt");
162
+ const tenantSlugKey = options.tenant?.formDataSlugKey || "tenant";
163
+ const tenantSlugRaw = formData.get(tenantSlugKey);
242
164
  const alt = typeof altRaw === "string" ? altRaw.trim() : "";
165
+ const tenantSlugFromForm = typeof tenantSlugRaw === "string" ? tenantSlugRaw.trim() : "";
243
166
  if (!(file instanceof File)) {
244
167
  return Response.json(
245
168
  { success: false, error: "Missing file." },
@@ -252,11 +175,27 @@ var createUploadEndpoint = (mediaCollectionSlug) => ({
252
175
  { status: 400, headers: corsHeaders(req) }
253
176
  );
254
177
  }
178
+ const mediaData = {
179
+ alt: alt || file.name
180
+ };
181
+ if (options.tenant?.enabled) {
182
+ const tenantId = await resolveFeedbackUploadTenantId(
183
+ req,
184
+ options,
185
+ tenantSlugFromForm || null
186
+ );
187
+ if (typeof tenantId !== "number") {
188
+ return Response.json(
189
+ { success: false, error: "Tenant context required." },
190
+ { status: 400, headers: corsHeaders(req) }
191
+ );
192
+ }
193
+ mediaData[options.tenant.fieldName || "tenant"] = tenantId;
194
+ }
255
195
  const media = await req.payload.create({
256
196
  collection: mediaCollectionSlug,
257
- data: {
258
- alt: alt || file.name
259
- },
197
+ overrideAccess: true,
198
+ data: mediaData,
260
199
  file: {
261
200
  data: Buffer.from(await file.arrayBuffer()),
262
201
  mimetype: file.type || "application/octet-stream",
@@ -277,15 +216,6 @@ var createUploadEndpoint = (mediaCollectionSlug) => ({
277
216
  }
278
217
  });
279
218
 
280
- // src/collections/admin-feedback/endpoints/index.ts
281
- var createAdminFeedbackEndpoints = (mediaCollectionSlug) => [
282
- createSubmitEndpoint(),
283
- createUploadEndpoint(mediaCollectionSlug),
284
- createDeleteUploadEndpoint(mediaCollectionSlug),
285
- createUpdateFeedbackEndpoint(),
286
- createDeleteFeedbackEndpoint(mediaCollectionSlug)
287
- ];
288
-
289
219
  // src/server/sendFeedbackEmail.ts
290
220
  async function sendFeedbackEmail(payload, options, data) {
291
221
  if (!options.emailTo) {
@@ -408,7 +338,7 @@ async function sendFeedbackEmail(payload, options, data) {
408
338
  await payload.sendEmail(emailMessage);
409
339
  }
410
340
 
411
- // src/collections/admin-feedback/hooks/afterChange.ts
341
+ // src/hooks/afterChange.ts
412
342
  var createAfterChangeHook = (options) => {
413
343
  return async ({ doc, operation, req }) => {
414
344
  if (operation !== "create") {
@@ -438,39 +368,35 @@ var createAfterChangeHook = (options) => {
438
368
  };
439
369
  };
440
370
 
441
- // src/collections/admin-feedback/hooks/beforeChange.ts
442
- var normalizeFeedbackBeforeChange = ({ data, req, operation }) => {
443
- if (!data) {
444
- return data;
445
- }
446
- const nextData = { ...data };
447
- const message = trim(nextData.message);
448
- const pagePath = trim(nextData.pagePath);
449
- nextData.message = message || "";
450
- nextData.pagePath = pagePath || "/";
451
- nextData.selector = trim(nextData.selector);
452
- nextData.selectedText = trim(nextData.selectedText);
453
- const existingMeta = typeof nextData.meta === "object" && nextData.meta !== null ? nextData.meta : {};
454
- nextData.meta = {
455
- ...existingMeta,
456
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
457
- userAgent: trim(existingMeta.userAgent),
458
- locale: trim(existingMeta.locale),
459
- viewport: trim(existingMeta.viewport)
371
+ // src/hooks/beforeChange.ts
372
+ var createBeforeChangeHook = () => {
373
+ return ({ data, req, operation }) => {
374
+ if (!data) {
375
+ return data;
376
+ }
377
+ const nextData = { ...data };
378
+ const message = trim(nextData.message);
379
+ const pagePath = trim(nextData.pagePath);
380
+ nextData.message = message || "";
381
+ nextData.pagePath = pagePath || "/";
382
+ nextData.selector = trim(nextData.selector);
383
+ nextData.selectedText = trim(nextData.selectedText);
384
+ const existingMeta = typeof nextData.meta === "object" && nextData.meta !== null ? nextData.meta : {};
385
+ nextData.meta = {
386
+ ...existingMeta,
387
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
388
+ userAgent: trim(existingMeta.userAgent),
389
+ locale: trim(existingMeta.locale),
390
+ viewport: trim(existingMeta.viewport)
391
+ };
392
+ if (operation === "create" && req.user && !nextData.createdBy) {
393
+ nextData.createdBy = req.user.id;
394
+ }
395
+ return nextData;
460
396
  };
461
- if (operation === "create" && req.user && !nextData.createdBy) {
462
- nextData.createdBy = req.user.id;
463
- }
464
- return nextData;
465
397
  };
466
398
 
467
- // src/collections/admin-feedback/hooks/index.ts
468
- var createAdminFeedbackHooks = (options) => ({
469
- beforeChange: [normalizeFeedbackBeforeChange],
470
- afterChange: [createAfterChangeHook(options)]
471
- });
472
-
473
- // src/collections/admin-feedback/index.ts
399
+ // src/collections/AdminFeedback.ts
474
400
  var createAdminFeedbackCollection = (options, mediaCollectionSlug) => {
475
401
  return {
476
402
  slug: "admin-feedback",
@@ -489,8 +415,15 @@ var createAdminFeedbackCollection = (options, mediaCollectionSlug) => {
489
415
  update: ({ req }) => Boolean(req.user),
490
416
  delete: ({ req }) => Boolean(req.user)
491
417
  },
492
- endpoints: createAdminFeedbackEndpoints(mediaCollectionSlug),
493
- hooks: createAdminFeedbackHooks(options),
418
+ endpoints: [
419
+ createSubmitEndpoint(),
420
+ createUploadEndpoint(mediaCollectionSlug, options),
421
+ createDeleteUploadEndpoint(mediaCollectionSlug)
422
+ ],
423
+ hooks: {
424
+ beforeChange: [createBeforeChangeHook()],
425
+ afterChange: [createAfterChangeHook(options)]
426
+ },
494
427
  fields: [
495
428
  {
496
429
  name: "message",
@@ -643,4 +576,5 @@ var adminFeedbackPlugin = payload.definePlugin({
643
576
  });
644
577
 
645
578
  exports.adminFeedbackPlugin = adminFeedbackPlugin;
579
+ exports.extractTenantSlugFromPathname = extractTenantSlugFromPathname;
646
580
  exports.pathMatchesAllowlist = pathMatchesAllowlist;
package/dist/index.d.cts CHANGED
@@ -1,6 +1,53 @@
1
1
  import * as payload from 'payload';
2
- import { A as AdminFeedbackPluginOptions } from './routeMatcher-CmCMn_gT.cjs';
3
- export { p as pathMatchesAllowlist } from './routeMatcher-CmCMn_gT.cjs';
2
+ import { Config, PayloadRequest } from 'payload';
3
+
4
+ type TenantResolveArgs = {
5
+ req: PayloadRequest;
6
+ tenantSlug: string | null;
7
+ };
8
+ type TenantConfig = {
9
+ enabled?: boolean;
10
+ /** Tenants collection slug used to resolve slug → id (default `tenants`). */
11
+ collectionSlug?: string;
12
+ /** Relationship field on the upload collection (default `tenant`). */
13
+ fieldName?: string;
14
+ /** FormData key for an explicit tenant slug from the client (default `tenant`). */
15
+ formDataSlugKey?: string;
16
+ /** URL path segments — tenant slug is the segment immediately before each marker. */
17
+ pathMarkers?: string[];
18
+ /** Host-specific fallback when slug lookup is not enough (admin cookie, subdomain, …). */
19
+ resolveTenantId?: (args: TenantResolveArgs) => Promise<number | null> | number | null;
20
+ };
21
+ type FrontendDisplayConfig = {
22
+ enabled?: boolean;
23
+ include?: string[];
24
+ };
25
+ type ScreenshotConfig = {
26
+ enabled?: boolean;
27
+ maxFileSizeBytes?: number;
28
+ allowedMimeTypes?: string[];
29
+ capturePolicy?: 'current-tab-first' | 'strict-current-tab' | 'any-surface';
30
+ };
31
+ type AdminFeedbackPluginOptions = {
32
+ enabled?: boolean;
33
+ emailTo: string | string[];
34
+ fromLabel?: string;
35
+ fromName?: string;
36
+ fromAddress?: string;
37
+ email?: Config['email'];
38
+ allowScreenshotUpload?: boolean;
39
+ maxMessageLength?: number;
40
+ mediaCollectionSlug?: string;
41
+ strictMediaCollection?: boolean;
42
+ screenshot?: ScreenshotConfig;
43
+ frontend?: FrontendDisplayConfig;
44
+ frontendRouteMatcher?: (pathname: string) => boolean;
45
+ tenant?: TenantConfig;
46
+ };
47
+
48
+ declare const pathMatchesAllowlist: (pathname: string, patterns: string[]) => boolean;
49
+
50
+ declare const extractTenantSlugFromPathname: (pathname: string, pathMarkers: string[]) => string | null;
4
51
 
5
52
  declare const adminFeedbackPlugin: (options: AdminFeedbackPluginOptions) => payload.Plugin;
6
53
 
@@ -10,4 +57,4 @@ declare module 'payload' {
10
57
  }
11
58
  }
12
59
 
13
- export { AdminFeedbackPluginOptions, adminFeedbackPlugin };
60
+ export { type AdminFeedbackPluginOptions, type TenantConfig, adminFeedbackPlugin, extractTenantSlugFromPathname, pathMatchesAllowlist };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,53 @@
1
1
  import * as payload from 'payload';
2
- import { A as AdminFeedbackPluginOptions } from './routeMatcher-CmCMn_gT.js';
3
- export { p as pathMatchesAllowlist } from './routeMatcher-CmCMn_gT.js';
2
+ import { Config, PayloadRequest } from 'payload';
3
+
4
+ type TenantResolveArgs = {
5
+ req: PayloadRequest;
6
+ tenantSlug: string | null;
7
+ };
8
+ type TenantConfig = {
9
+ enabled?: boolean;
10
+ /** Tenants collection slug used to resolve slug → id (default `tenants`). */
11
+ collectionSlug?: string;
12
+ /** Relationship field on the upload collection (default `tenant`). */
13
+ fieldName?: string;
14
+ /** FormData key for an explicit tenant slug from the client (default `tenant`). */
15
+ formDataSlugKey?: string;
16
+ /** URL path segments — tenant slug is the segment immediately before each marker. */
17
+ pathMarkers?: string[];
18
+ /** Host-specific fallback when slug lookup is not enough (admin cookie, subdomain, …). */
19
+ resolveTenantId?: (args: TenantResolveArgs) => Promise<number | null> | number | null;
20
+ };
21
+ type FrontendDisplayConfig = {
22
+ enabled?: boolean;
23
+ include?: string[];
24
+ };
25
+ type ScreenshotConfig = {
26
+ enabled?: boolean;
27
+ maxFileSizeBytes?: number;
28
+ allowedMimeTypes?: string[];
29
+ capturePolicy?: 'current-tab-first' | 'strict-current-tab' | 'any-surface';
30
+ };
31
+ type AdminFeedbackPluginOptions = {
32
+ enabled?: boolean;
33
+ emailTo: string | string[];
34
+ fromLabel?: string;
35
+ fromName?: string;
36
+ fromAddress?: string;
37
+ email?: Config['email'];
38
+ allowScreenshotUpload?: boolean;
39
+ maxMessageLength?: number;
40
+ mediaCollectionSlug?: string;
41
+ strictMediaCollection?: boolean;
42
+ screenshot?: ScreenshotConfig;
43
+ frontend?: FrontendDisplayConfig;
44
+ frontendRouteMatcher?: (pathname: string) => boolean;
45
+ tenant?: TenantConfig;
46
+ };
47
+
48
+ declare const pathMatchesAllowlist: (pathname: string, patterns: string[]) => boolean;
49
+
50
+ declare const extractTenantSlugFromPathname: (pathname: string, pathMarkers: string[]) => string | null;
4
51
 
5
52
  declare const adminFeedbackPlugin: (options: AdminFeedbackPluginOptions) => payload.Plugin;
6
53
 
@@ -10,4 +57,4 @@ declare module 'payload' {
10
57
  }
11
58
  }
12
59
 
13
- export { AdminFeedbackPluginOptions, adminFeedbackPlugin };
60
+ export { type AdminFeedbackPluginOptions, type TenantConfig, adminFeedbackPlugin, extractTenantSlugFromPathname, pathMatchesAllowlist };