intor 1.0.26 → 1.0.28

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.
@@ -1,10 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var React7 = require('react');
4
- var logry = require('logry');
5
- var intorTranslator = require('intor-translator');
6
- var server = require('next/server');
7
- var headers = require('next/headers');
3
+ var React = require('react');
8
4
  var NextLink = require('next/link');
9
5
  var navigation = require('next/navigation');
10
6
 
@@ -28,12 +24,10 @@ function _interopNamespace(e) {
28
24
  return Object.freeze(n);
29
25
  }
30
26
 
31
- var React7__namespace = /*#__PURE__*/_interopNamespace(React7);
27
+ var React__namespace = /*#__PURE__*/_interopNamespace(React);
32
28
  var NextLink__default = /*#__PURE__*/_interopDefault(NextLink);
33
29
 
34
30
  var __defProp = Object.defineProperty;
35
- var __defProps = Object.defineProperties;
36
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
37
31
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
38
32
  var __hasOwnProp = Object.prototype.hasOwnProperty;
39
33
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -49,7 +43,6 @@ var __spreadValues = (a, b) => {
49
43
  }
50
44
  return a;
51
45
  };
52
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
53
46
  var __objRest = (source, exclude) => {
54
47
  var target = {};
55
48
  for (var prop in source)
@@ -62,98 +55,16 @@ var __objRest = (source, exclude) => {
62
55
  }
63
56
  return target;
64
57
  };
65
- var IntorConfigContext = React7__namespace.createContext(void 0);
66
- var IntorConfigProvider = ({
67
- value: { config, pathname },
68
- children
69
- }) => {
70
- const value = React7__namespace.useMemo(
71
- () => ({
72
- config,
73
- pathname
74
- }),
75
- [config, pathname]
76
- );
77
- return /* @__PURE__ */ React7__namespace.createElement(IntorConfigContext.Provider, { value }, children);
78
- };
58
+ var IntorLocaleContext = React__namespace.createContext(void 0);
59
+ var IntorConfigContext = React__namespace.createContext(void 0);
79
60
  var useIntorConfig = () => {
80
- const context = React7__namespace.useContext(IntorConfigContext);
61
+ const context = React__namespace.useContext(IntorConfigContext);
81
62
  if (!context) {
82
63
  throw new Error("useIntorConfig must be used within IntorConfigProvider");
83
64
  }
84
65
  return context;
85
66
  };
86
- var IntorLocaleContext = React7__namespace.createContext(void 0);
87
-
88
- // src/adapters/next-client/utils/build-cookie-string.ts
89
- var buildCookieString = (cookie, locale) => {
90
- var _a;
91
- const parts = [];
92
- parts.push(`${cookie.name}=${encodeURIComponent(locale)}`);
93
- if (cookie.maxAge) {
94
- const expires = new Date(Date.now() + cookie.maxAge * 1e3).toUTCString();
95
- parts.push(`expires=${expires}`);
96
- parts.push(`max-age=${cookie.maxAge}`);
97
- }
98
- parts.push(`path=${(_a = cookie.path) != null ? _a : "/"}`);
99
- if (cookie.domain) {
100
- parts.push(`domain=${cookie.domain}`);
101
- }
102
- if (cookie.sameSite) {
103
- parts.push(
104
- `SameSite=${cookie.sameSite[0].toUpperCase()}${cookie.sameSite.slice(1).toLowerCase()}`
105
- );
106
- }
107
- if (cookie.secure !== false) {
108
- parts.push(`Secure`);
109
- }
110
- return parts.join("; ");
111
- };
112
-
113
- // src/adapters/next-client/utils/set-locale-cookie-client.ts
114
- var setLocaleCookieClient = ({
115
- cookie,
116
- locale
117
- }) => {
118
- if (typeof window === "undefined") {
119
- return;
120
- }
121
- if (cookie.disabled || !cookie.autoSetCookie) {
122
- return;
123
- }
124
- const cookieString = buildCookieString(cookie, locale);
125
- document.cookie = cookieString;
126
- };
127
-
128
- // src/adapters/next-client/contexts/intor-locale/utils/change-locale.ts
129
- var changeLocale = ({
130
- currentLocale,
131
- newLocale,
132
- loaderOptions,
133
- cookie,
134
- setLocale,
135
- refetchMessages
136
- }) => {
137
- if (typeof document === "undefined") {
138
- return;
139
- }
140
- const loaderType = loaderOptions == null ? void 0 : loaderOptions.type;
141
- if (newLocale === currentLocale) {
142
- return;
143
- }
144
- if (loaderType === "import") {
145
- console.warn(
146
- `[Intor] You are using dynamic import to switch languages. Please make sure to use the wrapped <Link> component to trigger a page reload, ensuring that the translation data is dynamically updated.`
147
- );
148
- }
149
- setLocale(newLocale);
150
- setLocaleCookieClient({ cookie, locale: newLocale });
151
- document.documentElement.lang = newLocale;
152
- if (loaderType === "api" && refetchMessages) {
153
- void refetchMessages(newLocale);
154
- }
155
- };
156
- var IntorMessagesContext = React7__namespace.createContext(void 0);
67
+ var IntorMessagesContext = React__namespace.createContext(void 0);
157
68
 
158
69
  // src/shared/utils/pathname/normalize-pathname.ts
159
70
  var normalizePathname = (rawPathname, options = {}) => {
@@ -189,127 +100,6 @@ var normalizePathname = (rawPathname, options = {}) => {
189
100
  return result || "/";
190
101
  };
191
102
 
192
- // src/modules/intor-messages-loader/fetch-api-messages/build-search-params.ts
193
- var buildSearchParams = (params) => {
194
- const searchParams = new URLSearchParams();
195
- const appendParam = (key, value) => {
196
- if (value === void 0 || value === null) {
197
- return;
198
- }
199
- if (Array.isArray(value) && value.length > 0) {
200
- value.forEach((v) => v && searchParams.append(key, v));
201
- } else {
202
- searchParams.append(key, value);
203
- }
204
- };
205
- Object.entries(params).forEach(([key, value]) => {
206
- appendParam(key, value);
207
- });
208
- return searchParams;
209
- };
210
- var fetcher = async ({
211
- apiUrl,
212
- locale,
213
- searchParams,
214
- loggerId
215
- }) => {
216
- const logger = logry.logry({ id: loggerId, scope: "fetcher" });
217
- try {
218
- const params = new URLSearchParams(searchParams);
219
- params.append("locale", locale);
220
- const url = `${apiUrl}?${params.toString()}`;
221
- const response = await fetch(url, {
222
- method: "GET",
223
- headers: { "Content-Type": "application/json" },
224
- cache: "no-store"
225
- });
226
- if (!response.ok) {
227
- throw new Error(
228
- `Fetch failed for locale "${locale}" at URL: ${url} - ${response.status} ${response.statusText}`
229
- );
230
- }
231
- const data = await response.json();
232
- if (data == null || typeof data === "object" && Object.keys(data).length === 0) {
233
- throw new Error(
234
- `Missing or invalid messages for locale "${locale}" at URL: ${url}`
235
- );
236
- }
237
- return data;
238
- } catch (e) {
239
- logger.warn(`Failed to fetch messages for locale "${locale}".`, {
240
- locale,
241
- apiUrl,
242
- searchParams: decodeURIComponent(searchParams.toString())
243
- });
244
- return void 0;
245
- }
246
- };
247
-
248
- // src/modules/intor-messages-loader/fetch-api-messages/fetch-fallback-messages.ts
249
- var fetchFallbackMessages = async (apiUrl, searchParams, fallbackLocales, loggerId) => {
250
- for (const fallbackLocale of fallbackLocales) {
251
- const result = await fetcher({
252
- apiUrl,
253
- searchParams,
254
- locale: fallbackLocale,
255
- loggerId
256
- });
257
- if (result) {
258
- return { locale: fallbackLocale, messages: result };
259
- }
260
- }
261
- return void 0;
262
- };
263
-
264
- // src/modules/intor-messages-loader/fetch-api-messages/fetch-api-messages.ts
265
- var fetchApiMessages = async ({
266
- apiUrl,
267
- basePath,
268
- locale,
269
- fallbackLocales = [],
270
- namespaces = [],
271
- loggerId
272
- }) => {
273
- const logger = logry.logry({ id: loggerId, scope: "fetchApiMessages" });
274
- if (!apiUrl) {
275
- logger.warn("No apiUrl provided for fetchApiMessages. Skipping fetch.");
276
- return void 0;
277
- }
278
- const searchParams = buildSearchParams({
279
- basePath,
280
- loggerId,
281
- namespaces
282
- });
283
- const messages = await fetcher({
284
- apiUrl,
285
- searchParams,
286
- locale,
287
- loggerId
288
- });
289
- if (messages) {
290
- return messages;
291
- }
292
- const fallbackResult = await fetchFallbackMessages(
293
- apiUrl,
294
- searchParams,
295
- fallbackLocales,
296
- loggerId
297
- );
298
- if (fallbackResult) {
299
- logger.info("Fallback locale succeeded.", {
300
- usedLocale: fallbackResult.locale,
301
- apiUrl,
302
- searchParams: decodeURIComponent(searchParams.toString())
303
- });
304
- return fallbackResult.messages;
305
- }
306
- logger.warn("Failed to fetch messages for all locales.", {
307
- locale,
308
- fallbackLocales
309
- });
310
- return void 0;
311
- };
312
-
313
103
  // src/shared/utils/pathname/extract-pathname.ts
314
104
  var extractPathname = ({
315
105
  config,
@@ -362,162 +152,8 @@ var standardizePathname = ({
362
152
  const standardizedPathname = parts.join("/").replace(/\/{2,}/g, "/");
363
153
  return normalizePathname(standardizedPathname);
364
154
  };
365
-
366
- // src/shared/utils/resolve-namespaces.ts
367
- var resolveNamespaces = ({
368
- config,
369
- pathname
370
- }) => {
371
- var _a, _b, _c, _d;
372
- const { loaderOptions, prefixPlaceHolder } = config;
373
- const {
374
- routeNamespaces = {},
375
- namespaces: fallbackNamespaces
376
- } = loaderOptions;
377
- const { unprefixedPathname } = extractPathname({ config, pathname });
378
- const standardizedPathname = standardizePathname({
379
- config,
380
- pathname: unprefixedPathname
381
- });
382
- const placeholderRemovedPathname = standardizedPathname.replace(
383
- `/${prefixPlaceHolder}`,
384
- ""
385
- );
386
- const defaultNamespaces = (_a = routeNamespaces.default) != null ? _a : [];
387
- const exactMatchNamespaces = (_b = routeNamespaces[standardizedPathname]) != null ? _b : routeNamespaces[placeholderRemovedPathname];
388
- if (exactMatchNamespaces) {
389
- return [...defaultNamespaces, ...exactMatchNamespaces];
390
- }
391
- let bestMatch = "";
392
- let bestNamespaces;
393
- const prefixPatterns = Object.keys(routeNamespaces).filter(
394
- (pattern) => pattern.endsWith("/*")
395
- );
396
- for (const pattern of prefixPatterns) {
397
- const basePath = pattern.replace(/\/\*$/, "");
398
- if (standardizedPathname.startsWith(basePath)) {
399
- if (basePath.length > bestMatch.length) {
400
- bestMatch = basePath;
401
- bestNamespaces = routeNamespaces[pattern];
402
- }
403
- }
404
- }
405
- const matchedNamespaces = (_d = (_c = bestNamespaces != null ? bestNamespaces : routeNamespaces["/*"]) != null ? _c : fallbackNamespaces) != null ? _d : [];
406
- if (matchedNamespaces.length > 0) {
407
- return [...defaultNamespaces, ...matchedNamespaces];
408
- } else {
409
- return [...defaultNamespaces];
410
- }
411
- };
412
-
413
- // src/adapters/next-client/hooks/api/use-fetch-messages.ts
414
- var useFetchMessages = ({
415
- onError
416
- }) => {
417
- const fetcher2 = async (params) => {
418
- try {
419
- const data = await fetchApiMessages(params);
420
- return data;
421
- } catch (error) {
422
- onError == null ? void 0 : onError(error, params.apiUrl);
423
- return null;
424
- }
425
- };
426
- return { fetcher: fetcher2 };
427
- };
428
-
429
- // src/shared/utils/merge-static-and-dynamic-messages.ts
430
- var mergeStaticAndDynamicMessages = (staticMessages = {}, dynamicMessages = {}) => {
431
- const result = Object.keys(staticMessages).length ? __spreadValues({}, staticMessages) : {};
432
- for (const locale in dynamicMessages) {
433
- const dynamic = dynamicMessages[locale];
434
- if (!result[locale]) {
435
- result[locale] = dynamic;
436
- continue;
437
- }
438
- result[locale] = __spreadValues(__spreadValues({}, result[locale]), dynamic);
439
- }
440
- return result;
441
- };
442
-
443
- // src/adapters/next-client/hooks/api/use-refetch-messages.ts
444
- var useRefetchMessages = ({
445
- config,
446
- pathname,
447
- setLoadedMessages,
448
- setIsLoadingMessages,
449
- onError
450
- // Error handler
451
- }) => {
452
- const { messages: staticMessages } = config;
453
- const namespaces = React7__namespace.useMemo(() => {
454
- if (!config.loaderOptions) {
455
- return [];
456
- }
457
- return resolveNamespaces({ config, pathname });
458
- }, [config, pathname]);
459
- const { fetcher: fetcher2 } = useFetchMessages({ onError });
460
- const refetchMessages = React7__namespace.useCallback(
461
- async (newLocale) => {
462
- var _a;
463
- if (((_a = config.loaderOptions) == null ? void 0 : _a.type) === "api") {
464
- setIsLoadingMessages(true);
465
- const dynamicMessages = await fetcher2(__spreadProps(__spreadValues({}, config.loaderOptions), {
466
- locale: newLocale,
467
- fallbackLocales: config.fallbackLocales[newLocale] || [],
468
- namespaces,
469
- loggerId: config.id
470
- }));
471
- const messages = mergeStaticAndDynamicMessages(
472
- staticMessages,
473
- dynamicMessages
474
- );
475
- setLoadedMessages(messages);
476
- setIsLoadingMessages(false);
477
- }
478
- },
479
- [
480
- config.loaderOptions,
481
- config.fallbackLocales,
482
- config.id,
483
- setIsLoadingMessages,
484
- fetcher2,
485
- namespaces,
486
- staticMessages,
487
- setLoadedMessages
488
- ]
489
- );
490
- return { refetchMessages };
491
- };
492
-
493
- // src/adapters/next-client/contexts/intor-messages/intor-messages-provider.tsx
494
- var IntorMessagesProvider = ({
495
- value: { messages },
496
- children
497
- }) => {
498
- const { config, pathname } = useIntorConfig();
499
- const [loadedMessages, setLoadedMessages] = React7__namespace.useState(null);
500
- const [isLoadingMessages, setIsLoadingMessages] = React7__namespace.useState(false);
501
- const { refetchMessages } = useRefetchMessages({
502
- config,
503
- pathname,
504
- setLoadedMessages,
505
- setIsLoadingMessages
506
- });
507
- const value = React7__namespace.useMemo(
508
- () => ({
509
- messages: loadedMessages || messages,
510
- isLoading: isLoadingMessages,
511
- setLoadedMessages,
512
- setIsLoadingMessages,
513
- refetchMessages
514
- }),
515
- [loadedMessages, messages, isLoadingMessages, refetchMessages]
516
- );
517
- return /* @__PURE__ */ React7__namespace.createElement(IntorMessagesContext.Provider, { value }, children);
518
- };
519
155
  var useIntorMessages = () => {
520
- const context = React7__namespace.useContext(IntorMessagesContext);
156
+ const context = React__namespace.useContext(IntorMessagesContext);
521
157
  if (!context) {
522
158
  throw new Error(
523
159
  "useIntorMessages must be used within a IntorMessagesProvider"
@@ -525,145 +161,21 @@ var useIntorMessages = () => {
525
161
  }
526
162
  return context;
527
163
  };
528
- var useInitLazyLoad = ({
529
- loaderOptions,
530
- currentLocale
531
- }) => {
532
- const { refetchMessages } = useIntorMessages();
533
- const lazyLoad = !!(loaderOptions == null ? void 0 : loaderOptions.lazyLoad);
534
- const isFirstLoadedRef = React7__namespace.useRef(false);
535
- React7__namespace.useEffect(() => {
536
- if (lazyLoad && !isFirstLoadedRef.current) {
537
- void refetchMessages(currentLocale);
538
- isFirstLoadedRef.current = true;
539
- }
540
- }, [lazyLoad, currentLocale, refetchMessages, isFirstLoadedRef]);
541
- };
542
- var useInitLocaleCookie = ({
543
- config,
544
- locale
545
- }) => {
546
- React7__namespace.useEffect(() => {
547
- if (typeof document === "undefined") {
548
- return;
549
- }
550
- const { cookie, routing } = config;
551
- const { firstVisit } = routing;
552
- const cookies = document.cookie.split(";").map((c) => c.trim());
553
- const isCookieExists = cookies.some((c) => c.startsWith(`${cookie.name}=`));
554
- if (isCookieExists) {
555
- return;
556
- }
557
- if (!firstVisit.redirect) {
558
- return;
559
- }
560
- if (cookie.disabled || !cookie.autoSetCookie) {
561
- return;
562
- }
563
- setLocaleCookieClient({ cookie, locale });
564
- }, []);
565
- };
566
-
567
- // src/adapters/next-client/contexts/intor-locale/intor-locale-provider.tsx
568
- var IntorLocaleProvider = ({
569
- value: { initialLocale },
570
- children
571
- }) => {
572
- const { config } = useIntorConfig();
573
- const { refetchMessages } = useIntorMessages();
574
- const { loaderOptions, cookie } = config;
575
- const [currentLocale, setCurrentLocale] = React7__namespace.useState(initialLocale);
576
- useInitLazyLoad({ loaderOptions, currentLocale });
577
- useInitLocaleCookie({ config, locale: initialLocale });
578
- const setLocale = React7__namespace.useCallback(
579
- (newLocale) => {
580
- changeLocale({
581
- currentLocale,
582
- newLocale,
583
- loaderOptions,
584
- cookie,
585
- setLocale: setCurrentLocale,
586
- refetchMessages
587
- });
588
- },
589
- [currentLocale, loaderOptions, cookie, refetchMessages]
590
- );
591
- const value = React7__namespace.useMemo(
592
- () => ({
593
- locale: currentLocale,
594
- setLocale
595
- }),
596
- [currentLocale, setLocale]
597
- );
598
- return /* @__PURE__ */ React7__namespace.createElement(IntorLocaleContext.Provider, { value }, children);
599
- };
600
164
  var useIntorLocale = () => {
601
- const context = React7__namespace.useContext(IntorLocaleContext);
165
+ const context = React__namespace.useContext(IntorLocaleContext);
602
166
  if (!context) {
603
167
  throw new Error("useIntorLocale must be used within a IntorLocaleProvider");
604
168
  }
605
169
  return context;
606
170
  };
607
- var IntorTranslatorContext = React7__namespace.createContext(void 0);
608
- var TranslateHandlersContext = React7__namespace.createContext(void 0);
609
- var TranslateHandlersProvider = ({
610
- children,
611
- handlers
612
- }) => {
613
- const value = handlers;
614
- return /* @__PURE__ */ React7__namespace.createElement(TranslateHandlersContext.Provider, { value }, children);
615
- };
171
+ var IntorTranslatorContext = React__namespace.createContext(void 0);
172
+ var TranslateHandlersContext = React__namespace.createContext(void 0);
616
173
  var useTranslateHandlers = () => {
617
- const context = React7__namespace.useContext(TranslateHandlersContext);
174
+ const context = React__namespace.useContext(TranslateHandlersContext);
618
175
  return context;
619
176
  };
620
- var useInitLoadingState = (config) => {
621
- var _a;
622
- const lazyLoad = !!((_a = config.loaderOptions) == null ? void 0 : _a.lazyLoad);
623
- const [isCsr, setIsCsr] = React7__namespace.useState(false);
624
- React7__namespace.useEffect(() => {
625
- setIsCsr(true);
626
- }, []);
627
- const isBeforeCSRLoading = lazyLoad && !isCsr;
628
- return isBeforeCSRLoading;
629
- };
630
-
631
- // src/adapters/next-client/contexts/intor-translator/intor-translator-provider.tsx
632
- var EMPTY_OBJECT = Object.freeze({});
633
- var IntorTranslatorProvider = ({
634
- children
635
- }) => {
636
- const { config } = useIntorConfig();
637
- const { messages, isLoading } = useIntorMessages();
638
- const { locale } = useIntorLocale();
639
- const translatorHandlers = useTranslateHandlers();
640
- const { fallbackLocales, translator: translatorOptions } = config;
641
- const isBeforeCSRLoading = useInitLoadingState(config);
642
- const value = React7__namespace.useMemo(() => {
643
- const translator = new intorTranslator.Translator({
644
- messages: messages || EMPTY_OBJECT,
645
- locale,
646
- fallbackLocales,
647
- loadingMessage: translatorOptions == null ? void 0 : translatorOptions.loadingMessage,
648
- placeholder: translatorOptions == null ? void 0 : translatorOptions.placeholder,
649
- handlers: translatorHandlers
650
- });
651
- translator.setLoading(isBeforeCSRLoading || isLoading);
652
- return { translator };
653
- }, [
654
- fallbackLocales,
655
- isBeforeCSRLoading,
656
- isLoading,
657
- locale,
658
- messages,
659
- translatorHandlers,
660
- translatorOptions == null ? void 0 : translatorOptions.loadingMessage,
661
- translatorOptions == null ? void 0 : translatorOptions.placeholder
662
- ]);
663
- return /* @__PURE__ */ React7__namespace.createElement(IntorTranslatorContext.Provider, { value }, children);
664
- };
665
177
  function useIntorTranslator() {
666
- const context = React7__namespace.useContext(IntorTranslatorContext);
178
+ const context = React__namespace.useContext(IntorTranslatorContext);
667
179
  if (!context) {
668
180
  throw new Error(
669
181
  "useIntorTranslator must be used within IntorTranslatorProvider"
@@ -672,19 +184,6 @@ function useIntorTranslator() {
672
184
  return context;
673
185
  }
674
186
 
675
- // src/adapters/next-client/contexts/intor-client-provider.tsx
676
- var IntorClientProvider = ({
677
- value: { config, pathname, initialLocale, messages },
678
- children
679
- }) => {
680
- return /* @__PURE__ */ React7__namespace.createElement(IntorConfigProvider, { value: { config, pathname } }, /* @__PURE__ */ React7__namespace.createElement(IntorMessagesProvider, { value: { messages } }, /* @__PURE__ */ React7__namespace.createElement(IntorLocaleProvider, { value: { initialLocale } }, /* @__PURE__ */ React7__namespace.createElement(IntorTranslatorProvider, null, children))));
681
- };
682
-
683
- // src/adapters/next-client/contexts/intor-provider.tsx
684
- var IntorProvider = (props) => {
685
- return /* @__PURE__ */ React7__namespace.createElement(IntorClientProvider, __spreadValues({}, props));
686
- };
687
-
688
187
  // src/adapters/next-client/hooks/use-intor/use-intor.ts
689
188
  function useIntorWithPreKey(preKey) {
690
189
  const { translator } = useIntorTranslator();
@@ -717,46 +216,6 @@ function useIntor(preKey) {
717
216
  return useIntorWithoutPreKey();
718
217
  }
719
218
 
720
- // src/adapters/next-client/routing/utils/set-locale-cookie-edge.ts
721
- function setLocaleCookieEdge({
722
- request,
723
- response,
724
- cookie,
725
- locale,
726
- override = false
727
- // Default to not override existed cookie
728
- }) {
729
- if (cookie.disabled || !cookie.autoSetCookie) {
730
- return;
731
- }
732
- const isCookieExists = request.cookies.has(cookie.name);
733
- if (isCookieExists && !override) {
734
- return;
735
- }
736
- response.cookies.set(cookie.name, locale, __spreadProps(__spreadValues({
737
- maxAge: cookie.maxAge,
738
- path: cookie.path
739
- }, cookie.domain ? { domain: cookie.domain } : {}), {
740
- secure: cookie.secure,
741
- httpOnly: cookie.httpOnly,
742
- sameSite: cookie.sameSite
743
- }));
744
- }
745
-
746
- // src/adapters/next-client/constants/header-key-constants.ts
747
- var DEFAULT_PATHNAME_HEADER_NAME = "x-intor-pathname";
748
-
749
- // src/adapters/next-client/routing/utils/set-pathname-header.ts
750
- var setPathnameHeader = ({
751
- request,
752
- response,
753
- key = DEFAULT_PATHNAME_HEADER_NAME
754
- }) => {
755
- const pathname = request.nextUrl.pathname;
756
- response.headers.set(key, pathname);
757
- return response;
758
- };
759
-
760
219
  // src/adapters/next-client/utils/locale-prefix-pathname.ts
761
220
  var localePrefixPathname = ({
762
221
  config,
@@ -807,240 +266,6 @@ var localizePathname = ({
807
266
  };
808
267
  };
809
268
 
810
- // src/adapters/next-client/routing/utils/create-response.ts
811
- var createResponse = ({
812
- request,
813
- config,
814
- locale,
815
- responseType = "next",
816
- setCookieOptions = { override: false }
817
- }) => {
818
- const { cookie } = config;
819
- const { override } = setCookieOptions;
820
- const url = request.nextUrl.clone();
821
- const { localePrefixedPathname } = localizePathname({
822
- config,
823
- pathname: url.pathname,
824
- locale
825
- });
826
- url.pathname = localePrefixedPathname;
827
- let response;
828
- switch (responseType) {
829
- case "next": {
830
- response = server.NextResponse.next();
831
- break;
832
- }
833
- case "redirect": {
834
- response = server.NextResponse.redirect(url);
835
- break;
836
- }
837
- default: {
838
- throw new Error(`Unsupported responseType: ${responseType}`);
839
- }
840
- }
841
- if (locale) {
842
- setLocaleCookieEdge({
843
- request,
844
- response,
845
- locale,
846
- cookie,
847
- override
848
- });
849
- }
850
- const finalResponse = setPathnameHeader({ request, response });
851
- return finalResponse;
852
- };
853
-
854
- // src/shared/utils/locale/normalize-locale.ts
855
- var normalizeLocale = (locale = "", supportedLocales = []) => {
856
- if (!locale || supportedLocales.length === 0) return void 0;
857
- const toCanonical = (input) => {
858
- var _a;
859
- try {
860
- return (_a = Intl.getCanonicalLocales(input)[0]) == null ? void 0 : _a.toLowerCase();
861
- } catch (e) {
862
- return void 0;
863
- }
864
- };
865
- const canonicalLocale = toCanonical(locale);
866
- if (!canonicalLocale) return void 0;
867
- const supportedCanonicalMap = /* @__PURE__ */ new Map();
868
- for (const l of supportedLocales) {
869
- const normalized = toCanonical(l);
870
- if (normalized) {
871
- supportedCanonicalMap.set(normalized, l);
872
- }
873
- }
874
- if (supportedCanonicalMap.has(canonicalLocale)) {
875
- return supportedCanonicalMap.get(canonicalLocale);
876
- }
877
- const baseLang = canonicalLocale.split("-")[0];
878
- for (const [key, original] of supportedCanonicalMap) {
879
- const supportedBase = key.split("-")[0];
880
- if (supportedBase === baseLang) {
881
- return original;
882
- }
883
- }
884
- return void 0;
885
- };
886
-
887
- // src/shared/utils/locale/resolve-preferred-locale.ts
888
- var resolvePreferredLocale = (acceptLanguageHeader, supportedLocales) => {
889
- var _a;
890
- if (!acceptLanguageHeader || !supportedLocales || supportedLocales.length === 0) {
891
- return;
892
- }
893
- const supportedLocalesSet = new Set(supportedLocales);
894
- const preferred = (_a = acceptLanguageHeader.split(",").map((part) => {
895
- const [lang, qValue] = part.split(";");
896
- const q = qValue ? parseFloat(qValue.split("=")[1]) : 1;
897
- if (isNaN(q)) {
898
- return { lang: lang.trim(), q: 0 };
899
- }
900
- return { lang: lang.trim(), q };
901
- }).sort((a, b) => b.q - a.q).find(({ lang }) => supportedLocalesSet.has(lang))) == null ? void 0 : _a.lang;
902
- return preferred;
903
- };
904
-
905
- // src/adapters/next-client/routing/utils/determine-initial-locale.ts
906
- var determineInitialLocale = async (config) => {
907
- const { defaultLocale, supportedLocales, routing } = config;
908
- let initialLocale = defaultLocale;
909
- if (routing.firstVisit.localeSource === "browser") {
910
- const acceptLanguageHeader = (await headers.headers()).get("accept-language") || void 0;
911
- const preferredLocale = resolvePreferredLocale(
912
- acceptLanguageHeader,
913
- supportedLocales
914
- );
915
- initialLocale = normalizeLocale(preferredLocale, supportedLocales) || defaultLocale;
916
- }
917
- return initialLocale;
918
- };
919
-
920
- // src/adapters/next-client/routing/handle-prefix/handle-prefix-all.ts
921
- var handlePrefixAll = async ({
922
- request,
923
- config
924
- }) => {
925
- var _a;
926
- const { cookie, routing } = config;
927
- const { maybeLocale, isLocalePrefixed } = extractPathname({
928
- config,
929
- pathname: request.nextUrl.pathname
930
- });
931
- const localeFromCookie = (_a = request.cookies.get(cookie.name)) == null ? void 0 : _a.value;
932
- if (isLocalePrefixed) {
933
- return createResponse({
934
- request,
935
- config,
936
- locale: maybeLocale,
937
- setCookieOptions: { override: true }
938
- });
939
- }
940
- if (!localeFromCookie) {
941
- if (!routing.firstVisit.redirect) {
942
- return createResponse({ request, config });
943
- }
944
- const initialLocale = await determineInitialLocale(config);
945
- return createResponse({
946
- request,
947
- config,
948
- locale: initialLocale,
949
- // Use locale from 'browser' | 'default'
950
- responseType: "redirect"
951
- });
952
- }
953
- return createResponse({
954
- request,
955
- config,
956
- locale: localeFromCookie,
957
- // Use locale from cookie
958
- responseType: "redirect"
959
- });
960
- };
961
-
962
- // src/adapters/next-client/routing/handle-prefix/handle-prefix-except-default.ts
963
- var handlePrefixExceptDefault = async ({
964
- request,
965
- config
966
- }) => {
967
- var _a;
968
- const { defaultLocale, cookie, routing } = config;
969
- const { maybeLocale, isLocalePrefixed } = extractPathname({
970
- config,
971
- pathname: request.nextUrl.pathname
972
- });
973
- const localeFromCookie = (_a = request.cookies.get(cookie.name)) == null ? void 0 : _a.value;
974
- if (isLocalePrefixed && maybeLocale !== defaultLocale) {
975
- return createResponse({
976
- request,
977
- config,
978
- locale: maybeLocale,
979
- setCookieOptions: { override: true }
980
- });
981
- }
982
- if (!localeFromCookie) {
983
- if (!routing.firstVisit.redirect) {
984
- return createResponse({ request, config });
985
- }
986
- const initialLocale = await determineInitialLocale(config);
987
- const isDefaultLocale2 = initialLocale === defaultLocale;
988
- if (isDefaultLocale2) {
989
- return createResponse({
990
- request,
991
- config,
992
- locale: defaultLocale
993
- });
994
- }
995
- return createResponse({
996
- request,
997
- config,
998
- locale: initialLocale,
999
- // Use locale from 'browser' | 'default'
1000
- responseType: "redirect"
1001
- });
1002
- }
1003
- const isDefaultLocale = localeFromCookie === defaultLocale;
1004
- if (isDefaultLocale) {
1005
- return createResponse({ request, config, locale: localeFromCookie });
1006
- }
1007
- return createResponse({
1008
- request,
1009
- config,
1010
- locale: localeFromCookie,
1011
- // Use locale from cookie
1012
- responseType: "redirect"
1013
- });
1014
- };
1015
-
1016
- // src/adapters/next-client/routing/handle-prefix/handle-prefix-none.ts
1017
- var handlePrefixNone = async ({
1018
- request,
1019
- config
1020
- }) => {
1021
- var _a;
1022
- let locale = (_a = request.cookies.get(config.cookie.name)) == null ? void 0 : _a.value;
1023
- if (!locale) {
1024
- locale = await determineInitialLocale(config);
1025
- }
1026
- return createResponse({ request, config, locale });
1027
- };
1028
-
1029
- // src/adapters/next-client/routing/intor-middleware.ts
1030
- async function intorMiddleware({
1031
- request,
1032
- config
1033
- }) {
1034
- const { prefix } = config.routing;
1035
- if (prefix === "none") {
1036
- return handlePrefixNone({ request, config });
1037
- }
1038
- if (prefix === "except-default") {
1039
- return await handlePrefixExceptDefault({ request, config });
1040
- }
1041
- return await handlePrefixAll({ request, config });
1042
- }
1043
-
1044
269
  // src/adapters/next-client/utils/should-use-full-reload.ts
1045
270
  var shouldUseFullReload = (loaderOptions) => {
1046
271
  return (loaderOptions == null ? void 0 : loaderOptions.type) === "import" || (loaderOptions == null ? void 0 : loaderOptions.type) === "api" && loaderOptions.fullReload === true;
@@ -1080,7 +305,7 @@ var Link = (_a) => {
1080
305
  setLocale(targetLocale);
1081
306
  }
1082
307
  };
1083
- return /* @__PURE__ */ React7__namespace.createElement(NextLink__default.default, __spreadValues({ href, onClick: handleClick }, props), children);
308
+ return /* @__PURE__ */ React__namespace.createElement(NextLink__default.default, __spreadValues({ href, onClick: handleClick }, props), children);
1084
309
  };
1085
310
  var usePathname = () => {
1086
311
  const { config } = useIntorConfig();
@@ -1139,10 +364,7 @@ var useRouter = () => {
1139
364
  }, rest);
1140
365
  };
1141
366
 
1142
- exports.IntorProvider = IntorProvider;
1143
367
  exports.Link = Link;
1144
- exports.TranslateHandlersProvider = TranslateHandlersProvider;
1145
- exports.intorMiddleware = intorMiddleware;
1146
368
  exports.useIntor = useIntor;
1147
369
  exports.useIntorConfig = useIntorConfig;
1148
370
  exports.useIntorLocale = useIntorLocale;