@hagicode/hagilight-core 0.14.1-dev.149.1.1dadf5c → 0.14.1-dev.150.1.68cde77

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/README.md CHANGED
@@ -150,6 +150,73 @@ A site whose Content Security Policy blocks the image host should either set
150
150
  `splash={false}` or allow `img-src https://img-gen.hagicode.com` and
151
151
  `connect-src https://img-gen.hagicode.com`.
152
152
 
153
+ ### Locale monitor
154
+
155
+ `localeMonitor` is off unless you set it. It shows what the browser's language inputs would resolve to,
156
+ so a maintainer can see why a visitor lands where they do. It never chooses a route.
157
+
158
+ ```astro
159
+ <RootTransit destination="/en-US/" siteName="My site" localeMonitor />
160
+ <RootTransit destination="/en-US/" siteName="My site" localeMonitor={{ sharedDomain: false }} />
161
+ ```
162
+
163
+ With the monitor on, a caption and five rows appear below the language links. Four rows are detection
164
+ inputs, in the same order as the official website's transit page (`repos/site`, `traceSiteEntryLocale()`):
165
+
166
+ | Order | Row | Read from | Wins when |
167
+ | --- | --- | --- | --- |
168
+ | 1 | `?lang=` | the page URL | the value is one of the ten supported locales |
169
+ | 2 | `hagicode:site-locale` | `localStorage`, falling back to the legacy `lang` key | the value is supported |
170
+ | 3 | `navigator.languages` | the browser, first supported entry | an entry is supported |
171
+ | 4 | `default` | fixed | nothing above is supported; always `en-US` |
172
+
173
+ The winning row carries the word **detected**. Unsupported values stay visible and are skipped. A regional
174
+ or legacy form such as `zh-TW`, `zh_CN`, `pt` or `de-AT` resolves to its supported locale, and the row shows
175
+ both, for example `de-AT → de-DE`.
176
+
177
+ The fifth row, **shared marker**, shows the marker recorded by a HagiCode site on the last visit. It is
178
+ evidence only. It never takes part in detection, and it never changes the target or the links.
179
+
180
+ Detection and navigation are separate, and the monitor keeps them separate:
181
+
182
+ | | Target and language links | Locale monitor |
183
+ | --- | --- | --- |
184
+ | Source | `destination` and `links` props | the four inputs above |
185
+ | Changed by a `?lang=` value | no; the forward target and the continue link stay as configured | no; it is reported as detected |
186
+ | Timer | the same 1,570 ms | unchanged; it adds no timer or listener |
187
+ | Marked as | `configured` | `detected` |
188
+
189
+ With `?lang=zh-CN` on a page configured for `/en-US/`, the page still forwards to `/en-US/?lang=zh-CN`
190
+ after the delay, and the monitor reports `zh-CN` as detected.
191
+
192
+ #### Cross-site marker
193
+
194
+ After it resolves the locale, the monitor records one marker: the locale, the winning input, the host and
195
+ the time, for example `zh-CN|query|docs.hagicode.com|1761000000`. It writes only two keys:
196
+
197
+ - `localStorage` key `hagicode:locale-monitor`, on every host.
198
+ - Cookie `hagicode_locale_monitor`, only when the page host is `hagicode.com` or one of its subdomains. It is
199
+ written with `Domain=.hagicode.com; Path=/; SameSite=Lax; Secure; Max-Age=15552000` (about 180 days), so
200
+ every HagiCode subdomain can read it.
201
+
202
+ `localStorage` is not shared between subdomains, which is why the cookie exists. Reading another site's
203
+ storage would need a hidden iframe bridge, and this component does not add one. The monitor never writes
204
+ `hagicode:site-locale` or `lang`, which belong to the official website.
205
+
206
+ `localeMonitor={{ sharedDomain }}` sets the cookie domain. The default is `hagicode.com`. Pass `false` for
207
+ same-origin only: no cookie is written anywhere, and the marker stays in `localStorage`. Any other value must
208
+ be a domain such as `example.test`, or the component throws a `TypeError` prefixed `Hagilight RootTransit`
209
+ during rendering.
210
+
211
+ #### Privacy and failure
212
+
213
+ The monitor reads the URL, the two storage keys, the marker and `navigator.languages`, and shows them on the
214
+ page. It sends nothing over the network and sends nothing to analytics. A blocked or throwing storage or
215
+ cookie fails only its own row or write, and the page still forwards on time. Without scripting, the five
216
+ rows are present in the HTML with placeholder values, and the continue link works. The cookie is sent with
217
+ every request to every `hagicode.com` subdomain, so it holds only the locale code, the winning input, a host
218
+ and a time, and it is kept small. Listing it in a cookie notice is the site owner's decision.
219
+
153
220
  ## Image paths from img-gen
154
221
 
155
222
  <!--
package/RootTransit.astro CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  import logo from './logo.png';
3
3
  import favicon from './favicon.ico';
4
- import { resolveTransitDestination } from './dist/root-transit.js';
4
+ import { DEFAULT_LOCALE, resolveLocaleMonitor, resolveTransitDestination, type LocaleMonitorOptions } from './dist/root-transit.js';
5
5
  import { resolveSplashConfig, type SplashOverrides } from './dist/splash-images.js';
6
6
 
7
7
  interface Props {
@@ -14,6 +14,8 @@ interface Props {
14
14
  links?: { destination: string; label: string; lang?: string }[];
15
15
  /** `false` turns the splash off; an object overrides its base URL, prefix, collection size or cache name. */
16
16
  splash?: false | SplashOverrides;
17
+ /** Shows the locale monitor: what the browser inputs resolve to. It never changes the target or the links. */
18
+ localeMonitor?: boolean | LocaleMonitorOptions;
17
19
  }
18
20
 
19
21
  const {
@@ -23,9 +25,18 @@ const {
23
25
  continueLabel = `Continue to ${siteName}`,
24
26
  links = [],
25
27
  splash,
28
+ localeMonitor,
26
29
  } = Astro.props;
27
30
  if (!siteName?.trim()) throw new TypeError('Hagilight RootTransit: siteName is required.');
28
31
  const splashConfig = resolveSplashConfig(splash);
32
+ const monitor = resolveLocaleMonitor(localeMonitor);
33
+ /** Detection rows in the reference order; the default row is fixed, the rest fill in from the browser. */
34
+ const monitorRows = [
35
+ ['query', '?lang=', '—'],
36
+ ['stored', 'hagicode:site-locale', '—'],
37
+ ['browser', 'navigator.languages', '—'],
38
+ ['default', 'default', DEFAULT_LOCALE],
39
+ ] as const;
29
40
  const base = import.meta.env.BASE_URL;
30
41
  const site = Astro.site ?? Astro.url;
31
42
  const href = resolveTransitDestination(destination, { site, base });
@@ -541,6 +552,24 @@ const trace = [
541
552
  outline-offset: 3px;
542
553
  }
543
554
 
555
+ /* ── 语言监测:只读检测结果,目标与链接不变;行样式沿用上面的解析过程 ── */
556
+ .locale-monitor {
557
+ grid-column: 1 / -1;
558
+ margin: 0;
559
+ }
560
+
561
+ .locale-monitor-caption {
562
+ margin: 0 0 0.5rem;
563
+ color: var(--muted);
564
+ font-family: var(--font-mono);
565
+ font-size: 0.8125rem;
566
+ line-height: 1.4;
567
+ }
568
+
569
+ .trace-evidence {
570
+ margin-top: 0.75rem;
571
+ }
572
+
544
573
  @media (prefers-reduced-motion: reduce) {
545
574
  *, *::before, *::after { animation: none !important; transition: none !important; }
546
575
  .splash { transition: none; }
@@ -592,6 +621,23 @@ const trace = [
592
621
  {localeLinks.map((link) => <li><a href={link.href} lang={link.lang} data-transit-alternative>{link.label}</a></li>)}
593
622
  </ul>
594
623
  </nav>
624
+ {monitor && (
625
+ <section class="locale-monitor" data-locale-monitor data-shared-domain={monitor.sharedDomain ?? ''} aria-label="Locale monitor">
626
+ <p class="locale-monitor-caption">Locale monitor · detected only, the target above is unchanged</p>
627
+ <dl class="trace">
628
+ {monitorRows.map(([key, label, placeholder], index) => (
629
+ <div class="trace-row" data-locale-trace={key} data-state="idle" style={`--i: ${index}`}>
630
+ <dt>{label}</dt><dd class="trace-value" data-locale-value>{placeholder}</dd><dd class="trace-verdict" data-locale-verdict></dd>
631
+ </div>
632
+ ))}
633
+ </dl>
634
+ <dl class="trace trace-evidence">
635
+ <div class="trace-row" data-locale-trace="shared" data-state="idle" style={`--i: ${monitorRows.length}`}>
636
+ <dt>shared marker</dt><dd class="trace-value" data-locale-value>—</dd><dd class="trace-verdict" data-locale-verdict></dd>
637
+ </div>
638
+ </dl>
639
+ </section>
640
+ )}
595
641
  </main>
596
642
  <footer><nav class="quick-links"><slot name="footer" /></nav></footer>
597
643
  </div>
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Locale monitor resolver. The input order and the normalization rules are copied from the official site:
3
+ * `traceSiteEntryLocale()` in repos/site/src/lib/site-entry-locale.ts and `normalizeSiteLocale()` in
4
+ * repos/site/src/i18n/locale-metadata.ts. The parity cases in test/root-transit-locale.test.mjs pin the two together.
5
+ * Nothing here selects a route: the result only reports which input the monitor would pick.
6
+ */
7
+ export declare const SITE_LOCALES: readonly [{
8
+ readonly code: "en-US";
9
+ readonly aliases: readonly ["en", "en-us"];
10
+ }, {
11
+ readonly code: "zh-CN";
12
+ readonly aliases: readonly ["zh", "zh-cn", "zh-hans", "zh-sg"];
13
+ }, {
14
+ readonly code: "zh-Hant";
15
+ readonly aliases: readonly ["zh-hant", "zh-tw", "zh-hk", "zh-mo"];
16
+ }, {
17
+ readonly code: "ja-JP";
18
+ readonly aliases: readonly ["ja", "ja-jp"];
19
+ }, {
20
+ readonly code: "ko-KR";
21
+ readonly aliases: readonly ["ko", "ko-kr"];
22
+ }, {
23
+ readonly code: "de-DE";
24
+ readonly aliases: readonly ["de", "de-de"];
25
+ }, {
26
+ readonly code: "fr-FR";
27
+ readonly aliases: readonly ["fr", "fr-fr"];
28
+ }, {
29
+ readonly code: "es-ES";
30
+ readonly aliases: readonly ["es", "es-es"];
31
+ }, {
32
+ readonly code: "pt-BR";
33
+ readonly aliases: readonly ["pt", "pt-br"];
34
+ }, {
35
+ readonly code: "ru-RU";
36
+ readonly aliases: readonly ["ru", "ru-ru"];
37
+ }];
38
+ export type SiteLocale = (typeof SITE_LOCALES)[number]['code'];
39
+ export declare const SITE_LOCALE_CODES: readonly SiteLocale[];
40
+ export declare const DEFAULT_LOCALE: SiteLocale;
41
+ export declare const SITE_LOCALE_STORAGE_KEY = "hagicode:site-locale";
42
+ export declare const LEGACY_SITE_LOCALE_STORAGE_KEY = "lang";
43
+ /** Which input decided the locale, in the order the official page consults them. */
44
+ export type LocaleSource = 'query' | 'stored' | 'browser' | 'default';
45
+ export interface LocaleInputEvidence {
46
+ /** The value that decided this input, or the first value read when none was supported; null when nothing was read. */
47
+ raw: string | null;
48
+ /** The supported locale that `raw` resolves to, or null. */
49
+ locale: SiteLocale | null;
50
+ }
51
+ export interface LocaleResolutionOptions {
52
+ requestedLang?: string | null;
53
+ storedLocale?: string | null;
54
+ legacyStoredLocale?: string | null;
55
+ clientLanguages?: readonly (string | null | undefined)[] | null;
56
+ }
57
+ export interface LocaleResolution {
58
+ locale: SiteLocale;
59
+ source: LocaleSource;
60
+ evidence: {
61
+ query: LocaleInputEvidence;
62
+ stored: LocaleInputEvidence;
63
+ browser: LocaleInputEvidence;
64
+ };
65
+ }
66
+ /** Maps a raw language tag to a supported locale: exact or alias first, then by language family. */
67
+ export declare function normalizeTransitLocale(value: string | null | undefined): SiteLocale | null;
68
+ /**
69
+ * Resolves the locale the official rules would pick and reports the evidence from each input. A supported `?lang=`
70
+ * wins, then the stored value (current key, then the legacy `lang` key), then the first supported browser language,
71
+ * then the default. Unsupported values are skipped. The function never reads or writes storage itself.
72
+ */
73
+ export declare function resolveTransitLocale(options?: LocaleResolutionOptions): LocaleResolution;
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Locale monitor resolver. The input order and the normalization rules are copied from the official site:
3
+ * `traceSiteEntryLocale()` in repos/site/src/lib/site-entry-locale.ts and `normalizeSiteLocale()` in
4
+ * repos/site/src/i18n/locale-metadata.ts. The parity cases in test/root-transit-locale.test.mjs pin the two together.
5
+ * Nothing here selects a route: the result only reports which input the monitor would pick.
6
+ */
7
+ export const SITE_LOCALES = [
8
+ { code: 'en-US', aliases: ['en', 'en-us'] },
9
+ { code: 'zh-CN', aliases: ['zh', 'zh-cn', 'zh-hans', 'zh-sg'] },
10
+ { code: 'zh-Hant', aliases: ['zh-hant', 'zh-tw', 'zh-hk', 'zh-mo'] },
11
+ { code: 'ja-JP', aliases: ['ja', 'ja-jp'] },
12
+ { code: 'ko-KR', aliases: ['ko', 'ko-kr'] },
13
+ { code: 'de-DE', aliases: ['de', 'de-de'] },
14
+ { code: 'fr-FR', aliases: ['fr', 'fr-fr'] },
15
+ { code: 'es-ES', aliases: ['es', 'es-es'] },
16
+ { code: 'pt-BR', aliases: ['pt', 'pt-br'] },
17
+ { code: 'ru-RU', aliases: ['ru', 'ru-ru'] },
18
+ ];
19
+ export const SITE_LOCALE_CODES = SITE_LOCALES.map((locale) => locale.code);
20
+ export const DEFAULT_LOCALE = 'en-US';
21
+ export const SITE_LOCALE_STORAGE_KEY = 'hagicode:site-locale';
22
+ export const LEGACY_SITE_LOCALE_STORAGE_KEY = 'lang';
23
+ const LOCALE_BY_INPUT = new Map();
24
+ const LOCALE_BY_LANGUAGE = new Map();
25
+ for (const { code, aliases } of SITE_LOCALES) {
26
+ LOCALE_BY_INPUT.set(code.toLowerCase(), code);
27
+ for (const alias of aliases)
28
+ LOCALE_BY_INPUT.set(canonicalLocale(alias).toLowerCase(), code);
29
+ // Later entries overwrite earlier ones, as in the official map: a bare language resolves to its last locale.
30
+ LOCALE_BY_LANGUAGE.set(code.split('-')[0].toLowerCase(), code);
31
+ }
32
+ function canonicalLocale(locale) {
33
+ const candidate = locale.trim().replace(/_/gu, '-');
34
+ if (!candidate)
35
+ return '';
36
+ try {
37
+ return Intl.getCanonicalLocales(candidate)[0] ?? candidate;
38
+ }
39
+ catch {
40
+ return candidate;
41
+ }
42
+ }
43
+ /** Maps a raw language tag to a supported locale: exact or alias first, then by language family. */
44
+ export function normalizeTransitLocale(value) {
45
+ if (!value)
46
+ return null;
47
+ const normalized = canonicalLocale(value).toLowerCase();
48
+ if (!normalized)
49
+ return null;
50
+ const direct = LOCALE_BY_INPUT.get(normalized);
51
+ if (direct)
52
+ return direct;
53
+ const [language] = normalized.split('-');
54
+ return LOCALE_BY_LANGUAGE.get(language) ?? null;
55
+ }
56
+ function evidenceFor(value) {
57
+ const raw = value || null;
58
+ return { raw, locale: normalizeTransitLocale(raw) };
59
+ }
60
+ function storedEvidence(storedLocale, legacyStoredLocale) {
61
+ const current = evidenceFor(storedLocale);
62
+ if (current.locale)
63
+ return current;
64
+ const legacy = evidenceFor(legacyStoredLocale);
65
+ if (legacy.locale)
66
+ return legacy;
67
+ return { raw: current.raw ?? legacy.raw, locale: null };
68
+ }
69
+ function browserEvidence(clientLanguages) {
70
+ let first = null;
71
+ for (const language of clientLanguages) {
72
+ if (!language)
73
+ continue;
74
+ first ??= language;
75
+ const locale = normalizeTransitLocale(language);
76
+ if (locale)
77
+ return { raw: language, locale };
78
+ }
79
+ return { raw: first, locale: null };
80
+ }
81
+ /**
82
+ * Resolves the locale the official rules would pick and reports the evidence from each input. A supported `?lang=`
83
+ * wins, then the stored value (current key, then the legacy `lang` key), then the first supported browser language,
84
+ * then the default. Unsupported values are skipped. The function never reads or writes storage itself.
85
+ */
86
+ export function resolveTransitLocale(options = {}) {
87
+ const { requestedLang, storedLocale, legacyStoredLocale, clientLanguages } = options;
88
+ const evidence = {
89
+ query: evidenceFor(requestedLang),
90
+ stored: storedEvidence(storedLocale, legacyStoredLocale),
91
+ browser: browserEvidence(clientLanguages ?? []),
92
+ };
93
+ if (evidence.query.locale)
94
+ return { locale: evidence.query.locale, source: 'query', evidence };
95
+ if (evidence.stored.locale)
96
+ return { locale: evidence.stored.locale, source: 'stored', evidence };
97
+ if (evidence.browser.locale)
98
+ return { locale: evidence.browser.locale, source: 'browser', evidence };
99
+ return { locale: DEFAULT_LOCALE, source: 'default', evidence };
100
+ }
@@ -0,0 +1,26 @@
1
+ import { type LocaleSource, type SiteLocale } from './root-transit-locale.js';
2
+ /** Same-origin copy of the monitor marker. The official keys `hagicode:site-locale` and `lang` are never written. */
3
+ export declare const LOCALE_MONITOR_STORAGE_KEY = "hagicode:locale-monitor";
4
+ /** Cross-subdomain copy, written with `Domain=.hagicode.com` on hagicode.com hosts only. */
5
+ export declare const LOCALE_MONITOR_COOKIE = "hagicode_locale_monitor";
6
+ export declare const LOCALE_MONITOR_MAX_AGE_SECONDS: number;
7
+ export declare const LOCALE_MONITOR_SHARED_DOMAIN = "hagicode.com";
8
+ export interface LocaleMarker {
9
+ locale: SiteLocale;
10
+ source: LocaleSource;
11
+ host: string;
12
+ /** Epoch seconds. */
13
+ time: number;
14
+ }
15
+ /** A lowercase host name such as `localhost` or `docs.hagicode.com`. */
16
+ export declare function isHostname(value: string): boolean;
17
+ /** Formats `locale|source|host|time`, or returns null when the result would not parse back. */
18
+ export declare function formatLocaleMarker(marker: LocaleMarker): string | null;
19
+ /** Strict parse: exactly four fields, a supported locale, a known input, a hostname and a plain epoch time. */
20
+ export declare function parseLocaleMarker(value: string): LocaleMarker | null;
21
+ /** True for the shared domain itself and its subdomains. `evilhagicode.com` and `hagicode.com.evil.test` do not match. */
22
+ export declare function isSharedHost(hostname: string, domain: string): boolean;
23
+ /** Reads the marker cookie from a `document.cookie` string, or null when it is absent. */
24
+ export declare function readLocaleMarkerCookie(cookies: string): string | null;
25
+ /** The `Set-Cookie`-style string for `document.cookie`. */
26
+ export declare function localeMarkerCookie(marker: string, domain: string): string;
@@ -0,0 +1,54 @@
1
+ import { SITE_LOCALE_CODES } from './root-transit-locale.js';
2
+ /** Same-origin copy of the monitor marker. The official keys `hagicode:site-locale` and `lang` are never written. */
3
+ export const LOCALE_MONITOR_STORAGE_KEY = 'hagicode:locale-monitor';
4
+ /** Cross-subdomain copy, written with `Domain=.hagicode.com` on hagicode.com hosts only. */
5
+ export const LOCALE_MONITOR_COOKIE = 'hagicode_locale_monitor';
6
+ export const LOCALE_MONITOR_MAX_AGE_SECONDS = 180 * 24 * 60 * 60;
7
+ export const LOCALE_MONITOR_SHARED_DOMAIN = 'hagicode.com';
8
+ /** Longest marker accepted on read. A valid marker is about 50 characters; the bound keeps the cookie small. */
9
+ const MAX_MARKER_LENGTH = 96;
10
+ const SOURCES = ['query', 'stored', 'browser', 'default'];
11
+ const LABEL = /^[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?$/u;
12
+ const TIME = /^\d{1,11}$/u;
13
+ /** A lowercase host name such as `localhost` or `docs.hagicode.com`. */
14
+ export function isHostname(value) {
15
+ return value.split('.').every((label) => LABEL.test(label));
16
+ }
17
+ /** Formats `locale|source|host|time`, or returns null when the result would not parse back. */
18
+ export function formatLocaleMarker(marker) {
19
+ const text = [marker.locale, marker.source, marker.host, String(marker.time)].join('|');
20
+ return parseLocaleMarker(text) ? text : null;
21
+ }
22
+ /** Strict parse: exactly four fields, a supported locale, a known input, a hostname and a plain epoch time. */
23
+ export function parseLocaleMarker(value) {
24
+ if (value.length > MAX_MARKER_LENGTH)
25
+ return null;
26
+ const parts = value.split('|');
27
+ if (parts.length !== 4)
28
+ return null;
29
+ const [locale, source, host, time] = parts;
30
+ if (!SITE_LOCALE_CODES.includes(locale))
31
+ return null;
32
+ if (!SOURCES.includes(source))
33
+ return null;
34
+ if (!isHostname(host) || !TIME.test(time))
35
+ return null;
36
+ return { locale: locale, source: source, host, time: Number(time) };
37
+ }
38
+ /** True for the shared domain itself and its subdomains. `evilhagicode.com` and `hagicode.com.evil.test` do not match. */
39
+ export function isSharedHost(hostname, domain) {
40
+ return hostname === domain || hostname.endsWith(`.${domain}`);
41
+ }
42
+ /** Reads the marker cookie from a `document.cookie` string, or null when it is absent. */
43
+ export function readLocaleMarkerCookie(cookies) {
44
+ for (const pair of cookies.split(';')) {
45
+ const [name, ...value] = pair.trim().split('=');
46
+ if (name === LOCALE_MONITOR_COOKIE)
47
+ return value.join('=');
48
+ }
49
+ return null;
50
+ }
51
+ /** The `Set-Cookie`-style string for `document.cookie`. */
52
+ export function localeMarkerCookie(marker, domain) {
53
+ return `${LOCALE_MONITOR_COOKIE}=${marker}; Domain=.${domain}; Path=/; SameSite=Lax; Secure; Max-Age=${LOCALE_MONITOR_MAX_AGE_SECONDS}`;
54
+ }
@@ -0,0 +1,13 @@
1
+ export interface LocaleMonitorOptions {
2
+ /** The domain the marker cookie is shared on. `false` keeps the marker on the visitor's own origin. */
3
+ sharedDomain?: string | false;
4
+ }
5
+ /** Turns the `localeMonitor` prop into the shared domain: null when the monitor is off, `sharedDomain: null` for same-origin only. */
6
+ export declare function resolveLocaleMonitor(option: boolean | LocaleMonitorOptions | undefined): {
7
+ sharedDomain: string | null;
8
+ } | null;
9
+ /**
10
+ * Observation only. Takes one snapshot of the four inputs and the shared marker, fills the rows as text, then records
11
+ * the marker once. It adds no listeners and no timers, and it never changes the forward target or the links.
12
+ */
13
+ export declare function mountLocaleMonitor(win: Window, doc: Document): void;
@@ -0,0 +1,105 @@
1
+ import { DEFAULT_LOCALE, LEGACY_SITE_LOCALE_STORAGE_KEY, SITE_LOCALE_STORAGE_KEY, resolveTransitLocale, } from './root-transit-locale.js';
2
+ import { LOCALE_MONITOR_SHARED_DOMAIN, LOCALE_MONITOR_STORAGE_KEY, formatLocaleMarker, isHostname, isSharedHost, localeMarkerCookie, parseLocaleMarker, readLocaleMarkerCookie, } from './root-transit-marker.js';
3
+ /** Turns the `localeMonitor` prop into the shared domain: null when the monitor is off, `sharedDomain: null` for same-origin only. */
4
+ export function resolveLocaleMonitor(option) {
5
+ if (!option)
6
+ return null;
7
+ const configured = option === true ? LOCALE_MONITOR_SHARED_DOMAIN : (option.sharedDomain ?? LOCALE_MONITOR_SHARED_DOMAIN);
8
+ if (configured === false)
9
+ return { sharedDomain: null };
10
+ const domain = configured.trim().toLowerCase();
11
+ if (!domain.includes('.') || !isHostname(domain)) {
12
+ throw new TypeError('Hagilight RootTransit: localeMonitor.sharedDomain must be a domain such as hagicode.com, or false.');
13
+ }
14
+ return { sharedDomain: domain };
15
+ }
16
+ const UNAVAILABLE = 'unavailable';
17
+ const EMPTY = '—';
18
+ const INPUT_LABEL = {
19
+ query: '?lang=',
20
+ stored: 'hagicode:site-locale',
21
+ browser: 'navigator.languages',
22
+ default: 'default',
23
+ };
24
+ function read(step) {
25
+ try {
26
+ return { value: step(), failed: false };
27
+ }
28
+ catch {
29
+ return { value: null, failed: true };
30
+ }
31
+ }
32
+ /** A blocked or throwing write loses only this step; the page keeps working. */
33
+ function attempt(step) {
34
+ try {
35
+ step();
36
+ }
37
+ catch {
38
+ // Storage and cookies may be blocked. Nothing else depends on this write.
39
+ }
40
+ }
41
+ function describeInput(evidence, failed) {
42
+ if (evidence.raw === null)
43
+ return failed ? UNAVAILABLE : EMPTY;
44
+ if (evidence.locale && evidence.locale !== evidence.raw)
45
+ return `${evidence.raw} → ${evidence.locale}`;
46
+ return evidence.raw;
47
+ }
48
+ function describeMarker({ locale, source, host }) {
49
+ return `${locale} · ${INPUT_LABEL[source]} · ${host}`;
50
+ }
51
+ /** The cookie copy wins when present; a malformed value is shown as unavailable rather than replaced by the local copy. */
52
+ function describeShared(cookie, localCopy) {
53
+ const raw = cookie.value ?? localCopy.value;
54
+ if (raw !== null) {
55
+ const marker = parseLocaleMarker(raw);
56
+ return marker ? describeMarker(marker) : UNAVAILABLE;
57
+ }
58
+ return cookie.failed || localCopy.failed ? UNAVAILABLE : EMPTY;
59
+ }
60
+ function setRow(panel, key, value, detected) {
61
+ const row = panel.querySelector(`[data-locale-trace="${key}"]`);
62
+ const valueCell = row?.querySelector('[data-locale-value]');
63
+ const verdict = row?.querySelector('[data-locale-verdict]');
64
+ if (!row || !valueCell || !verdict)
65
+ return;
66
+ row.dataset.state = detected ? 'used' : 'idle';
67
+ valueCell.textContent = value;
68
+ verdict.textContent = detected ? 'detected' : '';
69
+ }
70
+ /**
71
+ * Observation only. Takes one snapshot of the four inputs and the shared marker, fills the rows as text, then records
72
+ * the marker once. It adds no listeners and no timers, and it never changes the forward target or the links.
73
+ */
74
+ export function mountLocaleMonitor(win, doc) {
75
+ const panel = doc.querySelector('[data-locale-monitor]');
76
+ if (!panel)
77
+ return;
78
+ const sharedDomain = panel.dataset.sharedDomain || null;
79
+ const query = read(() => new URLSearchParams(win.location.search).get('lang'));
80
+ const stored = read(() => win.localStorage.getItem(SITE_LOCALE_STORAGE_KEY));
81
+ const legacy = read(() => win.localStorage.getItem(LEGACY_SITE_LOCALE_STORAGE_KEY));
82
+ const browser = read(() => [...win.navigator.languages]);
83
+ const cookie = read(() => readLocaleMarkerCookie(doc.cookie));
84
+ const localCopy = read(() => win.localStorage.getItem(LOCALE_MONITOR_STORAGE_KEY));
85
+ const resolution = resolveTransitLocale({
86
+ requestedLang: query.value,
87
+ storedLocale: stored.value,
88
+ legacyStoredLocale: legacy.value,
89
+ clientLanguages: browser.value ?? [],
90
+ });
91
+ const { evidence, source } = resolution;
92
+ setRow(panel, 'query', describeInput(evidence.query, query.failed), source === 'query');
93
+ setRow(panel, 'stored', describeInput(evidence.stored, stored.failed || legacy.failed), source === 'stored');
94
+ setRow(panel, 'browser', describeInput(evidence.browser, browser.failed), source === 'browser');
95
+ setRow(panel, 'default', DEFAULT_LOCALE, source === 'default');
96
+ setRow(panel, 'shared', describeShared(cookie, localCopy), false);
97
+ const host = win.location.hostname;
98
+ const marker = formatLocaleMarker({ locale: resolution.locale, source, host, time: Math.floor(Date.now() / 1000) });
99
+ if (!marker)
100
+ return;
101
+ attempt(() => win.localStorage.setItem(LOCALE_MONITOR_STORAGE_KEY, marker));
102
+ if (sharedDomain && isSharedHost(host, sharedDomain)) {
103
+ attempt(() => { doc.cookie = localeMarkerCookie(marker, sharedDomain); });
104
+ }
105
+ }
@@ -1,3 +1,6 @@
1
+ export { DEFAULT_LOCALE, LEGACY_SITE_LOCALE_STORAGE_KEY, SITE_LOCALE_STORAGE_KEY, SITE_LOCALES, normalizeTransitLocale, resolveTransitLocale, type LocaleInputEvidence, type LocaleResolution, type LocaleResolutionOptions, type LocaleSource, type SiteLocale, } from './root-transit-locale.js';
2
+ export { LOCALE_MONITOR_COOKIE, LOCALE_MONITOR_STORAGE_KEY, formatLocaleMarker, parseLocaleMarker, type LocaleMarker, } from './root-transit-marker.js';
3
+ export { mountLocaleMonitor, resolveLocaleMonitor, type LocaleMonitorOptions } from './root-transit-monitor.js';
1
4
  /** The reference route sweep (1,250 ms) and finished-state hold (320 ms). */
2
5
  export declare const ROOT_TRANSIT_DELAY_MS = 1570;
3
6
  export interface TransitDestinationOptions {
@@ -1,4 +1,8 @@
1
1
  import { SPLASH_IMAGE_DEFAULTS, loadSplashImage, pickSplashIndex, splashImageUrl, storeSplashImage, } from './splash-images.js';
2
+ import { mountLocaleMonitor } from './root-transit-monitor.js';
3
+ export { DEFAULT_LOCALE, LEGACY_SITE_LOCALE_STORAGE_KEY, SITE_LOCALE_STORAGE_KEY, SITE_LOCALES, normalizeTransitLocale, resolveTransitLocale, } from './root-transit-locale.js';
4
+ export { LOCALE_MONITOR_COOKIE, LOCALE_MONITOR_STORAGE_KEY, formatLocaleMarker, parseLocaleMarker, } from './root-transit-marker.js';
5
+ export { mountLocaleMonitor, resolveLocaleMonitor } from './root-transit-monitor.js';
2
6
  /** The reference route sweep (1,250 ms) and finished-state hold (320 ms). */
3
7
  export const ROOT_TRANSIT_DELAY_MS = 1570;
4
8
  /** Idle-time limit for storing a loaded splash image, so the store never waits on the page. */
@@ -216,6 +220,12 @@ export function mountRootTransit(win = window) {
216
220
  catch {
217
221
  releaseSplash = () => { };
218
222
  }
223
+ try {
224
+ mountLocaleMonitor(win, doc);
225
+ }
226
+ catch {
227
+ // The monitor only observes; a failure here never changes forwarding.
228
+ }
219
229
  doc.documentElement.dataset.transitReady = 'true';
220
230
  return cleanup;
221
231
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hagicode/hagilight-core",
3
- "version": "0.14.1-dev.149.1.1dadf5c",
3
+ "version": "0.14.1-dev.150.1.68cde77",
4
4
  "type": "module",
5
5
  "description": "Shared TypeScript utilities, components, and assets for HagiCode Astro and Starlight sites",
6
6
  "repository": {