create-nextblock 0.12.14 → 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.
- package/package.json +1 -1
- package/templates/nextblock-template/app/[slug]/page.tsx +12 -4
- package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +26 -1
- package/templates/nextblock-template/app/cms/components/FeatureImageField.tsx +1 -0
- package/templates/nextblock-template/app/cms/media/components/MediaPickerDialog.tsx +38 -35
- package/templates/nextblock-template/app/cms/media/components/MediaUploadForm.tsx +14 -11
- package/templates/nextblock-template/app/cms/products/ProductFormClientShell.tsx +62 -14
- package/templates/nextblock-template/app/cms/products/[id]/edit/page.tsx +2 -2
- package/templates/nextblock-template/app/cms/settings/languages/actions.ts +53 -1
- package/templates/nextblock-template/app/cms/settings/languages/components/LanguageDetectionPanel.tsx +188 -0
- package/templates/nextblock-template/app/cms/settings/languages/page.tsx +12 -1
- package/templates/nextblock-template/app/layout.tsx +42 -1
- package/templates/nextblock-template/app/product/[slug]/page.tsx +12 -4
- package/templates/nextblock-template/app/providers.tsx +2 -0
- package/templates/nextblock-template/context/LanguageContext.tsx +22 -7
- package/templates/nextblock-template/docs/TECHNICAL_SPECIFICATION.md +16 -11
- package/templates/nextblock-template/lib/i18n/country-languages.ts +247 -0
- package/templates/nextblock-template/lib/i18n/detection.test.ts +197 -0
- package/templates/nextblock-template/lib/i18n/detection.ts +192 -0
- package/templates/nextblock-template/package.json +1 -1
- package/templates/nextblock-template/proxy.ts +141 -8
- package/templates/nextblock-template/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_LANGUAGE_DETECTION_SETTINGS,
|
|
4
|
+
detectLocaleFromBrowser,
|
|
5
|
+
detectLocaleFromCountry,
|
|
6
|
+
getCountryFromRequestHeaders,
|
|
7
|
+
matchLocale,
|
|
8
|
+
normalizeLanguageDetectionSettings,
|
|
9
|
+
parseAcceptLanguage,
|
|
10
|
+
resolveDetectedLocale,
|
|
11
|
+
} from './detection';
|
|
12
|
+
|
|
13
|
+
function headersOf(record: Record<string, string>) {
|
|
14
|
+
const lower = Object.fromEntries(
|
|
15
|
+
Object.entries(record).map(([key, value]) => [key.toLowerCase(), value]),
|
|
16
|
+
);
|
|
17
|
+
return { get: (name: string) => lower[name.toLowerCase()] ?? null };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
describe('normalizeLanguageDetectionSettings', () => {
|
|
21
|
+
it('returns defaults for absent or malformed values', () => {
|
|
22
|
+
expect(normalizeLanguageDetectionSettings(null)).toEqual(DEFAULT_LANGUAGE_DETECTION_SETTINGS);
|
|
23
|
+
expect(normalizeLanguageDetectionSettings(undefined)).toEqual(
|
|
24
|
+
DEFAULT_LANGUAGE_DETECTION_SETTINGS,
|
|
25
|
+
);
|
|
26
|
+
expect(normalizeLanguageDetectionSettings('browser')).toEqual(
|
|
27
|
+
DEFAULT_LANGUAGE_DETECTION_SETTINGS,
|
|
28
|
+
);
|
|
29
|
+
expect(normalizeLanguageDetectionSettings([])).toEqual(DEFAULT_LANGUAGE_DETECTION_SETTINGS);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('keeps valid fields and coerces invalid ones individually', () => {
|
|
33
|
+
expect(
|
|
34
|
+
normalizeLanguageDetectionSettings({ mode: 'country', rememberVisitorChoice: false }),
|
|
35
|
+
).toEqual({ mode: 'country', rememberVisitorChoice: false });
|
|
36
|
+
expect(
|
|
37
|
+
normalizeLanguageDetectionSettings({ mode: 'ip-magic', rememberVisitorChoice: false }),
|
|
38
|
+
).toEqual({ mode: 'browser', rememberVisitorChoice: false });
|
|
39
|
+
expect(
|
|
40
|
+
normalizeLanguageDetectionSettings({ mode: 'default', rememberVisitorChoice: 'yes' }),
|
|
41
|
+
).toEqual({ mode: 'default', rememberVisitorChoice: true });
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
describe('parseAcceptLanguage', () => {
|
|
46
|
+
it('parses tags sorted by q-value with defaults', () => {
|
|
47
|
+
expect(parseAcceptLanguage('fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7')).toEqual([
|
|
48
|
+
{ tag: 'fr-ch', base: 'fr', quality: 1 },
|
|
49
|
+
{ tag: 'fr', base: 'fr', quality: 0.9 },
|
|
50
|
+
{ tag: 'en', base: 'en', quality: 0.8 },
|
|
51
|
+
{ tag: 'de', base: 'de', quality: 0.7 },
|
|
52
|
+
]);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('drops wildcards, q=0 entries, and malformed tags', () => {
|
|
56
|
+
expect(parseAcceptLanguage('*, en;q=0, <script>;q=1, fr')).toEqual([
|
|
57
|
+
{ tag: 'fr', base: 'fr', quality: 1 },
|
|
58
|
+
]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('handles empty and missing headers', () => {
|
|
62
|
+
expect(parseAcceptLanguage(null)).toEqual([]);
|
|
63
|
+
expect(parseAcceptLanguage('')).toEqual([]);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('keeps original order among equal q-values', () => {
|
|
67
|
+
expect(parseAcceptLanguage('es, pt').map((entry) => entry.tag)).toEqual(['es', 'pt']);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe('matchLocale', () => {
|
|
72
|
+
it('prefers exact matches, case-insensitively', () => {
|
|
73
|
+
expect(matchLocale(['fr-ca'], ['en', 'fr-CA'])).toBe('fr-CA');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('falls back from a regional candidate to its base language', () => {
|
|
77
|
+
expect(matchLocale(['fr-CA'], ['en', 'fr'])).toBe('fr');
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('matches a base candidate to a regional site code', () => {
|
|
81
|
+
expect(matchLocale(['pt'], ['en', 'pt-BR'])).toBe('pt-BR');
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('respects candidate priority over match quality', () => {
|
|
85
|
+
// First candidate only base-matches, but it still beats later exact matches.
|
|
86
|
+
expect(matchLocale(['de-AT', 'en'], ['en', 'de'])).toBe('de');
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('returns null when nothing matches', () => {
|
|
90
|
+
expect(matchLocale(['ja', 'ko'], ['en', 'fr'])).toBeNull();
|
|
91
|
+
expect(matchLocale([], ['en'])).toBeNull();
|
|
92
|
+
expect(matchLocale(['en'], [])).toBeNull();
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
describe('detectLocaleFromBrowser', () => {
|
|
97
|
+
it('uses q-value order against the site languages', () => {
|
|
98
|
+
expect(detectLocaleFromBrowser('de;q=0.5, fr;q=0.9', ['en', 'fr', 'de'])).toBe('fr');
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('returns null without a usable header', () => {
|
|
102
|
+
expect(detectLocaleFromBrowser(null, ['en'])).toBeNull();
|
|
103
|
+
expect(detectLocaleFromBrowser('ja', ['en'])).toBeNull();
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
describe('detectLocaleFromCountry', () => {
|
|
108
|
+
it('maps countries to their primary languages in order', () => {
|
|
109
|
+
expect(detectLocaleFromCountry('FR', ['en', 'fr'])).toBe('fr');
|
|
110
|
+
expect(detectLocaleFromCountry('BR', ['en', 'pt'])).toBe('pt');
|
|
111
|
+
// Belgium lists nl before fr; the site only offers fr.
|
|
112
|
+
expect(detectLocaleFromCountry('BE', ['en', 'fr'])).toBe('fr');
|
|
113
|
+
expect(detectLocaleFromCountry('be', ['nl', 'fr'])).toBe('nl');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('returns null for unknown countries or unmatched languages', () => {
|
|
117
|
+
expect(detectLocaleFromCountry('ZZ', ['en'])).toBeNull();
|
|
118
|
+
expect(detectLocaleFromCountry('JP', ['en', 'fr'])).toBeNull();
|
|
119
|
+
expect(detectLocaleFromCountry(null, ['en'])).toBeNull();
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe('getCountryFromRequestHeaders', () => {
|
|
124
|
+
it('reads host geo headers in precedence order', () => {
|
|
125
|
+
expect(getCountryFromRequestHeaders(headersOf({ 'x-vercel-ip-country': 'CA' }))).toBe('CA');
|
|
126
|
+
expect(getCountryFromRequestHeaders(headersOf({ 'cf-ipcountry': 'fr' }))).toBe('FR');
|
|
127
|
+
expect(
|
|
128
|
+
getCountryFromRequestHeaders(
|
|
129
|
+
headersOf({ 'x-vercel-ip-country': 'DE', 'cf-ipcountry': 'US' }),
|
|
130
|
+
),
|
|
131
|
+
).toBe('DE');
|
|
132
|
+
expect(getCountryFromRequestHeaders(headersOf({ 'cloudfront-viewer-country': 'JP' }))).toBe(
|
|
133
|
+
'JP',
|
|
134
|
+
);
|
|
135
|
+
expect(getCountryFromRequestHeaders(headersOf({ 'x-country-code': 'BR' }))).toBe('BR');
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('rejects unknown-country sentinels and malformed values', () => {
|
|
139
|
+
expect(getCountryFromRequestHeaders(headersOf({ 'cf-ipcountry': 'XX' }))).toBeNull();
|
|
140
|
+
expect(getCountryFromRequestHeaders(headersOf({ 'cf-ipcountry': 'T1' }))).toBeNull();
|
|
141
|
+
expect(getCountryFromRequestHeaders(headersOf({ 'x-country-code': 'USA' }))).toBeNull();
|
|
142
|
+
expect(getCountryFromRequestHeaders(headersOf({}))).toBeNull();
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
describe('resolveDetectedLocale', () => {
|
|
147
|
+
const base = {
|
|
148
|
+
acceptLanguage: 'fr-CA, en;q=0.5',
|
|
149
|
+
countryCode: 'DE',
|
|
150
|
+
availableCodes: ['en', 'fr', 'de'],
|
|
151
|
+
defaultCode: 'en',
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
it('browser mode uses Accept-Language', () => {
|
|
155
|
+
expect(resolveDetectedLocale({ ...base, mode: 'browser' })).toBe('fr');
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it('country mode uses the geo country', () => {
|
|
159
|
+
expect(resolveDetectedLocale({ ...base, mode: 'country' })).toBe('de');
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('browser_then_country prefers the browser and falls back to country', () => {
|
|
163
|
+
expect(resolveDetectedLocale({ ...base, mode: 'browser_then_country' })).toBe('fr');
|
|
164
|
+
expect(
|
|
165
|
+
resolveDetectedLocale({
|
|
166
|
+
...base,
|
|
167
|
+
mode: 'browser_then_country',
|
|
168
|
+
acceptLanguage: 'ja',
|
|
169
|
+
}),
|
|
170
|
+
).toBe('de');
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it('default mode ignores all signals', () => {
|
|
174
|
+
expect(resolveDetectedLocale({ ...base, mode: 'default' })).toBe('en');
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('always falls back to the default language when detection finds nothing', () => {
|
|
178
|
+
expect(
|
|
179
|
+
resolveDetectedLocale({
|
|
180
|
+
mode: 'browser_then_country',
|
|
181
|
+
acceptLanguage: 'ja',
|
|
182
|
+
countryCode: 'JP',
|
|
183
|
+
availableCodes: ['en', 'fr'],
|
|
184
|
+
defaultCode: 'fr',
|
|
185
|
+
}),
|
|
186
|
+
).toBe('fr');
|
|
187
|
+
expect(
|
|
188
|
+
resolveDetectedLocale({
|
|
189
|
+
mode: 'country',
|
|
190
|
+
acceptLanguage: null,
|
|
191
|
+
countryCode: null,
|
|
192
|
+
availableCodes: ['en'],
|
|
193
|
+
defaultCode: 'en',
|
|
194
|
+
}),
|
|
195
|
+
).toBe('en');
|
|
196
|
+
});
|
|
197
|
+
});
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Pure language-detection helpers shared by proxy.ts (edge), app/layout.tsx and
|
|
2
|
+
// the CMS languages settings. Keep this module free of server-only / next/*
|
|
3
|
+
// imports so the proxy can use it.
|
|
4
|
+
import { COUNTRY_PRIMARY_LANGUAGES } from './country-languages';
|
|
5
|
+
|
|
6
|
+
/** site_settings key holding the detection config (non-sensitive, anon-readable). */
|
|
7
|
+
export const LANGUAGE_DETECTION_SETTING_KEY = 'language_detection_settings';
|
|
8
|
+
|
|
9
|
+
/** next/cache tag for the layout's cached read of the detection settings. */
|
|
10
|
+
export const LANGUAGE_DETECTION_CACHE_TAG = 'public-language-detection';
|
|
11
|
+
|
|
12
|
+
export const LANGUAGE_DETECTION_MODES = [
|
|
13
|
+
'browser',
|
|
14
|
+
'country',
|
|
15
|
+
'browser_then_country',
|
|
16
|
+
'default',
|
|
17
|
+
] as const;
|
|
18
|
+
|
|
19
|
+
export type LanguageDetectionMode = (typeof LANGUAGE_DETECTION_MODES)[number];
|
|
20
|
+
|
|
21
|
+
export interface LanguageDetectionSettings {
|
|
22
|
+
/** How the first language served to a new visitor is chosen. */
|
|
23
|
+
mode: LanguageDetectionMode;
|
|
24
|
+
/** true = persist the visitor's language for a year; false = session-only cookie. */
|
|
25
|
+
rememberVisitorChoice: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// "browser" matches the long-standing page-level Accept-Language fallback, so an
|
|
29
|
+
// absent row keeps today's intended behavior.
|
|
30
|
+
export const DEFAULT_LANGUAGE_DETECTION_SETTINGS: LanguageDetectionSettings = {
|
|
31
|
+
mode: 'browser',
|
|
32
|
+
rememberVisitorChoice: true,
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Coerce an arbitrary site_settings jsonb value into valid settings. */
|
|
36
|
+
export function normalizeLanguageDetectionSettings(value: unknown): LanguageDetectionSettings {
|
|
37
|
+
const fallback = DEFAULT_LANGUAGE_DETECTION_SETTINGS;
|
|
38
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
39
|
+
return { ...fallback };
|
|
40
|
+
}
|
|
41
|
+
const record = value as Record<string, unknown>;
|
|
42
|
+
const mode = LANGUAGE_DETECTION_MODES.includes(record.mode as LanguageDetectionMode)
|
|
43
|
+
? (record.mode as LanguageDetectionMode)
|
|
44
|
+
: fallback.mode;
|
|
45
|
+
const rememberVisitorChoice =
|
|
46
|
+
typeof record.rememberVisitorChoice === 'boolean'
|
|
47
|
+
? record.rememberVisitorChoice
|
|
48
|
+
: fallback.rememberVisitorChoice;
|
|
49
|
+
return { mode, rememberVisitorChoice };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface AcceptLanguageEntry {
|
|
53
|
+
/** Full lowercased tag, e.g. "fr-ca". */
|
|
54
|
+
tag: string;
|
|
55
|
+
/** Base language, e.g. "fr". */
|
|
56
|
+
base: string;
|
|
57
|
+
quality: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Parse an Accept-Language header into tags sorted by q-value (wildcards and q=0 dropped). */
|
|
61
|
+
export function parseAcceptLanguage(header: string | null | undefined): AcceptLanguageEntry[] {
|
|
62
|
+
if (!header) return [];
|
|
63
|
+
const entries: AcceptLanguageEntry[] = [];
|
|
64
|
+
for (const part of header.split(',')) {
|
|
65
|
+
const [rawTag, ...params] = part.trim().split(';');
|
|
66
|
+
const tag = rawTag?.trim().toLowerCase();
|
|
67
|
+
if (!tag || tag === '*' || !/^[a-z]{1,8}(-[a-z0-9]{1,8})*$/.test(tag)) continue;
|
|
68
|
+
let quality = 1;
|
|
69
|
+
for (const param of params) {
|
|
70
|
+
const eq = param.indexOf('=');
|
|
71
|
+
if (eq === -1) continue;
|
|
72
|
+
if (param.slice(0, eq).trim() !== 'q') continue;
|
|
73
|
+
const parsed = Number(param.slice(eq + 1).trim());
|
|
74
|
+
if (!Number.isNaN(parsed)) quality = Math.min(Math.max(parsed, 0), 1);
|
|
75
|
+
}
|
|
76
|
+
if (quality <= 0) continue;
|
|
77
|
+
entries.push({ tag, base: tag.split('-')[0] as string, quality });
|
|
78
|
+
}
|
|
79
|
+
// Stable sort: q descending, original order preserved among equals.
|
|
80
|
+
return entries
|
|
81
|
+
.map((entry, index) => ({ entry, index }))
|
|
82
|
+
.sort((a, b) => b.entry.quality - a.entry.quality || a.index - b.index)
|
|
83
|
+
.map(({ entry }) => entry);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Match ordered candidate tags against the site's language codes.
|
|
88
|
+
* Candidate priority wins: for each candidate (in order) try, exact tag
|
|
89
|
+
* ("fr-ca" = "fr-CA"), then candidate base to site code ("fr-CA" -> "fr"),
|
|
90
|
+
* then candidate base to site code base ("fr" -> "fr-CA") — so a visitor's
|
|
91
|
+
* top language matched loosely beats a lower preference matched exactly.
|
|
92
|
+
* Returns the site code as configured (original casing) or null.
|
|
93
|
+
*/
|
|
94
|
+
export function matchLocale(candidates: string[], availableCodes: string[]): string | null {
|
|
95
|
+
if (candidates.length === 0 || availableCodes.length === 0) return null;
|
|
96
|
+
const available = availableCodes.map((code) => ({
|
|
97
|
+
code,
|
|
98
|
+
lower: code.toLowerCase(),
|
|
99
|
+
base: code.toLowerCase().split('-')[0] as string,
|
|
100
|
+
}));
|
|
101
|
+
|
|
102
|
+
for (const candidate of candidates) {
|
|
103
|
+
const tag = candidate.toLowerCase();
|
|
104
|
+
const base = tag.split('-')[0] as string;
|
|
105
|
+
const match =
|
|
106
|
+
available.find((lang) => lang.lower === tag) ??
|
|
107
|
+
available.find((lang) => lang.lower === base) ??
|
|
108
|
+
available.find((lang) => lang.base === base);
|
|
109
|
+
if (match) return match.code;
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Geo country headers injected by the popular hosts/CDNs, in precedence order.
|
|
115
|
+
const COUNTRY_HEADER_NAMES = [
|
|
116
|
+
'x-vercel-ip-country', // Vercel
|
|
117
|
+
'cf-ipcountry', // Cloudflare
|
|
118
|
+
'cloudfront-viewer-country', // AWS CloudFront
|
|
119
|
+
'x-country-code', // generic reverse proxies
|
|
120
|
+
] as const;
|
|
121
|
+
|
|
122
|
+
/** Read the visitor's ISO 3166-1 alpha-2 country from host geo headers, if any. */
|
|
123
|
+
export function getCountryFromRequestHeaders(headers: {
|
|
124
|
+
get(name: string): string | null;
|
|
125
|
+
}): string | null {
|
|
126
|
+
for (const name of COUNTRY_HEADER_NAMES) {
|
|
127
|
+
const value = headers.get(name)?.trim().toUpperCase();
|
|
128
|
+
// Cloudflare uses XX/T1 for unknown/Tor; only accept real alpha-2 codes.
|
|
129
|
+
if (value && /^[A-Z]{2}$/.test(value) && value !== 'XX' && value !== 'T1') {
|
|
130
|
+
return value;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function detectLocaleFromBrowser(
|
|
137
|
+
acceptLanguage: string | null | undefined,
|
|
138
|
+
availableCodes: string[],
|
|
139
|
+
): string | null {
|
|
140
|
+
return matchLocale(
|
|
141
|
+
parseAcceptLanguage(acceptLanguage).map((entry) => entry.tag),
|
|
142
|
+
availableCodes,
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function detectLocaleFromCountry(
|
|
147
|
+
countryCode: string | null | undefined,
|
|
148
|
+
availableCodes: string[],
|
|
149
|
+
): string | null {
|
|
150
|
+
if (!countryCode) return null;
|
|
151
|
+
const candidates = COUNTRY_PRIMARY_LANGUAGES[countryCode.toUpperCase()];
|
|
152
|
+
if (!candidates || candidates.length === 0) return null;
|
|
153
|
+
return matchLocale(candidates, availableCodes);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export interface ResolveDetectedLocaleInput {
|
|
157
|
+
mode: LanguageDetectionMode;
|
|
158
|
+
acceptLanguage: string | null | undefined;
|
|
159
|
+
countryCode: string | null | undefined;
|
|
160
|
+
availableCodes: string[];
|
|
161
|
+
defaultCode: string;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Pick the first language for a visitor with no (valid) language cookie.
|
|
166
|
+
* Always falls back to the site's default language when detection finds no match.
|
|
167
|
+
*/
|
|
168
|
+
export function resolveDetectedLocale({
|
|
169
|
+
mode,
|
|
170
|
+
acceptLanguage,
|
|
171
|
+
countryCode,
|
|
172
|
+
availableCodes,
|
|
173
|
+
defaultCode,
|
|
174
|
+
}: ResolveDetectedLocaleInput): string {
|
|
175
|
+
let detected: string | null = null;
|
|
176
|
+
switch (mode) {
|
|
177
|
+
case 'browser':
|
|
178
|
+
detected = detectLocaleFromBrowser(acceptLanguage, availableCodes);
|
|
179
|
+
break;
|
|
180
|
+
case 'country':
|
|
181
|
+
detected = detectLocaleFromCountry(countryCode, availableCodes);
|
|
182
|
+
break;
|
|
183
|
+
case 'browser_then_country':
|
|
184
|
+
detected =
|
|
185
|
+
detectLocaleFromBrowser(acceptLanguage, availableCodes) ??
|
|
186
|
+
detectLocaleFromCountry(countryCode, availableCodes);
|
|
187
|
+
break;
|
|
188
|
+
case 'default':
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
return detected ?? defaultCode;
|
|
192
|
+
}
|
|
@@ -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
|
|
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
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
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
|
-
} =
|
|
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
|
-
|
|
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:
|
|
657
|
+
...(rememberVisitorChoice ? { maxAge: LANGUAGE_COOKIE_MAX_AGE_SECONDS } : {}),
|
|
525
658
|
sameSite: 'lax',
|
|
526
659
|
});
|
|
527
660
|
}
|