includio-cms 0.1.2 → 0.1.4

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 (58) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/ROADMAP.md +9 -0
  3. package/dist/admin/api/accept-invite.d.ts +2 -0
  4. package/dist/admin/api/accept-invite.js +30 -0
  5. package/dist/admin/api/handler.d.ts +13 -0
  6. package/dist/admin/api/handler.js +36 -0
  7. package/dist/admin/api/invite.d.ts +5 -0
  8. package/dist/admin/api/invite.js +78 -0
  9. package/dist/admin/client/collection/collection-entries.svelte +4 -0
  10. package/dist/admin/client/collection/collection-page.svelte +5 -7
  11. package/dist/admin/client/collection/collection-page.svelte.d.ts +2 -2
  12. package/dist/admin/client/entry/entry-page.svelte +5 -7
  13. package/dist/admin/client/entry/entry-page.svelte.d.ts +2 -2
  14. package/dist/admin/client/index.d.ts +1 -0
  15. package/dist/admin/client/index.js +1 -0
  16. package/dist/cli/index.d.ts +2 -0
  17. package/dist/cli/index.js +28 -0
  18. package/dist/cli/scaffold/admin.d.ts +4 -0
  19. package/dist/cli/scaffold/admin.js +185 -0
  20. package/dist/components/ui/accordion/accordion.svelte.d.ts +1 -1
  21. package/dist/components/ui/calendar/calendar.svelte.d.ts +1 -1
  22. package/dist/components/ui/command/command-dialog.svelte.d.ts +1 -1
  23. package/dist/components/ui/command/command-input.svelte.d.ts +1 -1
  24. package/dist/components/ui/command/command.svelte.d.ts +1 -1
  25. package/dist/components/ui/dropdown-menu/dropdown-menu-radio-group.svelte.d.ts +1 -1
  26. package/dist/components/ui/input/input.svelte.d.ts +1 -1
  27. package/dist/components/ui/input-group/input-group-input.svelte.d.ts +1 -1
  28. package/dist/components/ui/input-group/input-group-textarea.svelte.d.ts +1 -1
  29. package/dist/components/ui/radio-group/radio-group.svelte.d.ts +1 -1
  30. package/dist/components/ui/sidebar/sidebar-input.svelte.d.ts +1 -1
  31. package/dist/components/ui/tabs/tabs.svelte.d.ts +1 -1
  32. package/dist/components/ui/textarea/textarea.svelte.d.ts +1 -1
  33. package/dist/components/ui/toggle-group/toggle-group-item.svelte.d.ts +1 -1
  34. package/dist/components/ui/toggle-group/toggle-group.svelte.d.ts +1 -1
  35. package/dist/core/cms.d.ts +2 -0
  36. package/dist/core/cms.js +2 -0
  37. package/dist/paraglide/.prettierignore +3 -0
  38. package/dist/paraglide/messages/_index.d.ts +36 -0
  39. package/dist/paraglide/messages/_index.js +72 -0
  40. package/dist/paraglide/messages/en.d.ts +5 -0
  41. package/dist/paraglide/messages/en.js +14 -0
  42. package/dist/paraglide/messages/pl.d.ts +5 -0
  43. package/dist/paraglide/messages/pl.js +14 -0
  44. package/dist/paraglide/messages.d.ts +2 -0
  45. package/dist/paraglide/messages.js +4 -0
  46. package/dist/paraglide/registry.d.ts +21 -0
  47. package/dist/paraglide/registry.js +31 -0
  48. package/dist/paraglide/runtime.d.ts +583 -0
  49. package/dist/paraglide/runtime.js +1402 -0
  50. package/dist/paraglide/server.d.ts +67 -0
  51. package/dist/paraglide/server.js +175 -0
  52. package/dist/types/cms.d.ts +18 -0
  53. package/dist/updates/0.1.3/index.d.ts +2 -0
  54. package/dist/updates/0.1.3/index.js +16 -0
  55. package/dist/updates/0.1.4/index.d.ts +2 -0
  56. package/dist/updates/0.1.4/index.js +11 -0
  57. package/dist/updates/index.js +3 -1
  58. package/package.json +11 -3
@@ -0,0 +1,1402 @@
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", "pl"]);
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
+ * The used URL patterns.
42
+ *
43
+ * @type {Array<{ pattern: string, localized: Array<[Locale, string]> }> }
44
+ */
45
+ export const urlPatterns = [
46
+ {
47
+ "pattern": ":protocol://:domain(.*)::port?/:path(.*)?",
48
+ "localized": [
49
+ [
50
+ "pl",
51
+ ":protocol://:domain(.*)::port?/pl/:path(.*)?"
52
+ ],
53
+ [
54
+ "en",
55
+ ":protocol://:domain(.*)::port?/:path(.*)?"
56
+ ]
57
+ ]
58
+ }
59
+ ];
60
+ /**
61
+ * @typedef {{
62
+ * getStore(): {
63
+ * locale?: Locale,
64
+ * origin?: string,
65
+ * messageCalls?: Set<string>
66
+ * } | undefined,
67
+ * run: (store: { locale?: Locale, origin?: string, messageCalls?: Set<string>},
68
+ * cb: any) => any
69
+ * }} ParaglideAsyncLocalStorage
70
+ */
71
+ /**
72
+ * Server side async local storage that is set by `serverMiddleware()`.
73
+ *
74
+ * The variable is used to retrieve the locale and origin in a server-side
75
+ * rendering context without effecting other requests.
76
+ *
77
+ * @type {ParaglideAsyncLocalStorage | undefined}
78
+ */
79
+ export let serverAsyncLocalStorage = undefined;
80
+ export const disableAsyncLocalStorage = false;
81
+ export const experimentalMiddlewareLocaleSplitting = false;
82
+ export const isServer = import.meta.env?.SSR ?? typeof window === 'undefined';
83
+ /**
84
+ * Sets the server side async local storage.
85
+ *
86
+ * The function is needed because the `runtime.js` file
87
+ * must define the `serverAsyncLocalStorage` variable to
88
+ * avoid a circular import between `runtime.js` and
89
+ * `server.js` files.
90
+ *
91
+ * @param {ParaglideAsyncLocalStorage | undefined} value
92
+ */
93
+ export function overwriteServerAsyncLocalStorage(value) {
94
+ serverAsyncLocalStorage = value;
95
+ }
96
+ const TREE_SHAKE_COOKIE_STRATEGY_USED = true;
97
+ const TREE_SHAKE_URL_STRATEGY_USED = false;
98
+ const TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED = true;
99
+ const TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED = false;
100
+ const TREE_SHAKE_DEFAULT_URL_PATTERN_USED = true;
101
+ const TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED = false;
102
+
103
+ globalThis.__paraglide = {}
104
+
105
+ /**
106
+ * This is a fallback to get started with a custom
107
+ * strategy and avoid type errors.
108
+ *
109
+ * The implementation is overwritten
110
+ * by \`overwriteGetLocale()\` and \`defineSetLocale()\`.
111
+ *
112
+ * @type {Locale|undefined}
113
+ */
114
+ let _locale;
115
+ let localeInitiallySet = false;
116
+ /**
117
+ * Get the current locale.
118
+ *
119
+ * @example
120
+ * if (getLocale() === 'de') {
121
+ * console.log('Germany 🇩🇪');
122
+ * } else if (getLocale() === 'nl') {
123
+ * console.log('Netherlands 🇳🇱');
124
+ * }
125
+ *
126
+ * @type {() => Locale}
127
+ */
128
+ export let getLocale = () => {
129
+ /** @type {string | undefined} */
130
+ let locale;
131
+ // if running in a server-side rendering context
132
+ // retrieve the locale from the async local storage
133
+ if (serverAsyncLocalStorage) {
134
+ const locale = serverAsyncLocalStorage?.getStore()?.locale;
135
+ if (locale) {
136
+ return locale;
137
+ }
138
+ }
139
+ for (const strat of strategy) {
140
+ if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
141
+ locale = extractLocaleFromCookie();
142
+ }
143
+ else if (strat === "baseLocale") {
144
+ locale = baseLocale;
145
+ }
146
+ else if (TREE_SHAKE_URL_STRATEGY_USED &&
147
+ strat === "url" &&
148
+ !isServer &&
149
+ typeof window !== "undefined") {
150
+ locale = extractLocaleFromUrl(window.location.href);
151
+ }
152
+ else if (TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED &&
153
+ strat === "globalVariable" &&
154
+ _locale !== undefined) {
155
+ locale = _locale;
156
+ }
157
+ else if (TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED &&
158
+ strat === "preferredLanguage" &&
159
+ !isServer) {
160
+ locale = extractLocaleFromNavigator();
161
+ }
162
+ else if (TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED &&
163
+ strat === "localStorage" &&
164
+ !isServer) {
165
+ locale = localStorage.getItem(localStorageKey) ?? undefined;
166
+ }
167
+ else if (isCustomStrategy(strat) && customClientStrategies.has(strat)) {
168
+ const handler = customClientStrategies.get(strat);
169
+ if (handler) {
170
+ const result = handler.getLocale();
171
+ // Handle both sync and async results - skip async in sync getLocale
172
+ if (result instanceof Promise) {
173
+ // Can't await in sync function, skip async strategies
174
+ continue;
175
+ }
176
+ locale = result;
177
+ }
178
+ }
179
+ // check if match, else continue loop
180
+ if (locale !== undefined) {
181
+ const asserted = assertIsLocale(locale);
182
+ if (!localeInitiallySet) {
183
+ _locale = asserted;
184
+ // https://github.com/opral/inlang-paraglide-js/issues/455
185
+ localeInitiallySet = true;
186
+ setLocale(asserted, { reload: false });
187
+ }
188
+ return asserted;
189
+ }
190
+ }
191
+ throw new Error("No locale found. Read the docs https://inlang.com/m/gerre34r/library-inlang-paraglideJs/errors#no-locale-found");
192
+ };
193
+ /**
194
+ * Overwrite the \`getLocale()\` function.
195
+ *
196
+ * Use this function to overwrite how the locale is resolved. For example,
197
+ * you can resolve the locale from the browser's preferred language,
198
+ * a cookie, env variable, or a user's preference.
199
+ *
200
+ * @example
201
+ * overwriteGetLocale(() => {
202
+ * // resolve the locale from a cookie. fallback to the base locale.
203
+ * return Cookies.get('locale') ?? baseLocale
204
+ * }
205
+ *
206
+ * @type {(fn: () => Locale) => void}
207
+ */
208
+ export const overwriteGetLocale = (fn) => {
209
+ getLocale = fn;
210
+ };
211
+
212
+ /**
213
+ * Navigates to the localized URL, or reloads the current page
214
+ *
215
+ * @param {string} [newLocation] The new location
216
+ * @return {undefined}
217
+ */
218
+ const navigateOrReload = (newLocation) => {
219
+ if (newLocation) {
220
+ // reload the page by navigating to the new url
221
+ window.location.href = newLocation;
222
+ }
223
+ else {
224
+ // reload the page to reflect the new locale
225
+ window.location.reload();
226
+ }
227
+ };
228
+ /**
229
+ * @typedef {(newLocale: Locale, options?: { reload?: boolean }) => void | Promise<void>} SetLocaleFn
230
+ */
231
+ /**
232
+ * Set the locale.
233
+ *
234
+ * Set locale reloads the site by default on the client. Reloading
235
+ * can be disabled by passing \`reload: false\` as an option. If
236
+ * reloading is disabled, you need to ensure that the UI is updated
237
+ * to reflect the new locale.
238
+ *
239
+ * If any custom strategy's \`setLocale\` function is async, then this
240
+ * function will become async as well.
241
+ *
242
+ * @example
243
+ * setLocale('en');
244
+ *
245
+ * @example
246
+ * setLocale('en', { reload: false });
247
+ *
248
+ * @type {SetLocaleFn}
249
+ */
250
+ export let setLocale = (newLocale, options) => {
251
+ const optionsWithDefaults = {
252
+ reload: true,
253
+ ...options,
254
+ };
255
+ // locale is already set
256
+ // https://github.com/opral/inlang-paraglide-js/issues/430
257
+ /** @type {Locale | undefined} */
258
+ let currentLocale;
259
+ try {
260
+ currentLocale = getLocale();
261
+ }
262
+ catch {
263
+ // do nothing, no locale has been set yet.
264
+ }
265
+ /** @type {Array<Promise<any>>} */
266
+ const customSetLocalePromises = [];
267
+ /** @type {string | undefined} */
268
+ let newLocation = undefined;
269
+ for (const strat of strategy) {
270
+ if (TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED &&
271
+ strat === "globalVariable") {
272
+ // a default for a custom strategy to get started quickly
273
+ // is likely overwritten by `defineSetLocale()`
274
+ _locale = newLocale;
275
+ }
276
+ else if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
277
+ if (isServer ||
278
+ typeof document === "undefined" ||
279
+ typeof window === "undefined") {
280
+ continue;
281
+ }
282
+ // set the cookie
283
+ const cookieString = `${cookieName}=${newLocale}; path=/; max-age=${cookieMaxAge}`;
284
+ document.cookie = cookieDomain
285
+ ? `${cookieString}; domain=${cookieDomain}`
286
+ : cookieString;
287
+ }
288
+ else if (strat === "baseLocale") {
289
+ // nothing to be set here. baseLocale is only a fallback
290
+ continue;
291
+ }
292
+ else if (TREE_SHAKE_URL_STRATEGY_USED &&
293
+ strat === "url" &&
294
+ typeof window !== "undefined") {
295
+ // route to the new url
296
+ //
297
+ // this triggers a page reload but a user rarely
298
+ // switches locales, so this should be fine.
299
+ //
300
+ // if the behavior is not desired, the implementation
301
+ // can be overwritten by `defineSetLocale()` to avoid
302
+ // a full page reload.
303
+ newLocation = localizeUrl(window.location.href, {
304
+ locale: newLocale,
305
+ }).href;
306
+ }
307
+ else if (TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED &&
308
+ strat === "localStorage" &&
309
+ typeof window !== "undefined") {
310
+ // set the localStorage
311
+ localStorage.setItem(localStorageKey, newLocale);
312
+ }
313
+ else if (isCustomStrategy(strat) && customClientStrategies.has(strat)) {
314
+ const handler = customClientStrategies.get(strat);
315
+ if (handler) {
316
+ let result = handler.setLocale(newLocale);
317
+ // Handle async setLocale
318
+ if (result instanceof Promise) {
319
+ result = result.catch((error) => {
320
+ throw new Error(`Custom strategy "${strat}" setLocale failed.`, {
321
+ cause: error,
322
+ });
323
+ });
324
+ customSetLocalePromises.push(result);
325
+ }
326
+ }
327
+ }
328
+ }
329
+ const runReload = () => {
330
+ if (!isServer &&
331
+ optionsWithDefaults.reload &&
332
+ window.location &&
333
+ newLocale !== currentLocale) {
334
+ navigateOrReload(newLocation);
335
+ }
336
+ };
337
+ if (customSetLocalePromises.length) {
338
+ return Promise.all(customSetLocalePromises).then(() => {
339
+ runReload();
340
+ });
341
+ }
342
+ runReload();
343
+ return;
344
+ };
345
+ /**
346
+ * Overwrite the \`setLocale()\` function.
347
+ *
348
+ * Use this function to overwrite how the locale is set. For example,
349
+ * modify a cookie, env variable, or a user's preference.
350
+ *
351
+ * @example
352
+ * overwriteSetLocale((newLocale) => {
353
+ * // set the locale in a cookie
354
+ * return Cookies.set('locale', newLocale)
355
+ * });
356
+ *
357
+ * @param {SetLocaleFn} fn
358
+ */
359
+ export const overwriteSetLocale = (fn) => {
360
+ setLocale = /** @type {SetLocaleFn} */ (fn);
361
+ };
362
+
363
+ /**
364
+ * The origin of the current URL.
365
+ *
366
+ * Defaults to "http://y.com" in non-browser environments. If this
367
+ * behavior is not desired, the implementation can be overwritten
368
+ * by `overwriteGetUrlOrigin()`.
369
+ *
370
+ * @type {() => string}
371
+ */
372
+ export let getUrlOrigin = () => {
373
+ if (serverAsyncLocalStorage) {
374
+ return serverAsyncLocalStorage.getStore()?.origin ?? "http://fallback.com";
375
+ }
376
+ else if (typeof window !== "undefined") {
377
+ return window.location.origin;
378
+ }
379
+ return "http://fallback.com";
380
+ };
381
+ /**
382
+ * Overwrite the getUrlOrigin function.
383
+ *
384
+ * Use this function in server environments to
385
+ * define how the URL origin is resolved.
386
+ *
387
+ * @type {(fn: () => string) => void}
388
+ */
389
+ export let overwriteGetUrlOrigin = (fn) => {
390
+ getUrlOrigin = fn;
391
+ };
392
+
393
+ /**
394
+ * Check if something is an available locale.
395
+ *
396
+ * @example
397
+ * if (isLocale(params.locale)) {
398
+ * setLocale(params.locale);
399
+ * } else {
400
+ * setLocale('en');
401
+ * }
402
+ *
403
+ * @param {any} locale
404
+ * @returns {locale is Locale}
405
+ */
406
+ export function isLocale(locale) {
407
+ return !locale ? false : locales.includes(locale);
408
+ }
409
+
410
+ /**
411
+ * Asserts that the input is a locale.
412
+ *
413
+ * @param {any} input - The input to check.
414
+ * @returns {Locale} The input if it is a locale.
415
+ * @throws {Error} If the input is not a locale.
416
+ */
417
+ export function assertIsLocale(input) {
418
+ if (isLocale(input) === false) {
419
+ throw new Error(`Invalid locale: ${input}. Expected one of: ${locales.join(", ")}`);
420
+ }
421
+ return input;
422
+ }
423
+
424
+ /**
425
+ * Extracts a locale from a request.
426
+ *
427
+ * Use the function on the server to extract the locale
428
+ * from a request.
429
+ *
430
+ * The function goes through the strategies in the order
431
+ * they are defined. If a strategy returns an invalid locale,
432
+ * it will fall back to the next strategy.
433
+ *
434
+ * Note: Custom server strategies are not supported in this synchronous version.
435
+ * Use `extractLocaleFromRequestAsync` if you need custom server strategies with async getLocale methods.
436
+ *
437
+ * @example
438
+ * const locale = extractLocaleFromRequest(request);
439
+ *
440
+ * @type {(request: Request) => Locale}
441
+ */
442
+ export const extractLocaleFromRequest = (request) => {
443
+ /** @type {string|undefined} */
444
+ let locale;
445
+ for (const strat of strategy) {
446
+ if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
447
+ locale = request.headers
448
+ .get("cookie")
449
+ ?.split("; ")
450
+ .find((c) => c.startsWith(cookieName + "="))
451
+ ?.split("=")[1];
452
+ }
453
+ else if (TREE_SHAKE_URL_STRATEGY_USED && strat === "url") {
454
+ locale = extractLocaleFromUrl(request.url);
455
+ }
456
+ else if (TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED &&
457
+ strat === "preferredLanguage") {
458
+ locale = extractLocaleFromHeader(request);
459
+ }
460
+ else if (strat === "globalVariable") {
461
+ locale = _locale;
462
+ }
463
+ else if (strat === "baseLocale") {
464
+ return baseLocale;
465
+ }
466
+ else if (strat === "localStorage") {
467
+ continue;
468
+ }
469
+ else if (isCustomStrategy(strat)) {
470
+ // Custom strategies are not supported in sync version
471
+ // Use extractLocaleFromRequestAsync for custom server strategies
472
+ continue;
473
+ }
474
+ if (locale !== undefined) {
475
+ if (!isLocale(locale)) {
476
+ locale = undefined;
477
+ }
478
+ else {
479
+ return assertIsLocale(locale);
480
+ }
481
+ }
482
+ }
483
+ 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");
484
+ };
485
+
486
+ /**
487
+ * Asynchronously extracts a locale from a request.
488
+ *
489
+ * This function supports async custom server strategies, unlike the synchronous
490
+ * `extractLocaleFromRequest`. Use this function when you have custom server strategies
491
+ * that need to perform asynchronous operations (like database calls) in their getLocale method.
492
+ *
493
+ * The function first processes any custom server strategies asynchronously, then falls back
494
+ * to the synchronous `extractLocaleFromRequest` for all other strategies.
495
+ *
496
+ * @see {@link https://github.com/opral/inlang-paraglide-js/issues/527#issuecomment-2978151022}
497
+ *
498
+ * @example
499
+ * // Basic usage
500
+ * const locale = await extractLocaleFromRequestAsync(request);
501
+ *
502
+ * @example
503
+ * // With custom async server strategy
504
+ * defineCustomServerStrategy("custom-database", {
505
+ * getLocale: async (request) => {
506
+ * const userId = extractUserIdFromRequest(request);
507
+ * return await getUserLocaleFromDatabase(userId);
508
+ * }
509
+ * });
510
+ *
511
+ * const locale = await extractLocaleFromRequestAsync(request);
512
+ *
513
+ * @type {(request: Request) => Promise<Locale>}
514
+ */
515
+ export const extractLocaleFromRequestAsync = async (request) => {
516
+ /** @type {string|undefined} */
517
+ let locale;
518
+ // Process custom strategies first, in order
519
+ for (const strat of strategy) {
520
+ if (isCustomStrategy(strat) && customServerStrategies.has(strat)) {
521
+ const handler = customServerStrategies.get(strat);
522
+ if (handler) {
523
+ /** @type {string|undefined} */
524
+ locale = await handler.getLocale(request);
525
+ }
526
+ // If we got a valid locale from this custom strategy, use it
527
+ if (locale !== undefined && isLocale(locale)) {
528
+ return assertIsLocale(locale);
529
+ }
530
+ }
531
+ }
532
+ // If no custom strategy provided a valid locale, fall back to sync version
533
+ locale = extractLocaleFromRequest(request);
534
+ return assertIsLocale(locale);
535
+ };
536
+
537
+ /**
538
+ * Extracts a cookie from the document.
539
+ *
540
+ * Will return undefined if the document is not available or if the cookie is not set.
541
+ * The `document` object is not available in server-side rendering, so this function should not be called in that context.
542
+ *
543
+ * @returns {string | undefined}
544
+ */
545
+ export function extractLocaleFromCookie() {
546
+ if (typeof document === "undefined" || !document.cookie) {
547
+ return;
548
+ }
549
+ const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));
550
+ const locale = match?.[2];
551
+ if (isLocale(locale)) {
552
+ return locale;
553
+ }
554
+ return undefined;
555
+ }
556
+
557
+ /**
558
+ * Extracts a locale from the accept-language header.
559
+ *
560
+ * Use the function on the server to extract the locale
561
+ * from the accept-language header that is sent by the client.
562
+ *
563
+ * @example
564
+ * const locale = extractLocaleFromHeader(request);
565
+ *
566
+ * @type {(request: Request) => Locale}
567
+ * @param {Request} request - The request object to extract the locale from.
568
+ * @returns {string|undefined} The negotiated preferred language.
569
+ */
570
+ export function extractLocaleFromHeader(request) {
571
+ const acceptLanguageHeader = request.headers.get("accept-language");
572
+ if (acceptLanguageHeader) {
573
+ // Parse language preferences with their q-values and base language codes
574
+ const languages = acceptLanguageHeader
575
+ .split(",")
576
+ .map((lang) => {
577
+ const [tag, q = "1"] = lang.trim().split(";q=");
578
+ // Get both the full tag and base language code
579
+ const baseTag = tag?.split("-")[0]?.toLowerCase();
580
+ return {
581
+ fullTag: tag?.toLowerCase(),
582
+ baseTag,
583
+ q: Number(q),
584
+ };
585
+ })
586
+ .sort((a, b) => b.q - a.q);
587
+ for (const lang of languages) {
588
+ if (isLocale(lang.fullTag)) {
589
+ return lang.fullTag;
590
+ }
591
+ else if (isLocale(lang.baseTag)) {
592
+ return lang.baseTag;
593
+ }
594
+ }
595
+ return undefined;
596
+ }
597
+ return undefined;
598
+ }
599
+
600
+ /**
601
+ * Negotiates a preferred language from navigator.languages.
602
+ *
603
+ * Use the function on the client to extract the locale
604
+ * from the navigator.languages array.
605
+ *
606
+ * @example
607
+ * const locale = extractLocaleFromNavigator();
608
+ *
609
+ * @type {() => Locale | undefined}
610
+ * @returns {string | undefined}
611
+ */
612
+ export function extractLocaleFromNavigator() {
613
+ if (!navigator?.languages?.length) {
614
+ return undefined;
615
+ }
616
+ const languages = navigator.languages.map((lang) => ({
617
+ fullTag: lang.toLowerCase(),
618
+ baseTag: lang.split("-")[0]?.toLowerCase(),
619
+ }));
620
+ for (const lang of languages) {
621
+ if (isLocale(lang.fullTag)) {
622
+ return lang.fullTag;
623
+ }
624
+ else if (isLocale(lang.baseTag)) {
625
+ return lang.baseTag;
626
+ }
627
+ }
628
+ return undefined;
629
+ }
630
+
631
+ /**
632
+ * If extractLocaleFromUrl is called many times on the same page and the URL
633
+ * hasn't changed, we don't need to recompute it every time which can get expensive.
634
+ * We might use a LRU cache if needed, but for now storing only the last result is enough.
635
+ * https://github.com/opral/monorepo/pull/3575#discussion_r2066731243
636
+ */
637
+ /** @type {string|undefined} */
638
+ let cachedUrl;
639
+ /** @type {Locale|undefined} */
640
+ let cachedLocale;
641
+ /**
642
+ * Extracts the locale from a given URL using native URLPattern.
643
+ *
644
+ * @param {URL|string} url - The full URL from which to extract the locale.
645
+ * @returns {Locale|undefined} The extracted locale, or undefined if no locale is found.
646
+ */
647
+ export function extractLocaleFromUrl(url) {
648
+ const urlString = typeof url === "string" ? url : url.href;
649
+ if (cachedUrl === urlString) {
650
+ return cachedLocale;
651
+ }
652
+ let result;
653
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
654
+ result = defaultUrlPatternExtractLocale(url);
655
+ }
656
+ else {
657
+ const urlObj = typeof url === "string" ? new URL(url) : url;
658
+ // Iterate over URL patterns
659
+ for (const element of urlPatterns) {
660
+ for (const [locale, localizedPattern] of element.localized) {
661
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
662
+ if (!match) {
663
+ continue;
664
+ }
665
+ // Check if the locale is valid
666
+ if (assertIsLocale(locale)) {
667
+ result = locale;
668
+ break;
669
+ }
670
+ }
671
+ if (result)
672
+ break;
673
+ }
674
+ }
675
+ cachedUrl = urlString;
676
+ cachedLocale = result;
677
+ return result;
678
+ }
679
+ /**
680
+ * https://github.com/opral/inlang-paraglide-js/issues/381
681
+ *
682
+ * @param {URL|string} url - The full URL from which to extract the locale.
683
+ * @returns {Locale|undefined} The extracted locale, or undefined if no locale is found.
684
+ */
685
+ function defaultUrlPatternExtractLocale(url) {
686
+ const urlObj = new URL(url, "http://dummy.com");
687
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
688
+ if (pathSegments.length > 0) {
689
+ const potentialLocale = pathSegments[0];
690
+ if (isLocale(potentialLocale)) {
691
+ return potentialLocale;
692
+ }
693
+ }
694
+ // everything else has to be the base locale
695
+ return baseLocale;
696
+ }
697
+
698
+ /**
699
+ * Lower-level URL localization function, primarily used in server contexts.
700
+ *
701
+ * This function is designed for server-side usage where you need precise control
702
+ * over URL localization, such as in middleware or request handlers. It works with
703
+ * URL objects and always returns absolute URLs.
704
+ *
705
+ * For client-side UI components, use `localizeHref()` instead, which provides
706
+ * a more convenient API with relative paths and automatic locale detection.
707
+ *
708
+ * @example
709
+ * ```typescript
710
+ * // Server middleware example
711
+ * app.use((req, res, next) => {
712
+ * const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
713
+ * const localized = localizeUrl(url, { locale: "de" });
714
+ *
715
+ * if (localized.href !== url.href) {
716
+ * return res.redirect(localized.href);
717
+ * }
718
+ * next();
719
+ * });
720
+ * ```
721
+ *
722
+ * @example
723
+ * ```typescript
724
+ * // Using with URL patterns
725
+ * const url = new URL("https://example.com/about");
726
+ * localizeUrl(url, { locale: "de" });
727
+ * // => URL("https://example.com/de/about")
728
+ *
729
+ * // Using with domain-based localization
730
+ * const url = new URL("https://example.com/store");
731
+ * localizeUrl(url, { locale: "de" });
732
+ * // => URL("https://de.example.com/store")
733
+ * ```
734
+ *
735
+ * @param {string | URL} url - The URL to localize. If string, must be absolute.
736
+ * @param {Object} [options] - Options for localization
737
+ * @param {string} [options.locale] - Target locale. If not provided, uses getLocale()
738
+ * @returns {URL} The localized URL, always absolute
739
+ */
740
+ export function localizeUrl(url, options) {
741
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
742
+ return localizeUrlDefaultPattern(url, options);
743
+ }
744
+ const targetLocale = options?.locale ?? getLocale();
745
+ const urlObj = typeof url === "string" ? new URL(url) : url;
746
+ // Iterate over URL patterns
747
+ for (const element of urlPatterns) {
748
+ // match localized patterns
749
+ for (const [, localizedPattern] of element.localized) {
750
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
751
+ if (!match) {
752
+ continue;
753
+ }
754
+ const targetPattern = element.localized.find(([locale]) => locale === targetLocale)?.[1];
755
+ if (!targetPattern) {
756
+ continue;
757
+ }
758
+ const localizedUrl = fillPattern(targetPattern, aggregateGroups(match), urlObj.origin);
759
+ return fillMissingUrlParts(localizedUrl, match);
760
+ }
761
+ const unlocalizedMatch = new URLPattern(element.pattern, urlObj.href).exec(urlObj.href);
762
+ if (unlocalizedMatch) {
763
+ const targetPattern = element.localized.find(([locale]) => locale === targetLocale)?.[1];
764
+ if (targetPattern) {
765
+ const localizedUrl = fillPattern(targetPattern, aggregateGroups(unlocalizedMatch), urlObj.origin);
766
+ return fillMissingUrlParts(localizedUrl, unlocalizedMatch);
767
+ }
768
+ }
769
+ }
770
+ // If no match found, return the original URL
771
+ return urlObj;
772
+ }
773
+ /**
774
+ * https://github.com/opral/inlang-paraglide-js/issues/381
775
+ *
776
+ * @param {string | URL} url
777
+ * @param {Object} [options]
778
+ * @param {string} [options.locale]
779
+ * @returns {URL}
780
+ */
781
+ function localizeUrlDefaultPattern(url, options) {
782
+ const urlObj = typeof url === "string" ? new URL(url, getUrlOrigin()) : new URL(url);
783
+ const locale = options?.locale ?? getLocale();
784
+ const currentLocale = extractLocaleFromUrl(urlObj);
785
+ // If current locale matches target locale, no change needed
786
+ if (currentLocale === locale) {
787
+ return urlObj;
788
+ }
789
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
790
+ // If current path starts with a locale, remove it
791
+ if (pathSegments.length > 0 && isLocale(pathSegments[0])) {
792
+ pathSegments.shift();
793
+ }
794
+ // For base locale, don't add prefix
795
+ if (locale === baseLocale) {
796
+ urlObj.pathname = "/" + pathSegments.join("/");
797
+ }
798
+ else {
799
+ // For other locales, add prefix
800
+ urlObj.pathname = "/" + locale + "/" + pathSegments.join("/");
801
+ }
802
+ return urlObj;
803
+ }
804
+ /**
805
+ * Low-level URL de-localization function, primarily used in server contexts.
806
+ *
807
+ * This function is designed for server-side usage where you need precise control
808
+ * over URL de-localization, such as in middleware or request handlers. It works with
809
+ * URL objects and always returns absolute URLs.
810
+ *
811
+ * For client-side UI components, use `deLocalizeHref()` instead, which provides
812
+ * a more convenient API with relative paths.
813
+ *
814
+ * @example
815
+ * ```typescript
816
+ * // Server middleware example
817
+ * app.use((req, res, next) => {
818
+ * const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
819
+ * const baseUrl = deLocalizeUrl(url);
820
+ *
821
+ * // Store the base URL for later use
822
+ * req.baseUrl = baseUrl;
823
+ * next();
824
+ * });
825
+ * ```
826
+ *
827
+ * @example
828
+ * ```typescript
829
+ * // Using with URL patterns
830
+ * const url = new URL("https://example.com/de/about");
831
+ * deLocalizeUrl(url); // => URL("https://example.com/about")
832
+ *
833
+ * // Using with domain-based localization
834
+ * const url = new URL("https://de.example.com/store");
835
+ * deLocalizeUrl(url); // => URL("https://example.com/store")
836
+ * ```
837
+ *
838
+ * @param {string | URL} url - The URL to de-localize. If string, must be absolute.
839
+ * @returns {URL} The de-localized URL, always absolute
840
+ */
841
+ export function deLocalizeUrl(url) {
842
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
843
+ return deLocalizeUrlDefaultPattern(url);
844
+ }
845
+ const urlObj = typeof url === "string" ? new URL(url) : url;
846
+ // Iterate over URL patterns
847
+ for (const element of urlPatterns) {
848
+ // Iterate over localized versions
849
+ for (const [, localizedPattern] of element.localized) {
850
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
851
+ if (match) {
852
+ // Convert localized URL back to the base pattern
853
+ const groups = aggregateGroups(match);
854
+ const baseUrl = fillPattern(element.pattern, groups, urlObj.origin);
855
+ return fillMissingUrlParts(baseUrl, match);
856
+ }
857
+ }
858
+ // match unlocalized pattern
859
+ const unlocalizedMatch = new URLPattern(element.pattern, urlObj.href).exec(urlObj.href);
860
+ if (unlocalizedMatch) {
861
+ const baseUrl = fillPattern(element.pattern, aggregateGroups(unlocalizedMatch), urlObj.origin);
862
+ return fillMissingUrlParts(baseUrl, unlocalizedMatch);
863
+ }
864
+ }
865
+ // no match found return the original url
866
+ return urlObj;
867
+ }
868
+ /**
869
+ * De-localizes a URL using the default pattern (/:locale/*)
870
+ * @param {string|URL} url
871
+ * @returns {URL}
872
+ */
873
+ function deLocalizeUrlDefaultPattern(url) {
874
+ const urlObj = typeof url === "string" ? new URL(url, getUrlOrigin()) : new URL(url);
875
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
876
+ // If first segment is a locale, remove it
877
+ if (pathSegments.length > 0 && isLocale(pathSegments[0])) {
878
+ urlObj.pathname = "/" + pathSegments.slice(1).join("/");
879
+ }
880
+ return urlObj;
881
+ }
882
+ /**
883
+ * Takes matches of implicit wildcards in the UrlPattern (when a part is missing
884
+ * it is equal to '*') and adds them back to the result of fillPattern.
885
+ *
886
+ * At least protocol and hostname are required to create a valid URL inside fillPattern.
887
+ *
888
+ * @param {URL} url
889
+ * @param {any} match
890
+ * @returns {URL}
891
+ */
892
+ function fillMissingUrlParts(url, match) {
893
+ if (match.protocol.groups["0"]) {
894
+ url.protocol = match.protocol.groups["0"] ?? "";
895
+ }
896
+ if (match.hostname.groups["0"]) {
897
+ url.hostname = match.hostname.groups["0"] ?? "";
898
+ }
899
+ if (match.username.groups["0"]) {
900
+ url.username = match.username.groups["0"] ?? "";
901
+ }
902
+ if (match.password.groups["0"]) {
903
+ url.password = match.password.groups["0"] ?? "";
904
+ }
905
+ if (match.port.groups["0"]) {
906
+ url.port = match.port.groups["0"] ?? "";
907
+ }
908
+ if (match.pathname.groups["0"]) {
909
+ url.pathname = match.pathname.groups["0"] ?? "";
910
+ }
911
+ if (match.search.groups["0"]) {
912
+ url.search = match.search.groups["0"] ?? "";
913
+ }
914
+ if (match.hash.groups["0"]) {
915
+ url.hash = match.hash.groups["0"] ?? "";
916
+ }
917
+ return url;
918
+ }
919
+ /**
920
+ * Fills a URL pattern with values for named groups, supporting all URLPattern-style modifiers.
921
+ *
922
+ * This function will eventually be replaced by https://github.com/whatwg/urlpattern/issues/73
923
+ *
924
+ * Matches:
925
+ * - :name -> Simple
926
+ * - :name? -> Optional
927
+ * - :name+ -> One or more
928
+ * - :name* -> Zero or more
929
+ * - :name(...) -> Regex group
930
+ * - {text} -> Group delimiter
931
+ * - {text}? -> Optional group delimiter
932
+ *
933
+ * If the value is `null`, the segment is removed.
934
+ *
935
+ * @param {string} pattern - The URL pattern containing named groups.
936
+ * @param {Record<string, string | null | undefined>} values - Object of values for named groups.
937
+ * @param {string} origin - Base URL to use for URL construction.
938
+ * @returns {URL} - The constructed URL with named groups filled.
939
+ */
940
+ function fillPattern(pattern, values, origin) {
941
+ // Pre-process the pattern to handle explicit port numbers
942
+ // This detects patterns like "http://localhost:5173" and protects the port number
943
+ // from being interpreted as a parameter
944
+ let processedPattern = pattern.replace(/(https?:\/\/[^:/]+):(\d+)(\/|$)/g, (_, protocol, port, slash) => {
945
+ // Replace ":5173" with "#PORT-5173#" to protect it from parameter replacement
946
+ return `${protocol}#PORT-${port}#${slash}`;
947
+ });
948
+ // First, handle group delimiters with curly braces
949
+ let processedGroupDelimiters = processedPattern.replace(/\{([^{}]*)\}([?+*]?)/g, (_, content, modifier) => {
950
+ // For optional group delimiters
951
+ if (modifier === "?") {
952
+ // For optional groups, we'll include the content
953
+ return content;
954
+ }
955
+ // For non-optional group delimiters, always include the content
956
+ return content;
957
+ });
958
+ // Then handle named groups
959
+ let filled = processedGroupDelimiters.replace(/(\/?):([a-zA-Z0-9_]+)(\([^)]*\))?([?+*]?)/g, (_, slash, name, __, modifier) => {
960
+ const value = values[name];
961
+ if (value === null) {
962
+ // If value is null, remove the entire segment including the preceding slash
963
+ return "";
964
+ }
965
+ if (modifier === "?") {
966
+ // Optional segment
967
+ return value !== undefined ? `${slash}${value}` : "";
968
+ }
969
+ if (modifier === "+" || modifier === "*") {
970
+ // Repeatable segments
971
+ if (value === undefined && modifier === "+") {
972
+ throw new Error(`Missing value for "${name}" (one or more required)`);
973
+ }
974
+ return value ? `${slash}${value}` : "";
975
+ }
976
+ // Simple named group (no modifier)
977
+ if (value === undefined) {
978
+ throw new Error(`Missing value for "${name}"`);
979
+ }
980
+ return `${slash}${value}`;
981
+ });
982
+ // Restore port numbers
983
+ filled = filled.replace(/#PORT-(\d+)#/g, ":$1");
984
+ return new URL(filled, origin);
985
+ }
986
+ /**
987
+ * Aggregates named groups from various parts of the URLPattern match result.
988
+ *
989
+ *
990
+ * @type {(match: any) => Record<string, string | null | undefined>}
991
+ */
992
+ export function aggregateGroups(match) {
993
+ return {
994
+ ...match.hash.groups,
995
+ ...match.hostname.groups,
996
+ ...match.password.groups,
997
+ ...match.pathname.groups,
998
+ ...match.port.groups,
999
+ ...match.protocol.groups,
1000
+ ...match.search.groups,
1001
+ ...match.username.groups,
1002
+ };
1003
+ }
1004
+
1005
+ /**
1006
+ * @typedef {object} ShouldRedirectServerInput
1007
+ * @property {Request} request
1008
+ * @property {string | URL} [url]
1009
+ * @property {ReturnType<typeof assertIsLocale>} [locale]
1010
+ *
1011
+ * @typedef {object} ShouldRedirectClientInput
1012
+ * @property {undefined} [request]
1013
+ * @property {string | URL} [url]
1014
+ * @property {ReturnType<typeof assertIsLocale>} [locale]
1015
+ *
1016
+ * @typedef {ShouldRedirectServerInput | ShouldRedirectClientInput} ShouldRedirectInput
1017
+ *
1018
+ * @typedef {object} ShouldRedirectResult
1019
+ * @property {boolean} shouldRedirect - Indicates whether the consumer should perform a redirect.
1020
+ * @property {ReturnType<typeof assertIsLocale>} locale - Locale resolved using the configured strategies.
1021
+ * @property {URL | undefined} redirectUrl - Destination URL when a redirect is required.
1022
+ */
1023
+ /**
1024
+ * Determines whether a redirect is required to align the current URL with the active locale.
1025
+ *
1026
+ * This helper mirrors the logic that powers `paraglideMiddleware`, but works in both server
1027
+ * and client environments. It evaluates the configured strategies in order, computes the
1028
+ * canonical localized URL, and reports when the current URL does not match.
1029
+ *
1030
+ * When called in the browser without arguments, the current `window.location.href` is used.
1031
+ *
1032
+ * @example
1033
+ * // Client side usage (e.g. TanStack Router beforeLoad hook)
1034
+ * async function beforeLoad({ location }) {
1035
+ * const decision = await shouldRedirect({ url: location.href });
1036
+ *
1037
+ * if (decision.shouldRedirect) {
1038
+ * throw redirect({ to: decision.redirectUrl.href });
1039
+ * }
1040
+ * }
1041
+ *
1042
+ * @example
1043
+ * // Server side usage with a Request
1044
+ * export async function handle(request) {
1045
+ * const decision = await shouldRedirect({ request });
1046
+ *
1047
+ * if (decision.shouldRedirect) {
1048
+ * return Response.redirect(decision.redirectUrl, 307);
1049
+ * }
1050
+ *
1051
+ * return render(request, decision.locale);
1052
+ * }
1053
+ *
1054
+ * @param {ShouldRedirectInput} [input]
1055
+ * @returns {Promise<ShouldRedirectResult>}
1056
+ */
1057
+ export async function shouldRedirect(input = {}) {
1058
+ const locale = /** @type {ReturnType<typeof assertIsLocale>} */ (await resolveLocale(input));
1059
+ if (!strategy.includes("url")) {
1060
+ return { shouldRedirect: false, locale, redirectUrl: undefined };
1061
+ }
1062
+ const currentUrl = resolveUrl(input);
1063
+ const localizedUrl = localizeUrl(currentUrl.href, { locale });
1064
+ const shouldRedirectToLocalizedUrl = normalizeUrl(localizedUrl.href) !== normalizeUrl(currentUrl.href);
1065
+ return {
1066
+ shouldRedirect: shouldRedirectToLocalizedUrl,
1067
+ locale,
1068
+ redirectUrl: shouldRedirectToLocalizedUrl ? localizedUrl : undefined,
1069
+ };
1070
+ }
1071
+ /**
1072
+ * Resolves the locale either from the provided input or by using the configured strategies.
1073
+ *
1074
+ * @param {ShouldRedirectInput} input
1075
+ * @returns {Promise<ReturnType<typeof assertIsLocale>>}
1076
+ */
1077
+ async function resolveLocale(input) {
1078
+ if (input.locale) {
1079
+ return assertIsLocale(input.locale);
1080
+ }
1081
+ if (input.request) {
1082
+ return extractLocaleFromRequestAsync(input.request);
1083
+ }
1084
+ return getLocale();
1085
+ }
1086
+ /**
1087
+ * Resolves the current URL from the provided input or runtime context.
1088
+ *
1089
+ * @param {ShouldRedirectInput} input
1090
+ * @returns {URL}
1091
+ */
1092
+ function resolveUrl(input) {
1093
+ if (input.request) {
1094
+ return new URL(input.request.url);
1095
+ }
1096
+ if (input.url instanceof URL) {
1097
+ return new URL(input.url.href);
1098
+ }
1099
+ if (typeof input.url === "string") {
1100
+ return new URL(input.url, getUrlOrigin());
1101
+ }
1102
+ if (typeof window !== "undefined" && window?.location?.href) {
1103
+ return new URL(window.location.href);
1104
+ }
1105
+ throw new Error("shouldRedirect() requires either a request, an absolute URL, or must run in a browser environment.");
1106
+ }
1107
+ /**
1108
+ * Normalize url for comparison by stripping the trailing slash.
1109
+ *
1110
+ * @param {string} url
1111
+ * @returns {string}
1112
+ */
1113
+ function normalizeUrl(url) {
1114
+ const urlObj = new URL(url);
1115
+ urlObj.pathname = urlObj.pathname.replace(/\/$/, "");
1116
+ return urlObj.href;
1117
+ }
1118
+
1119
+ /**
1120
+ * High-level URL localization function optimized for client-side UI usage.
1121
+ *
1122
+ * This is a convenience wrapper around `localizeUrl()` that provides features
1123
+ * needed in UI:
1124
+ *
1125
+ * - Accepts relative paths (e.g., "/about")
1126
+ * - Returns relative paths when possible
1127
+ * - Automatically detects current locale if not specified
1128
+ * - Handles string input/output instead of URL objects
1129
+ *
1130
+ * @example
1131
+ * ```typescript
1132
+ * // In a React/Vue/Svelte component
1133
+ * const NavLink = ({ href }) => {
1134
+ * // Automatically uses current locale, keeps path relative
1135
+ * return <a href={localizeHref(href)}>...</a>;
1136
+ * };
1137
+ *
1138
+ * // Examples:
1139
+ * localizeHref("/about")
1140
+ * // => "/de/about" (if current locale is "de")
1141
+ * localizeHref("/store", { locale: "fr" })
1142
+ * // => "/fr/store" (explicit locale)
1143
+ *
1144
+ * // Cross-origin links remain absolute
1145
+ * localizeHref("https://other-site.com/about")
1146
+ * // => "https://other-site.com/de/about"
1147
+ * ```
1148
+ *
1149
+ * For server-side URL localization (e.g., in middleware), use `localizeUrl()`
1150
+ * which provides more precise control over URL handling.
1151
+ *
1152
+ * @param {string} href - The href to localize (can be relative or absolute)
1153
+ * @param {Object} [options] - Options for localization
1154
+ * @param {string} [options.locale] - Target locale. If not provided, uses `getLocale()`
1155
+ * @returns {string} The localized href, relative if input was relative
1156
+ */
1157
+ export function localizeHref(href, options) {
1158
+ const currentLocale = getLocale();
1159
+ const locale = options?.locale ?? currentLocale;
1160
+ const url = new URL(href, getUrlOrigin());
1161
+ const localized = localizeUrl(url, { locale });
1162
+ // if the origin is identical and the href is relative,
1163
+ // return the relative path
1164
+ if (href.startsWith("/") && url.origin === localized.origin) {
1165
+ // check for cross origin localization in which case an absolute URL must be returned.
1166
+ if (locale !== currentLocale) {
1167
+ const localizedCurrentLocale = localizeUrl(url, {
1168
+ locale: currentLocale,
1169
+ });
1170
+ if (localizedCurrentLocale.origin !== localized.origin) {
1171
+ return localized.href;
1172
+ }
1173
+ }
1174
+ return localized.pathname + localized.search + localized.hash;
1175
+ }
1176
+ return localized.href;
1177
+ }
1178
+ /**
1179
+ * High-level URL de-localization function optimized for client-side UI usage.
1180
+ *
1181
+ * This is a convenience wrapper around `deLocalizeUrl()` that provides features
1182
+ * needed in the UI:
1183
+ *
1184
+ * - Accepts relative paths (e.g., "/de/about")
1185
+ * - Returns relative paths when possible
1186
+ * - Handles string input/output instead of URL objects
1187
+ *
1188
+ * @example
1189
+ * ```typescript
1190
+ * // In a React/Vue/Svelte component
1191
+ * const LocaleSwitcher = ({ href }) => {
1192
+ * // Remove locale prefix before switching
1193
+ * const baseHref = deLocalizeHref(href);
1194
+ * return locales.map(locale =>
1195
+ * <a href={localizeHref(baseHref, { locale })}>
1196
+ * Switch to {locale}
1197
+ * </a>
1198
+ * );
1199
+ * };
1200
+ *
1201
+ * // Examples:
1202
+ * deLocalizeHref("/de/about") // => "/about"
1203
+ * deLocalizeHref("/fr/store") // => "/store"
1204
+ *
1205
+ * // Cross-origin links remain absolute
1206
+ * deLocalizeHref("https://example.com/de/about")
1207
+ * // => "https://example.com/about"
1208
+ * ```
1209
+ *
1210
+ * For server-side URL de-localization (e.g., in middleware), use `deLocalizeUrl()`
1211
+ * which provides more precise control over URL handling.
1212
+ *
1213
+ * @param {string} href - The href to de-localize (can be relative or absolute)
1214
+ * @returns {string} The de-localized href, relative if input was relative
1215
+ * @see deLocalizeUrl - For low-level URL de-localization in server contexts
1216
+ */
1217
+ export function deLocalizeHref(href) {
1218
+ const url = new URL(href, getUrlOrigin());
1219
+ const deLocalized = deLocalizeUrl(url);
1220
+ // If the origin is identical and the href is relative,
1221
+ // return the relative path instead of the full URL.
1222
+ if (href.startsWith("/") && url.origin === deLocalized.origin) {
1223
+ return deLocalized.pathname + deLocalized.search + deLocalized.hash;
1224
+ }
1225
+ return deLocalized.href;
1226
+ }
1227
+
1228
+ /**
1229
+ * @param {string} safeModuleId
1230
+ * @param {Locale} locale
1231
+ */
1232
+ export function trackMessageCall(safeModuleId, locale) {
1233
+ if (isServer === false)
1234
+ return;
1235
+ const store = serverAsyncLocalStorage?.getStore();
1236
+ if (store) {
1237
+ store.messageCalls?.add(`${safeModuleId}:${locale}`);
1238
+ }
1239
+ }
1240
+
1241
+ /**
1242
+ * Generates a list of localized URLs for all provided URLs.
1243
+ *
1244
+ * This is useful for SSG (Static Site Generation) and sitemap generation.
1245
+ * NextJS and other frameworks use this function for SSG.
1246
+ *
1247
+ * @example
1248
+ * ```typescript
1249
+ * const urls = generateStaticLocalizedUrls([
1250
+ * "https://example.com/about",
1251
+ * "https://example.com/blog",
1252
+ * ]);
1253
+ * urls[0].href // => "https://example.com/about"
1254
+ * urls[1].href // => "https://example.com/blog"
1255
+ * urls[2].href // => "https://example.com/de/about"
1256
+ * urls[3].href // => "https://example.com/de/blog"
1257
+ * ...
1258
+ * ```
1259
+ *
1260
+ * @param {(string | URL)[]} urls - List of URLs to generate localized versions for. Can be absolute URLs or paths.
1261
+ * @returns {URL[]} List of localized URLs as URL objects
1262
+ */
1263
+ export function generateStaticLocalizedUrls(urls) {
1264
+ const localizedUrls = new Set();
1265
+ // For default URL pattern, we can optimize the generation
1266
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
1267
+ for (const urlInput of urls) {
1268
+ const url = urlInput instanceof URL
1269
+ ? urlInput
1270
+ : new URL(urlInput, "http://localhost");
1271
+ // Base locale doesn't get a prefix
1272
+ localizedUrls.add(url);
1273
+ // Other locales get their code as prefix
1274
+ for (const locale of locales) {
1275
+ if (locale !== baseLocale) {
1276
+ const localizedPath = `/${locale}${url.pathname}${url.search}${url.hash}`;
1277
+ const localizedUrl = new URL(localizedPath, url.origin);
1278
+ localizedUrls.add(localizedUrl);
1279
+ }
1280
+ }
1281
+ }
1282
+ return Array.from(localizedUrls);
1283
+ }
1284
+ // For custom URL patterns, we need to use localizeUrl for each URL and locale
1285
+ for (const urlInput of urls) {
1286
+ const url = urlInput instanceof URL
1287
+ ? urlInput
1288
+ : new URL(urlInput, "http://localhost");
1289
+ // Try each URL pattern to find one that matches
1290
+ let patternFound = false;
1291
+ for (const pattern of urlPatterns) {
1292
+ try {
1293
+ // Try to match the unlocalized pattern
1294
+ const unlocalizedMatch = new URLPattern(pattern.pattern, url.href).exec(url.href);
1295
+ if (!unlocalizedMatch)
1296
+ continue;
1297
+ patternFound = true;
1298
+ // Track unique localized URLs to avoid duplicates when patterns are the same
1299
+ const seenUrls = new Set();
1300
+ // Generate localized URL for each locale
1301
+ for (const [locale] of pattern.localized) {
1302
+ try {
1303
+ const localizedUrl = localizeUrl(url, { locale });
1304
+ const urlString = localizedUrl.href;
1305
+ // Only add if we haven't seen this exact URL before
1306
+ if (!seenUrls.has(urlString)) {
1307
+ seenUrls.add(urlString);
1308
+ localizedUrls.add(localizedUrl);
1309
+ }
1310
+ }
1311
+ catch {
1312
+ // Skip if localization fails for this locale
1313
+ continue;
1314
+ }
1315
+ }
1316
+ break;
1317
+ }
1318
+ catch {
1319
+ // Skip if pattern matching fails
1320
+ continue;
1321
+ }
1322
+ }
1323
+ // If no pattern matched, use the URL as is
1324
+ if (!patternFound) {
1325
+ localizedUrls.add(url);
1326
+ }
1327
+ }
1328
+ return Array.from(localizedUrls);
1329
+ }
1330
+
1331
+ /**
1332
+ * @typedef {"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage"} BuiltInStrategy
1333
+ */
1334
+ /**
1335
+ * @typedef {`custom_${string}`} CustomStrategy
1336
+ */
1337
+ /**
1338
+ * @typedef {BuiltInStrategy | CustomStrategy} Strategy
1339
+ */
1340
+ /**
1341
+ * @typedef {Array<Strategy>} Strategies
1342
+ */
1343
+ /**
1344
+ * @typedef {{ getLocale: (request?: Request) => Promise<string | undefined> | (string | undefined) }} CustomServerStrategyHandler
1345
+ */
1346
+ /**
1347
+ * @typedef {{ getLocale: () => Promise<string|undefined> | (string | undefined), setLocale: (locale: string) => Promise<void> | void }} CustomClientStrategyHandler
1348
+ */
1349
+ /** @type {Map<string, CustomServerStrategyHandler>} */
1350
+ export const customServerStrategies = new Map();
1351
+ /** @type {Map<string, CustomClientStrategyHandler>} */
1352
+ export const customClientStrategies = new Map();
1353
+ /**
1354
+ * Checks if the given strategy is a custom strategy.
1355
+ *
1356
+ * @param {any} strategy The name of the custom strategy to validate.
1357
+ * Must be a string that starts with "custom-" followed by alphanumeric characters, hyphens, or underscores.
1358
+ * @returns {boolean} Returns true if it is a custom strategy, false otherwise.
1359
+ */
1360
+ export function isCustomStrategy(strategy) {
1361
+ return (typeof strategy === "string" && /^custom-[A-Za-z0-9_-]+$/.test(strategy));
1362
+ }
1363
+ /**
1364
+ * Defines a custom strategy that is executed on the server.
1365
+ *
1366
+ * @param {any} strategy The name of the custom strategy to define. Must follow the pattern custom-name with alphanumeric characters, hyphens, or underscores.
1367
+ * @param {CustomServerStrategyHandler} handler The handler for the custom strategy, which should implement
1368
+ * the method getLocale.
1369
+ * @returns {void}
1370
+ */
1371
+ export function defineCustomServerStrategy(strategy, handler) {
1372
+ if (!isCustomStrategy(strategy)) {
1373
+ throw new Error(`Invalid custom strategy: "${strategy}". Must be a custom strategy following the pattern custom-name.`);
1374
+ }
1375
+ customServerStrategies.set(strategy, handler);
1376
+ }
1377
+ /**
1378
+ * Defines a custom strategy that is executed on the client.
1379
+ *
1380
+ * @param {any} strategy The name of the custom strategy to define. Must follow the pattern custom-name with alphanumeric characters, hyphens, or underscores.
1381
+ * @param {CustomClientStrategyHandler} handler The handler for the custom strategy, which should implement the
1382
+ * methods getLocale and setLocale.
1383
+ * @returns {void}
1384
+ */
1385
+ export function defineCustomClientStrategy(strategy, handler) {
1386
+ if (!isCustomStrategy(strategy)) {
1387
+ throw new Error(`Invalid custom strategy: "${strategy}". Must be a custom strategy following the pattern custom-name.`);
1388
+ }
1389
+ customClientStrategies.set(strategy, handler);
1390
+ }
1391
+
1392
+ // ------ TYPES ------
1393
+
1394
+ /**
1395
+ * A locale that is available in the project.
1396
+ *
1397
+ * @example
1398
+ * setLocale(request.locale as Locale)
1399
+ *
1400
+ * @typedef {(typeof locales)[number]} Locale
1401
+ */
1402
+