create-nextblock 0.13.7 → 0.13.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 (44) hide show
  1. package/package.json +1 -1
  2. package/templates/nextblock-template/app/(auth-pages)/two-factor/actions.ts +21 -1
  3. package/templates/nextblock-template/app/(auth-pages)/two-factor/components/TwoFactorForm.tsx +34 -10
  4. package/templates/nextblock-template/app/actions/email.ts +78 -7
  5. package/templates/nextblock-template/app/actions/feedback.ts +57 -14
  6. package/templates/nextblock-template/app/actions/interactions.test.ts +3 -0
  7. package/templates/nextblock-template/app/actions/productGridActions.ts +40 -0
  8. package/templates/nextblock-template/app/actions.ts +17 -4
  9. package/templates/nextblock-template/app/api/cms/ecommerce/product-picker/route.ts +151 -0
  10. package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +4 -1
  11. package/templates/nextblock-template/app/cms/blocks/components/BlockTypeSelector.tsx +17 -5
  12. package/templates/nextblock-template/app/cms/blocks/components/MultiEntityPicker.tsx +251 -0
  13. package/templates/nextblock-template/app/cms/blocks/editors/ProductGridBlockEditor.tsx +375 -18
  14. package/templates/nextblock-template/app/cms/components/EcommerceActiveContext.tsx +27 -0
  15. package/templates/nextblock-template/app/cms/settings/bot-protection/actions.ts +9 -6
  16. package/templates/nextblock-template/app/cms/settings/bot-protection/components/BotProtectionForm.tsx +1 -5
  17. package/templates/nextblock-template/app/cms/settings/copyright/actions.ts +9 -6
  18. package/templates/nextblock-template/app/cms/settings/copyright/components/CopyrightForm.tsx +1 -5
  19. package/templates/nextblock-template/app/cms/settings/cortex-ai/actions.ts +18 -8
  20. package/templates/nextblock-template/app/cms/settings/email/actions.ts +59 -29
  21. package/templates/nextblock-template/app/cms/settings/email/components/EmailForm.tsx +5 -1
  22. package/templates/nextblock-template/app/cms/settings/global-css/actions.ts +6 -5
  23. package/templates/nextblock-template/app/cms/settings/global-css/components/GlobalCssForm.tsx +2 -1
  24. package/templates/nextblock-template/app/cms/settings/google-analytics/actions.ts +18 -7
  25. package/templates/nextblock-template/app/cms/settings/google-analytics/components/GoogleAnalyticsForm.tsx +1 -1
  26. package/templates/nextblock-template/app/cms/settings/privacy/actions.ts +16 -7
  27. package/templates/nextblock-template/app/cms/settings/privacy/components/PrivacyForm.tsx +1 -1
  28. package/templates/nextblock-template/app/cms/settings/registration/actions.ts +18 -7
  29. package/templates/nextblock-template/app/cms/settings/registration/components/RegistrationForm.tsx +1 -1
  30. package/templates/nextblock-template/app/cms/settings/security/actions.ts +227 -131
  31. package/templates/nextblock-template/app/cms/settings/security/components/SecurityPanel.tsx +134 -18
  32. package/templates/nextblock-template/components/blocks/ProductGridClient.tsx +114 -0
  33. package/templates/nextblock-template/lib/auth/twoFactor.test.ts +254 -0
  34. package/templates/nextblock-template/lib/auth/twoFactor.ts +56 -13
  35. package/templates/nextblock-template/lib/blocks/ProductGridBlock.tsx +78 -139
  36. package/templates/nextblock-template/lib/blocks/blockRegistry.ts +3 -3
  37. package/templates/nextblock-template/lib/blocks/blockTypes.ts +19 -0
  38. package/templates/nextblock-template/lib/blocks/ecommerce-block-schemas.ts +61 -2
  39. package/templates/nextblock-template/lib/blocks/product-grid-data.ts +210 -0
  40. package/templates/nextblock-template/lib/cms/action-result.ts +12 -0
  41. package/templates/nextblock-template/lib/config/email-settings.ts +40 -3
  42. package/templates/nextblock-template/next-env.d.ts +1 -1
  43. package/templates/nextblock-template/package.json +1 -1
  44. package/templates/nextblock-template/tsconfig.tsbuildinfo +1 -1
@@ -1,32 +1,238 @@
1
1
  "use client";
2
2
 
3
3
  import React from 'react';
4
- import { Label, Input } from "@nextblock-cms/ui";
4
+ import { AlertTriangle, Clock, Folder, ListChecks } from 'lucide-react';
5
+ import { Label, Input, Checkbox } from "@nextblock-cms/ui";
6
+ import { cn } from "@nextblock-cms/utils";
5
7
  import { BlockEditorProps } from '../components/BlockEditorModal';
6
- import { ProductGridBlockContent } from '../../../../lib/blocks/ecommerce-block-schemas';
8
+ import MultiEntityPicker, { type PickerOption } from '../components/MultiEntityPicker';
9
+ import {
10
+ PRODUCT_GRID_DEFAULT_PAGE_SIZE,
11
+ PRODUCT_GRID_MAX_CATEGORIES,
12
+ PRODUCT_GRID_MAX_LIMIT,
13
+ PRODUCT_GRID_MAX_PRODUCTS,
14
+ PRODUCT_GRID_UNLIMITED,
15
+ resolveProductGridCategoryIds,
16
+ resolveProductGridLimit,
17
+ resolveProductGridProductIds,
18
+ type ProductGridBlockContent,
19
+ } from '../../../../lib/blocks/ecommerce-block-schemas';
20
+
21
+ type SourceType = NonNullable<ProductGridBlockContent['type']>;
22
+
23
+ const SOURCE_OPTIONS: { value: SourceType; label: string; icon: React.ElementType; hint: string }[] = [
24
+ {
25
+ value: 'latest',
26
+ label: 'Latest',
27
+ icon: Clock,
28
+ hint: 'Newest products first — the grid updates itself as you add products.',
29
+ },
30
+ {
31
+ value: 'category',
32
+ label: 'By category',
33
+ icon: Folder,
34
+ hint: 'Products belonging to any of the selected categories, newest first.',
35
+ },
36
+ {
37
+ value: 'manual',
38
+ label: 'Hand-picked',
39
+ icon: ListChecks,
40
+ hint: 'Exactly the products you choose, shown in the order you add them.',
41
+ },
42
+ ];
43
+
44
+ interface PickerProduct {
45
+ id: string;
46
+ title: string;
47
+ sku: string | null;
48
+ status: string | null;
49
+ languageCode: string | null;
50
+ }
51
+
52
+ interface PickerData {
53
+ categories: { id: string; name: string; slug: string }[];
54
+ products: PickerProduct[];
55
+ hasMore: boolean;
56
+ }
57
+
58
+ const EMPTY_DATA: PickerData = { categories: [], products: [], hasMore: false };
59
+
60
+ function toProductOption(product: PickerProduct): PickerOption {
61
+ return {
62
+ id: product.id,
63
+ label: product.title,
64
+ description: product.sku ? `SKU ${product.sku}` : null,
65
+ badge:
66
+ [product.languageCode, product.status !== 'active' ? product.status : null]
67
+ .filter(Boolean)
68
+ .join(' · ') || null,
69
+ };
70
+ }
7
71
 
8
72
  export default function ProductGridBlockEditor({ content, onChange }: BlockEditorProps<Partial<ProductGridBlockContent>>) {
73
+ const [data, setData] = React.useState<PickerData>(EMPTY_DATA);
74
+ const [isLoading, setIsLoading] = React.useState(true);
75
+ const [loadError, setLoadError] = React.useState<string | null>(null);
76
+ const [productSearch, setProductSearch] = React.useState('');
77
+ // Every product seen so far, so a chip keeps its label after the search that
78
+ // surfaced it is cleared.
79
+ const [knownProducts, setKnownProducts] = React.useState<Map<string, PickerProduct>>(
80
+ () => new Map()
81
+ );
9
82
 
10
- const handleChange = (field: keyof ProductGridBlockContent, value: any) => {
83
+ const sourceType: SourceType = content.type ?? 'latest';
84
+ const selectedCategoryIds = React.useMemo(
85
+ () => resolveProductGridCategoryIds(content),
86
+ [content]
87
+ );
88
+ const selectedProductIds = React.useMemo(
89
+ () => resolveProductGridProductIds(content),
90
+ [content]
91
+ );
92
+
93
+ // Only the ids present when the editor mounts need hydrating — anything picked
94
+ // afterwards is already in `data.products`. Keeping this out of the fetch
95
+ // dependencies avoids a refetch on every selection change.
96
+ const initialProductIdsRef = React.useRef(selectedProductIds.join(','));
97
+
98
+ React.useEffect(() => {
99
+ const controller = new AbortController();
100
+ const handle = setTimeout(() => {
101
+ setIsLoading(true);
102
+ const params = new URLSearchParams();
103
+ if (productSearch.trim()) params.set('search', productSearch.trim());
104
+ if (initialProductIdsRef.current) params.set('ids', initialProductIdsRef.current);
105
+
106
+ fetch(`/api/cms/ecommerce/product-picker?${params.toString()}`, {
107
+ signal: controller.signal,
108
+ })
109
+ .then(async (response) => {
110
+ if (!response.ok) {
111
+ const body = await response.json().catch(() => ({}));
112
+ throw new Error(body?.error || 'Failed to load products.');
113
+ }
114
+ return response.json();
115
+ })
116
+ .then((payload: PickerData) => {
117
+ const products = payload.products ?? [];
118
+ setData({
119
+ categories: payload.categories ?? [],
120
+ products,
121
+ hasMore: Boolean(payload.hasMore),
122
+ });
123
+ setKnownProducts((previous) => {
124
+ const next = new Map(previous);
125
+ for (const product of products) next.set(product.id, product);
126
+ return next;
127
+ });
128
+ setLoadError(null);
129
+ })
130
+ .catch((error: unknown) => {
131
+ if (error instanceof DOMException && error.name === 'AbortError') return;
132
+ setLoadError(error instanceof Error ? error.message : 'Failed to load products.');
133
+ })
134
+ .finally(() => {
135
+ if (!controller.signal.aborted) setIsLoading(false);
136
+ });
137
+ // Debounce so typing in the product search does not fire a request per keystroke.
138
+ }, productSearch ? 250 : 0);
139
+
140
+ return () => {
141
+ controller.abort();
142
+ clearTimeout(handle);
143
+ };
144
+ }, [productSearch]);
145
+
146
+ const handleChange = <K extends keyof ProductGridBlockContent>(
147
+ field: K,
148
+ value: ProductGridBlockContent[K]
149
+ ) => {
11
150
  onChange({ ...content, [field]: value });
12
151
  };
13
152
 
153
+ /**
154
+ * Writing `categoryIds` has to drop the legacy `categoryId`, otherwise
155
+ * `resolveProductGridCategoryIds` falls back to it and a category the author
156
+ * just removed comes straight back.
157
+ */
158
+ const handleCategoryChange = (ids: string[]) => {
159
+ const { categoryId: _legacyCategoryId, ...rest } = content;
160
+ onChange({ ...rest, categoryIds: ids });
161
+ };
162
+
163
+ const limit = resolveProductGridLimit(content);
164
+ const isUnlimited = limit === PRODUCT_GRID_UNLIMITED;
165
+ const showPagination = Boolean(content.showPagination);
166
+
167
+ /**
168
+ * Pagination needs a page size, so switching it on for an unlimited grid picks
169
+ * a sensible one instead of leaving the block in a contradictory state.
170
+ */
171
+ const handlePaginationChange = (checked: boolean) => {
172
+ onChange({
173
+ ...content,
174
+ showPagination: checked,
175
+ limit: checked && isUnlimited ? PRODUCT_GRID_DEFAULT_PAGE_SIZE : limit,
176
+ });
177
+ };
178
+
179
+ // The field is backed by a draft string so it can be emptied mid-edit; only
180
+ // parseable values are committed to the block.
181
+ const [limitDraft, setLimitDraft] = React.useState(() => String(limit));
182
+ React.useEffect(() => {
183
+ setLimitDraft(String(limit));
184
+ }, [limit]);
185
+
186
+ const handleLimitChange = (raw: string) => {
187
+ setLimitDraft(raw);
188
+ const parsed = parseInt(raw, 10);
189
+ if (Number.isNaN(parsed)) return;
190
+ const floor = showPagination ? 1 : PRODUCT_GRID_UNLIMITED;
191
+ handleChange('limit', Math.min(Math.max(parsed, floor), PRODUCT_GRID_MAX_LIMIT));
192
+ };
193
+
194
+ const handleSourceChange = (nextType: SourceType) => {
195
+ const { categoryId: _legacyCategoryId, ...rest } = content;
196
+ onChange({
197
+ ...rest,
198
+ type: nextType,
199
+ // Both selections are kept so switching source back and forth is
200
+ // non-destructive; the renderer only reads the one matching `type`.
201
+ categoryIds: selectedCategoryIds,
202
+ productIds: selectedProductIds,
203
+ });
204
+ };
205
+
206
+ const categoryOptions: PickerOption[] = React.useMemo(
207
+ () =>
208
+ data.categories.map((category) => ({
209
+ id: category.id,
210
+ label: category.name,
211
+ description: `/${category.slug}`,
212
+ })),
213
+ [data.categories]
214
+ );
215
+
216
+ const productOptions: PickerOption[] = React.useMemo(
217
+ () => data.products.map(toProductOption),
218
+ [data.products]
219
+ );
220
+
221
+ const selectedProductOptions: PickerOption[] = React.useMemo(
222
+ () =>
223
+ selectedProductIds
224
+ .map((id) => knownProducts.get(id))
225
+ .filter((product): product is PickerProduct => Boolean(product))
226
+ .map(toProductOption),
227
+ [selectedProductIds, knownProducts]
228
+ );
229
+
230
+ const activeSource = SOURCE_OPTIONS.find((option) => option.value === sourceType) ?? SOURCE_OPTIONS[0];
231
+
14
232
  return (
15
- <div className="space-y-4 p-3 border-t mt-2">
16
- <div>
17
- <Label htmlFor="pg-limit">Item Limit</Label>
18
- <Input
19
- id="pg-limit"
20
- type="number"
21
- min={1}
22
- max={20}
23
- value={content.limit || 6}
24
- onChange={(e) => handleChange('limit', parseInt(e.target.value) || 6)}
25
- className="mt-1"
26
- />
27
- </div>
233
+ <div className="mt-2 space-y-5 border-t p-3">
28
234
  <div>
29
- <Label htmlFor="pg-title">Grid Title (Optional)</Label>
235
+ <Label htmlFor="pg-title">Grid title (optional)</Label>
30
236
  <Input
31
237
  id="pg-title"
32
238
  value={content.title || ""}
@@ -34,8 +240,159 @@ export default function ProductGridBlockEditor({ content, onChange }: BlockEdito
34
240
  placeholder="New Arrivals"
35
241
  className="mt-1"
36
242
  />
243
+ <p className="mt-1 text-[11px] text-muted-foreground">
244
+ Shown as a heading above the grid. Leave empty for no heading.
245
+ </p>
246
+ </div>
247
+
248
+ <div>
249
+ <Label>Which products?</Label>
250
+ <div
251
+ role="radiogroup"
252
+ aria-label="Product source"
253
+ className="mt-1 grid grid-cols-3 gap-1 rounded-lg border bg-muted/40 p-1"
254
+ >
255
+ {SOURCE_OPTIONS.map((option) => {
256
+ const Icon = option.icon;
257
+ const isActive = option.value === sourceType;
258
+ return (
259
+ <button
260
+ key={option.value}
261
+ type="button"
262
+ role="radio"
263
+ aria-checked={isActive}
264
+ onClick={() => handleSourceChange(option.value)}
265
+ className={cn(
266
+ 'flex items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs transition-colors',
267
+ isActive
268
+ ? 'bg-background font-medium text-foreground shadow-sm'
269
+ : 'text-muted-foreground hover:text-foreground'
270
+ )}
271
+ >
272
+ <Icon className="h-3.5 w-3.5" />
273
+ {option.label}
274
+ </button>
275
+ );
276
+ })}
277
+ </div>
278
+ <p className="mt-1.5 text-[11px] leading-snug text-muted-foreground">{activeSource.hint}</p>
279
+ </div>
280
+
281
+ {loadError && (
282
+ <p className="flex items-start gap-1.5 rounded-md bg-destructive/10 p-2 text-[11px] text-destructive">
283
+ <AlertTriangle className="mt-px h-3.5 w-3.5 shrink-0" />
284
+ {loadError}
285
+ </p>
286
+ )}
287
+
288
+ {sourceType === 'category' && (
289
+ <div>
290
+ <Label>Categories</Label>
291
+ <div className="mt-1">
292
+ <MultiEntityPicker
293
+ options={categoryOptions}
294
+ selectedIds={selectedCategoryIds}
295
+ onChange={handleCategoryChange}
296
+ nouns={['category', 'categories']}
297
+ placeholder="Select categories…"
298
+ searchPlaceholder="Search categories…"
299
+ emptyMessage="No categories yet."
300
+ isLoading={isLoading}
301
+ maxSelected={PRODUCT_GRID_MAX_CATEGORIES}
302
+ hint={
303
+ selectedCategoryIds.length === 0
304
+ ? 'No category selected — the grid falls back to the latest products.'
305
+ : 'A product appears if it belongs to any of these categories.'
306
+ }
307
+ />
308
+ </div>
309
+ </div>
310
+ )}
311
+
312
+ {sourceType === 'manual' && (
313
+ <div>
314
+ <Label>Products</Label>
315
+ <div className="mt-1">
316
+ <MultiEntityPicker
317
+ options={productOptions}
318
+ selectedOptions={selectedProductOptions}
319
+ selectedIds={selectedProductIds}
320
+ onChange={(ids) => handleChange('productIds', ids)}
321
+ nouns={['product', 'products']}
322
+ placeholder="Select products…"
323
+ searchPlaceholder="Search by title or SKU…"
324
+ emptyMessage="No products match that search."
325
+ isLoading={isLoading}
326
+ onSearchChange={setProductSearch}
327
+ showOrder
328
+ maxSelected={PRODUCT_GRID_MAX_PRODUCTS}
329
+ hint={
330
+ selectedProductIds.length === 0
331
+ ? 'Pick at least one product — an empty list renders nothing on the page.'
332
+ : `Shown in this order. ${data.hasMore ? 'Search to find products beyond the 50 most recent. ' : ''}Products are matched to the page language automatically.`
333
+ }
334
+ />
335
+ </div>
336
+ </div>
337
+ )}
338
+
339
+ <div className="space-y-3">
340
+ {/* A hand-picked list has no cap to set — the picks are the cap — so the
341
+ count field only appears there once it means "per page". */}
342
+ {(sourceType !== 'manual' || showPagination) && (
343
+ <div>
344
+ <Label htmlFor="pg-limit">
345
+ {showPagination ? 'Products per page' : 'Products to show'}
346
+ </Label>
347
+ <Input
348
+ id="pg-limit"
349
+ type="number"
350
+ min={showPagination ? 1 : PRODUCT_GRID_UNLIMITED}
351
+ max={PRODUCT_GRID_MAX_LIMIT}
352
+ value={limitDraft}
353
+ onChange={(e) => handleLimitChange(e.target.value)}
354
+ onBlur={() => setLimitDraft(String(limit))}
355
+ className="mt-1 w-28"
356
+ />
357
+ <p className="mt-1 text-[11px] leading-snug text-muted-foreground">
358
+ {showPagination ? (
359
+ <>
360
+ How many products fill one page (1–{PRODUCT_GRID_MAX_LIMIT}). Visitors page
361
+ through {sourceType === 'manual' ? 'the whole list' : 'everything that matches'}.
362
+ </>
363
+ ) : isUnlimited ? (
364
+ <>
365
+ <strong className="font-medium text-foreground">0 = unlimited</strong> — every
366
+ matching product is shown on one page.
367
+ </>
368
+ ) : (
369
+ <>
370
+ Maximum number of products in this grid (max {PRODUCT_GRID_MAX_LIMIT}). Set it to{' '}
371
+ <strong className="font-medium text-foreground">0</strong> to show them all.
372
+ </>
373
+ )}
374
+ </p>
375
+ </div>
376
+ )}
377
+
378
+ <div className="flex items-start gap-2">
379
+ <Checkbox
380
+ id="pg-pagination"
381
+ checked={showPagination}
382
+ onCheckedChange={(checked) => handlePaginationChange(checked === true)}
383
+ className="mt-0.5"
384
+ />
385
+ <div>
386
+ <Label htmlFor="pg-pagination" className="cursor-pointer">
387
+ Paginate
388
+ </Label>
389
+ <p className="text-[11px] leading-snug text-muted-foreground">
390
+ Adds Previous / Next controls so visitors can reach every product
391
+ {isUnlimited ? `, ${PRODUCT_GRID_DEFAULT_PAGE_SIZE} at a time.` : '.'}
392
+ </p>
393
+ </div>
394
+ </div>
37
395
  </div>
38
- {/* Type selection could be added here, currently defaulting to 'latest' */}
39
396
  </div>
40
397
  );
41
398
  }
@@ -0,0 +1,27 @@
1
+ "use client";
2
+
3
+ import React, { createContext, useContext } from "react";
4
+
5
+ const EcommerceActiveContext = createContext<boolean>(false);
6
+
7
+ export function EcommerceActiveProvider({
8
+ children,
9
+ isActive,
10
+ }: {
11
+ children: React.ReactNode;
12
+ isActive: boolean;
13
+ }) {
14
+ return (
15
+ <EcommerceActiveContext.Provider value={isActive}>
16
+ {children}
17
+ </EcommerceActiveContext.Provider>
18
+ );
19
+ }
20
+
21
+ /**
22
+ * Whether the premium `ecommerce` package is activated for this install.
23
+ * Defaults to `false` outside the provider so any UI gated on it fails closed.
24
+ */
25
+ export function useEcommerceActive() {
26
+ return useContext(EcommerceActiveContext);
27
+ }
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { createClient } from '@nextblock-cms/db/server';
5
5
  import { revalidatePath } from 'next/cache';
6
+ import type { SettingsActionResult } from '../../../../lib/cms/action-result';
6
7
 
7
8
  export type BotProtectionSettings = {
8
9
  provider: 'none' | 'turnstile' | 'recaptcha';
@@ -37,13 +38,15 @@ export async function getBotProtectionSettings(): Promise<BotProtectionSettings>
37
38
  };
38
39
  }
39
40
 
40
- export async function updateBotProtectionSettings(formData: FormData) {
41
+ export async function updateBotProtectionSettings(
42
+ formData: FormData,
43
+ ): Promise<SettingsActionResult> {
41
44
  const supabase = createClient();
42
45
 
43
46
  // Verify auth and role
44
47
  const { data: { user } } = await supabase.auth.getUser();
45
48
  if (!user) {
46
- throw new Error('You must be logged in to update settings.');
49
+ return { ok: false, error: 'You must be logged in to update settings.' };
47
50
  }
48
51
 
49
52
  const { data: profile, error: profileError } = await supabase
@@ -53,7 +56,7 @@ export async function updateBotProtectionSettings(formData: FormData) {
53
56
  .single();
54
57
 
55
58
  if (profileError || !profile || profile.role !== 'ADMIN') {
56
- throw new Error('You do not have permission to perform this action.');
59
+ return { ok: false, error: 'You do not have permission to perform this action.' };
57
60
  }
58
61
 
59
62
  const provider = formData.get('provider') as 'none' | 'turnstile' | 'recaptcha';
@@ -70,7 +73,7 @@ export async function updateBotProtectionSettings(formData: FormData) {
70
73
 
71
74
  if (publicError) {
72
75
  console.error('Error updating public bot protection settings:', publicError);
73
- throw new Error('Failed to update bot protection settings.');
76
+ return { ok: false, error: 'Failed to update bot protection settings.' };
74
77
  }
75
78
 
76
79
  // Update secret settings (secretKey)
@@ -83,11 +86,11 @@ export async function updateBotProtectionSettings(formData: FormData) {
83
86
 
84
87
  if (secretError) {
85
88
  console.error('Error updating secret bot protection settings:', secretError);
86
- throw new Error('Failed to update bot protection secrets.');
89
+ return { ok: false, error: 'Failed to update bot protection secrets.' };
87
90
  }
88
91
 
89
92
  // Revalidate root layout so scripts update instantly
90
93
  revalidatePath('/', 'layout');
91
94
 
92
- return { success: true, message: 'Bot protection settings updated successfully.' };
95
+ return { ok: true, message: 'Bot protection settings updated successfully.' };
93
96
  }
@@ -33,11 +33,7 @@ export default function BotProtectionForm({ initialSettings }: BotProtectionForm
33
33
  startTransition(async () => {
34
34
  try {
35
35
  const result = await updateBotProtectionSettings(formData);
36
- if (result.success) {
37
- setMessage({ success: result.message });
38
- } else {
39
- setMessage({ error: 'An unexpected error occurred.' });
40
- }
36
+ setMessage(result.ok ? { success: result.message } : { error: result.error });
41
37
  } catch (error) {
42
38
  setMessage({ error: error instanceof Error ? error.message : 'An unknown error occurred.' });
43
39
  }
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { createClient } from '@nextblock-cms/db/server';
5
5
  import { revalidatePath } from 'next/cache';
6
+ import type { SettingsActionResult } from '../../../../lib/cms/action-result';
6
7
 
7
8
  export type CopyrightSettings = {
8
9
  [key: string]: string;
@@ -50,13 +51,15 @@ export async function getCopyrightSettings(): Promise<CopyrightSettings> {
50
51
  return data.value as CopyrightSettings;
51
52
  }
52
53
 
53
- export async function updateCopyrightSettings(formData: FormData) {
54
+ export async function updateCopyrightSettings(
55
+ formData: FormData,
56
+ ): Promise<SettingsActionResult> {
54
57
  const supabase = createClient();
55
58
 
56
59
  // Check if user is an admin
57
60
  const { data: { user } } = await supabase.auth.getUser();
58
61
  if (!user) {
59
- throw new Error('You must be logged in to update settings.');
62
+ return { ok: false, error: 'You must be logged in to update settings.' };
60
63
  }
61
64
  const { data: profile, error: profileError } = await supabase
62
65
  .from('profiles')
@@ -65,7 +68,7 @@ export async function updateCopyrightSettings(formData: FormData) {
65
68
  .single();
66
69
 
67
70
  if (profileError || !profile || !['ADMIN', 'WRITER'].includes(profile.role)) {
68
- throw new Error('You do not have permission to perform this action.');
71
+ return { ok: false, error: 'You do not have permission to perform this action.' };
69
72
  }
70
73
 
71
74
  const newSettings: CopyrightSettings = {};
@@ -82,7 +85,7 @@ export async function updateCopyrightSettings(formData: FormData) {
82
85
 
83
86
  if (error) {
84
87
  console.error('Error updating copyright settings:', error);
85
- throw new Error('Failed to update copyright settings.');
88
+ return { ok: false, error: 'Failed to update copyright settings.' };
86
89
  }
87
90
 
88
91
  // Persist the footer attribution toggle. The client always submits an explicit
@@ -94,11 +97,11 @@ export async function updateCopyrightSettings(formData: FormData) {
94
97
 
95
98
  if (attributionError) {
96
99
  console.error('Error updating footer attribution setting:', attributionError);
97
- throw new Error('Failed to update footer attribution setting.');
100
+ return { ok: false, error: 'Failed to update footer attribution setting.' };
98
101
  }
99
102
 
100
103
  // Revalidate the root layout to reflect changes immediately across the site.
101
104
  revalidatePath('/', 'layout');
102
105
 
103
- return { success: true, message: 'Copyright settings updated successfully.' };
106
+ return { ok: true, message: 'Copyright settings updated successfully.' };
104
107
  }
@@ -44,11 +44,7 @@ export default function CopyrightForm({ languages, initialSettings, initialAttri
44
44
  startTransition(async () => {
45
45
  try {
46
46
  const result = await updateCopyrightSettings(formData);
47
- if (result.success) {
48
- setMessage({ success: result.message });
49
- } else {
50
- setMessage({ error: 'An unexpected error occurred.' });
51
- }
47
+ setMessage(result.ok ? { success: result.message } : { error: result.error });
52
48
  } catch (error) {
53
49
  setMessage({ error: error instanceof Error ? error.message : 'An unknown error occurred.' });
54
50
  }
@@ -50,6 +50,16 @@ type CortexAiSettingsStatus = {
50
50
  unsplashAppName: string | null;
51
51
  };
52
52
 
53
+ /**
54
+ * How every action in this file reports back: the page reads `?success=` / `?error=` and
55
+ * renders it. These are plain `<form action={fn}>` submissions, so a return value would be
56
+ * discarded and a thrown error would take out the page (with its message replaced by a
57
+ * generic string in production).
58
+ *
59
+ * Must be called OUTSIDE the try blocks below. `redirect()` signals itself by throwing
60
+ * NEXT_REDIRECT, so calling this inside a `try` would have the `catch` swallow the
61
+ * navigation and re-redirect with the framework's digest as the user-facing message.
62
+ */
53
63
  function redirectWithStatus(status: 'success' | 'error', message: string): never {
54
64
  redirect(`${CORTEX_AI_SETTINGS_PATH}?${status}=${encodeURIComponent(message)}`);
55
65
  }
@@ -173,7 +183,7 @@ export async function getCortexAiSettingsStatus(): Promise<CortexAiSettingsStatu
173
183
 
174
184
  export async function saveOpenRouterApiKeyAction(formData: FormData) {
175
185
  if (process.env.NEXT_PUBLIC_IS_SANDBOX === 'true') {
176
- throw new Error('Sandbox environment cannot save keys to the database.');
186
+ redirectWithStatus('error', 'Sandbox environment cannot save keys to the database.');
177
187
  }
178
188
 
179
189
  try {
@@ -206,7 +216,7 @@ export async function saveOpenRouterApiKeyAction(formData: FormData) {
206
216
 
207
217
  export async function clearOpenRouterApiKeyAction() {
208
218
  if (process.env.NEXT_PUBLIC_IS_SANDBOX === 'true') {
209
- throw new Error('Sandbox environment cannot clear keys from the database.');
219
+ redirectWithStatus('error', 'Sandbox environment cannot clear keys from the database.');
210
220
  }
211
221
 
212
222
  try {
@@ -235,7 +245,7 @@ export async function clearOpenRouterApiKeyAction() {
235
245
 
236
246
  export async function saveStockPhotoKeysAction(formData: FormData) {
237
247
  if (process.env.NEXT_PUBLIC_IS_SANDBOX === 'true') {
238
- throw new Error('Sandbox environment cannot save keys to the database.');
248
+ redirectWithStatus('error', 'Sandbox environment cannot save keys to the database.');
239
249
  }
240
250
 
241
251
  try {
@@ -287,7 +297,7 @@ export async function saveStockPhotoKeysAction(formData: FormData) {
287
297
 
288
298
  export async function clearStockPhotoKeysAction() {
289
299
  if (process.env.NEXT_PUBLIC_IS_SANDBOX === 'true') {
290
- throw new Error('Sandbox environment cannot clear keys from the database.');
300
+ redirectWithStatus('error', 'Sandbox environment cannot clear keys from the database.');
291
301
  }
292
302
 
293
303
  try {
@@ -313,7 +323,7 @@ export async function clearStockPhotoKeysAction() {
313
323
 
314
324
  export async function saveCortexAiAgentSettingsAction(formData: FormData) {
315
325
  if (process.env.NEXT_PUBLIC_IS_SANDBOX === 'true') {
316
- throw new Error('Sandbox environment cannot save settings to the database.');
326
+ redirectWithStatus('error', 'Sandbox environment cannot save settings to the database.');
317
327
  }
318
328
 
319
329
  try {
@@ -357,7 +367,7 @@ export async function saveCortexAiAgentSettingsAction(formData: FormData) {
357
367
 
358
368
  export async function resetCortexAiAgentSettingsAction() {
359
369
  if (process.env.NEXT_PUBLIC_IS_SANDBOX === 'true') {
360
- throw new Error('Sandbox environment cannot change settings in the database.');
370
+ redirectWithStatus('error', 'Sandbox environment cannot change settings in the database.');
361
371
  }
362
372
 
363
373
  try {
@@ -383,7 +393,7 @@ export async function resetCortexAiAgentSettingsAction() {
383
393
 
384
394
  export async function saveCortexAiModelSelectionAction(formData: FormData) {
385
395
  if (process.env.NEXT_PUBLIC_IS_SANDBOX === 'true') {
386
- throw new Error('Sandbox environment cannot save model selection to the database.');
396
+ redirectWithStatus('error', 'Sandbox environment cannot save model selection to the database.');
387
397
  }
388
398
 
389
399
  try {
@@ -440,7 +450,7 @@ export async function saveCortexAiModelSelectionAction(formData: FormData) {
440
450
 
441
451
  export async function clearCortexAiModelSelectionAction() {
442
452
  if (process.env.NEXT_PUBLIC_IS_SANDBOX === 'true') {
443
- throw new Error('Sandbox environment cannot clear model selection from the database.');
453
+ redirectWithStatus('error', 'Sandbox environment cannot clear model selection from the database.');
444
454
  }
445
455
 
446
456
  try {