create-nextblock 0.12.13 → 0.12.15

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 (42) hide show
  1. package/package.json +1 -1
  2. package/templates/nextblock-template/app/(auth-pages)/sign-in/page.tsx +0 -13
  3. package/templates/nextblock-template/app/(auth-pages)/sign-up/SignUpForm.tsx +0 -14
  4. package/templates/nextblock-template/app/[slug]/page.tsx +12 -4
  5. package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +209 -101
  6. package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +2 -3
  7. package/templates/nextblock-template/app/cms/components/FeatureImageField.tsx +1 -0
  8. package/templates/nextblock-template/app/cms/interactions/InteractionsModerationClient.tsx +1 -1
  9. package/templates/nextblock-template/app/cms/interactions/page.tsx +1 -1
  10. package/templates/nextblock-template/app/cms/media/components/MediaPickerDialog.tsx +38 -35
  11. package/templates/nextblock-template/app/cms/media/components/MediaUploadForm.tsx +14 -11
  12. package/templates/nextblock-template/app/cms/products/ProductFormClientShell.tsx +62 -14
  13. package/templates/nextblock-template/app/cms/products/[id]/edit/page.tsx +2 -2
  14. package/templates/nextblock-template/app/cms/revisions/RevisionHistoryButton.tsx +2 -2
  15. package/templates/nextblock-template/app/cms/revisions/actions.ts +5 -5
  16. package/templates/nextblock-template/app/cms/settings/languages/actions.ts +53 -1
  17. package/templates/nextblock-template/app/cms/settings/languages/components/LanguageDetectionPanel.tsx +188 -0
  18. package/templates/nextblock-template/app/cms/settings/languages/page.tsx +12 -1
  19. package/templates/nextblock-template/app/cms/users/actions.ts +0 -3
  20. package/templates/nextblock-template/app/cms/users/components/UserForm.tsx +0 -2
  21. package/templates/nextblock-template/app/cms/users/page.tsx +0 -2
  22. package/templates/nextblock-template/app/layout.tsx +42 -1
  23. package/templates/nextblock-template/app/product/[slug]/page.tsx +12 -4
  24. package/templates/nextblock-template/app/profile/ProfileAccountSidebar.tsx +1 -1
  25. package/templates/nextblock-template/app/profile/account-data.ts +1 -1
  26. package/templates/nextblock-template/app/profile/account-types.ts +0 -1
  27. package/templates/nextblock-template/app/profile/page.tsx +0 -1
  28. package/templates/nextblock-template/app/providers.tsx +2 -0
  29. package/templates/nextblock-template/components/PostCommentsSection.tsx +2 -2
  30. package/templates/nextblock-template/components/ProductReviewsSection.tsx +2 -2
  31. package/templates/nextblock-template/components/header-auth.tsx +1 -1
  32. package/templates/nextblock-template/context/LanguageContext.tsx +22 -7
  33. package/templates/nextblock-template/docs/TECHNICAL_SPECIFICATION.md +46 -43
  34. package/templates/nextblock-template/lib/custom-block-relation-registry.ts +3 -3
  35. package/templates/nextblock-template/lib/i18n/country-languages.ts +247 -0
  36. package/templates/nextblock-template/lib/i18n/detection.test.ts +197 -0
  37. package/templates/nextblock-template/lib/i18n/detection.ts +192 -0
  38. package/templates/nextblock-template/lib/setup/migrations-bundle.ts +72 -37
  39. package/templates/nextblock-template/package.json +1 -1
  40. package/templates/nextblock-template/proxy.ts +141 -8
  41. package/templates/nextblock-template/tsconfig.tsbuildinfo +1 -1
  42. package/templates/nextblock-template/components/GitHubLoginButton.tsx +0 -36
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nextblock-cms/template",
3
- "version": "0.12.13",
3
+ "version": "0.12.15",
4
4
  "private": true,
5
5
  "scripts": {
6
6
  "dev": "next dev",
@@ -3,13 +3,24 @@ import { NextResponse, type NextRequest } from 'next/server';
3
3
  import type { SupabaseClient } from '@supabase/supabase-js';
4
4
  import type { Database } from '@nextblock-cms/db';
5
5
  import { resolveSupabaseAnonKey, resolveSupabaseUrl } from './lib/setup/env-status';
6
+ import {
7
+ LANGUAGE_DETECTION_SETTING_KEY,
8
+ DEFAULT_LANGUAGE_DETECTION_SETTINGS,
9
+ getCountryFromRequestHeaders,
10
+ normalizeLanguageDetectionSettings,
11
+ resolveDetectedLocale,
12
+ type LanguageDetectionSettings,
13
+ } from './lib/i18n/detection';
6
14
 
7
15
  type Profile = Database['public']['Tables']['profiles']['Row'];
8
16
  type UserRole = Database['public']['Enums']['user_role'];
9
17
 
10
18
  const LANGUAGE_COOKIE_KEY = 'NEXT_USER_LOCALE';
19
+ // Fallbacks used only when the languages table can't be read (unprovisioned
20
+ // instance, transient DB error). The live language list comes from the DB.
11
21
  const DEFAULT_LOCALE = 'en';
12
- const SUPPORTED_LOCALES = ['en', 'fr'];
22
+ const FALLBACK_LOCALES = ['en', 'fr'];
23
+ const LANGUAGE_COOKIE_MAX_AGE_SECONDS = 31_536_000;
13
24
  const cacheLoggingEnabled = process.env.NEXTBLOCK_CACHE_LOGGING_ENABLED === 'true';
14
25
 
15
26
  const cmsRoutePermissions: Record<string, UserRole[]> = {
@@ -138,6 +149,88 @@ async function hasProvisionedAdmin(supabase: SupabaseClient): Promise<boolean> {
138
149
  }
139
150
  }
140
151
 
152
+ interface LocaleRuntimeConfig {
153
+ /** Active language codes as configured in the CMS (is_active null counts as active). */
154
+ activeCodes: string[];
155
+ /** The is_default language, falling back to the first active language. */
156
+ defaultCode: string;
157
+ detection: LanguageDetectionSettings;
158
+ }
159
+
160
+ // Module-level cache for the language list + detection settings, mirroring
161
+ // provisionedAdminCache: middleware modules persist across requests in a worker,
162
+ // so this keeps locale resolution to at most one DB round-trip per minute.
163
+ let localeConfigCache: { value: LocaleRuntimeConfig | null; expires: number } | null = null;
164
+ // In-flight load shared by concurrent cache misses so a burst of requests right
165
+ // after expiry (or on a cold isolate) collapses to a single DB round-trip.
166
+ let localeConfigInflight: Promise<LocaleRuntimeConfig | null> | null = null;
167
+
168
+ async function loadLocaleRuntimeConfig(
169
+ supabase: SupabaseClient,
170
+ ): Promise<LocaleRuntimeConfig | null> {
171
+ const now = Date.now();
172
+ try {
173
+ const [languagesResult, detectionResult] = await Promise.all([
174
+ supabase.from('languages').select('code, is_default, is_active'),
175
+ supabase
176
+ .from('site_settings')
177
+ .select('value')
178
+ .eq('key', LANGUAGE_DETECTION_SETTING_KEY)
179
+ .maybeSingle(),
180
+ ]);
181
+
182
+ const activeLanguages = (languagesResult.data ?? []).filter(
183
+ (language: { is_active: boolean | null }) => language.is_active !== false,
184
+ );
185
+ if (languagesResult.error || activeLanguages.length === 0) {
186
+ localeConfigCache = { value: null, expires: now + 10_000 };
187
+ return null;
188
+ }
189
+
190
+ const defaultCode =
191
+ activeLanguages.find((language: { is_default: boolean }) => language.is_default)?.code ??
192
+ activeLanguages[0].code;
193
+ // A missing/failed settings row means "use defaults" — detection must not
194
+ // break just because the setting was never saved.
195
+ const detection = detectionResult.error
196
+ ? { ...DEFAULT_LANGUAGE_DETECTION_SETTINGS }
197
+ : normalizeLanguageDetectionSettings(detectionResult.data?.value);
198
+
199
+ const value: LocaleRuntimeConfig = {
200
+ activeCodes: activeLanguages.map((language: { code: string }) => language.code),
201
+ defaultCode,
202
+ detection,
203
+ };
204
+ localeConfigCache = { value, expires: now + 60_000 };
205
+ return value;
206
+ } catch {
207
+ localeConfigCache = { value: null, expires: now + 10_000 };
208
+ return null;
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Loads the active languages and the admin-configured detection settings
214
+ * (site_settings.language_detection_settings — non-sensitive, anon-readable).
215
+ * Returns null when the DB can't answer (unprovisioned/transient error); the
216
+ * caller then falls back to the legacy hardcoded locale behavior. Results (and
217
+ * failures) are cached briefly so an outage never adds per-request queries, and
218
+ * concurrent misses share one in-flight load.
219
+ */
220
+ function getLocaleRuntimeConfig(
221
+ supabase: SupabaseClient,
222
+ ): Promise<LocaleRuntimeConfig | null> {
223
+ if (localeConfigCache && localeConfigCache.expires > Date.now()) {
224
+ return Promise.resolve(localeConfigCache.value);
225
+ }
226
+ if (!localeConfigInflight) {
227
+ localeConfigInflight = loadLocaleRuntimeConfig(supabase).finally(() => {
228
+ localeConfigInflight = null;
229
+ });
230
+ }
231
+ return localeConfigInflight;
232
+ }
233
+
141
234
  function getHttpOrigin(value: string | undefined): string | null {
142
235
  if (!value) {
143
236
  return null;
@@ -414,11 +507,35 @@ export async function proxy(request: NextRequest) {
414
507
 
415
508
  await supabase.auth.getSession();
416
509
 
510
+ // Locale resolution needs nothing from the authenticated user, so load the
511
+ // locale config concurrently with the user lookup instead of serially.
417
512
  const cookieLocale = request.cookies.get(LANGUAGE_COOKIE_KEY)?.value;
418
- let currentLocale = cookieLocale;
419
-
420
- if (!currentLocale || !SUPPORTED_LOCALES.includes(currentLocale)) {
421
- currentLocale = DEFAULT_LOCALE;
513
+ const [localeConfig, userResult] = await Promise.all([
514
+ getLocaleRuntimeConfig(supabase),
515
+ supabase.auth.getUser(),
516
+ ]);
517
+
518
+ let currentLocale: string;
519
+ let rememberVisitorChoice = DEFAULT_LANGUAGE_DETECTION_SETTINGS.rememberVisitorChoice;
520
+
521
+ if (localeConfig) {
522
+ rememberVisitorChoice = localeConfig.detection.rememberVisitorChoice;
523
+ if (cookieLocale && localeConfig.activeCodes.includes(cookieLocale)) {
524
+ // An explicit or previously detected choice always wins over detection.
525
+ currentLocale = cookieLocale;
526
+ } else {
527
+ currentLocale = resolveDetectedLocale({
528
+ mode: localeConfig.detection.mode,
529
+ acceptLanguage: request.headers.get('accept-language'),
530
+ countryCode: getCountryFromRequestHeaders(request.headers),
531
+ availableCodes: localeConfig.activeCodes,
532
+ defaultCode: localeConfig.defaultCode,
533
+ });
534
+ }
535
+ } else {
536
+ // Languages unreadable (unprovisioned / transient error): legacy behavior.
537
+ currentLocale =
538
+ cookieLocale && FALLBACK_LOCALES.includes(cookieLocale) ? cookieLocale : DEFAULT_LOCALE;
422
539
  }
423
540
 
424
541
  requestHeaders.set('X-User-Locale', currentLocale);
@@ -426,7 +543,7 @@ export async function proxy(request: NextRequest) {
426
543
  const {
427
544
  data: { user },
428
545
  error: userError,
429
- } = await supabase.auth.getUser();
546
+ } = userResult;
430
547
 
431
548
  // First-boot setup gate (configured but no admin yet, and nobody signed in): funnel
432
549
  // anonymous traffic to /setup so the wizard can create the first admin. A logged-in
@@ -518,10 +635,26 @@ export async function proxy(request: NextRequest) {
518
635
  finalResponse.cookies.set(cookie.name, cookie.value, cookie);
519
636
  });
520
637
 
521
- if (request.cookies.get(LANGUAGE_COOKIE_KEY)?.value !== currentLocale) {
638
+ // Only persist the locale cookie when we actually resolved it against the DB.
639
+ // If localeConfig is null (unprovisioned / transient DB error) we still stamp
640
+ // X-User-Locale for rendering, but writing the fallback would clobber a
641
+ // returning visitor's valid non-fallback cookie (e.g. 'es') with 'en' for a
642
+ // year — so a transient outage must never overwrite a stored preference.
643
+ const requestCookieLocale = request.cookies.get(LANGUAGE_COOKIE_KEY)?.value;
644
+ // Re-issue when the value changed OR whenever "remember" is off: the request
645
+ // Cookie header carries no expiry, so rewriting a same-value session cookie is
646
+ // the only way to downgrade a previously persistent cookie after an admin
647
+ // turns remembering off (without it, old 1-year cookies would linger).
648
+ if (
649
+ localeConfig &&
650
+ (requestCookieLocale !== currentLocale || !rememberVisitorChoice)
651
+ ) {
652
+ // "Remember visitor's choice" ON -> persist for a year; OFF -> session cookie,
653
+ // so detection runs again on the next browser session while the language still
654
+ // sticks for the current one (switcher + in-session consistency).
522
655
  finalResponse.cookies.set(LANGUAGE_COOKIE_KEY, currentLocale, {
523
656
  path: '/',
524
- maxAge: 31_536_000,
657
+ ...(rememberVisitorChoice ? { maxAge: LANGUAGE_COOKIE_MAX_AGE_SECONDS } : {}),
525
658
  sameSite: 'lax',
526
659
  });
527
660
  }