dh-remixer-sdk 0.0.42 → 0.0.43-904bedf

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dh-remixer-sdk",
3
- "version": "0.0.42",
3
+ "version": "0.0.43-904bedf",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "templates",
@@ -6,7 +6,7 @@
6
6
  * - Fills missing fields from available data (og/title/twitter propagation, canonical, og:url, etc.)
7
7
  * - Preserves existing application/ld+json scripts; if none exist AND indexable, emits fallback WebPage JSON-LD
8
8
  * - Forces robots to "noindex, follow" when isIndexable=false
9
- * - Ensures <html lang="en">
9
+ * - Carries <html lang> through from the prerendered document, defaulting to "en"
10
10
  * - Canonical is DOMAIN + route (3rd param), not window.location
11
11
  * - Avoids double-escaping (&amp;amp;) by decoding extracted text before output
12
12
  * - Ensures JSON-LD contains real characters (e.g. "&" not "&amp;")
@@ -14,6 +14,10 @@
14
14
 
15
15
  import * as prettier from "prettier";
16
16
  import { SINGLETON_LD_JSON_STATE, TARGET_DOMAIN } from "./vars.mjs";
17
+ import {
18
+ splitHeadFence,
19
+ withIntegrationFencesPreserved,
20
+ } from "./integration-fences.mjs";
17
21
  import path from "node:path";
18
22
  import fs from "node:fs/promises";
19
23
 
@@ -128,9 +132,12 @@ export async function injectMetadata(
128
132
  // --- helpers --------------------------------------------------------------
129
133
 
130
134
  // --- extract head ---------------------------------------------------------
131
- const lang = "en";
135
+ // The prerenderer captures outerHTML after mount, so the provider's resolved language is on this tag.
136
+ const lang = pick(/<html\b[^>]*\blang=["']([^"']+)["']/i, prerenderedHtml) || "en";
132
137
 
133
- const headInner = pick(/<head\b[^>]*>([\s\S]*?)<\/head>/i, prerenderedHtml);
138
+ const { headFence, headInner } = splitHeadFence(
139
+ pick(/<head\b[^>]*>([\s\S]*?)<\/head>/i, prerenderedHtml),
140
+ );
134
141
 
135
142
  const titleTags = [
136
143
  ...headInner.matchAll(/<title\b([^>]*)>([\s\S]*?)<\/title>/gi),
@@ -337,6 +344,7 @@ export async function injectMetadata(
337
344
 
338
345
  // App bootstrap last, so the SPA mounts on top of the prerendered content.
339
346
  out.push(...bootstrapScripts);
347
+ out.push(headFence);
340
348
 
341
349
  const bodyTag = pick(/(<body\b[^>]*>)/i, prerenderedHtml) || "<body>";
342
350
  const bodyInner = pick(/<body\b[^>]*>([\s\S]*?)<\/body>/i, prerenderedHtml);
@@ -354,15 +362,17 @@ ${revealCleanupScript}
354
362
  </body>
355
363
  </html>`;
356
364
 
357
- try {
358
- return await prettier.format(rawHtml, {
359
- parser: "html",
360
- printWidth: 120,
361
- });
362
- } catch (err) {
363
- console.error(
364
- `[ssg-helmet] [format ${route}] prettier failed, writing unformatted HTML: ${err.message}`,
365
- );
366
- return rawHtml;
367
- }
365
+ return withIntegrationFencesPreserved(rawHtml, async (html) => {
366
+ try {
367
+ return await prettier.format(html, {
368
+ parser: "html",
369
+ printWidth: 120,
370
+ });
371
+ } catch (err) {
372
+ console.error(
373
+ `[ssg-helmet] [format ${route}] prettier failed, writing unformatted HTML: ${err.message}`,
374
+ );
375
+ return html;
376
+ }
377
+ });
368
378
  }
@@ -83,10 +83,7 @@ test("JSON-LD description follows the page-level description (AI-7092)", async (
83
83
 
84
84
  test("a head with only the static description still keeps it", async () => {
85
85
  const out = await injectMetadata(SAMPLE, "/", true);
86
- assert.match(
87
- out,
88
- /<meta\s+name="description"\s+content="A sample description"/,
89
- );
86
+ assert.match(out, /<meta\s+name="description"\s+content="A sample description"/);
90
87
  });
91
88
 
92
89
  // og:locale is derived from http-equiv="content-language", which follows the
@@ -178,3 +175,121 @@ test("markStaticHead is idempotent and survives a '>' inside content", () => {
178
175
  /<meta data-ssg-static name="description" content="a > b" \/>/,
179
176
  );
180
177
  });
178
+
179
+ /*
180
+ * AI-7669: a non-English site declares its language in .env, the LanguageProvider applies it on
181
+ * mount, and the prerenderer captures the resulting <html lang>. This step used to re-emit a
182
+ * constant "en", so every published non-English page served the wrong language to crawlers and to
183
+ * anyone without JS.
184
+ */
185
+ test("carries the prerendered <html lang> through to the output (AI-7669)", async () => {
186
+ const polish = `<html lang="pl">
187
+ <head><title>Introligatornia</title></head>
188
+ <body></body>
189
+ </html>`;
190
+
191
+ const out = await injectMetadata(polish, "/", true);
192
+
193
+ assert.match(out, /<html lang="pl">/);
194
+ assert.ok(!out.includes('<html lang="en">'));
195
+ });
196
+
197
+ test("defaults <html lang> to en when the prerendered document has none", async () => {
198
+ const out = await injectMetadata("<html><head><title>T</title></head><body></body></html>", "/", true);
199
+
200
+ assert.match(out, /<html lang="en">/);
201
+ });
202
+
203
+ /*
204
+ * The website-build Lambda injects the integration snippets as fenced blocks: a head fence right
205
+ * before </head> and a body-start fence right after <body>. Both are platform-owned and must reach
206
+ * the published page byte for byte.
207
+ */
208
+ const HEAD_FENCE = `<!-- remixer:integrations:head -->
209
+ <script>if(!window.__PRERENDER__){window.dataLayer=window.dataLayer||[];window.gtag=window.gtag||function(){window.dataLayer.push(arguments);};window.gtag('consent','default',{ad_storage:'denied',wait_for_update:500,region:["AT","BE"]});}</script>
210
+ <script>if(!window.__PRERENDER__){(function(d,i){var s=d.createElement('script');s.async=true;s.src='https://www.googletagmanager.com/gtag/js?id='+i;d.head.appendChild(s);})(document,"G-ABC123XYZ9");window.gtag('config',"G-ABC123XYZ9");}</script>
211
+ <!-- /remixer:integrations:head -->`;
212
+ const BODY_START_FENCE = `<!-- remixer:integrations:body-start -->
213
+ <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-ABCD123" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
214
+ <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=123456789012345&amp;ev=PageView&amp;noscript=1"/></noscript>
215
+ <!-- /remixer:integrations:body-start -->`;
216
+ const CONTEXT_SCRIPT = `<script>window.__REMIXER_CTX__={"projectId":"p1","integrations":[{"slug":"google-analytics","config":{"measurementId":"G-ABC123XYZ9"}}]};</script>`;
217
+ const FENCED_PAGE = `<!doctype html>
218
+ <html lang="en">
219
+ <head>
220
+ <meta charset="UTF-8" />
221
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
222
+ <title>Fenced Page</title>
223
+ <meta name="description" content="A page with integrations" />
224
+ <script type="module" crossorigin src="/assets/index-abc123.js"></script>
225
+ <link rel="stylesheet" crossorigin href="/assets/index-abc123.css" />
226
+ ${CONTEXT_SCRIPT}
227
+ ${HEAD_FENCE}
228
+ </head>
229
+ <body class="antialiased">
230
+ ${BODY_START_FENCE}
231
+ <div id="root"><h1>Hello</h1></div>
232
+ </body>
233
+ </html>`;
234
+ const UNFENCED_PAGE = FENCED_PAGE.replace(HEAD_FENCE, "").replace(BODY_START_FENCE, "");
235
+
236
+ const count = (haystack, needle) => haystack.split(needle).length - 1;
237
+
238
+ test("keeps the integrations head fence verbatim as the last child of <head>", async () => {
239
+ const out = await injectMetadata(FENCED_PAGE, "/", true);
240
+
241
+ assert.equal(count(out, HEAD_FENCE), 1);
242
+ assert.equal(count(out, "<!-- remixer:integrations:head -->"), 1);
243
+ assert.equal(count(out, "<!-- /remixer:integrations:head -->"), 1);
244
+
245
+ const fenceEnd = out.indexOf(HEAD_FENCE) + HEAD_FENCE.length;
246
+ const headEnd = out.indexOf("</head>");
247
+ assert.ok(fenceEnd <= headEnd);
248
+ assert.equal(out.slice(fenceEnd, headEnd).trim(), "");
249
+ });
250
+
251
+ test("the fenced scripts are not reformatted and not re-emitted outside the fence", async () => {
252
+ const out = await injectMetadata(FENCED_PAGE, "/", true);
253
+
254
+ assert.equal(count(out, "if(!window.__PRERENDER__){"), 2);
255
+ assert.equal(count(out, "__PRERENDER__"), 2);
256
+ assert.doesNotMatch(out, /if \(!window\.__PRERENDER__\)/);
257
+ });
258
+
259
+ test("the head fence comes after the app bootstrap and the Remixer context", async () => {
260
+ const out = await injectMetadata(FENCED_PAGE, "/", true);
261
+ const fenceStart = out.indexOf(HEAD_FENCE);
262
+
263
+ assert.ok(out.indexOf('src="/assets/index-abc123.js"') < fenceStart);
264
+ assert.ok(out.indexOf("window.__REMIXER_CTX__") < fenceStart);
265
+ assert.ok(out.indexOf('<link rel="canonical"') < fenceStart);
266
+ assert.ok(out.indexOf('<meta name="generator"') < fenceStart);
267
+ });
268
+
269
+ test("a second run over its own output keeps exactly one head fence", async () => {
270
+ const once = await injectMetadata(FENCED_PAGE, "/", true);
271
+ const twice = await injectMetadata(once, "/", true);
272
+
273
+ assert.equal(count(twice, HEAD_FENCE), 1);
274
+ assert.equal(count(twice, "<!-- remixer:integrations:head -->"), 1);
275
+ assert.equal(count(twice, "__PRERENDER__"), 2);
276
+ });
277
+
278
+ test("keeps the body-start fence verbatim right after <body>", async () => {
279
+ const out = await injectMetadata(FENCED_PAGE, "/", true);
280
+
281
+ assert.equal(count(out, BODY_START_FENCE), 1);
282
+ const bodyOpen = out.match(/<body\b[^>]*>/);
283
+ const gap = out.slice(bodyOpen.index + bodyOpen[0].length, out.indexOf(BODY_START_FENCE));
284
+ assert.equal(gap.trim(), "");
285
+ assert.doesNotMatch(out, /<noscript\s*\n/);
286
+ });
287
+
288
+ test("a page without integration fences is rebuilt and formatted as before", async () => {
289
+ const out = await injectMetadata(UNFENCED_PAGE, "/", true);
290
+
291
+ assert.doesNotMatch(out, /remixer:integrations/);
292
+ assert.match(out, /window\.__REMIXER_CTX__ = \{/);
293
+ assert.match(out, /<meta\s+name="description"\s+content="A page with integrations"/);
294
+ assert.equal(count(out, "<script"), 4);
295
+ });
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { REMIXER_BUILD_DIR } from "./vars.mjs";
4
+ import { insertAtHeadEnd } from "./integration-fences.mjs";
4
5
 
5
6
  async function findCssFiles(dir) {
6
7
  const entries = await fs.readdir(dir, { withFileTypes: true });
@@ -34,5 +35,5 @@ export async function injectStylesHead(metadataHtml) {
34
35
  })
35
36
  .join("\n");
36
37
 
37
- return metadataHtml.replace("</head>", `\t${linkTags}\n\t</head>`);
38
+ return insertAtHeadEnd(metadataHtml, `\t${linkTags}\n\t`);
38
39
  }
@@ -0,0 +1,36 @@
1
+ const FENCE_RE =
2
+ /<!-- remixer:integrations:(head|body-start|body-end) -->[\s\S]*?<!-- \/remixer:integrations:\1 -->/g;
3
+ const HEAD_FENCE_RE =
4
+ /<!-- remixer:integrations:head -->[\s\S]*?<!-- \/remixer:integrations:head -->/;
5
+ const PLACEHOLDER_RE = /<!-- remixer:integrations:preserved:(\d+) -->/g;
6
+
7
+ const placeholder = (index) =>
8
+ `<!-- remixer:integrations:preserved:${index} -->`;
9
+
10
+ export function splitHeadFence(headInner) {
11
+ const match = headInner.match(HEAD_FENCE_RE);
12
+ if (!match) return { headFence: "", headInner };
13
+ return {
14
+ headFence: match[0],
15
+ headInner: headInner.replace(HEAD_FENCE_RE, ""),
16
+ };
17
+ }
18
+
19
+ export async function withIntegrationFencesPreserved(html, transform) {
20
+ const fences = [];
21
+ const masked = html.replace(FENCE_RE, (fence) => {
22
+ fences.push(fence);
23
+ return placeholder(fences.length - 1);
24
+ });
25
+ const transformed = await transform(masked);
26
+ return transformed.replace(
27
+ PLACEHOLDER_RE,
28
+ (match, index) => fences[Number(index)] ?? match,
29
+ );
30
+ }
31
+
32
+ export function insertAtHeadEnd(html, fragment) {
33
+ const index = html.match(HEAD_FENCE_RE)?.index ?? html.indexOf("</head>");
34
+ if (index < 0) return html;
35
+ return html.slice(0, index) + fragment + html.slice(index);
36
+ }
@@ -0,0 +1,149 @@
1
+ import { test, after, mock } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import fs from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ const buildDir = await fs.mkdtemp(path.join(os.tmpdir(), "ssg-helmet-fences-"));
8
+ await fs.mkdir(path.join(buildDir, "assets"), { recursive: true });
9
+ await fs.writeFile(path.join(buildDir, "assets", "index-abc123.css"), "body{margin:0}", "utf8");
10
+ process.env.REMIXER_BUILD_DIR = buildDir;
11
+
12
+ const { insertAtHeadEnd, splitHeadFence, withIntegrationFencesPreserved } =
13
+ await import("./integration-fences.mjs");
14
+ const { writeHelmetFile } = await import("./fs-utils.mjs");
15
+ const { applyBusinessLdJson } = await import("./parse-html-for-contact-info.mjs");
16
+
17
+ after(() => fs.rm(buildDir, { recursive: true, force: true }));
18
+
19
+ const HEAD_FENCE = `<!-- remixer:integrations:head -->
20
+ <script>if(!window.__PRERENDER__){(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);})(window,document,"clarity","script","abcdefghij");}</script>
21
+ <!-- /remixer:integrations:head -->`;
22
+ const BODY_START_FENCE = `<!-- remixer:integrations:body-start -->
23
+ <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=123456789012345&amp;ev=PageView&amp;noscript=1"/></noscript>
24
+ <!-- /remixer:integrations:body-start -->`;
25
+ const BODY_END_FENCE = `<!-- remixer:integrations:body-end -->
26
+ <script>if(!window.__PRERENDER__){console.log("end")}</script>
27
+ <!-- /remixer:integrations:body-end -->`;
28
+ const FENCED_PAGE = `<!doctype html>
29
+ <html lang="en">
30
+ <head>
31
+ <meta charset="UTF-8" />
32
+ <title>Fenced Page</title>
33
+ <meta name="description" content="A page with integrations" />
34
+ <script type="module" crossorigin src="/assets/index-abc123.js"></script>
35
+ <script>window.__REMIXER_CTX__={"projectId":"p1"};</script>
36
+ ${HEAD_FENCE}
37
+ </head>
38
+ <body class="antialiased">
39
+ ${BODY_START_FENCE}
40
+ <div id="root"><h1>Hello</h1></div>
41
+ ${BODY_END_FENCE}
42
+ </body>
43
+ </html>`;
44
+ const STYLESHEET_LINK = `<link rel="stylesheet" href="/assets/index-abc123.css" />`;
45
+
46
+ const count = (haystack, needle) => haystack.split(needle).length - 1;
47
+
48
+ test("splitHeadFence hands back the fence and the head without it", () => {
49
+ const { headFence, headInner } = splitHeadFence(`<title>T</title>\n${HEAD_FENCE}\n<meta name="x" content="y" />`);
50
+
51
+ assert.equal(headFence, HEAD_FENCE);
52
+ assert.equal(headInner, `<title>T</title>\n\n<meta name="x" content="y" />`);
53
+ });
54
+
55
+ test("splitHeadFence leaves a head without a fence alone", () => {
56
+ const { headFence, headInner } = splitHeadFence("<title>T</title>");
57
+
58
+ assert.equal(headFence, "");
59
+ assert.equal(headInner, "<title>T</title>");
60
+ });
61
+
62
+ test("withIntegrationFencesPreserved hides every fence from the transform and restores it verbatim", async () => {
63
+ let seen = "";
64
+ const out = await withIntegrationFencesPreserved(FENCED_PAGE, (html) => {
65
+ seen = html;
66
+ return html.replace(/\s+/g, " ");
67
+ });
68
+
69
+ assert.doesNotMatch(seen, /remixer:integrations:(head|body-start|body-end)/);
70
+ assert.doesNotMatch(seen, /__PRERENDER__/);
71
+ for (const fence of [HEAD_FENCE, BODY_START_FENCE, BODY_END_FENCE]) {
72
+ assert.equal(count(out, fence), 1);
73
+ }
74
+ assert.doesNotMatch(out, /remixer:integrations:preserved/);
75
+ assert.equal(count(out, "\n"), count(HEAD_FENCE + BODY_START_FENCE + BODY_END_FENCE, "\n"));
76
+ });
77
+
78
+ test("withIntegrationFencesPreserved passes a page without fences through unchanged", async () => {
79
+ const page = "<html><head><title>T</title></head><body></body></html>";
80
+ let seen = "";
81
+ const out = await withIntegrationFencesPreserved(page, async (html) => {
82
+ seen = html;
83
+ return html;
84
+ });
85
+
86
+ assert.equal(seen, page);
87
+ assert.equal(out, page);
88
+ });
89
+
90
+ test("withIntegrationFencesPreserved restores fences containing replacement patterns literally", async () => {
91
+ const fence = `<!-- remixer:integrations:head -->\n<script>var s="$&$1$$";</script>\n<!-- /remixer:integrations:head -->`;
92
+ const out = await withIntegrationFencesPreserved(`<head>${fence}</head>`, (html) => html);
93
+
94
+ assert.equal(out, `<head>${fence}</head>`);
95
+ });
96
+
97
+ test("insertAtHeadEnd lands above the head fence when the page has one", () => {
98
+ const out = insertAtHeadEnd(`<head>\n<title>T</title>\n${HEAD_FENCE}\n</head>`, "<link />\n");
99
+
100
+ assert.equal(out, `<head>\n<title>T</title>\n<link />\n${HEAD_FENCE}\n</head>`);
101
+ });
102
+
103
+ test("insertAtHeadEnd lands right before </head> otherwise", () => {
104
+ assert.equal(insertAtHeadEnd("<head><title>T</title></head>", "<link />"), "<head><title>T</title><link /></head>");
105
+ assert.equal(insertAtHeadEnd("<p>no head</p>", "<link />"), "<p>no head</p>");
106
+ });
107
+
108
+ test("writeHelmetFile keeps every fence verbatim, with the head fence last before </head>", async () => {
109
+ await writeHelmetFile(FENCED_PAGE, "/", true);
110
+ const out = await fs.readFile(path.join(buildDir, "index.html"), "utf8");
111
+
112
+ for (const fence of [HEAD_FENCE, BODY_START_FENCE, BODY_END_FENCE]) {
113
+ assert.equal(count(out, fence), 1);
114
+ }
115
+ assert.equal(count(out, "if(!window.__PRERENDER__){"), 2);
116
+ assert.doesNotMatch(out, /if \(!window\.__PRERENDER__\)/);
117
+
118
+ const headEnd = out.indexOf("</head>");
119
+ const fenceStart = out.indexOf(HEAD_FENCE);
120
+ assert.equal(out.slice(fenceStart + HEAD_FENCE.length, headEnd).trim(), "");
121
+ assert.ok(out.indexOf(STYLESHEET_LINK) < fenceStart);
122
+ assert.ok(out.indexOf("window.__REMIXER_CTX__") < fenceStart);
123
+
124
+ const bodyOpen = out.match(/<body\b[^>]*>/);
125
+ assert.equal(out.slice(bodyOpen.index + bodyOpen[0].length, out.indexOf(BODY_START_FENCE)).trim(), "");
126
+ });
127
+
128
+ test("the business ld+json pass formats the page again without touching the fences", async () => {
129
+ mock.method(console, "log", () => {});
130
+ await writeHelmetFile(FENCED_PAGE, "/", true);
131
+ await applyBusinessLdJson();
132
+ const out = await fs.readFile(path.join(buildDir, "index.html"), "utf8");
133
+
134
+ for (const fence of [HEAD_FENCE, BODY_START_FENCE, BODY_END_FENCE]) {
135
+ assert.equal(count(out, fence), 1);
136
+ }
137
+ assert.doesNotMatch(out, /remixer:integrations:preserved/);
138
+ assert.equal(out.slice(out.indexOf(HEAD_FENCE) + HEAD_FENCE.length, out.indexOf("</head>")).trim(), "");
139
+ assert.match(out, /"@type":\s*"WebPage"/);
140
+ });
141
+
142
+ test("writeHelmetFile output for a page without fences carries no fence markup", async () => {
143
+ const unfenced = FENCED_PAGE.replace(HEAD_FENCE, "").replace(BODY_START_FENCE, "").replace(BODY_END_FENCE, "");
144
+ await writeHelmetFile(unfenced, "/plain", true);
145
+ const out = await fs.readFile(path.join(buildDir, "plain", "index.html"), "utf8");
146
+
147
+ assert.doesNotMatch(out, /remixer:integrations/);
148
+ assert.match(out, new RegExp(`${STYLESHEET_LINK.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}\\s*</head>`));
149
+ });
@@ -5,6 +5,7 @@ import {
5
5
  SINGLETON_LD_JSON_STATE,
6
6
  } from "./vars.mjs";
7
7
  import { safeJson } from "./inject-metadata-head.mjs";
8
+ import { withIntegrationFencesPreserved } from "./integration-fences.mjs";
8
9
  import path from "node:path";
9
10
  import * as prettier from "prettier";
10
11
 
@@ -189,10 +190,12 @@ export async function applyBusinessLdJson() {
189
190
  const block = `<script type="application/ld+json">${safeJson(merged)}</script>`;
190
191
  const next = content.replace(LD_JSON_RE, () => block);
191
192
 
192
- const formatted = await prettier.format(next, {
193
- parser: "html",
194
- printWidth: 120,
195
- });
193
+ const formatted = await withIntegrationFencesPreserved(next, (html) =>
194
+ prettier.format(html, {
195
+ parser: "html",
196
+ printWidth: 120,
197
+ }),
198
+ );
196
199
  await fs.writeFile(filePath, formatted, "utf-8");
197
200
  }
198
201
  }
@@ -47,6 +47,30 @@ const buildLocales = (): Record<string, LocaleDict> => {
47
47
 
48
48
  const locales = buildLocales();
49
49
 
50
+ // The default is declared in .env as VITE_DEFAULT_LANG because this file is platform-owned. It is
51
+ // honoured only when that language has a dictionary — a provider opened on a language with no locale
52
+ // tree renders every t() key as raw text. A site with no dictionaries at all (inline text) keeps it.
53
+ // A declaration may be looser than the folder name (pl-PL, PL, pt-br) — match the dictionary, then its base subtag.
54
+ const dictionaryFor = (code: string): string | undefined => {
55
+ const keys = Object.keys(locales);
56
+ const lower = code.toLowerCase();
57
+ const base = lower.split("-")[0];
58
+
59
+ return keys.find((k) => k.toLowerCase() === lower) ?? keys.find((k) => k.toLowerCase() === base);
60
+ };
61
+
62
+ const resolveInitialLanguage = (): string => {
63
+ const declared = import.meta.env.VITE_DEFAULT_LANG as string | undefined;
64
+ const present = Object.keys(locales);
65
+ const declaredDictionary = declared ? dictionaryFor(declared) : undefined;
66
+
67
+ if (declaredDictionary) return declaredDictionary;
68
+ if (locales["en"]) return "en";
69
+ if (present.length) return present[0];
70
+
71
+ return declared || "en";
72
+ };
73
+
50
74
  interface LanguageContextType {
51
75
  language: string;
52
76
  setLanguage: (lang: string) => void;
@@ -60,7 +84,7 @@ interface LanguageProviderProps {
60
84
  }
61
85
 
62
86
  export const LanguageProvider = ({ children }: LanguageProviderProps) => {
63
- const [language, setLanguage] = useState<string>("en");
87
+ const [language, setLanguage] = useState<string>(resolveInitialLanguage);
64
88
 
65
89
  // Reflect the active language on <html lang> (a11y/SEO, and so tools can read it).
66
90
  useEffect(() => {
@@ -7,6 +7,18 @@ export type SignInWithGoogleOptions = {
7
7
 
8
8
  export type SignupMetadata = Record<string, unknown>;
9
9
 
10
+ function resolveReturnTo(returnTo: unknown): string {
11
+ const account = `${window.location.origin}/account`;
12
+
13
+ if (typeof returnTo !== 'string' || returnTo.length === 0) return account;
14
+
15
+ try {
16
+ return new URL(returnTo, window.location.origin).href;
17
+ } catch {
18
+ return account;
19
+ }
20
+ }
21
+
10
22
  async function brokerEmailAuth(path: 'signin' | 'signup', email: string, password: string, metadata?: SignupMetadata) {
11
23
  const res = await fetch(`${getAuthBrokerBaseUrl()}/auth/email/${path}`, {
12
24
  method: 'POST',
@@ -53,7 +65,7 @@ export const auth = {
53
65
  },
54
66
  signInWithGoogle(options: SignInWithGoogleOptions = {}) {
55
67
  const startUrl = new URL(`${getAuthBrokerBaseUrl()}/auth/start`);
56
- startUrl.searchParams.set('return_to', options.returnTo || `${window.location.origin}/account`);
68
+ startUrl.searchParams.set('return_to', resolveReturnTo(options?.returnTo));
57
69
  startUrl.searchParams.set('nonce', crypto.randomUUID());
58
70
  window.location.href = startUrl.toString();
59
71
  },