create-feedbax 0.2.0 → 0.2.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.
Files changed (99) hide show
  1. package/dist/cli.js +2042 -16
  2. package/dist/index.js +1997 -5
  3. package/package.json +1 -1
  4. package/template/.feedbax-template.sha256 +1 -1
  5. package/template/AGENTS.md +13 -0
  6. package/template/CONNECTED.md +404 -0
  7. package/template/README.md +58 -0
  8. package/template/components.json +1 -1
  9. package/template/eslint.config.mjs +23 -0
  10. package/template/migrations/0001_connected.sql +6 -0
  11. package/template/migrations/0002_participation.sql +8 -0
  12. package/template/migrations/0003_images.sql +3 -0
  13. package/template/migrations/0004_followed_status.sql +9 -0
  14. package/template/package.json +9 -5
  15. package/template/src/authorized-draft-post.tsx +1 -0
  16. package/template/src/changelog-page.tsx +63 -54
  17. package/template/src/cloudflare-workers.d.ts +6 -0
  18. package/template/src/comment-creation.test.tsx +42 -1
  19. package/template/src/comment-thread-page.ts +11 -1
  20. package/template/src/components/command-palette.tsx +59 -30
  21. package/template/src/components/connected-identity-provider.tsx +108 -0
  22. package/template/src/components/device-profile-provider.tsx +41 -26
  23. package/template/src/components/follow-post-button.tsx +89 -0
  24. package/template/src/components/header.tsx +2 -0
  25. package/template/src/components/image-attachments.tsx +187 -0
  26. package/template/src/components/loader.tsx +48 -5
  27. package/template/src/components/notification-inbox.tsx +232 -0
  28. package/template/src/components/portal-footer.tsx +14 -0
  29. package/template/src/components/profile-menu.tsx +30 -0
  30. package/template/src/components/ui/components/command.tsx +30 -29
  31. package/template/src/components/ui/components/message-scroller.tsx +2 -2
  32. package/template/src/components/ui/components/scroll-area.tsx +0 -1
  33. package/template/src/components/ui/components/switch.tsx +29 -0
  34. package/template/src/components/ui/styles/globals.css +1 -1
  35. package/template/src/connected-identity.test.ts +144 -0
  36. package/template/src/connected-identity.ts +122 -0
  37. package/template/src/connected-participation.test.tsx +67 -0
  38. package/template/src/connected-runtime.test.ts +241 -0
  39. package/template/src/connected-runtime.ts +176 -0
  40. package/template/src/connected-social.test.tsx +158 -0
  41. package/template/src/feedback-cache-invalidation.ts +1 -0
  42. package/template/src/feedback-runtime.ts +79 -12
  43. package/template/src/feedbax/config/index.test.ts +28 -0
  44. package/template/src/feedbax/config/index.ts +93 -0
  45. package/template/src/feedbax/feedback/connected-feedback.ts +206 -0
  46. package/template/src/feedbax/feedback/connected.test.ts +272 -0
  47. package/template/src/feedbax/feedback/connected.ts +215 -0
  48. package/template/src/feedbax/feedback/email-delivery.test.ts +65 -0
  49. package/template/src/feedbax/feedback/email-delivery.ts +66 -0
  50. package/template/src/feedbax/feedback/identity-handoff.test.ts +81 -0
  51. package/template/src/feedbax/feedback/identity-handoff.ts +119 -0
  52. package/template/src/feedbax/feedback/image-feedback.ts +101 -0
  53. package/template/src/feedbax/feedback/images.test.ts +223 -0
  54. package/template/src/feedbax/feedback/images.ts +324 -0
  55. package/template/src/feedbax/feedback/index.ts +55 -1
  56. package/template/src/feedbax/feedback/notion-image-review.ts +55 -0
  57. package/template/src/feedbax/feedback/participation.test.ts +653 -0
  58. package/template/src/feedbax/feedback/participation.ts +502 -0
  59. package/template/src/images-runtime.test.ts +133 -0
  60. package/template/src/images-runtime.ts +125 -0
  61. package/template/src/index.css +97 -440
  62. package/template/src/lazy-post-detail-overlay.tsx +13 -2
  63. package/template/src/overlay-post-detail.test.tsx +59 -8
  64. package/template/src/overlay-post-detail.tsx +20 -69
  65. package/template/src/participation-client.ts +63 -0
  66. package/template/src/participation-runtime.test.ts +35 -0
  67. package/template/src/participation-runtime.ts +255 -0
  68. package/template/src/portal-comments.ts +24 -5
  69. package/template/src/portal-feedback-form.tsx +18 -3
  70. package/template/src/portal-feedback-runtime.ts +3 -0
  71. package/template/src/portal-feedback-server-function.ts +6 -3
  72. package/template/src/portal-feedback-submission.ts +10 -0
  73. package/template/src/portal-server-entry.ts +4 -0
  74. package/template/src/post-creation-flow.tsx +2 -2
  75. package/template/src/post-detail-content.test.tsx +233 -0
  76. package/template/src/post-detail-content.tsx +162 -0
  77. package/template/src/post-detail-query.ts +34 -0
  78. package/template/src/post-results.tsx +1 -1
  79. package/template/src/public-cache-policy.test.ts +11 -4
  80. package/template/src/public-cache-policy.ts +1 -1
  81. package/template/src/public-feedback-index.tsx +9 -39
  82. package/template/src/public-feedback-page.test.tsx +65 -0
  83. package/template/src/public-feedback-page.ts +12 -1
  84. package/template/src/public-post-detail-skeleton.tsx +54 -0
  85. package/template/src/public-post-detail.tsx +298 -208
  86. package/template/src/public-post-route.test.tsx +39 -3
  87. package/template/src/public-post-route.tsx +15 -28
  88. package/template/src/public-roadmap-route.test.tsx +38 -2
  89. package/template/src/public-roadmap-view.tsx +56 -23
  90. package/template/src/public-shell.test.tsx +26 -0
  91. package/template/src/routeTree.gen.ts +49 -3
  92. package/template/src/router.tsx +2 -0
  93. package/template/src/routes/__root.tsx +3 -5
  94. package/template/src/routes/email-preferences.tsx +77 -0
  95. package/template/src/routes/submit.tsx +1 -1
  96. package/template/src/safe-public-failure.ts +3 -1
  97. package/template/src/server.ts +41 -1
  98. package/template/src/trusted-feedback-handler.test.ts +1 -1
  99. package/template/src/vote-toggle.tsx +42 -9
@@ -1,10 +1,21 @@
1
- import { OverlayPostDetail } from "./overlay-post-detail";
1
+ import { lazy, Suspense } from "react";
2
2
  import { PostDetailOverlay } from "./post-detail-overlay";
3
+ import { PublicPostDetailSkeleton } from "./public-post-detail-skeleton";
4
+
5
+ const OverlayPostDetail = lazy(() =>
6
+ import("./overlay-post-detail").then((module) => ({
7
+ default: module.OverlayPostDetail,
8
+ })),
9
+ );
3
10
 
4
11
  export function LazyPostDetailOverlay() {
5
12
  return (
6
13
  <PostDetailOverlay
7
- renderDetail={(slug) => <OverlayPostDetail slug={slug} />}
14
+ renderDetail={(slug) => (
15
+ <Suspense fallback={<PublicPostDetailSkeleton display="overlay" />}>
16
+ <OverlayPostDetail key={slug} slug={slug} />
17
+ </Suspense>
18
+ )}
8
19
  />
9
20
  );
10
21
  }
@@ -1,7 +1,15 @@
1
1
  // @vitest-environment jsdom
2
2
 
3
- import { cleanup, render, screen, within } from "@testing-library/react";
3
+ import {
4
+ cleanup,
5
+ fireEvent,
6
+ render as renderView,
7
+ screen,
8
+ within,
9
+ } from "@testing-library/react";
4
10
  import { afterEach, beforeEach, expect, it, vi } from "vitest";
11
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
12
+ import type { ReactNode } from "react";
5
13
 
6
14
  import { OverlayPostDetail } from "./overlay-post-detail";
7
15
  import {
@@ -60,7 +68,7 @@ it("shows loading instead of stale content when the requested slug changes", asy
60
68
  ).toBeTruthy();
61
69
  });
62
70
 
63
- it("shows the designed Post detail with a canonical full-page link", async () => {
71
+ it("shows Post details without the redundant full-page toolbar", async () => {
64
72
  vi.mocked(getPublicPost).mockResolvedValue(firstPost);
65
73
  vi.mocked(getPublicPostComments).mockResolvedValue({
66
74
  items: [
@@ -83,25 +91,50 @@ it("shows the designed Post detail with a canonical full-page link", async () =>
83
91
  expect(
84
92
  await screen.findByRole("heading", { name: "First Post" }),
85
93
  ).toBeTruthy();
86
- expect(
87
- screen.getByRole("link", { name: "Open full page" }).getAttribute("href"),
88
- ).toBe("/p/first-post");
94
+ expect(screen.queryByRole("link", { name: "Open full page" })).toBeNull();
89
95
  expect(screen.getByRole("complementary", { name: "Details" })).toBeTruthy();
90
96
  expect(
91
- within(screen.getByRole("region", { name: "Comments" })).getByText(
97
+ await within(screen.getByRole("region", { name: "Comments" })).findByText(
92
98
  "Visible in the dialog",
93
99
  ),
94
100
  ).toBeTruthy();
95
101
  expect(
96
102
  await screen.findByRole("form", { name: "Comment composer" }),
97
103
  ).toBeTruthy();
104
+ const composer = screen.getByRole("form", { name: "Comment composer" });
105
+ const threads = screen.getByRole("region", { name: "Comment threads" });
106
+ expect(
107
+ composer.compareDocumentPosition(threads) &
108
+ Node.DOCUMENT_POSITION_FOLLOWING,
109
+ ).toBeTruthy();
110
+ expect(
111
+ within(threads).queryByRole("form", { name: "Comment composer" }),
112
+ ).toBeNull();
98
113
  expect(getPublicPostComments).toHaveBeenCalledWith({
99
114
  data: { slug: "first-post" },
100
115
  });
101
116
  expect(screen.queryByRole("link", { name: "Back to Feedback" })).toBeNull();
102
117
  });
103
118
 
104
- it("keeps the Post and Comment composer available when Comment loading fails", async () => {
119
+ it("shows the Post while Comments are still loading", async () => {
120
+ vi.mocked(getPublicPost).mockResolvedValue(firstPost);
121
+ let finish!: (page: { items: [] }) => void;
122
+ vi.mocked(getPublicPostComments).mockReturnValue(
123
+ new Promise((resolve) => {
124
+ finish = resolve;
125
+ }),
126
+ );
127
+ render(<OverlayPostDetail slug="first-post" />);
128
+ expect(
129
+ await screen.findByRole("heading", { name: "First Post" }),
130
+ ).toBeTruthy();
131
+ expect(screen.getByRole("status", { name: "Loading Comments" })).toBeTruthy();
132
+ expect(screen.queryByText("No comments yet")).toBeNull();
133
+ finish({ items: [] });
134
+ expect(await screen.findByText("No comments yet")).toBeTruthy();
135
+ });
136
+
137
+ it("keeps the Post available and retries a failed Comment load", async () => {
105
138
  vi.mocked(getPublicPost).mockResolvedValue(firstPost);
106
139
  vi.mocked(getPublicPostComments).mockRejectedValue(
107
140
  new Error("Comments temporarily unavailable"),
@@ -115,7 +148,14 @@ it("keeps the Post and Comment composer available when Comment loading fails", a
115
148
  expect(
116
149
  await screen.findByRole("form", { name: "Comment composer" }),
117
150
  ).toBeTruthy();
118
- expect(screen.getByText("No comments yet")).toBeTruthy();
151
+ expect(await screen.findByRole("alert")).toHaveProperty(
152
+ "textContent",
153
+ "Comments could not be loaded.",
154
+ );
155
+ expect(screen.queryByText("No comments yet")).toBeNull();
156
+ vi.mocked(getPublicPostComments).mockResolvedValue({ items: [] });
157
+ fireEvent.click(screen.getByRole("button", { name: "Retry Comments" }));
158
+ expect(await screen.findByText("No comments yet")).toBeTruthy();
119
159
  expect(screen.queryByText("Draft fallback")).toBeNull();
120
160
  });
121
161
 
@@ -128,3 +168,14 @@ const firstPost = {
128
168
  createdAt: new Date("2026-08-22T10:00:00.000Z"),
129
169
  updatedAt: new Date("2026-08-22T10:00:00.000Z"),
130
170
  };
171
+
172
+ function render(ui: ReactNode) {
173
+ const client = new QueryClient({
174
+ defaultOptions: { queries: { retry: false } },
175
+ });
176
+ return renderView(ui, {
177
+ wrapper: ({ children }) => (
178
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
179
+ ),
180
+ });
181
+ }
@@ -1,88 +1,39 @@
1
- import { useEffect, useState } from "react";
2
- import type { CommentThreadPage, PublicPost } from "@feedbax/feedback";
3
- import { ExternalLink } from "lucide-react";
1
+ import { useQuery } from "@tanstack/react-query";
4
2
 
5
3
  import {
6
4
  getPublicPost,
7
5
  getPublicPostComments,
8
6
  } from "./public-post-server-function";
9
- import {
10
- PublicPostDetail,
11
- PublicPostDetailSkeleton,
12
- } from "./public-post-detail";
7
+ import { PublicPostDetailSkeleton } from "./public-post-detail-skeleton";
8
+ import { publicPostQuery } from "./post-detail-query";
9
+ import { PostDetailContent } from "./post-detail-content";
13
10
  import { AuthorizedDraftPost } from "./authorized-draft-post";
14
11
  import { mutatePublicComment, submitPublicComment } from "./public-post-route";
15
- import { mergeCommentThreads } from "./comment-thread-page";
16
12
 
17
- type OverlayDetail = {
18
- post: PublicPost | null;
19
- comments: CommentThreadPage;
20
- };
13
+ const loadComments = (slug: string, cursor?: string) =>
14
+ getPublicPostComments({ data: { slug, ...(cursor ? { cursor } : {}) } });
21
15
 
22
16
  export function OverlayPostDetail({ slug }: { slug: string }) {
23
- const [detail, setDetail] = useState<OverlayDetail>();
24
- useEffect(() => {
25
- let current = true;
26
- setDetail(undefined);
27
- getPublicPost({ data: { slug } })
28
- .then(async (post) => ({
29
- post: post ?? null,
30
- comments: post
31
- ? await getPublicPostComments({ data: { slug } }).catch(() => ({
32
- items: [],
33
- }))
34
- : { items: [] },
35
- }))
36
- .then((value) => current && setDetail(value))
37
- .catch(
38
- () => current && setDetail({ post: null, comments: { items: [] } }),
39
- );
40
- return () => {
41
- current = false;
42
- };
43
- }, [slug]);
17
+ return <OverlayPost key={slug} slug={slug} />;
18
+ }
19
+
20
+ function OverlayPost({ slug }: { slug: string }) {
21
+ const query = useQuery(
22
+ publicPostQuery(slug, (value) => getPublicPost({ data: { slug: value } })),
23
+ );
24
+ const post = query.data;
44
25
 
45
- if (detail === undefined) return <PublicPostDetailSkeleton />;
46
26
  return (
47
27
  <div className="overlay-post-detail">
48
- <a
49
- className="post-full-page-link"
50
- href={`/p/${encodeURIComponent(slug)}`}
51
- >
52
- Open full page <ExternalLink aria-hidden="true" />
53
- </a>
54
- {detail.post ? (
55
- <PublicPostDetail
56
- post={detail.post}
28
+ {query.isPending ? (
29
+ <PublicPostDetailSkeleton display="overlay" />
30
+ ) : post ? (
31
+ <PostDetailContent
32
+ post={post}
57
33
  display="overlay"
58
- comments={detail.comments}
34
+ loadComments={loadComments}
59
35
  submitComment={submitPublicComment}
60
36
  mutateComment={mutatePublicComment}
61
- loadMore={
62
- detail.comments.nextCursor
63
- ? async () => {
64
- const next = await getPublicPostComments({
65
- data: { slug, cursor: detail.comments.nextCursor },
66
- });
67
- setDetail((current) =>
68
- current
69
- ? {
70
- ...current,
71
- comments: {
72
- items: mergeCommentThreads(
73
- current.comments.items,
74
- next.items,
75
- ),
76
- ...(next.nextCursor
77
- ? { nextCursor: next.nextCursor }
78
- : {}),
79
- },
80
- }
81
- : current,
82
- );
83
- }
84
- : undefined
85
- }
86
37
  />
87
38
  ) : (
88
39
  <AuthorizedDraftPost slug={slug} />
@@ -0,0 +1,63 @@
1
+ import { queryOptions } from "@tanstack/react-query";
2
+ import type { ParticipantNotification, FollowState } from "@feedbax/feedback";
3
+ export interface NotificationPage {
4
+ items: ParticipantNotification[];
5
+ unreadCount: number;
6
+ nextCursor?: string;
7
+ }
8
+ export interface EmailPreferences {
9
+ emailAvailable: boolean;
10
+ emailEnabled: boolean;
11
+ }
12
+ export async function participationRequest<T>(
13
+ path: string,
14
+ body?: unknown,
15
+ ): Promise<T> {
16
+ const response = await fetch(`/internal/connected/${path}`, {
17
+ cache: "no-store",
18
+ ...(body === undefined
19
+ ? {}
20
+ : {
21
+ method: "POST",
22
+ headers: { "Content-Type": "application/json" },
23
+ body: JSON.stringify(body),
24
+ }),
25
+ });
26
+ const value = await response.json();
27
+ if (!response.ok)
28
+ throw new Error(
29
+ value && typeof value === "object" && "error" in value
30
+ ? String(value.error)
31
+ : "Updates are temporarily unavailable.",
32
+ );
33
+ return value as T;
34
+ }
35
+ export const followQuery = (slug: string) =>
36
+ queryOptions({
37
+ queryKey: ["participant-follow", slug],
38
+ queryFn: () =>
39
+ participationRequest<FollowState>(
40
+ `follow?slug=${encodeURIComponent(slug)}`,
41
+ ),
42
+ staleTime: 0,
43
+ retry: false,
44
+ refetchInterval: (query) =>
45
+ query.state.data?.initializing ? 15000 : false,
46
+ });
47
+ export const preferencesQuery = () =>
48
+ queryOptions({
49
+ queryKey: ["participant-email-preferences"],
50
+ queryFn: () => participationRequest<EmailPreferences>("preferences"),
51
+ staleTime: 0,
52
+ retry: false,
53
+ });
54
+ export const notificationQuery = {
55
+ queryKey: ["participant-notifications"],
56
+ initialPageParam: undefined as string | undefined,
57
+ queryFn: ({ pageParam }: { pageParam: string | undefined }) =>
58
+ participationRequest<NotificationPage>(
59
+ `notifications${pageParam ? `?cursor=${encodeURIComponent(pageParam)}` : ""}`,
60
+ ),
61
+ getNextPageParam: (last: NotificationPage) => last.nextCursor,
62
+ retry: false as const,
63
+ };
@@ -0,0 +1,35 @@
1
+ import { expect, it } from "vitest";
2
+ import { createParticipationRequestHandler } from "./participation-runtime";
3
+
4
+ it("keeps social routes private and rejects cross-origin mutations before touching participation", async () => {
5
+ let read = false;
6
+ const handler = createParticipationRequestHandler({
7
+ siteUrl: "https://feedback.example.com",
8
+ enabled: true,
9
+ getParticipant: async () => undefined,
10
+ getModule: () => {
11
+ read = true;
12
+ throw new Error();
13
+ },
14
+ rateLimit: async () => true,
15
+ });
16
+ const privateRead = await handler(
17
+ new Request(
18
+ "https://feedback.example.com/internal/connected/notifications",
19
+ ),
20
+ );
21
+ expect(privateRead?.status).toBe(401);
22
+ expect(privateRead?.headers.get("Cache-Control")).toBe("no-store");
23
+ const mutation = await handler(
24
+ new Request("https://feedback.example.com/internal/connected/follow", {
25
+ method: "POST",
26
+ headers: { Origin: "https://evil.example.com" },
27
+ body: JSON.stringify({ slug: "public", following: true }),
28
+ }),
29
+ );
30
+ expect(mutation?.status).toBe(403);
31
+ expect(read).toBe(false);
32
+ expect(
33
+ await handler(new Request("https://feedback.example.com/roadmap")),
34
+ ).toBeUndefined();
35
+ });
@@ -0,0 +1,255 @@
1
+ import {
2
+ createEmailSender,
3
+ createParticipationModule,
4
+ type VerifiedParticipant,
5
+ } from "@feedbax/feedback";
6
+ import { env } from "cloudflare:workers";
7
+ import feedbax from "./feedbax";
8
+ import {
9
+ configuredImages,
10
+ createConfiguredNotionFeedbackModule,
11
+ getConnectedStore,
12
+ } from "./feedback-runtime";
13
+ import {
14
+ readSessionToken,
15
+ sameOrigin,
16
+ sessionHash,
17
+ } from "./connected-identity";
18
+
19
+ type ParticipationModule = ReturnType<typeof createParticipationModule>;
20
+ const paths = new Set([
21
+ "follow",
22
+ "notifications",
23
+ "preferences",
24
+ "unsubscribe",
25
+ ]);
26
+ export function createParticipationRequestHandler(options: {
27
+ siteUrl: string;
28
+ enabled: boolean;
29
+ getParticipant(request: Request): Promise<VerifiedParticipant | undefined>;
30
+ getModule(participant?: VerifiedParticipant): ParticipationModule;
31
+ rateLimit(request: Request): Promise<boolean>;
32
+ }) {
33
+ return async (request: Request): Promise<Response | undefined> => {
34
+ const url = new URL(request.url);
35
+ const route = url.pathname.replace("/internal/connected/", "");
36
+ if (!url.pathname.startsWith("/internal/connected/") || !paths.has(route))
37
+ return;
38
+ const json = (body: unknown, status = 200) =>
39
+ Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
40
+ if (!options.enabled) return json({ error: "Not found." }, 404);
41
+ if (!["GET", "POST"].includes(request.method))
42
+ return json({ error: "Method not allowed." }, 405);
43
+ if (
44
+ route !== "unsubscribe" &&
45
+ request.method !== "GET" &&
46
+ !sameOrigin(request, options.siteUrl)
47
+ )
48
+ return json({ error: "Request origin is invalid." }, 403);
49
+ try {
50
+ if (route === "unsubscribe") {
51
+ const token = url.searchParams.get("token") ?? "";
52
+ if (!/^[a-f0-9]{32}\.[A-Za-z0-9_-]{43}$/.test(token))
53
+ return json({ error: "Invalid unsubscribe link." }, 400);
54
+ if (request.method === "GET")
55
+ return new Response(null, {
56
+ status: 303,
57
+ headers: {
58
+ Location: `/email-preferences?token=${encodeURIComponent(token)}`,
59
+ "Cache-Control": "no-store",
60
+ "Referrer-Policy": "no-referrer",
61
+ },
62
+ });
63
+ if (!(await options.rateLimit(request)))
64
+ return json({ error: "Try again shortly." }, 429);
65
+ await options.getModule().unsubscribe(token);
66
+ return new Response(
67
+ "Email notifications are turned off. You can turn them on again in Feedbax.",
68
+ {
69
+ headers: {
70
+ "Content-Type": "text/plain; charset=utf-8",
71
+ "Cache-Control": "no-store",
72
+ },
73
+ },
74
+ );
75
+ }
76
+ const participant = await options.getParticipant(request);
77
+ if (!participant)
78
+ return json(
79
+ {
80
+ error: "Sign in through the product to continue.",
81
+ code: "sign_in_required",
82
+ },
83
+ 401,
84
+ );
85
+ const module = options.getModule(participant);
86
+ if (request.method === "GET") {
87
+ if (route === "follow")
88
+ return json(
89
+ await module.followState(url.searchParams.get("slug") ?? ""),
90
+ );
91
+ if (route === "notifications")
92
+ return json(
93
+ await module.inbox(url.searchParams.get("cursor") ?? undefined),
94
+ );
95
+ if (route === "preferences") return json(await module.preferences());
96
+ }
97
+ if (!(await options.rateLimit(request)))
98
+ return json({ error: "Too many changes. Try again shortly." }, 429);
99
+ if (Number(request.headers.get("Content-Length")) > 4096)
100
+ return json({ error: "Request is too large." }, 413);
101
+ const reader = request.body?.getReader();
102
+ const chunks: Uint8Array[] = [];
103
+ let length = 0;
104
+ if (reader)
105
+ while (true) {
106
+ const { done, value } = await reader.read();
107
+ if (done) break;
108
+ length += value.byteLength;
109
+ if (length > 4096) {
110
+ await reader.cancel();
111
+ return json({ error: "Request is too large." }, 413);
112
+ }
113
+ chunks.push(value);
114
+ }
115
+ const bytes = new Uint8Array(length);
116
+ let offset = 0;
117
+ for (const chunk of chunks) {
118
+ bytes.set(chunk, offset);
119
+ offset += chunk.byteLength;
120
+ }
121
+ const text = new TextDecoder().decode(bytes);
122
+ if (text.length > 4096)
123
+ return json({ error: "Request is too large." }, 413);
124
+ let body: Record<string, unknown>;
125
+ try {
126
+ body = JSON.parse(text);
127
+ } catch {
128
+ return json({ error: "Invalid request." }, 400);
129
+ }
130
+ if (!body || typeof body !== "object" || Array.isArray(body))
131
+ return json({ error: "Invalid request." }, 400);
132
+ if (
133
+ route === "follow" &&
134
+ typeof body.slug === "string" &&
135
+ body.slug.length <= 512 &&
136
+ typeof body.following === "boolean"
137
+ )
138
+ return json(await module.follow(body.slug, body.following));
139
+ if (
140
+ route === "notifications" &&
141
+ (body.id === undefined ||
142
+ (typeof body.id === "string" && /^[a-f0-9]{32}$/.test(body.id)))
143
+ ) {
144
+ await module.markRead(body.id as string | undefined);
145
+ return json({ updated: true });
146
+ }
147
+ if (route === "preferences" && typeof body.emailEnabled === "boolean") {
148
+ await module.setEmailPreference(body.emailEnabled);
149
+ return json(await module.preferences());
150
+ }
151
+ return json({ error: "Invalid request." }, 400);
152
+ } catch (error) {
153
+ const message = error instanceof Error ? error.message : "";
154
+ const known = [
155
+ "Post is unavailable.",
156
+ "Invalid notification cursor.",
157
+ "Invalid unsubscribe link.",
158
+ "Email notifications require a verified application email and a configured sender.",
159
+ ];
160
+ return json(
161
+ {
162
+ error: known.includes(message)
163
+ ? message
164
+ : "Updates are temporarily unavailable. Try again.",
165
+ },
166
+ message === "Post is unavailable."
167
+ ? 404
168
+ : known.includes(message)
169
+ ? 400
170
+ : 503,
171
+ );
172
+ }
173
+ };
174
+ }
175
+
176
+ export function configuredParticipation(participant?: VerifiedParticipant) {
177
+ return createConfiguredParticipation(
178
+ createConfiguredNotionFeedbackModule(),
179
+ participant,
180
+ );
181
+ }
182
+
183
+ function createConfiguredParticipation(
184
+ feedback: import("@feedbax/feedback").FeedbackModule,
185
+ participant?: VerifiedParticipant,
186
+ ) {
187
+ if (!feedbax.connected || !env.FEEDBAX_DB)
188
+ throw new Error("Connected database is missing.");
189
+ const config = feedbax.connected.email;
190
+ let email: Parameters<typeof createParticipationModule>[0]["email"];
191
+ if (config) {
192
+ const sender =
193
+ config.provider === "cloudflare"
194
+ ? createEmailSender({
195
+ provider: "cloudflare",
196
+ binding: requireBinding(env.FEEDBAX_EMAIL),
197
+ })
198
+ : config.provider === "resend"
199
+ ? createEmailSender({
200
+ provider: "resend",
201
+ token: env.EMAIL_PROVIDER_SECRET ?? "",
202
+ })
203
+ : createEmailSender({
204
+ provider: "custom",
205
+ url: config.endpoint!,
206
+ token: env.EMAIL_PROVIDER_SECRET ?? "",
207
+ });
208
+ email = {
209
+ sender,
210
+ from: config.from,
211
+ siteUrl: feedbax.product.siteUrl!,
212
+ unsubscribeSecret: env.PARTICIPATION_SIGNING_SECRET ?? "",
213
+ };
214
+ }
215
+ return createParticipationModule({
216
+ database: env.FEEDBAX_DB,
217
+ feedback,
218
+ participant,
219
+ processing: feedbax.connected.processing ?? "small",
220
+ email,
221
+ });
222
+ }
223
+ const requireBinding = <T>(value: T | undefined): T => {
224
+ if (!value) throw new Error("Email binding is missing.");
225
+ return value;
226
+ };
227
+ export const handleParticipationRequest = createParticipationRequestHandler({
228
+ enabled: Boolean(feedbax.connected),
229
+ siteUrl: feedbax.product.siteUrl ?? "https://not-configured.invalid",
230
+ getParticipant: async (request) => {
231
+ const token = readSessionToken(request);
232
+ return token ? getConnectedStore().session(sessionHash(token)) : undefined;
233
+ },
234
+ getModule: configuredParticipation,
235
+ rateLimit: async (request) =>
236
+ (
237
+ await env.PORTAL_SUBMISSIONS_RATE_LIMITER.limit({
238
+ key: `updates:${request.headers.get("CF-Connecting-IP") ?? "unknown"}`,
239
+ })
240
+ ).success,
241
+ });
242
+ export async function synchronizeConnectedUpdates() {
243
+ if (!feedbax.connected) return;
244
+ const content = createConfiguredNotionFeedbackModule();
245
+ const module = createConfiguredParticipation(content);
246
+ const observation = await module.synchronize();
247
+ const email = await module.deliverEmails();
248
+ if (feedbax.connected.images) await configuredImages(content).cleanup();
249
+ // Counts only: never log identities, addresses, provider responses, or message bodies.
250
+ if (observation.failed || email.failed)
251
+ console.warn("Connected update processing will retry", {
252
+ observations: observation.failed,
253
+ deliveries: email.failed,
254
+ });
255
+ }
@@ -26,6 +26,7 @@ export interface PortalCommentResult {
26
26
  const commentCapabilityLifetime = 15 * 60 * 1_000;
27
27
 
28
28
  export interface PortalCommentRequest {
29
+ imageIds?: string[];
29
30
  slug: string;
30
31
  body: string;
31
32
  displayName: string;
@@ -36,6 +37,7 @@ export interface PortalCommentRequest {
36
37
  }
37
38
 
38
39
  export function createPortalCommentHandler(options: {
40
+ verifiedParticipant?: { displayName: string };
39
41
  feedback: Pick<FeedbackModule, "createComment" | "replyToCommentThread">;
40
42
  commentsEnabled: boolean;
41
43
  rateLimiter: PortalSubmissionRateLimiter;
@@ -50,7 +52,7 @@ export function createPortalCommentHandler(options: {
50
52
  "Comments are disabled for this Installation.",
51
53
  "comments_disabled",
52
54
  );
53
- const value = validateCommentInput(input);
55
+ const value = validateCommentInput(input, options.verifiedParticipant);
54
56
  const { success } = await options.rateLimiter.limit({
55
57
  key: `comment:${options.rateLimitKey}`,
56
58
  });
@@ -89,6 +91,7 @@ export function createPortalCommentHandler(options: {
89
91
  }
90
92
 
91
93
  const command = {
94
+ ...(value.imageIds ? { imageIds: value.imageIds } : {}),
92
95
  slug: value.slug,
93
96
  body: value.body,
94
97
  displayName: value.displayName,
@@ -338,10 +341,16 @@ export function createPortalCommentMutationRequestHandler(
338
341
  };
339
342
  }
340
343
 
341
- function validateCommentInput(input: unknown): PortalCommentRequest {
344
+ function validateCommentInput(
345
+ input: unknown,
346
+ participant?: { displayName: string },
347
+ ): PortalCommentRequest {
342
348
  if (!input || typeof input !== "object" || Array.isArray(input))
343
349
  throw invalidCommentRequest();
344
- const value = input as Record<string, unknown>;
350
+ const value: Record<string, unknown> = {
351
+ ...(input as Record<string, unknown>),
352
+ ...(participant ? { displayName: participant.displayName } : {}),
353
+ };
345
354
  if (typeof value.slug !== "string" || !value.slug.trim())
346
355
  throw invalidCommentRequest();
347
356
  if (typeof value.body !== "string" || !value.body.trim())
@@ -354,16 +363,26 @@ function validateCommentInput(input: unknown): PortalCommentRequest {
354
363
  "Device Profile display name is required before commenting.",
355
364
  "profile_required",
356
365
  );
357
- if (!isValidCommentEmail(value.email))
366
+ if (!participant && !isValidCommentEmail(value.email))
358
367
  throw new ActionablePortalFailure(
359
368
  "A Device Profile with a valid email is required before commenting.",
360
369
  "profile_required",
361
370
  );
371
+ if (
372
+ value.imageIds !== undefined &&
373
+ (!Array.isArray(value.imageIds) ||
374
+ value.imageIds.length > 4 ||
375
+ value.imageIds.some(
376
+ (id) => typeof id !== "string" || !/^[-a-f0-9]{36}$/.test(id),
377
+ ))
378
+ )
379
+ throw invalidCommentRequest();
362
380
  return {
381
+ ...(value.imageIds ? { imageIds: value.imageIds as string[] } : {}),
363
382
  slug: value.slug.trim(),
364
383
  body: value.body.trim(),
365
384
  displayName: value.displayName.trim(),
366
- email: value.email.trim(),
385
+ email: typeof value.email === "string" ? value.email.trim() : "",
367
386
  ...(typeof value.discussionId === "string" && value.discussionId
368
387
  ? { discussionId: value.discussionId }
369
388
  : {}),