@nr1e/commons 0.4.8 → 0.4.9

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