@turnipxenon/pineapple 5.3.16 → 5.3.17

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.
@@ -0,0 +1,1892 @@
1
+ /* eslint-disable */
2
+
3
+ /** @type {any} */
4
+ const URLPattern = {}
5
+
6
+ /**
7
+ * The project's base locale.
8
+ *
9
+ * @example
10
+ * if (locale === baseLocale) {
11
+ * // do something
12
+ * }
13
+ */
14
+ export const baseLocale = "en";
15
+ /**
16
+ * The project's locales that have been specified in the settings.
17
+ *
18
+ * @example
19
+ * if (locales.includes(userSelectedLocale) === false) {
20
+ * throw new Error('Locale is not available');
21
+ * }
22
+ */
23
+ export const locales = /** @type {const} */ (["en","fr","tl"]);
24
+ /** @type {string} */
25
+ export const cookieName = "PARAGLIDE_LOCALE";
26
+ /** @type {number} */
27
+ export const cookieMaxAge = 34560000;
28
+ /** @type {string} */
29
+ export const cookieDomain = "";
30
+ /** @type {string} */
31
+ export const localStorageKey = "PARAGLIDE_LOCALE";
32
+ /**
33
+ * @type {Array<"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage" | `custom-${string}`>}
34
+ */
35
+ export const strategy = [
36
+ "cookie",
37
+ "globalVariable",
38
+ "baseLocale"
39
+ ];
40
+ /**
41
+ * Route-level strategy overrides.
42
+ *
43
+ * `match` uses URLPattern syntax.
44
+ *
45
+ * @type {Array<{
46
+ * match: string;
47
+ * strategy?: Array<"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage" | `custom-${string}`>;
48
+ * exclude?: boolean;
49
+ * }>}
50
+ */
51
+ export const routeStrategies = [];
52
+ /**
53
+ * The used URL patterns.
54
+ *
55
+ * @type {Array<{ pattern: string, localized: Array<[Locale, string]> }>}
56
+ */
57
+ export const urlPatterns = [
58
+ {
59
+ "pattern": ":protocol://:domain(.*)::port?/:path(.*)?",
60
+ "localized": [
61
+ [
62
+ "fr",
63
+ ":protocol://:domain(.*)::port?/fr/:path(.*)?"
64
+ ],
65
+ [
66
+ "tl",
67
+ ":protocol://:domain(.*)::port?/tl/:path(.*)?"
68
+ ],
69
+ [
70
+ "en",
71
+ ":protocol://:domain(.*)::port?/:path(.*)?"
72
+ ]
73
+ ]
74
+ }
75
+ ];
76
+ /**
77
+ * @typedef {{
78
+ * getStore(): {
79
+ * locale?: Locale,
80
+ * origin?: string,
81
+ * messageCalls?: Set<string>
82
+ * } | undefined,
83
+ * run: (store: { locale?: Locale, origin?: string, messageCalls?: Set<string>},
84
+ * cb: any) => any
85
+ * }} ParaglideAsyncLocalStorage
86
+ */
87
+ /**
88
+ * Server side async local storage that is set by `serverMiddleware()`.
89
+ *
90
+ * The variable is used to retrieve the locale and origin in a server-side
91
+ * rendering context without effecting other requests.
92
+ *
93
+ * @type {ParaglideAsyncLocalStorage | undefined}
94
+ */
95
+ export let serverAsyncLocalStorage = undefined;
96
+ /**
97
+ * Returns the current server-side async local storage instance.
98
+ *
99
+ * Accessing the mutable value through a function keeps it observable when
100
+ * module interceptors wrap exported bindings and snapshot their initial value.
101
+ *
102
+ * @returns {ParaglideAsyncLocalStorage | undefined}
103
+ */
104
+ export function getServerAsyncLocalStorage() {
105
+ return serverAsyncLocalStorage;
106
+ }
107
+ export const disableAsyncLocalStorage = false;
108
+ export const experimentalMiddlewareLocaleSplitting = false;
109
+ export const isServer = typeof window === 'undefined';
110
+ /** @type {Locale | undefined} */
111
+ export const experimentalStaticLocale = undefined;
112
+ /**
113
+ * Sets the server side async local storage.
114
+ *
115
+ * The function is needed because the `runtime.js` file
116
+ * must define the `serverAsyncLocalStorage` variable to
117
+ * avoid a circular import between `runtime.js` and
118
+ * `server.js` files.
119
+ *
120
+ * @param {ParaglideAsyncLocalStorage | undefined} value
121
+ */
122
+ export function overwriteServerAsyncLocalStorage(value) {
123
+ serverAsyncLocalStorage = value;
124
+ }
125
+ const TREE_SHAKE_COOKIE_STRATEGY_USED = true;
126
+ const TREE_SHAKE_URL_STRATEGY_USED = false;
127
+ const TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED = true;
128
+ const TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED = false;
129
+ const TREE_SHAKE_DEFAULT_URL_PATTERN_USED = true;
130
+ const TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED = false;
131
+
132
+ /** @type {any} */ (globalThis).__paraglide =
133
+ /** @type {any} */ (globalThis).__paraglide ?? {};
134
+ /** @type {any} */ (globalThis).__paraglide.ssr =
135
+ /** @type {any} */ (globalThis).__paraglide.ssr ?? {};
136
+
137
+ /**
138
+ * This is a fallback to get started with a custom
139
+ * strategy and avoid type errors.
140
+ *
141
+ * The implementation is overwritten
142
+ * by `overwriteGetLocale()` and `defineSetLocale()`.
143
+ *
144
+ * @type {Locale | undefined}
145
+ */
146
+ let _locale;
147
+ let localeInitiallySet = false;
148
+ /**
149
+ * Get the current locale.
150
+ *
151
+ * The locale is resolved using your configured strategies (URL, cookie, localStorage, etc.)
152
+ * in the order they are defined. In SSR contexts, the locale is retrieved from AsyncLocalStorage
153
+ * which is set by the `paraglideMiddleware()`.
154
+ *
155
+ * @see https://paraglidejs.com/strategy - Configure locale detection strategies
156
+ *
157
+ * @example
158
+ * if (getLocale() === 'de') {
159
+ * console.log('Germany 🇩🇪');
160
+ * } else if (getLocale() === 'nl') {
161
+ * console.log('Netherlands 🇳🇱');
162
+ * }
163
+ *
164
+ * @returns {Locale} The current locale.
165
+ */
166
+ export let getLocale = () => {
167
+ if (experimentalStaticLocale !== undefined) {
168
+ return experimentalStaticLocale;
169
+ }
170
+ // if running in a server-side rendering context
171
+ // retrieve the locale from the async local storage
172
+ if (serverAsyncLocalStorage) {
173
+ const locale = serverAsyncLocalStorage?.getStore()?.locale;
174
+ if (locale) {
175
+ return locale;
176
+ }
177
+ }
178
+ let strategyToUse = strategy;
179
+ if (!isServer && typeof window !== "undefined" && window.location?.href) {
180
+ strategyToUse = getStrategyForUrl(window.location.href);
181
+ }
182
+ const resolved = resolveLocaleWithStrategies(strategyToUse, typeof window !== "undefined" ? window.location?.href : undefined);
183
+ if (resolved) {
184
+ if (!localeInitiallySet) {
185
+ _locale = resolved;
186
+ // https://github.com/opral/inlang-paraglide-js/issues/455
187
+ localeInitiallySet = true;
188
+ setLocale(resolved, { reload: false });
189
+ }
190
+ return resolved;
191
+ }
192
+ throw new Error("No locale found. Read the docs https://paraglidejs.com/errors#no-locale-found");
193
+ };
194
+ /**
195
+ * Resolve locale for a given URL using route-aware strategies.
196
+ *
197
+ * @param {string | URL} url
198
+ * @returns {Locale}
199
+ */
200
+ export function getLocaleForUrl(url) {
201
+ if (experimentalStaticLocale !== undefined) {
202
+ return experimentalStaticLocale;
203
+ }
204
+ const strategyToUse = getStrategyForUrl(url);
205
+ const resolved = resolveLocaleWithStrategies(strategyToUse, typeof url === "string" ? url : url.href);
206
+ if (resolved) {
207
+ return resolved;
208
+ }
209
+ throw new Error("No locale found. Read the docs https://paraglidejs.com/errors#no-locale-found");
210
+ }
211
+ /**
212
+ * @param {typeof strategy} strategyToUse
213
+ * @param {string | undefined} urlForUrlStrategy
214
+ * @returns {Locale | undefined}
215
+ */
216
+ function resolveLocaleWithStrategies(strategyToUse, urlForUrlStrategy) {
217
+ /** @type {string | undefined} */
218
+ let locale;
219
+ for (const strat of strategyToUse) {
220
+ if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
221
+ locale = extractLocaleFromCookie();
222
+ }
223
+ else if (strat === "baseLocale") {
224
+ locale = baseLocale;
225
+ }
226
+ else if (TREE_SHAKE_URL_STRATEGY_USED &&
227
+ strat === "url" &&
228
+ !isServer &&
229
+ typeof urlForUrlStrategy === "string") {
230
+ locale = extractLocaleFromUrl(urlForUrlStrategy);
231
+ }
232
+ else if (TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED &&
233
+ strat === "globalVariable" &&
234
+ _locale !== undefined) {
235
+ locale = _locale;
236
+ }
237
+ else if (TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED &&
238
+ strat === "preferredLanguage" &&
239
+ !isServer) {
240
+ locale = extractLocaleFromNavigator();
241
+ }
242
+ else if (TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED &&
243
+ strat === "localStorage" &&
244
+ !isServer) {
245
+ locale = localStorage.getItem(localStorageKey) ?? undefined;
246
+ }
247
+ else if (isCustomStrategy(strat) && customClientStrategies.has(strat)) {
248
+ const handler = customClientStrategies.get(strat);
249
+ if (handler) {
250
+ const result = handler.getLocale();
251
+ // Handle both sync and async results - skip async in sync getLocale
252
+ if (result instanceof Promise) {
253
+ // Can't await in sync function, skip async strategies
254
+ continue;
255
+ }
256
+ if (result !== undefined) {
257
+ return assertIsLocale(result);
258
+ }
259
+ }
260
+ }
261
+ const matchedLocale = toLocale(locale);
262
+ if (matchedLocale) {
263
+ return matchedLocale;
264
+ }
265
+ }
266
+ return undefined;
267
+ }
268
+ /**
269
+ * Overwrite the `getLocale()` function.
270
+ *
271
+ * Use this function to overwrite how the locale is resolved. This is useful
272
+ * for custom locale resolution or advanced use cases like SSG with concurrent rendering.
273
+ *
274
+ * @see https://paraglidejs.com/strategy
275
+ *
276
+ * @example
277
+ * overwriteGetLocale(() => {
278
+ * return Cookies.get('locale') ?? baseLocale
279
+ * });
280
+ *
281
+ * @param {() => Locale} fn - The new implementation for `getLocale()`.
282
+ */
283
+ export const overwriteGetLocale = (fn) => {
284
+ getLocale = fn;
285
+ };
286
+
287
+ const rtlLanguages = new Set([
288
+ "ar",
289
+ "dv",
290
+ "fa",
291
+ "he",
292
+ "ks",
293
+ "ku",
294
+ "ps",
295
+ "sd",
296
+ "ug",
297
+ "ur",
298
+ "yi",
299
+ ]);
300
+ /**
301
+ * Get writing direction for a locale.
302
+ *
303
+ * Uses `Intl.Locale` text info when available and falls back to a
304
+ * language-based RTL check for runtimes without `getTextInfo()`.
305
+ *
306
+ * @example
307
+ * getTextDirection(); // "ltr" or "rtl" for current locale
308
+ * getTextDirection("ar"); // "rtl"
309
+ * getTextDirection("en"); // "ltr"
310
+ *
311
+ * @param {string} [locale] - Target locale. If not provided, uses `getLocale()`
312
+ * @returns {"ltr" | "rtl"}
313
+ */
314
+ export function getTextDirection(locale = getLocale()) {
315
+ try {
316
+ const intlLocale = /** @type {Intl.Locale & {
317
+ getTextInfo?: () => { direction?: string };
318
+ textInfo?: { direction?: string };
319
+ }} */ (new Intl.Locale(locale));
320
+ const direction = intlLocale.getTextInfo?.().direction ?? intlLocale.textInfo?.direction;
321
+ if (direction === "ltr" || direction === "rtl") {
322
+ return direction;
323
+ }
324
+ }
325
+ catch {
326
+ // Ignore Intl.Locale parsing/runtime errors and use fallback below.
327
+ }
328
+ const language = locale.split("-")[0]?.toLowerCase();
329
+ return rtlLanguages.has(language ?? "") ? "rtl" : "ltr";
330
+ }
331
+
332
+ /**
333
+ * Navigates to the localized URL, or reloads the current page
334
+ *
335
+ * @param {string} [newLocation] The new location
336
+ */
337
+ const navigateOrReload = (newLocation) => {
338
+ if (newLocation) {
339
+ // reload the page by navigating to the new url
340
+ window.location.href = newLocation;
341
+ }
342
+ else {
343
+ // reload the page to reflect the new locale
344
+ window.location.reload();
345
+ }
346
+ };
347
+ /**
348
+ * @typedef {(newLocale: Locale, options?: { reload?: boolean }) => void | Promise<void>} SetLocaleFn
349
+ */
350
+ /**
351
+ * Set the locale.
352
+ *
353
+ * Updates the locale using your configured strategies (cookie, localStorage, URL, etc.).
354
+ * By default, this navigates the client to the localized URL or reloads the current
355
+ * document to reflect the new locale. `reload: false` is a narrow browser-only escape
356
+ * hatch for a fully client-rendered, non-URL-routed surface that owns its reactive
357
+ * updates and document state. It does not re-render the UI or update the document.
358
+ * Do not use it for normal locale pickers, URL-routed pages, or switching an SSR,
359
+ * SSG, or hydrated document. It is incompatible with per-locale builds.
360
+ *
361
+ * If any custom strategy's `setLocale` function is async, then this function
362
+ * will become async as well.
363
+ *
364
+ * @see https://paraglidejs.com/strategy
365
+ *
366
+ * @example
367
+ * setLocale('en');
368
+ *
369
+ * @example
370
+ * setLocale('en', { reload: false });
371
+ *
372
+ * @type {SetLocaleFn}
373
+ */
374
+ export let setLocale = (newLocale, options) => {
375
+ const optionsWithDefaults = {
376
+ reload: true,
377
+ ...options,
378
+ };
379
+ if (experimentalStaticLocale !== undefined &&
380
+ newLocale !== experimentalStaticLocale &&
381
+ optionsWithDefaults.reload === false) {
382
+ console.warn(`Paraglide: setLocale(${JSON.stringify(newLocale)}, { reload: false }) cannot switch away from the statically built locale ${JSON.stringify(experimentalStaticLocale)}. A document navigation is required; reload has been forced to true.`);
383
+ optionsWithDefaults.reload = true;
384
+ }
385
+ // locale is already set
386
+ // https://github.com/opral/inlang-paraglide-js/issues/430
387
+ /** @type {Locale | undefined} */
388
+ let currentLocale;
389
+ try {
390
+ currentLocale = getLocale();
391
+ }
392
+ catch {
393
+ // do nothing, no locale has been set yet.
394
+ }
395
+ /** @type {Array<Promise<void>>} */
396
+ const customSetLocalePromises = [];
397
+ /** @type {string | undefined} */
398
+ let newLocation = undefined;
399
+ let strategyToUse = strategy;
400
+ if (!isServer && typeof window !== "undefined" && window.location?.href) {
401
+ strategyToUse = getStrategyForUrl(window.location.href);
402
+ }
403
+ for (const strat of strategyToUse) {
404
+ if (TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED &&
405
+ strat === "globalVariable") {
406
+ // a default for a custom strategy to get started quickly
407
+ // is likely overwritten by `defineSetLocale()`
408
+ _locale = newLocale;
409
+ }
410
+ else if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
411
+ if (isServer ||
412
+ typeof document === "undefined" ||
413
+ typeof window === "undefined") {
414
+ continue;
415
+ }
416
+ // set the cookie
417
+ const cookieString = `${cookieName}=${newLocale}; path=/; max-age=${cookieMaxAge}`;
418
+ document.cookie = cookieDomain
419
+ ? `${cookieString}; domain=${cookieDomain}`
420
+ : cookieString;
421
+ clearLocaleCookieCache();
422
+ }
423
+ else if (strat === "baseLocale") {
424
+ // nothing to be set here. baseLocale is only a fallback
425
+ continue;
426
+ }
427
+ else if (TREE_SHAKE_URL_STRATEGY_USED &&
428
+ strat === "url" &&
429
+ typeof window !== "undefined") {
430
+ // route to the new url
431
+ //
432
+ // this triggers a page reload but a user rarely
433
+ // switches locales, so this should be fine.
434
+ //
435
+ // if the behavior is not desired, the implementation
436
+ // can be overwritten by `defineSetLocale()` to avoid
437
+ // a full page reload.
438
+ newLocation = localizeUrl(window.location.href, {
439
+ locale: newLocale,
440
+ }).href;
441
+ }
442
+ else if (TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED &&
443
+ strat === "localStorage" &&
444
+ typeof window !== "undefined") {
445
+ // set the localStorage
446
+ localStorage.setItem(localStorageKey, newLocale);
447
+ }
448
+ else if (isCustomStrategy(strat) && customClientStrategies.has(strat)) {
449
+ const handler = customClientStrategies.get(strat);
450
+ if (handler) {
451
+ let result = handler.setLocale(newLocale);
452
+ // Handle async setLocale
453
+ if (result instanceof Promise) {
454
+ result = result.catch((error) => {
455
+ throw new Error(`Custom strategy "${strat}" setLocale failed.`, {
456
+ cause: error,
457
+ });
458
+ });
459
+ customSetLocalePromises.push(result);
460
+ }
461
+ }
462
+ }
463
+ }
464
+ const runReload = () => {
465
+ if (!isServer &&
466
+ optionsWithDefaults.reload &&
467
+ window.location &&
468
+ newLocale !== currentLocale) {
469
+ navigateOrReload(newLocation);
470
+ }
471
+ };
472
+ if (customSetLocalePromises.length) {
473
+ return Promise.all(customSetLocalePromises).then(() => {
474
+ runReload();
475
+ });
476
+ }
477
+ runReload();
478
+ return;
479
+ };
480
+ /**
481
+ * Overwrite the `setLocale()` function.
482
+ *
483
+ * Use this function to overwrite how the locale is set. For example,
484
+ * modify a cookie, env variable, or a user's preference.
485
+ *
486
+ * @example
487
+ * overwriteSetLocale((newLocale) => {
488
+ * // set the locale in a cookie
489
+ * return Cookies.set('locale', newLocale)
490
+ * });
491
+ *
492
+ * @param {SetLocaleFn} fn
493
+ */
494
+ export const overwriteSetLocale = (fn) => {
495
+ setLocale = fn;
496
+ };
497
+
498
+ /**
499
+ * The origin of the current URL.
500
+ *
501
+ * Defaults to "http://example.com" in non-browser environments. If this
502
+ * behavior is not desired, the implementation can be overwritten
503
+ * by `overwriteGetUrlOrigin()`.
504
+ *
505
+ * @type {() => string}
506
+ */
507
+ export let getUrlOrigin = () => {
508
+ if (serverAsyncLocalStorage) {
509
+ return serverAsyncLocalStorage.getStore()?.origin ?? "http://fallback.com";
510
+ }
511
+ else if (typeof window !== "undefined") {
512
+ return window.location.origin;
513
+ }
514
+ return "http://fallback.com";
515
+ };
516
+ /**
517
+ * Overwrite the getUrlOrigin function.
518
+ *
519
+ * Use this function in server environments to
520
+ * define how the URL origin is resolved.
521
+ *
522
+ * @param {() => string} fn - The new implementation for `getUrlOrigin()`.
523
+ */
524
+ export let overwriteGetUrlOrigin = (fn) => {
525
+ getUrlOrigin = fn;
526
+ };
527
+
528
+ /**
529
+ * Coerces a locale-like string to the canonical locale value used by the runtime.
530
+ *
531
+ * @param {unknown} value
532
+ * @returns {Locale | undefined}
533
+ */
534
+ export function toLocale(value) {
535
+ if (typeof value !== "string") {
536
+ return undefined;
537
+ }
538
+ const lowerValue = value.toLowerCase();
539
+ for (const locale of locales) {
540
+ if (locale.toLowerCase() === lowerValue) {
541
+ return locale;
542
+ }
543
+ }
544
+ return undefined;
545
+ }
546
+ /**
547
+ * Check if something is an available locale with the canonical project casing.
548
+ *
549
+ * @example
550
+ * if (isLocale(params.locale)) {
551
+ * setLocale(params.locale);
552
+ * } else {
553
+ * setLocale('en');
554
+ * }
555
+ *
556
+ * Use `toLocale()` when you want case-insensitive matching and canonicalization.
557
+ *
558
+ * @param {unknown} locale
559
+ * @returns {locale is Locale}
560
+ */
561
+ export function isLocale(locale) {
562
+ return !!locale && locales.some((item) => item === locale);
563
+ }
564
+ /**
565
+ * Asserts that the input can be normalized to a locale.
566
+ *
567
+ * @param {unknown} input - The input to check.
568
+ * @returns {Locale} The input normalized to a Locale.
569
+ * @throws {Error} If the input is not a locale.
570
+ */
571
+ export function assertIsLocale(input) {
572
+ const locale = toLocale(input);
573
+ if (locale)
574
+ return locale;
575
+ throw new Error(`Invalid locale: ${input}. Expected one of: ${locales.join(", ")}`);
576
+ }
577
+
578
+ /**
579
+ * @typedef {object} ExtractLocaleFromRequestOptions
580
+ * @property {string | URL} [effectiveRequestUrl] - Effective request URL to use for route matching and locale detection with the URL strategy.
581
+ */
582
+ /**
583
+ * Extracts a locale from a request.
584
+ *
585
+ * Use the function on the server to extract the locale
586
+ * from a request.
587
+ *
588
+ * The function goes through the strategies in the order
589
+ * they are defined. If a strategy returns an invalid locale,
590
+ * it will fall back to the next strategy.
591
+ *
592
+ * Note: Custom server strategies are not supported in this synchronous version.
593
+ * Use `extractLocaleFromRequestAsync` if you need custom server strategies with async getLocale methods.
594
+ *
595
+ * @example
596
+ * const locale = extractLocaleFromRequest(request);
597
+ *
598
+ * @param {Request} request
599
+ * @param {ExtractLocaleFromRequestOptions} [options]
600
+ * @returns {Locale}
601
+ */
602
+ export const extractLocaleFromRequest = (request, options = {}) => {
603
+ const effectiveRequestUrl = resolveEffectiveRequestUrl(request, options.effectiveRequestUrl);
604
+ return extractLocaleFromRequestWithStrategies(request, getStrategyForUrl(effectiveRequestUrl), effectiveRequestUrl);
605
+ };
606
+ /**
607
+ * Extracts a locale from a request using the provided strategy order.
608
+ *
609
+ * @param {Request} request
610
+ * @param {typeof strategy} strategies
611
+ * @param {string | URL} [url]
612
+ * @returns {Locale}
613
+ */
614
+ export const extractLocaleFromRequestWithStrategies = (request, strategies, url = request.url) => {
615
+ const effectiveRequestUrl = resolveEffectiveRequestUrl(request, url);
616
+ /** @type {string|undefined} */
617
+ let locale;
618
+ for (const strat of strategies) {
619
+ if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
620
+ const cookiePrefix = cookieName + "=";
621
+ locale = request.headers
622
+ .get("cookie")
623
+ ?.split(";")
624
+ .map((c) => c.trim())
625
+ .find((c) => c.startsWith(cookiePrefix))
626
+ ?.slice(cookiePrefix.length);
627
+ }
628
+ else if (TREE_SHAKE_URL_STRATEGY_USED && strat === "url") {
629
+ locale = extractLocaleFromUrl(effectiveRequestUrl);
630
+ }
631
+ else if (TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED &&
632
+ strat === "preferredLanguage") {
633
+ locale = extractLocaleFromHeader(request);
634
+ }
635
+ else if (strat === "globalVariable") {
636
+ locale = _locale;
637
+ }
638
+ else if (strat === "baseLocale") {
639
+ return baseLocale;
640
+ }
641
+ else if (strat === "localStorage") {
642
+ continue;
643
+ }
644
+ else if (isCustomStrategy(strat)) {
645
+ // Custom strategies are not supported in sync version
646
+ // Use extractLocaleFromRequestAsync for custom server strategies
647
+ continue;
648
+ }
649
+ const matchedLocale = toLocale(locale);
650
+ if (matchedLocale) {
651
+ return matchedLocale;
652
+ }
653
+ }
654
+ throw new Error("No locale found. There is an error in your strategy. Try adding 'baseLocale' as the very last strategy. Read more here https://paraglidejs.com/errors#no-locale-found");
655
+ };
656
+ /**
657
+ * @param {Request} request
658
+ * @param {string | URL | undefined} effectiveRequestUrl
659
+ * @returns {URL}
660
+ */
661
+ function resolveEffectiveRequestUrl(request, effectiveRequestUrl = request.url) {
662
+ if (effectiveRequestUrl instanceof URL) {
663
+ return new URL(effectiveRequestUrl.href);
664
+ }
665
+ return new URL(effectiveRequestUrl, request.url);
666
+ }
667
+
668
+ /**
669
+ * Asynchronously extracts a locale from a request.
670
+ *
671
+ * This function supports async custom server strategies, unlike the synchronous
672
+ * `extractLocaleFromRequest`. Use this function when you have custom server strategies
673
+ * that need to perform asynchronous operations (like database calls) in their getLocale method.
674
+ *
675
+ * The function first processes any custom server strategies asynchronously, then falls back
676
+ * to the synchronous `extractLocaleFromRequest` for all other strategies.
677
+ *
678
+ * @see {@link https://github.com/opral/inlang-paraglide-js/issues/527#issuecomment-2978151022}
679
+ *
680
+ * @example
681
+ * // Basic usage
682
+ * const locale = await extractLocaleFromRequestAsync(request);
683
+ *
684
+ * @example
685
+ * // With custom async server strategy
686
+ * defineCustomServerStrategy("custom-database", {
687
+ * getLocale: async (request) => {
688
+ * const userId = extractUserIdFromRequest(request);
689
+ * return await getUserLocaleFromDatabase(userId);
690
+ * }
691
+ * });
692
+ *
693
+ * const locale = await extractLocaleFromRequestAsync(request);
694
+ *
695
+ * @param {Request} request - The request object to extract the locale from.
696
+ * @param {{ effectiveRequestUrl?: string | URL }} [options] - Effective request URL to use for route matching and locale detection with the URL strategy.
697
+ * @returns {Promise<Locale>} The extracted locale.
698
+ */
699
+ export const extractLocaleFromRequestAsync = async (request, options = {}) => {
700
+ /** @type {string|undefined} */
701
+ let locale;
702
+ const effectiveRequestUrl = resolveEffectiveRequestUrlFromRequestAsync(request, options.effectiveRequestUrl);
703
+ const strategy = getStrategyForUrl(effectiveRequestUrl);
704
+ // Process custom strategies first, in order
705
+ for (const strat of strategy) {
706
+ if (isCustomStrategy(strat) && customServerStrategies.has(strat)) {
707
+ const handler = customServerStrategies.get(strat);
708
+ if (handler) {
709
+ /** @type {string|undefined} */
710
+ locale = await handler.getLocale(request);
711
+ }
712
+ // If we got a valid locale from this custom strategy, use it
713
+ const matchedLocale = toLocale(locale);
714
+ if (matchedLocale) {
715
+ return matchedLocale;
716
+ }
717
+ }
718
+ }
719
+ // If no custom strategy provided a valid locale, fall back to sync version
720
+ return extractLocaleFromRequestWithStrategies(request, strategy, effectiveRequestUrl);
721
+ };
722
+ /**
723
+ * @param {Request} request
724
+ * @param {string | URL | undefined} effectiveRequestUrl
725
+ * @returns {URL}
726
+ */
727
+ function resolveEffectiveRequestUrlFromRequestAsync(request, effectiveRequestUrl = request.url) {
728
+ if (effectiveRequestUrl instanceof URL) {
729
+ return new URL(effectiveRequestUrl.href);
730
+ }
731
+ return new URL(effectiveRequestUrl, request.url);
732
+ }
733
+
734
+ const cookieNamePattern = cookieName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
735
+ const localeCookiePattern = new RegExp(`(?:^|;\\s*)${cookieNamePattern}=([^;]*)`);
736
+ const noCachedLocale = Symbol();
737
+ /** @type {Locale | undefined | typeof noCachedLocale} */
738
+ let cachedLocaleFromCookie = noCachedLocale;
739
+ /**
740
+ * Clears the cached locale from `document.cookie`.
741
+ */
742
+ function clearLocaleCookieCache() {
743
+ cachedLocaleFromCookie = noCachedLocale;
744
+ }
745
+ function scheduleLocaleCookieCacheClear() {
746
+ if (typeof queueMicrotask === "function") {
747
+ queueMicrotask(clearLocaleCookieCache);
748
+ }
749
+ else {
750
+ Promise.resolve().then(clearLocaleCookieCache);
751
+ }
752
+ }
753
+ /**
754
+ * Extracts a cookie from the document.
755
+ *
756
+ * Will return undefined if the document is not available or if the cookie is not set.
757
+ * The `document` object is not available in server-side rendering, so this function should not be called in that context.
758
+ *
759
+ * @returns {Locale | undefined}
760
+ */
761
+ export function extractLocaleFromCookie() {
762
+ if (typeof document === "undefined") {
763
+ return;
764
+ }
765
+ if (cachedLocaleFromCookie !== noCachedLocale) {
766
+ return cachedLocaleFromCookie;
767
+ }
768
+ const match = document.cookie.match(localeCookiePattern);
769
+ const locale = match?.[1];
770
+ cachedLocaleFromCookie = toLocale(locale);
771
+ scheduleLocaleCookieCacheClear();
772
+ return cachedLocaleFromCookie;
773
+ }
774
+
775
+ /**
776
+ * Extracts a locale from the accept-language header.
777
+ *
778
+ * Use the function on the server to extract the locale
779
+ * from the accept-language header that is sent by the client.
780
+ *
781
+ * @example
782
+ * const locale = extractLocaleFromHeader(request);
783
+ *
784
+ * @param {Request} request - The request object to extract the locale from.
785
+ * @returns {Locale | undefined} The negotiated preferred language.
786
+ */
787
+ export function extractLocaleFromHeader(request) {
788
+ const acceptLanguageHeader = request.headers.get("accept-language");
789
+ if (acceptLanguageHeader) {
790
+ // Parse language preferences with their q-values and base language codes
791
+ const languages = acceptLanguageHeader
792
+ .split(",")
793
+ .map((lang) => {
794
+ const [tag, q = "1"] = lang.trim().split(";q=");
795
+ // Get both the full tag and base language code
796
+ const baseTag = tag?.split("-")[0];
797
+ return {
798
+ fullTag: tag,
799
+ baseTag,
800
+ q: Number(q),
801
+ };
802
+ })
803
+ .sort((a, b) => b.q - a.q);
804
+ for (const lang of languages) {
805
+ const fullLocale = toLocale(lang.fullTag);
806
+ if (fullLocale) {
807
+ return fullLocale;
808
+ }
809
+ const baseLocale = toLocale(lang.baseTag);
810
+ if (baseLocale) {
811
+ return baseLocale;
812
+ }
813
+ }
814
+ return undefined;
815
+ }
816
+ return undefined;
817
+ }
818
+
819
+ /**
820
+ * Negotiates a preferred language from navigator.languages.
821
+ *
822
+ * Use the function on the client to extract the locale
823
+ * from the navigator.languages array.
824
+ *
825
+ * @example
826
+ * const locale = extractLocaleFromNavigator();
827
+ *
828
+ * @returns {Locale | undefined}
829
+ */
830
+ export function extractLocaleFromNavigator() {
831
+ if (!navigator?.languages?.length) {
832
+ return undefined;
833
+ }
834
+ const languages = navigator.languages.map((lang) => ({
835
+ fullTag: lang,
836
+ baseTag: lang.split("-")[0],
837
+ }));
838
+ for (const lang of languages) {
839
+ const fullLocale = toLocale(lang.fullTag);
840
+ if (fullLocale) {
841
+ return fullLocale;
842
+ }
843
+ const baseLocale = toLocale(lang.baseTag);
844
+ if (baseLocale) {
845
+ return baseLocale;
846
+ }
847
+ }
848
+ return undefined;
849
+ }
850
+
851
+ /**
852
+ * If extractLocaleFromUrl is called many times on the same page and the URL
853
+ * hasn't changed, we don't need to recompute it every time which can get expensive.
854
+ * We might use a LRU cache if needed, but for now storing only the last result is enough.
855
+ * https://github.com/opral/monorepo/pull/3575#discussion_r2066731243
856
+ */
857
+ /** @type {string|undefined} */
858
+ let cachedUrl;
859
+ /** @type {Locale|undefined} */
860
+ let cachedLocale;
861
+ /**
862
+ * Extracts the locale from a given URL using native URLPattern.
863
+ *
864
+ * The built-in default `/:locale/...` routing is case-insensitive because it
865
+ * canonicalizes the first path segment with `toLocale()`. Custom `urlPatterns`
866
+ * keep URLPattern's normal exact matching semantics for path segments.
867
+ *
868
+ * @param {URL|string} url - The full URL from which to extract the locale.
869
+ * @returns {Locale|undefined} The extracted locale, or undefined if no locale is found.
870
+ */
871
+ export function extractLocaleFromUrl(url) {
872
+ const urlString = typeof url === "string" ? url : url.href;
873
+ if (cachedUrl === urlString) {
874
+ return cachedLocale;
875
+ }
876
+ /** @type {Locale | undefined} */
877
+ let result;
878
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
879
+ result = defaultUrlPatternExtractLocale(url);
880
+ }
881
+ else {
882
+ const urlObj = typeof url === "string" ? new URL(url) : url;
883
+ // Iterate over URL patterns
884
+ for (const element of urlPatterns) {
885
+ for (const [locale, localizedPattern] of element.localized) {
886
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
887
+ if (match) {
888
+ result = locale;
889
+ break;
890
+ }
891
+ }
892
+ if (result)
893
+ break;
894
+ }
895
+ }
896
+ cachedUrl = urlString;
897
+ cachedLocale = result;
898
+ return result;
899
+ }
900
+ /**
901
+ * https://github.com/opral/inlang-paraglide-js/issues/381
902
+ *
903
+ * @param {URL | string} url - The full URL from which to extract the locale.
904
+ * @returns {Locale | undefined} The extracted locale, or undefined if no locale is found.
905
+ */
906
+ function defaultUrlPatternExtractLocale(url) {
907
+ const urlObj = new URL(url, "http://example.com");
908
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
909
+ return toLocale(pathSegments[0]) || baseLocale;
910
+ }
911
+
912
+ /**
913
+ * Lower-level URL localization function, primarily used in server contexts.
914
+ *
915
+ * This function is designed for server-side usage where you need precise control
916
+ * over URL localization, such as in middleware or request handlers. It works with
917
+ * URL objects and always returns absolute URLs.
918
+ *
919
+ * For client-side UI components, use `localizeHref()` instead, which provides
920
+ * a more convenient API with relative paths and automatic locale detection.
921
+ *
922
+ * @see https://paraglidejs.com/i18n-routing
923
+ *
924
+ * @example
925
+ * ```typescript
926
+ * // Server middleware example
927
+ * app.use((req, res, next) => {
928
+ * const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
929
+ * const localized = localizeUrl(url, { locale: "de" });
930
+ *
931
+ * if (localized.href !== url.href) {
932
+ * return res.redirect(localized.href);
933
+ * }
934
+ * next();
935
+ * });
936
+ * ```
937
+ *
938
+ * @example
939
+ * ```typescript
940
+ * // Using with URL patterns
941
+ * const url = new URL("https://example.com/about");
942
+ * localizeUrl(url, { locale: "de" });
943
+ * // => URL("https://example.com/de/about")
944
+ *
945
+ * // Using with domain-based localization
946
+ * const url = new URL("https://example.com/store");
947
+ * localizeUrl(url, { locale: "de" });
948
+ * // => URL("https://de.example.com/store")
949
+ * ```
950
+ *
951
+ * @param {string | URL} url - The URL to localize. If string, must be absolute.
952
+ * @param {object} [options] - Options for localization
953
+ * @param {Locale} [options.locale] - Target locale. If not provided, uses getLocale()
954
+ * @returns {URL} The localized URL, always absolute
955
+ */
956
+ export function localizeUrl(url, options) {
957
+ const targetLocale = options?.locale
958
+ ? assertIsLocale(options?.locale)
959
+ : getLocale();
960
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
961
+ return localizeUrlDefaultPattern(url, targetLocale);
962
+ }
963
+ const urlObj = typeof url === "string" ? new URL(url) : url;
964
+ // Iterate over URL patterns
965
+ for (const element of urlPatterns) {
966
+ // match localized patterns
967
+ for (const [, localizedPattern] of element.localized) {
968
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
969
+ if (!match) {
970
+ continue;
971
+ }
972
+ const targetPattern = element.localized.find(([locale]) => locale === targetLocale)?.[1];
973
+ if (!targetPattern) {
974
+ continue;
975
+ }
976
+ const localizedUrl = fillPattern(targetPattern, aggregateGroups(match), urlObj.origin);
977
+ return fillMissingUrlParts(localizedUrl, match);
978
+ }
979
+ const unlocalizedMatch = new URLPattern(element.pattern, urlObj.href).exec(urlObj.href);
980
+ if (unlocalizedMatch) {
981
+ const targetPattern = element.localized.find(([locale]) => locale === targetLocale)?.[1];
982
+ if (targetPattern) {
983
+ const localizedUrl = fillPattern(targetPattern, aggregateGroups(unlocalizedMatch), urlObj.origin);
984
+ return fillMissingUrlParts(localizedUrl, unlocalizedMatch);
985
+ }
986
+ }
987
+ }
988
+ // If no match found, return the original URL
989
+ return urlObj;
990
+ }
991
+ /**
992
+ * https://github.com/opral/inlang-paraglide-js/issues/381
993
+ *
994
+ * @param {string | URL} url
995
+ * @param {Locale} locale
996
+ * @returns {URL}
997
+ */
998
+ function localizeUrlDefaultPattern(url, locale) {
999
+ const urlObj = typeof url === "string" ? new URL(url, getUrlOrigin()) : new URL(url);
1000
+ const currentLocale = extractLocaleFromUrl(urlObj);
1001
+ // If current locale matches target locale, no change needed
1002
+ if (currentLocale === locale) {
1003
+ return urlObj;
1004
+ }
1005
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
1006
+ // If current path starts with a locale, remove it
1007
+ if (pathSegments.length > 0 && toLocale(pathSegments[0])) {
1008
+ pathSegments.shift();
1009
+ }
1010
+ // For base locale, don't add prefix
1011
+ if (locale === baseLocale) {
1012
+ urlObj.pathname = "/" + pathSegments.join("/");
1013
+ }
1014
+ else {
1015
+ // For other locales, add prefix
1016
+ urlObj.pathname = "/" + locale + "/" + pathSegments.join("/");
1017
+ }
1018
+ return urlObj;
1019
+ }
1020
+ /**
1021
+ * Low-level URL de-localization function, primarily used in server contexts.
1022
+ *
1023
+ * This function is designed for server-side usage where you need precise control
1024
+ * over URL de-localization, such as in middleware or request handlers. It works with
1025
+ * URL objects and always returns absolute URLs.
1026
+ *
1027
+ * For client-side UI components, use `deLocalizeHref()` instead, which provides
1028
+ * a more convenient API with relative paths.
1029
+ *
1030
+ * @see https://paraglidejs.com/i18n-routing
1031
+ *
1032
+ * @example
1033
+ * ```typescript
1034
+ * // Server middleware example
1035
+ * app.use((req, res, next) => {
1036
+ * const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
1037
+ * const baseUrl = deLocalizeUrl(url);
1038
+ *
1039
+ * // Store the base URL for later use
1040
+ * req.baseUrl = baseUrl;
1041
+ * next();
1042
+ * });
1043
+ * ```
1044
+ *
1045
+ * @example
1046
+ * ```typescript
1047
+ * // Using with URL patterns
1048
+ * const url = new URL("https://example.com/de/about");
1049
+ * deLocalizeUrl(url); // => URL("https://example.com/about")
1050
+ *
1051
+ * // Using with domain-based localization
1052
+ * const url = new URL("https://de.example.com/store");
1053
+ * deLocalizeUrl(url); // => URL("https://example.com/store")
1054
+ * ```
1055
+ *
1056
+ * @param {string | URL} url - The URL to de-localize. If string, must be absolute.
1057
+ * @returns {URL} The de-localized URL, always absolute
1058
+ */
1059
+ export function deLocalizeUrl(url) {
1060
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
1061
+ return deLocalizeUrlDefaultPattern(url);
1062
+ }
1063
+ const urlObj = typeof url === "string" ? new URL(url) : url;
1064
+ // Iterate over URL patterns
1065
+ for (const element of urlPatterns) {
1066
+ // Iterate over localized versions
1067
+ for (const [, localizedPattern] of element.localized) {
1068
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
1069
+ if (match) {
1070
+ // Convert localized URL back to the base pattern
1071
+ const groups = aggregateGroups(match);
1072
+ const baseUrl = fillPattern(element.pattern, groups, urlObj.origin);
1073
+ return fillMissingUrlParts(baseUrl, match);
1074
+ }
1075
+ }
1076
+ // match unlocalized pattern
1077
+ const unlocalizedMatch = new URLPattern(element.pattern, urlObj.href).exec(urlObj.href);
1078
+ if (unlocalizedMatch) {
1079
+ const baseUrl = fillPattern(element.pattern, aggregateGroups(unlocalizedMatch), urlObj.origin);
1080
+ return fillMissingUrlParts(baseUrl, unlocalizedMatch);
1081
+ }
1082
+ }
1083
+ // no match found return the original url
1084
+ return urlObj;
1085
+ }
1086
+ /**
1087
+ * De-localizes a URL using the default pattern (/:locale/*)
1088
+ * @param {string|URL} url
1089
+ * @returns {URL}
1090
+ */
1091
+ function deLocalizeUrlDefaultPattern(url) {
1092
+ const urlObj = typeof url === "string" ? new URL(url, getUrlOrigin()) : new URL(url);
1093
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
1094
+ // If first segment is a locale, remove it
1095
+ if (pathSegments.length > 0 && toLocale(pathSegments[0])) {
1096
+ urlObj.pathname = "/" + pathSegments.slice(1).join("/");
1097
+ }
1098
+ return urlObj;
1099
+ }
1100
+ /**
1101
+ * Takes matches of implicit wildcards in the UrlPattern (when a part is missing
1102
+ * it is equal to '*') and adds them back to the result of fillPattern.
1103
+ *
1104
+ * At least protocol and hostname are required to create a valid URL inside fillPattern.
1105
+ *
1106
+ * @param {URL} url
1107
+ * @param {any} match
1108
+ * @returns {URL}
1109
+ */
1110
+ function fillMissingUrlParts(url, match) {
1111
+ if (match.protocol.groups["0"]) {
1112
+ url.protocol = match.protocol.groups["0"] ?? "";
1113
+ }
1114
+ if (match.hostname.groups["0"]) {
1115
+ url.hostname = match.hostname.groups["0"] ?? "";
1116
+ }
1117
+ if (match.username.groups["0"]) {
1118
+ url.username = match.username.groups["0"] ?? "";
1119
+ }
1120
+ if (match.password.groups["0"]) {
1121
+ url.password = match.password.groups["0"] ?? "";
1122
+ }
1123
+ if (match.port.groups["0"]) {
1124
+ url.port = match.port.groups["0"] ?? "";
1125
+ }
1126
+ if (match.pathname.groups["0"]) {
1127
+ url.pathname = match.pathname.groups["0"] ?? "";
1128
+ }
1129
+ if (match.search.groups["0"]) {
1130
+ url.search = match.search.groups["0"] ?? "";
1131
+ }
1132
+ if (match.hash.groups["0"]) {
1133
+ url.hash = match.hash.groups["0"] ?? "";
1134
+ }
1135
+ return url;
1136
+ }
1137
+ /**
1138
+ * Fills a URL pattern with values for named groups, supporting all URLPattern-style modifiers.
1139
+ *
1140
+ * This function will eventually be replaced by https://github.com/whatwg/urlpattern/issues/73
1141
+ *
1142
+ * Matches:
1143
+ * - :name -> Simple
1144
+ * - :name? -> Optional
1145
+ * - :name+ -> One or more
1146
+ * - :name* -> Zero or more
1147
+ * - :name(...) -> Regex group
1148
+ * - {text} -> Group delimiter
1149
+ * - {text}? -> Optional group delimiter
1150
+ *
1151
+ * If the value is `null`, the segment is removed.
1152
+ *
1153
+ * @param {string} pattern - The URL pattern containing named groups.
1154
+ * @param {Record<string, string | null | undefined>} values - Object of values for named groups.
1155
+ * @param {string} origin - Base URL to use for URL construction.
1156
+ * @returns {URL} - The constructed URL with named groups filled.
1157
+ */
1158
+ function fillPattern(pattern, values, origin) {
1159
+ // Pre-process the pattern to handle explicit port numbers
1160
+ // This detects patterns like "http://localhost:5173" and protects the port number
1161
+ // from being interpreted as a parameter
1162
+ let processedPattern = pattern.replace(/(https?:\/\/[^:/]+):(\d+)(\/|$)/g, (_, protocol, port, slash) => {
1163
+ // Replace ":5173" with "#PORT-5173#" to protect it from parameter replacement
1164
+ return `${protocol}#PORT-${port}#${slash}`;
1165
+ });
1166
+ // First, handle group delimiters with curly braces
1167
+ let processedGroupDelimiters = processedPattern.replace(/\{([^{}]*)\}([?+*]?)/g, (_, content, modifier) => {
1168
+ // For optional group delimiters
1169
+ if (modifier === "?") {
1170
+ // For optional groups, we'll include the content
1171
+ return content;
1172
+ }
1173
+ // For non-optional group delimiters, always include the content
1174
+ return content;
1175
+ });
1176
+ // Then handle named groups
1177
+ let filled = processedGroupDelimiters.replace(/(\/?):([a-zA-Z0-9_]+)(\([^)]*\))?([?+*]?)/g, (_, slash, name, __, modifier) => {
1178
+ const value = values[name];
1179
+ if (value === null) {
1180
+ // If value is null, remove the entire segment including the preceding slash
1181
+ return "";
1182
+ }
1183
+ if (modifier === "?") {
1184
+ // Optional segment
1185
+ return value !== undefined ? `${slash}${value}` : "";
1186
+ }
1187
+ if (modifier === "+" || modifier === "*") {
1188
+ // Repeatable segments
1189
+ if (value === undefined && modifier === "+") {
1190
+ throw new Error(`Missing value for "${name}" (one or more required)`);
1191
+ }
1192
+ return value ? `${slash}${value}` : "";
1193
+ }
1194
+ // Simple named group (no modifier)
1195
+ if (value === undefined) {
1196
+ throw new Error(`Missing value for "${name}"`);
1197
+ }
1198
+ return `${slash}${value}`;
1199
+ });
1200
+ // Restore port numbers
1201
+ filled = filled.replace(/#PORT-(\d+)#/g, ":$1");
1202
+ return new URL(filled, origin);
1203
+ }
1204
+ /**
1205
+ * Aggregates named groups from various parts of the URLPattern match result.
1206
+ *
1207
+ *
1208
+ * @param {any} match - The URLPattern match result object.
1209
+ * @returns {Record<string, string | null | undefined>} An object containing all named groups from the match.
1210
+ */
1211
+ export function aggregateGroups(match) {
1212
+ return {
1213
+ ...match.hash.groups,
1214
+ ...match.hostname.groups,
1215
+ ...match.password.groups,
1216
+ ...match.pathname.groups,
1217
+ ...match.port.groups,
1218
+ ...match.protocol.groups,
1219
+ ...match.search.groups,
1220
+ ...match.username.groups,
1221
+ };
1222
+ }
1223
+
1224
+ /** @type {string | undefined} */
1225
+ let cachedRouteStrategyUrl;
1226
+ /** @type {{ match: string; strategy?: typeof strategy; exclude?: boolean } | undefined} */
1227
+ let cachedRouteStrategy;
1228
+ /**
1229
+ * Match route policy against both the public URL and its canonical URL.
1230
+ *
1231
+ * The function is deliberately separate from variables.js: configuration is
1232
+ * inert data, while canonicalization and route selection form a routing layer.
1233
+ *
1234
+ * @param {string | URL} url
1235
+ * @returns {{ match: string; strategy?: typeof strategy; exclude?: boolean } | undefined}
1236
+ */
1237
+ export function findMatchingRouteStrategy(url) {
1238
+ if (routeStrategies.length === 0) {
1239
+ return undefined;
1240
+ }
1241
+ const urlString = typeof url === "string" ? url : url.href;
1242
+ if (cachedRouteStrategyUrl === urlString) {
1243
+ return cachedRouteStrategy;
1244
+ }
1245
+ const publicUrl = new URL(urlString, "http://example.com");
1246
+ const canonicalUrl = deLocalizeUrl(publicUrl);
1247
+ const candidateUrls = canonicalUrl.href === publicUrl.href
1248
+ ? [publicUrl]
1249
+ : [publicUrl, canonicalUrl];
1250
+ let match;
1251
+ for (const candidateUrl of candidateUrls) {
1252
+ for (const routeStrategy of routeStrategies) {
1253
+ const pattern = new URLPattern(routeStrategy.match, candidateUrl.href);
1254
+ if (pattern.exec(candidateUrl.href)) {
1255
+ match = routeStrategy;
1256
+ break;
1257
+ }
1258
+ }
1259
+ if (match)
1260
+ break;
1261
+ }
1262
+ cachedRouteStrategyUrl = urlString;
1263
+ cachedRouteStrategy = match;
1264
+ return match;
1265
+ }
1266
+ /**
1267
+ * Returns the strategy to use for a specific URL.
1268
+ *
1269
+ * If no route strategy matches (or the matching rule is `exclude: true`),
1270
+ * the global strategy is returned.
1271
+ *
1272
+ * @param {string | URL} url
1273
+ * @returns {typeof strategy}
1274
+ */
1275
+ export function getStrategyForUrl(url) {
1276
+ const routeStrategy = findMatchingRouteStrategy(url);
1277
+ if (routeStrategy &&
1278
+ routeStrategy.exclude !== true &&
1279
+ Array.isArray(routeStrategy.strategy)) {
1280
+ return routeStrategy.strategy;
1281
+ }
1282
+ return strategy;
1283
+ }
1284
+ /**
1285
+ * Returns whether the given URL is excluded from middleware i18n processing.
1286
+ *
1287
+ * @param {string | URL} url
1288
+ * @returns {boolean}
1289
+ */
1290
+ export function isExcludedByRouteStrategy(url) {
1291
+ return findMatchingRouteStrategy(url)?.exclude === true;
1292
+ }
1293
+
1294
+ /**
1295
+ * @typedef {object} ShouldRedirectServerInput
1296
+ * @property {Request} request
1297
+ * @property {string | URL} [effectiveRequestUrl] - Effective request URL to use for route matching, locale detection with the URL strategy, and redirect targets.
1298
+ * @property {Locale} [locale]
1299
+ *
1300
+ * @typedef {object} ShouldRedirectClientInput
1301
+ * @property {undefined} [request]
1302
+ * @property {string | URL} [url]
1303
+ * @property {Locale} [locale]
1304
+ *
1305
+ * @typedef {ShouldRedirectServerInput | ShouldRedirectClientInput} ShouldRedirectInput
1306
+ *
1307
+ * @typedef {object} ShouldRedirectResult
1308
+ * @property {boolean} shouldRedirect - Indicates whether the consumer should perform a redirect.
1309
+ * @property {Locale} locale - Locale resolved using the configured strategies.
1310
+ * @property {URL | undefined} redirectUrl - Destination URL when a redirect is required.
1311
+ */
1312
+ /**
1313
+ * Determines whether a redirect is required to align the current URL with the active locale.
1314
+ *
1315
+ * This helper mirrors the logic that powers `paraglideMiddleware`, but works in both server
1316
+ * and client environments. It evaluates the configured strategies in order, computes the
1317
+ * canonical localized URL, and reports when the current URL does not match.
1318
+ *
1319
+ * When called in the browser without arguments, the current `window.location.href` is used.
1320
+ *
1321
+ * @see https://paraglidejs.com/i18n-routing#redirects
1322
+ *
1323
+ * @example
1324
+ * // Client side usage (e.g. TanStack Router beforeLoad hook)
1325
+ * async function beforeLoad({ location }) {
1326
+ * const decision = await shouldRedirect({ url: location.href });
1327
+ *
1328
+ * if (decision.shouldRedirect) {
1329
+ * throw redirect({ to: decision.redirectUrl.href });
1330
+ * }
1331
+ * }
1332
+ *
1333
+ * @example
1334
+ * // Server side usage with a Request
1335
+ * export async function handle(request) {
1336
+ * const decision = await shouldRedirect({ request });
1337
+ *
1338
+ * if (decision.shouldRedirect) {
1339
+ * return Response.redirect(decision.redirectUrl, 307);
1340
+ * }
1341
+ *
1342
+ * return render(request, decision.locale);
1343
+ * }
1344
+ *
1345
+ * @example
1346
+ * // Server side usage behind a proxy where request.url is not public-facing
1347
+ * export async function handle(request) {
1348
+ * const effectiveRequestUrl = new URL(request.url);
1349
+ * effectiveRequestUrl.protocol = "https:";
1350
+ * effectiveRequestUrl.host = "example.com";
1351
+ *
1352
+ * const decision = await shouldRedirect({
1353
+ * request,
1354
+ * effectiveRequestUrl,
1355
+ * });
1356
+ *
1357
+ * if (decision.shouldRedirect) {
1358
+ * return Response.redirect(decision.redirectUrl, 307);
1359
+ * }
1360
+ * }
1361
+ *
1362
+ * @param {ShouldRedirectInput} [input]
1363
+ * @returns {Promise<ShouldRedirectResult>}
1364
+ */
1365
+ export async function shouldRedirect(input = {}) {
1366
+ const currentUrl = resolveUrl(input);
1367
+ const locale = await resolveLocale(input, currentUrl);
1368
+ const strategy = getStrategyForUrl(currentUrl.href);
1369
+ if (isExcludedByRouteStrategy(currentUrl.href) || !strategy.includes("url")) {
1370
+ return { shouldRedirect: false, locale, redirectUrl: undefined };
1371
+ }
1372
+ const localizedUrl = localizeUrl(currentUrl.href, { locale });
1373
+ const shouldRedirectToLocalizedUrl = normalizeUrl(localizedUrl.href) !== normalizeUrl(currentUrl.href);
1374
+ return {
1375
+ shouldRedirect: shouldRedirectToLocalizedUrl,
1376
+ locale,
1377
+ redirectUrl: shouldRedirectToLocalizedUrl ? localizedUrl : undefined,
1378
+ };
1379
+ }
1380
+ /**
1381
+ * Resolves the locale either from the provided input or by using the configured strategies.
1382
+ *
1383
+ * @param {ShouldRedirectInput} input
1384
+ * @param {URL} currentUrl
1385
+ * @returns {Promise<Locale>}
1386
+ */
1387
+ async function resolveLocale(input, currentUrl) {
1388
+ const locale = toLocale(input.locale);
1389
+ if (locale) {
1390
+ return locale;
1391
+ }
1392
+ if (input.request) {
1393
+ return extractLocaleFromRequestAsync(input.request, {
1394
+ effectiveRequestUrl: currentUrl,
1395
+ });
1396
+ }
1397
+ if ("url" in input && typeof input.url !== "undefined") {
1398
+ return getLocaleForUrl(currentUrl.href);
1399
+ }
1400
+ return getLocale();
1401
+ }
1402
+ /**
1403
+ * Resolves the current URL from the provided input or runtime context.
1404
+ *
1405
+ * @param {ShouldRedirectInput} input
1406
+ * @returns {URL}
1407
+ */
1408
+ function resolveUrl(input) {
1409
+ if ("effectiveRequestUrl" in input &&
1410
+ input.effectiveRequestUrl instanceof URL) {
1411
+ return new URL(input.effectiveRequestUrl.href);
1412
+ }
1413
+ if ("effectiveRequestUrl" in input &&
1414
+ typeof input.effectiveRequestUrl === "string") {
1415
+ return new URL(input.effectiveRequestUrl, input.request ? input.request.url : getUrlOrigin());
1416
+ }
1417
+ if (input.request) {
1418
+ return new URL(input.request.url);
1419
+ }
1420
+ if ("url" in input && input.url instanceof URL) {
1421
+ return new URL(input.url.href);
1422
+ }
1423
+ if ("url" in input && typeof input.url === "string") {
1424
+ return new URL(input.url, getUrlOrigin());
1425
+ }
1426
+ if (typeof window !== "undefined" && window?.location?.href) {
1427
+ return new URL(window.location.href);
1428
+ }
1429
+ throw new Error("shouldRedirect() requires either a request, an absolute URL, or must run in a browser environment.");
1430
+ }
1431
+ /**
1432
+ * Normalize url for comparison by stripping the trailing slash.
1433
+ *
1434
+ * @param {string} url
1435
+ * @returns {string}
1436
+ */
1437
+ function normalizeUrl(url) {
1438
+ const urlObj = new URL(url);
1439
+ urlObj.pathname = urlObj.pathname.replace(/\/$/, "");
1440
+ return urlObj.href;
1441
+ }
1442
+
1443
+ /**
1444
+ * High-level URL localization function optimized for client-side UI usage.
1445
+ *
1446
+ * This is a convenience wrapper around `localizeUrl()` that provides features
1447
+ * needed in UI:
1448
+ *
1449
+ * - Accepts relative paths (e.g., "/about")
1450
+ * - Returns relative paths when possible
1451
+ * - Automatically detects current locale if not specified
1452
+ * - Handles string input/output instead of URL objects
1453
+ *
1454
+ * @see https://paraglidejs.com/i18n-routing
1455
+ *
1456
+ * @example
1457
+ * ```typescript
1458
+ * // In a React/Vue/Svelte component
1459
+ * const NavLink = ({ href }) => {
1460
+ * // Automatically uses current locale, keeps path relative
1461
+ * return <a href={localizeHref(href)}>...</a>;
1462
+ * };
1463
+ *
1464
+ * // Examples:
1465
+ * localizeHref("/about")
1466
+ * // => "/de/about" (if current locale is "de")
1467
+ * localizeHref("/store", { locale: "fr" })
1468
+ * // => "/fr/store" (explicit locale)
1469
+ *
1470
+ * // Cross-origin links remain absolute
1471
+ * localizeHref("https://other-site.com/about")
1472
+ * // => "https://other-site.com/de/about"
1473
+ * ```
1474
+ *
1475
+ * For server-side URL localization (e.g., in middleware), use `localizeUrl()`
1476
+ * which provides more precise control over URL handling.
1477
+ *
1478
+ * @param {string} href - The href to localize (can be relative or absolute)
1479
+ * @param {object} [options] - Options for localization
1480
+ * @param {Locale} [options.locale] - Target locale. If not provided, uses `getLocale()`
1481
+ * @returns {string} The localized href, relative if input was relative
1482
+ */
1483
+ export function localizeHref(href, options) {
1484
+ const currentLocale = getLocale();
1485
+ const locale = options?.locale ?? currentLocale;
1486
+ const url = new URL(href, getUrlOrigin());
1487
+ const localized = localizeUrl(url, { locale });
1488
+ // if the origin is identical and the href is relative,
1489
+ // return the relative path
1490
+ if (href.startsWith("/") && url.origin === localized.origin) {
1491
+ // check for cross origin localization in which case an absolute URL must be returned.
1492
+ if (locale !== currentLocale) {
1493
+ const localizedCurrentLocale = localizeUrl(url, {
1494
+ locale: currentLocale,
1495
+ });
1496
+ if (localizedCurrentLocale.origin !== localized.origin) {
1497
+ return localized.href;
1498
+ }
1499
+ }
1500
+ return localized.pathname + localized.search + localized.hash;
1501
+ }
1502
+ return localized.href;
1503
+ }
1504
+ /**
1505
+ * High-level URL de-localization function optimized for client-side UI usage.
1506
+ *
1507
+ * This is a convenience wrapper around `deLocalizeUrl()` that provides features
1508
+ * needed in the UI:
1509
+ *
1510
+ * - Accepts relative paths (e.g., "/de/about")
1511
+ * - Returns relative paths when possible
1512
+ * - Handles string input/output instead of URL objects
1513
+ *
1514
+ * @see https://paraglidejs.com/i18n-routing
1515
+ *
1516
+ * @example
1517
+ * ```typescript
1518
+ * // In a React/Vue/Svelte component
1519
+ * const LocaleSwitcher = ({ href }) => {
1520
+ * // Remove locale prefix before switching
1521
+ * const baseHref = deLocalizeHref(href);
1522
+ * return locales.map(locale =>
1523
+ * <a href={localizeHref(baseHref, { locale })}>
1524
+ * Switch to {locale}
1525
+ * </a>
1526
+ * );
1527
+ * };
1528
+ *
1529
+ * // Examples:
1530
+ * deLocalizeHref("/de/about") // => "/about"
1531
+ * deLocalizeHref("/fr/store") // => "/store"
1532
+ *
1533
+ * // Cross-origin links remain absolute
1534
+ * deLocalizeHref("https://example.com/de/about")
1535
+ * // => "https://example.com/about"
1536
+ * ```
1537
+ *
1538
+ * For server-side URL de-localization (e.g., in middleware), use `deLocalizeUrl()`
1539
+ * which provides more precise control over URL handling.
1540
+ *
1541
+ * @param {string} href - The href to de-localize (can be relative or absolute)
1542
+ * @returns {string} The de-localized href, relative if input was relative
1543
+ */
1544
+ export function deLocalizeHref(href) {
1545
+ const url = new URL(href, getUrlOrigin());
1546
+ const deLocalized = deLocalizeUrl(url);
1547
+ // If the origin is identical and the href is relative,
1548
+ // return the relative path instead of the full URL.
1549
+ if (href.startsWith("/") && url.origin === deLocalized.origin) {
1550
+ return deLocalized.pathname + deLocalized.search + deLocalized.hash;
1551
+ }
1552
+ return deLocalized.href;
1553
+ }
1554
+
1555
+ /**
1556
+ * @param {string} safeModuleId
1557
+ * @param {Locale} locale
1558
+ */
1559
+ export function trackMessageCall(safeModuleId, locale) {
1560
+ if (isServer === false)
1561
+ return;
1562
+ const store = serverAsyncLocalStorage?.getStore();
1563
+ if (store) {
1564
+ store.messageCalls?.add(`${safeModuleId}:${locale}`);
1565
+ }
1566
+ }
1567
+
1568
+ /**
1569
+ * Generates localized URL variants for all provided URLs based on your configured locales and URL patterns.
1570
+ *
1571
+ * This function is essential for Static Site Generation (SSG) where you need to tell your framework
1572
+ * which pages to pre-render at build time. It's also useful for generating sitemaps and
1573
+ * `<link rel="alternate" hreflang>` tags for SEO.
1574
+ *
1575
+ * The function respects your `urlPatterns` configuration - if you have translated pathnames
1576
+ * (e.g., `/about` → `/ueber-uns` for German), it will generate the correct localized paths.
1577
+ *
1578
+ * @see https://paraglidejs.com/static-site-generation
1579
+ *
1580
+ * @example
1581
+ * // Basic usage - generate all locale variants for a list of paths
1582
+ * const localizedUrls = generateStaticLocalizedUrls([
1583
+ * "/",
1584
+ * "/about",
1585
+ * "/blog/post-1",
1586
+ * ]);
1587
+ * // Returns URL objects for each locale:
1588
+ * // ["/en/", "/de/", "/en/about", "/de/about", "/en/blog/post-1", "/de/blog/post-1"]
1589
+ *
1590
+ * @example
1591
+ * // Use with framework SSG APIs
1592
+ * // SvelteKit
1593
+ * export function entries() {
1594
+ * const paths = ["/", "/about", "/contact"];
1595
+ * return generateStaticLocalizedUrls(paths).map(url => ({
1596
+ * locale: extractLocaleFromUrl(url)
1597
+ * }));
1598
+ * }
1599
+ *
1600
+ * @example
1601
+ * // Sitemap generation
1602
+ * const allPages = ["/", "/about", "/blog"];
1603
+ * const sitemapUrls = generateStaticLocalizedUrls(allPages);
1604
+ *
1605
+ * @param {(string | URL)[]} urls - List of canonical URLs or paths to generate localized versions for.
1606
+ * Can be absolute URLs (`https://example.com/about`) or paths (`/about`).
1607
+ * Paths are resolved against `http://localhost` internally.
1608
+ * @returns {URL[]} Array of URL objects representing all localized variants.
1609
+ * The order follows each input URL with all its locale variants before moving to the next URL.
1610
+ */
1611
+ export function generateStaticLocalizedUrls(urls) {
1612
+ /** @type {Set<URL>} */
1613
+ const localizedUrls = new Set();
1614
+ // For default URL pattern, we can optimize the generation
1615
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
1616
+ for (const urlInput of urls) {
1617
+ const url = urlInput instanceof URL
1618
+ ? urlInput
1619
+ : new URL(urlInput, "http://localhost");
1620
+ // Base locale doesn't get a prefix
1621
+ localizedUrls.add(url);
1622
+ // Other locales get their code as prefix
1623
+ for (const locale of locales) {
1624
+ if (locale !== baseLocale) {
1625
+ const localizedPath = `/${locale}${url.pathname}${url.search}${url.hash}`;
1626
+ const localizedUrl = new URL(localizedPath, url.origin);
1627
+ localizedUrls.add(localizedUrl);
1628
+ }
1629
+ }
1630
+ }
1631
+ return Array.from(localizedUrls);
1632
+ }
1633
+ // For custom URL patterns, we need to use localizeUrl for each URL and locale
1634
+ for (const urlInput of urls) {
1635
+ const url = urlInput instanceof URL
1636
+ ? urlInput
1637
+ : new URL(urlInput, "http://localhost");
1638
+ // Try each URL pattern to find one that matches
1639
+ let patternFound = false;
1640
+ for (const pattern of urlPatterns) {
1641
+ try {
1642
+ // Try to match the unlocalized pattern
1643
+ const unlocalizedMatch = new URLPattern(pattern.pattern, url.href).exec(url.href);
1644
+ if (!unlocalizedMatch)
1645
+ continue;
1646
+ patternFound = true;
1647
+ // Track unique localized URLs to avoid duplicates when patterns are the same
1648
+ const seenUrls = new Set();
1649
+ // Generate localized URL for each locale
1650
+ for (const [locale] of pattern.localized) {
1651
+ try {
1652
+ const localizedUrl = localizeUrl(url, { locale });
1653
+ const urlString = localizedUrl.href;
1654
+ // Only add if we haven't seen this exact URL before
1655
+ if (!seenUrls.has(urlString)) {
1656
+ seenUrls.add(urlString);
1657
+ localizedUrls.add(localizedUrl);
1658
+ }
1659
+ }
1660
+ catch {
1661
+ // Skip if localization fails for this locale
1662
+ continue;
1663
+ }
1664
+ }
1665
+ break;
1666
+ }
1667
+ catch {
1668
+ // Skip if pattern matching fails
1669
+ continue;
1670
+ }
1671
+ }
1672
+ // If no pattern matched, use the URL as is
1673
+ if (!patternFound) {
1674
+ localizedUrls.add(url);
1675
+ }
1676
+ }
1677
+ return Array.from(localizedUrls);
1678
+ }
1679
+
1680
+ /**
1681
+ * @typedef {"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage"} BuiltInStrategy
1682
+ */
1683
+ /**
1684
+ * @typedef {`custom_${string}`} CustomStrategy
1685
+ */
1686
+ /**
1687
+ * @typedef {BuiltInStrategy | CustomStrategy} Strategy
1688
+ */
1689
+ /**
1690
+ * @typedef {Array<Strategy>} Strategies
1691
+ */
1692
+ /**
1693
+ * @typedef {{ getLocale: (request?: Request) => Promise<string | undefined> | (string | undefined) }} CustomServerStrategyHandler
1694
+ */
1695
+ /**
1696
+ * @typedef {{ getLocale: () => Promise<string|undefined> | (string | undefined), setLocale: (locale: string) => Promise<void> | void }} CustomClientStrategyHandler
1697
+ */
1698
+ /** @type {Map<string, CustomServerStrategyHandler>} */
1699
+ export const customServerStrategies = new Map();
1700
+ /** @type {Map<string, CustomClientStrategyHandler>} */
1701
+ export const customClientStrategies = new Map();
1702
+ /**
1703
+ * Checks if the given strategy is a custom strategy.
1704
+ *
1705
+ * @param {unknown} strategy The name of the custom strategy to validate.
1706
+ * Must be a string that starts with "custom-" followed by alphanumeric characters, hyphens, or underscores.
1707
+ * @returns {boolean} Returns true if it is a custom strategy, false otherwise.
1708
+ */
1709
+ export function isCustomStrategy(strategy) {
1710
+ return (typeof strategy === "string" && /^custom-[A-Za-z0-9_-]+$/.test(strategy));
1711
+ }
1712
+ /**
1713
+ * Defines a custom strategy that is executed on the server.
1714
+ *
1715
+ * @see https://paraglidejs.com/strategy#write-your-own-strategy
1716
+ *
1717
+ * @param {string} strategy The name of the custom strategy to define. Must follow the pattern custom-name with alphanumeric characters, hyphens, or underscores.
1718
+ * @param {CustomServerStrategyHandler} handler The handler for the custom strategy, which should implement
1719
+ * the method getLocale.
1720
+ * @returns {void}
1721
+ */
1722
+ export function defineCustomServerStrategy(strategy, handler) {
1723
+ if (!isCustomStrategy(strategy)) {
1724
+ throw new Error(`Invalid custom strategy: "${strategy}". Must be a custom strategy following the pattern custom-name.`);
1725
+ }
1726
+ customServerStrategies.set(strategy, handler);
1727
+ }
1728
+ /**
1729
+ * Defines a custom strategy that is executed on the client.
1730
+ *
1731
+ * @see https://paraglidejs.com/strategy#write-your-own-strategy
1732
+ *
1733
+ * @param {string} strategy The name of the custom strategy to define. Must follow the pattern custom-name with alphanumeric characters, hyphens, or underscores.
1734
+ * @param {CustomClientStrategyHandler} handler The handler for the custom strategy, which should implement the
1735
+ * methods getLocale and setLocale.
1736
+ * @returns {void}
1737
+ */
1738
+ export function defineCustomClientStrategy(strategy, handler) {
1739
+ if (!isCustomStrategy(strategy)) {
1740
+ throw new Error(`Invalid custom strategy: "${strategy}". Must be a custom strategy following the pattern custom-name.`);
1741
+ }
1742
+ customClientStrategies.set(strategy, handler);
1743
+ }
1744
+
1745
+ // ------ TYPES ------
1746
+ export {};
1747
+ /**
1748
+ * A locale that is available in the project.
1749
+ *
1750
+ * @example
1751
+ * setLocale(request.locale as Locale)
1752
+ *
1753
+ * @typedef {typeof locales[number]} Locale
1754
+ */
1755
+ /**
1756
+ * A branded type representing a localized string.
1757
+ *
1758
+ * Message functions return this type instead of \`string\`, enabling TypeScript
1759
+ * to distinguish translated strings from regular strings at compile time.
1760
+ * This allows you to enforce that only properly localized content is used
1761
+ * in your UI components.
1762
+ *
1763
+ * Since \`LocalizedString\` is a branded subtype of \`string\`, it remains fully
1764
+ * backward compatible—you can pass it anywhere a \`string\` is expected.
1765
+ *
1766
+ * @example
1767
+ * // Enforce localized strings in your components
1768
+ * function PageTitle(props: { title: LocalizedString }) {
1769
+ * return <h1>{props.title}</h1>
1770
+ * }
1771
+ *
1772
+ * // ✅ Correct: using a message function
1773
+ * <PageTitle title={m.welcome_title()} />
1774
+ *
1775
+ * // ❌ Type error: raw strings are not LocalizedString
1776
+ * <PageTitle title="Welcome" />
1777
+ *
1778
+ * @example
1779
+ * // LocalizedString is assignable to string (backward compatible)
1780
+ * const localized: LocalizedString = m.greeting()
1781
+ * const str: string = localized // ✅ works fine
1782
+ *
1783
+ * // But string is not assignable to LocalizedString
1784
+ * const raw: LocalizedString = "Hello" // ❌ Type error
1785
+ *
1786
+ * @example
1787
+ * // Catches accidental string concatenation
1788
+ * function showMessage(msg: LocalizedString) { ... }
1789
+ *
1790
+ * showMessage(m.hello()) // ✅
1791
+ * showMessage("Hello " + userName) // ❌ Type error
1792
+ * showMessage(m.hello_user({ name: userName })) // ✅ use params instead
1793
+ *
1794
+ * @typedef {string & { readonly __brand: 'LocalizedString' }} LocalizedString
1795
+ */
1796
+ /**
1797
+ * A single markup option passed to a tag instance.
1798
+ *
1799
+ * @typedef {{
1800
+ * name: string;
1801
+ * value: unknown;
1802
+ * }} MessageMarkupOption
1803
+ */
1804
+ /**
1805
+ * A single static markup attribute attached to a tag instance.
1806
+ *
1807
+ * @typedef {{
1808
+ * name: string;
1809
+ * value: string | true;
1810
+ * }} MessageMarkupAttribute
1811
+ */
1812
+ /**
1813
+ * Record of markup options for a tag instance.
1814
+ *
1815
+ * @typedef {Record<string, unknown>} MessageMarkupOptions
1816
+ */
1817
+ /**
1818
+ * Record of markup attributes for a tag instance.
1819
+ *
1820
+ * @typedef {Record<string, string | true>} MessageMarkupAttributes
1821
+ */
1822
+ /**
1823
+ * Type-level schema for a single markup tag.
1824
+ *
1825
+ * @typedef {{
1826
+ * options: MessageMarkupOptions;
1827
+ * attributes: MessageMarkupAttributes;
1828
+ * children: boolean;
1829
+ * }} MessageMarkupTag
1830
+ */
1831
+ /**
1832
+ * Type-level schema for all markup tags in a message.
1833
+ *
1834
+ * @typedef {Record<string, MessageMarkupTag>} MessageMarkupSchema
1835
+ */
1836
+ /**
1837
+ * Type-only metadata attached to compiled message functions.
1838
+ *
1839
+ * @template Inputs
1840
+ * @template Options
1841
+ * @template {MessageMarkupSchema} [Markup = MessageMarkupSchema]
1842
+ * @typedef {{
1843
+ * readonly __paraglide?: {
1844
+ * inputs: Inputs;
1845
+ * options: Options;
1846
+ * markup: Markup;
1847
+ * };
1848
+ * }} MessageMetadata
1849
+ */
1850
+ /**
1851
+ * A compiled, framework-neutral message part.
1852
+ *
1853
+ * @typedef {{
1854
+ * type: "text";
1855
+ * value: string;
1856
+ * } | {
1857
+ * type: "markup-start";
1858
+ * name: string;
1859
+ * options: MessageMarkupOptions;
1860
+ * attributes: MessageMarkupAttributes;
1861
+ * } | {
1862
+ * type: "markup-end";
1863
+ * name: string;
1864
+ * options: MessageMarkupOptions;
1865
+ * attributes: MessageMarkupAttributes;
1866
+ * } | {
1867
+ * type: "markup-standalone";
1868
+ * name: string;
1869
+ * options: MessageMarkupOptions;
1870
+ * attributes: MessageMarkupAttributes;
1871
+ * }} MessagePart
1872
+ */
1873
+ /**
1874
+ * A message function is a message for a specific locale.
1875
+ *
1876
+ * @example
1877
+ * m.hello({ name: 'world' })
1878
+ *
1879
+ * @typedef {(inputs?: Record<string, never>) => LocalizedString} MessageFunction
1880
+ */
1881
+ /**
1882
+ * A message bundle function that selects the message to be returned.
1883
+ *
1884
+ * Uses `getLocale()` under the hood to determine the locale with an option.
1885
+ *
1886
+ * @template {string} T
1887
+ *
1888
+ * @example
1889
+ * * m.hello({ name: 'world' }, { locale: "en" })
1890
+ *
1891
+ * @typedef {(params: Record<string, never>, options: { locale: T }) => LocalizedString} MessageBundleFunction
1892
+ */