create-nextblock 0.15.8 → 0.15.9

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 (71) hide show
  1. package/package.json +1 -1
  2. package/templates/nextblock-template/app/ToasterProvider.tsx +26 -17
  3. package/templates/nextblock-template/app/actions/contactSellerActions.test.ts +280 -0
  4. package/templates/nextblock-template/app/actions/contactSellerActions.ts +222 -0
  5. package/templates/nextblock-template/app/actions/email-retry.test.ts +62 -0
  6. package/templates/nextblock-template/app/actions/email.ts +241 -110
  7. package/templates/nextblock-template/app/actions/formActions.ts +245 -116
  8. package/templates/nextblock-template/app/actions/interactions.ts +489 -396
  9. package/templates/nextblock-template/app/actions/threadActions.ts +166 -0
  10. package/templates/nextblock-template/app/api/checkout/route.ts +162 -146
  11. package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +664 -1
  12. package/templates/nextblock-template/app/checkout/page.tsx +57 -52
  13. package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +552 -529
  14. package/templates/nextblock-template/app/cms/blocks/editors/FormBlockEditor.tsx +304 -181
  15. package/templates/nextblock-template/app/cms/components/ContactReminderBanner.tsx +75 -0
  16. package/templates/nextblock-template/app/cms/components/PaymentsReminderBanner.tsx +58 -0
  17. package/templates/nextblock-template/app/cms/components/VisibilityControl.tsx +542 -528
  18. package/templates/nextblock-template/app/cms/inquiries/actions.ts +66 -0
  19. package/templates/nextblock-template/app/cms/inquiries/page.tsx +12 -0
  20. package/templates/nextblock-template/app/cms/interactions/page.tsx +12 -51
  21. package/templates/nextblock-template/app/cms/layout.tsx +101 -73
  22. package/templates/nextblock-template/app/cms/messages/MessagesClient.tsx +661 -0
  23. package/templates/nextblock-template/app/cms/messages/actions.ts +404 -0
  24. package/templates/nextblock-template/app/cms/messages/loadInbox.ts +333 -0
  25. package/templates/nextblock-template/app/cms/messages/page.tsx +87 -0
  26. package/templates/nextblock-template/app/cms/messages/require-admin.ts +37 -0
  27. package/templates/nextblock-template/app/cms/products/[id]/edit/page.tsx +370 -362
  28. package/templates/nextblock-template/app/cms/revisions/service.ts +20 -0
  29. package/templates/nextblock-template/app/cms/settings/email/components/EmailForm.tsx +227 -185
  30. package/templates/nextblock-template/app/layout.tsx +671 -671
  31. package/templates/nextblock-template/app/product/[slug]/page.tsx +502 -482
  32. package/templates/nextblock-template/app/providers.tsx +96 -96
  33. package/templates/nextblock-template/app/thread/ThreadView.tsx +164 -0
  34. package/templates/nextblock-template/app/thread/[token]/route.ts +57 -0
  35. package/templates/nextblock-template/app/thread/layout.tsx +15 -0
  36. package/templates/nextblock-template/app/thread/page.tsx +98 -0
  37. package/templates/nextblock-template/components/BlockRenderer.tsx +312 -296
  38. package/templates/nextblock-template/components/ContactSellerSection.tsx +188 -0
  39. package/templates/nextblock-template/components/PostCommentsSection.tsx +378 -369
  40. package/templates/nextblock-template/components/ProductReviewsSection.tsx +426 -419
  41. package/templates/nextblock-template/components/StaffReplies.tsx +102 -0
  42. package/templates/nextblock-template/components/blocks/renderers/CartBlockRenderer.tsx +18 -17
  43. package/templates/nextblock-template/components/blocks/renderers/CheckoutBlockRenderer.tsx +20 -19
  44. package/templates/nextblock-template/components/blocks/renderers/FeaturedProductBlockRenderer.tsx +25 -22
  45. package/templates/nextblock-template/components/blocks/renderers/FormBlockRenderer.tsx +385 -381
  46. package/templates/nextblock-template/components/blocks/renderers/ProductDetailsBlockRenderer.tsx +157 -92
  47. package/templates/nextblock-template/components/blocks/renderers/ProductGridBlockRenderer.tsx +34 -31
  48. package/templates/nextblock-template/components/blocks/renderers/SectionBlockRenderer.tsx +612 -600
  49. package/templates/nextblock-template/components/commerce/PaymentReadinessBoundary.tsx +32 -0
  50. package/templates/nextblock-template/docs/14-MESSAGES-INBOX.md +309 -0
  51. package/templates/nextblock-template/docs/README.md +42 -41
  52. package/templates/nextblock-template/docs/assets/lighthouse-scores.png +0 -0
  53. package/templates/nextblock-template/lib/blocks/blockColors.test.ts +22 -2
  54. package/templates/nextblock-template/lib/blocks/blockColors.ts +44 -1
  55. package/templates/nextblock-template/lib/blocks/blockRegistry.ts +761 -753
  56. package/templates/nextblock-template/lib/cms/contact-reminder.ts +64 -0
  57. package/templates/nextblock-template/lib/cms/payments-reminder.ts +98 -0
  58. package/templates/nextblock-template/lib/cms/unread-messages.ts +42 -0
  59. package/templates/nextblock-template/lib/commerce/seller-contact.ts +162 -0
  60. package/templates/nextblock-template/lib/config/email-settings.ts +323 -254
  61. package/templates/nextblock-template/lib/config/email-tls.test.ts +57 -0
  62. package/templates/nextblock-template/lib/email/placeholder-address.test.ts +59 -0
  63. package/templates/nextblock-template/lib/email/placeholder-address.ts +39 -0
  64. package/templates/nextblock-template/lib/messages/thread-reference.test.ts +70 -0
  65. package/templates/nextblock-template/lib/messages/thread-token.test.ts +93 -0
  66. package/templates/nextblock-template/lib/messages/thread-token.ts +157 -0
  67. package/templates/nextblock-template/lib/messages/threads.ts +579 -0
  68. package/templates/nextblock-template/lib/setup/migrations-bundle.ts +20 -0
  69. package/templates/nextblock-template/lib/site-url.test.ts +89 -0
  70. package/templates/nextblock-template/lib/site-url.ts +102 -48
  71. package/templates/nextblock-template/package.json +1 -1
@@ -1,96 +1,96 @@
1
- "use client";
2
-
3
- import { ThemeProvider } from "next-themes";
4
-
5
- // Suppress the React 19 warning for the <script> tag generated by next-themes in development
6
- if (typeof window !== 'undefined' && process.env.NODE_ENV === 'development') {
7
- const orig = console.error;
8
- console.error = (...args: any[]) => {
9
- if (typeof args[0] === 'string' && args[0].includes('Encountered a script tag')) {
10
- return;
11
- }
12
- orig.apply(console, args);
13
- };
14
- }
15
- import { AuthProvider } from '../context/AuthContext';
16
- import { LanguageProvider, useLanguage } from '../context/LanguageContext';
17
- import { CurrentContentProvider } from '../context/CurrentContentContext';
18
- import { ThemeCatalogProvider } from '../context/ThemeCatalogContext';
19
- import { DeferredCartTranslator } from '../components/DeferredCartTranslator';
20
- import { CurrencyProvider } from '@nextblock-cms/ecommerce/CurrencyProvider';
21
- import { TranslationsProvider } from '@nextblock-cms/utils';
22
-
23
- function TranslationBridge({
24
- children,
25
- translations,
26
- }: {
27
- children: React.ReactNode;
28
- translations: { key: string; translations: Record<string, string> }[];
29
- }) {
30
- const { currentLocale } = useLanguage();
31
-
32
- return (
33
- <TranslationsProvider translations={translations} lang={currentLocale}>
34
- {children}
35
- </TranslationsProvider>
36
- );
37
- }
38
-
39
- export function Providers({ children, ...props }: { children: React.ReactNode;[key: string]: any; }) {
40
- const {
41
- serverUser,
42
- serverProfile,
43
- serverLocale,
44
- initialCurrencies,
45
- initialCurrencyCode,
46
- initialAvailableLanguages,
47
- initialDefaultLanguage,
48
- rememberVisitorChoice,
49
- translations,
50
- nonce,
51
- themeSlugs,
52
- initialTheme,
53
- themeCatalog,
54
- } = props;
55
-
56
- // Themes come from the site_themes table. Fall back to the three that ship in
57
- // libs/ui/src/styles/theme.css if the table is empty or unreachable, so the
58
- // switcher never renders an empty list.
59
- const resolvedThemes: string[] =
60
- Array.isArray(themeSlugs) && themeSlugs.length > 0 ? themeSlugs : ['light', 'dark', 'vibrant'];
61
- const resolvedDefault: string =
62
- typeof initialTheme === 'string' && resolvedThemes.includes(initialTheme) ? initialTheme : 'light';
63
-
64
- return (
65
- <AuthProvider serverUser={serverUser} serverProfile={serverProfile}>
66
- <LanguageProvider
67
- serverLocale={serverLocale}
68
- initialAvailableLanguages={initialAvailableLanguages}
69
- initialDefaultLanguage={initialDefaultLanguage}
70
- rememberVisitorChoice={rememberVisitorChoice}
71
- >
72
- <CurrencyProvider
73
- initialCurrencies={initialCurrencies}
74
- initialCurrencyCode={initialCurrencyCode}
75
- locale={serverLocale}
76
- >
77
- <CurrentContentProvider>
78
- <DeferredCartTranslator />
79
- <TranslationBridge translations={translations}>
80
- <ThemeProvider
81
- attribute="class"
82
- defaultTheme={resolvedDefault}
83
- enableSystem
84
- disableTransitionOnChange
85
- nonce={nonce}
86
- themes={resolvedThemes}
87
- >
88
- <ThemeCatalogProvider themes={themeCatalog}>{children}</ThemeCatalogProvider>
89
- </ThemeProvider>
90
- </TranslationBridge>
91
- </CurrentContentProvider>
92
- </CurrencyProvider>
93
- </LanguageProvider>
94
- </AuthProvider>
95
- );
96
- }
1
+ "use client";
2
+
3
+ import { ThemeProvider } from "next-themes";
4
+
5
+ // Suppress the React 19 warning for the <script> tag generated by next-themes in development
6
+ if (typeof window !== 'undefined' && process.env.NODE_ENV === 'development') {
7
+ const orig = console.error;
8
+ console.error = (...args: any[]) => {
9
+ if (typeof args[0] === 'string' && args[0].includes('Encountered a script tag')) {
10
+ return;
11
+ }
12
+ orig.apply(console, args);
13
+ };
14
+ }
15
+ import { AuthProvider } from '../context/AuthContext';
16
+ import { LanguageProvider, useLanguage } from '../context/LanguageContext';
17
+ import { CurrentContentProvider } from '../context/CurrentContentContext';
18
+ import { ThemeCatalogProvider } from '../context/ThemeCatalogContext';
19
+ import { DeferredCartTranslator } from '../components/DeferredCartTranslator';
20
+ import { CurrencyProvider } from '@nextblock-cms/ecommerce/CurrencyProvider';
21
+ import { TranslationsProvider } from '@nextblock-cms/utils';
22
+
23
+ function TranslationBridge({
24
+ children,
25
+ translations,
26
+ }: {
27
+ children: React.ReactNode;
28
+ translations: { key: string; translations: Record<string, string> }[];
29
+ }) {
30
+ const { currentLocale } = useLanguage();
31
+
32
+ return (
33
+ <TranslationsProvider translations={translations} lang={currentLocale}>
34
+ {children}
35
+ </TranslationsProvider>
36
+ );
37
+ }
38
+
39
+ export function Providers({ children, ...props }: { children: React.ReactNode;[key: string]: any; }) {
40
+ const {
41
+ serverUser,
42
+ serverProfile,
43
+ serverLocale,
44
+ initialCurrencies,
45
+ initialCurrencyCode,
46
+ initialAvailableLanguages,
47
+ initialDefaultLanguage,
48
+ rememberVisitorChoice,
49
+ translations,
50
+ nonce,
51
+ themeSlugs,
52
+ initialTheme,
53
+ themeCatalog,
54
+ } = props;
55
+
56
+ // Themes come from the site_themes table. Fall back to the three that ship in
57
+ // libs/ui/src/styles/theme.css if the table is empty or unreachable, so the
58
+ // switcher never renders an empty list.
59
+ const resolvedThemes: string[] =
60
+ Array.isArray(themeSlugs) && themeSlugs.length > 0 ? themeSlugs : ['light', 'dark', 'vibrant'];
61
+ const resolvedDefault: string =
62
+ typeof initialTheme === 'string' && resolvedThemes.includes(initialTheme) ? initialTheme : 'light';
63
+
64
+ return (
65
+ <AuthProvider serverUser={serverUser} serverProfile={serverProfile}>
66
+ <LanguageProvider
67
+ serverLocale={serverLocale}
68
+ initialAvailableLanguages={initialAvailableLanguages}
69
+ initialDefaultLanguage={initialDefaultLanguage}
70
+ rememberVisitorChoice={rememberVisitorChoice}
71
+ >
72
+ <CurrencyProvider
73
+ initialCurrencies={initialCurrencies}
74
+ initialCurrencyCode={initialCurrencyCode}
75
+ locale={serverLocale}
76
+ >
77
+ <CurrentContentProvider>
78
+ <DeferredCartTranslator />
79
+ <TranslationBridge translations={translations}>
80
+ <ThemeProvider
81
+ attribute="class"
82
+ defaultTheme={resolvedDefault}
83
+ enableSystem
84
+ disableTransitionOnChange
85
+ nonce={nonce}
86
+ themes={resolvedThemes}
87
+ >
88
+ <ThemeCatalogProvider themes={themeCatalog}>{children}</ThemeCatalogProvider>
89
+ </ThemeProvider>
90
+ </TranslationBridge>
91
+ </CurrentContentProvider>
92
+ </CurrencyProvider>
93
+ </LanguageProvider>
94
+ </AuthProvider>
95
+ );
96
+ }
@@ -0,0 +1,164 @@
1
+ 'use client';
2
+
3
+ import { useActionState } from 'react';
4
+ import { useFormStatus } from 'react-dom';
5
+ import { Button } from '@nextblock-cms/ui';
6
+ import { Textarea } from '@nextblock-cms/ui';
7
+ import { useTranslations } from '@nextblock-cms/utils';
8
+ import { CheckCircle2, Loader2, Send } from 'lucide-react';
9
+
10
+ import { AuthBotProtection } from '../../components/auth/AuthBotProtection';
11
+ import { submitThreadReply, type ThreadReplyState } from '../actions/threadActions';
12
+
13
+ export interface ThreadMessage {
14
+ id: string;
15
+ direction: 'inbound' | 'outbound';
16
+ body: string;
17
+ author_name: string | null;
18
+ created_at: string;
19
+ }
20
+
21
+ interface ThreadViewProps {
22
+ invalid?: boolean;
23
+ subjectLabel?: string;
24
+ closed?: boolean;
25
+ messages?: ThreadMessage[];
26
+ botProtectionProvider?: 'none' | 'turnstile' | 'recaptcha';
27
+ botProtectionSiteKey?: string;
28
+ scriptNonce?: string;
29
+ }
30
+
31
+ const INITIAL_STATE: ThreadReplyState = { success: false, messageKey: '' };
32
+
33
+ // `t()` returns the key itself when a translation row is missing, so every string
34
+ // carries the English literal it should fall back to.
35
+ const FALLBACKS: Record<string, string> = {
36
+ 'thread.heading': 'Your conversation',
37
+ 'thread.reply_label': 'Write a reply',
38
+ 'thread.send': 'Send reply',
39
+ 'thread.sending': 'Sending…',
40
+ 'thread.sent': 'Thanks - your reply has been sent.',
41
+ 'thread.error': "Sorry, your reply couldn't be sent. Please try again in a moment.",
42
+ 'thread.throttled': "You've sent several replies already. Please wait a few minutes.",
43
+ 'thread.closed': 'This conversation has been closed.',
44
+ 'thread.invalid':
45
+ 'This link has expired or is no longer valid. If you still need help, please contact us again from our website.',
46
+ 'thread.you': 'You',
47
+ };
48
+
49
+ function SendButton({ label, pendingLabel }: { label: string; pendingLabel: string }) {
50
+ const { pending } = useFormStatus();
51
+ return (
52
+ <Button type="submit" disabled={pending} className="min-w-[140px]">
53
+ {pending ? (
54
+ <>
55
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
56
+ {pendingLabel}
57
+ </>
58
+ ) : (
59
+ <>
60
+ <Send className="mr-2 h-4 w-4" />
61
+ {label}
62
+ </>
63
+ )}
64
+ </Button>
65
+ );
66
+ }
67
+
68
+ export default function ThreadView({
69
+ invalid = false,
70
+ subjectLabel,
71
+ closed = false,
72
+ messages = [],
73
+ botProtectionProvider = 'none',
74
+ botProtectionSiteKey = '',
75
+ scriptNonce,
76
+ }: ThreadViewProps) {
77
+ const { t } = useTranslations();
78
+ const [state, formAction] = useActionState(submitThreadReply, INITIAL_STATE);
79
+
80
+ const label = (key: string): string => {
81
+ const value = t(key);
82
+ return value === key ? (FALLBACKS[key] ?? key) : value;
83
+ };
84
+
85
+ // One page for every failure: expired, revoked, and never-existed are indistinguishable
86
+ // on purpose, so this page cannot be used to probe for valid threads.
87
+ if (invalid) {
88
+ return (
89
+ <div className="rounded-2xl border border-border/80 bg-card/50 p-6 text-center">
90
+ <p className="text-sm text-muted-foreground">{label('thread.invalid')}</p>
91
+ </div>
92
+ );
93
+ }
94
+
95
+ const errorText = state.message || (!state.success && state.messageKey ? label(state.messageKey) : null);
96
+
97
+ return (
98
+ <div className="space-y-6">
99
+ <header>
100
+ <h1 className="text-xl font-semibold text-foreground">{label('thread.heading')}</h1>
101
+ {subjectLabel && <p className="text-sm text-muted-foreground">{subjectLabel}</p>}
102
+ </header>
103
+
104
+ <ol className="space-y-4">
105
+ {messages.map((message) => {
106
+ const fromVisitor = message.direction === 'inbound';
107
+ return (
108
+ <li
109
+ key={message.id}
110
+ className={`rounded-2xl border p-4 ${
111
+ fromVisitor
112
+ ? 'border-border/80 bg-card/50'
113
+ : 'border-primary/30 bg-primary/5'
114
+ }`}
115
+ >
116
+ <div className="mb-1 flex items-baseline justify-between gap-3">
117
+ <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
118
+ {fromVisitor ? label('thread.you') : message.author_name || 'Support'}
119
+ </span>
120
+ <time className="text-xs text-muted-foreground" suppressHydrationWarning>
121
+ {new Date(message.created_at).toLocaleString()}
122
+ </time>
123
+ </div>
124
+ <p className="whitespace-pre-wrap text-sm text-foreground">{message.body}</p>
125
+ </li>
126
+ );
127
+ })}
128
+ </ol>
129
+
130
+ {state.success ? (
131
+ <div className="flex items-start gap-3 rounded-2xl border border-emerald-200 bg-emerald-50 p-4 dark:border-emerald-900/50 dark:bg-emerald-950/30">
132
+ <CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0 text-emerald-600 dark:text-emerald-400" />
133
+ <p className="text-sm text-emerald-900 dark:text-emerald-200">{label('thread.sent')}</p>
134
+ </div>
135
+ ) : closed ? (
136
+ <p className="rounded-2xl border border-dashed border-border p-4 text-center text-sm text-muted-foreground">
137
+ {label('thread.closed')}
138
+ </p>
139
+ ) : (
140
+ <form action={formAction} className="space-y-3 rounded-2xl border border-border/80 bg-card/50 p-4">
141
+ <label
142
+ htmlFor="thread-reply"
143
+ className="block text-xs font-semibold uppercase tracking-wider text-muted-foreground"
144
+ >
145
+ {label('thread.reply_label')}
146
+ </label>
147
+ <Textarea id="thread-reply" name="body" required maxLength={5000} className="min-h-[120px]" />
148
+
149
+ <AuthBotProtection
150
+ provider={botProtectionProvider}
151
+ siteKey={botProtectionSiteKey}
152
+ scriptNonce={scriptNonce}
153
+ />
154
+
155
+ {errorText && <p className="text-sm font-semibold text-destructive">{errorText}</p>}
156
+
157
+ <div className="flex justify-end">
158
+ <SendButton label={label('thread.send')} pendingLabel={label('thread.sending')} />
159
+ </div>
160
+ </form>
161
+ )}
162
+ </div>
163
+ );
164
+ }
@@ -0,0 +1,57 @@
1
+ import { NextResponse } from 'next/server';
2
+ import { getServiceRoleSupabaseClient } from '@nextblock-cms/db/server';
3
+
4
+ import { setSecureCookie } from '../../../lib/auth/cookies';
5
+ import {
6
+ THREAD_COOKIE,
7
+ secondsUntilExpiry,
8
+ verifyThreadToken,
9
+ } from '../../../lib/messages/thread-token';
10
+ export const runtime = 'nodejs';
11
+ export const dynamic = 'force-dynamic';
12
+
13
+ /**
14
+ * Exchange a mailed thread link for a session cookie, then get the token out of the URL.
15
+ *
16
+ * This redirect is the most important control in the whole feature. The app sends
17
+ * `Referrer-Policy: strict-origin-when-cross-origin`, which means the FULL url travels in
18
+ * the Referer header on same-origin navigations — so a token left in the address bar
19
+ * would leak to every internal link the visitor clicks, into browser history, into any
20
+ * screenshot they share, and into proxy access logs. Held in an HttpOnly cookie it does
21
+ * none of that, and script on the page cannot read it either.
22
+ *
23
+ * Every failure lands on the same token-less page with no cookie set. The visitor is
24
+ * never told which kind of failure it was: distinguishing "expired" from "never existed"
25
+ * would turn this route into an oracle.
26
+ */
27
+ export async function GET(
28
+ request: Request,
29
+ { params }: { params: Promise<{ token: string }> }
30
+ ) {
31
+ const { token } = await params;
32
+ // Built from the REQUEST's own origin, not the configured site URL: the visitor must
33
+ // land back on the host they arrived at. Deriving it from settings sends anyone whose
34
+ // host differs from NEXT_PUBLIC_URL (a preview deploy, a custom domain, local dev on a
35
+ // non-default port) to the wrong origin — and the cookie set here would not follow.
36
+ const redirect = NextResponse.redirect(new URL('/thread', request.url), { status: 302 });
37
+ redirect.headers.set('Cache-Control', 'no-store');
38
+
39
+ try {
40
+ const supabase = getServiceRoleSupabaseClient();
41
+ const verification = await verifyThreadToken(supabase, token);
42
+
43
+ if (!verification.valid) {
44
+ console.warn(`[thread] Rejected thread link (${verification.reason}).`);
45
+ return redirect;
46
+ }
47
+
48
+ const maxAge = secondsUntilExpiry(verification.thread.token_expires_at);
49
+ if (maxAge <= 0) return redirect;
50
+
51
+ await setSecureCookie(THREAD_COOKIE, token, maxAge);
52
+ } catch (error) {
53
+ console.error('[thread] Could not process a thread link:', error);
54
+ }
55
+
56
+ return redirect;
57
+ }
@@ -0,0 +1,15 @@
1
+ import type { ReactNode } from 'react';
2
+
3
+ /**
4
+ * A private conversation between one visitor and the store. Never indexed: the page is
5
+ * reached by a personal link, and a search engine that crawled it would both expose the
6
+ * exchange and burn the token by following it.
7
+ */
8
+ export const metadata = {
9
+ title: 'Your conversation',
10
+ robots: { index: false, follow: false },
11
+ };
12
+
13
+ export default function ThreadLayout({ children }: { children: ReactNode }) {
14
+ return <div className="mx-auto w-full max-w-2xl px-4 py-10 sm:py-16">{children}</div>;
15
+ }
@@ -0,0 +1,98 @@
1
+ import { headers } from 'next/headers';
2
+ import { getServiceRoleSupabaseClient } from '@nextblock-cms/db/server';
3
+
4
+ import { getCookieValue } from '../../lib/auth/cookies';
5
+ import {
6
+ THREAD_COOKIE,
7
+ touchThreadToken,
8
+ verifyThreadToken,
9
+ } from '../../lib/messages/thread-token';
10
+ import ThreadView, { type ThreadMessage } from './ThreadView';
11
+
12
+ // A conversation changes whenever either side writes; a cached copy would show the
13
+ // visitor a reply that is no longer the latest, or hide one that just arrived.
14
+ export const dynamic = 'force-dynamic';
15
+ export const fetchCache = 'force-no-store';
16
+
17
+ const MAX_MESSAGES = 200;
18
+
19
+ /**
20
+ * The visitor's half of a private conversation.
21
+ *
22
+ * Authentication is the HttpOnly cookie set by `/thread/[token]`, verified here in
23
+ * application code and then read with the service role — no RLS policy in this schema
24
+ * authenticates an anonymous caller by token, and this page does not invent one.
25
+ *
26
+ * There is exactly one failure page. A visitor whose link expired, was revoked, or never
27
+ * existed sees the same words, because anything else would let someone probe for valid
28
+ * threads.
29
+ */
30
+ export default async function ThreadPage() {
31
+ const supabase = getServiceRoleSupabaseClient();
32
+ const token = await getCookieValue(THREAD_COOKIE);
33
+ const check = await verifyThreadToken(supabase, token);
34
+
35
+ if (!check.valid) {
36
+ return <ThreadView invalid />;
37
+ }
38
+
39
+ const thread = check.thread;
40
+
41
+ const [{ data: rows }, botProtection, scriptNonce] = await Promise.all([
42
+ supabase
43
+ .from('thread_messages')
44
+ .select('id, direction, body, author_name, created_at')
45
+ .eq('thread_id', thread.id)
46
+ .order('created_at', { ascending: true })
47
+ .limit(MAX_MESSAGES),
48
+ loadBotProtection(supabase),
49
+ loadNonce(),
50
+ ]);
51
+
52
+ // The visitor is looking at it, so it is no longer unread for them.
53
+ if (thread.unread_for_visitor) {
54
+ await supabase
55
+ .from('message_threads')
56
+ .update({ unread_for_visitor: false })
57
+ .eq('id', thread.id);
58
+ }
59
+ await touchThreadToken(supabase, thread.id);
60
+
61
+ return (
62
+ <ThreadView
63
+ subjectLabel={thread.subject_label}
64
+ closed={thread.status === 'closed'}
65
+ messages={(rows ?? []) as ThreadMessage[]}
66
+ botProtectionProvider={botProtection.provider}
67
+ botProtectionSiteKey={botProtection.siteKey}
68
+ scriptNonce={scriptNonce}
69
+ />
70
+ );
71
+ }
72
+
73
+ async function loadBotProtection(supabase: {
74
+ from: (table: string) => any;
75
+ }): Promise<{ provider: 'none' | 'turnstile' | 'recaptcha'; siteKey: string }> {
76
+ try {
77
+ const { data } = await supabase
78
+ .from('site_settings')
79
+ .select('value')
80
+ .eq('key', 'bot_protection_public')
81
+ .maybeSingle();
82
+ if (data?.value) {
83
+ const value = data.value as Record<string, any>;
84
+ return { provider: value.provider || 'none', siteKey: value.siteKey || '' };
85
+ }
86
+ } catch (error) {
87
+ console.error('[thread] Could not load bot protection settings:', error);
88
+ }
89
+ return { provider: 'none', siteKey: '' };
90
+ }
91
+
92
+ async function loadNonce(): Promise<string> {
93
+ try {
94
+ return (await headers()).get('x-nonce') || '';
95
+ } catch {
96
+ return '';
97
+ }
98
+ }