remix-intlayer 9.5.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.
- package/README.md +331 -0
- package/dist/cjs/IntlayerProvider.cjs +36 -0
- package/dist/cjs/IntlayerProvider.cjs.map +1 -0
- package/dist/cjs/context.cjs +23 -0
- package/dist/cjs/context.cjs.map +1 -0
- package/dist/cjs/format/index.cjs +20 -0
- package/dist/cjs/format/useCompact.cjs +18 -0
- package/dist/cjs/format/useCompact.cjs.map +1 -0
- package/dist/cjs/format/useCurrency.cjs +18 -0
- package/dist/cjs/format/useCurrency.cjs.map +1 -0
- package/dist/cjs/format/useDate.cjs +27 -0
- package/dist/cjs/format/useDate.cjs.map +1 -0
- package/dist/cjs/format/useIntl.cjs +24 -0
- package/dist/cjs/format/useIntl.cjs.map +1 -0
- package/dist/cjs/format/useList.cjs +18 -0
- package/dist/cjs/format/useList.cjs.map +1 -0
- package/dist/cjs/format/useNumber.cjs +21 -0
- package/dist/cjs/format/useNumber.cjs.map +1 -0
- package/dist/cjs/format/usePercentage.cjs +18 -0
- package/dist/cjs/format/usePercentage.cjs.map +1 -0
- package/dist/cjs/format/useRelativeTime.cjs +18 -0
- package/dist/cjs/format/useRelativeTime.cjs.map +1 -0
- package/dist/cjs/format/useUnit.cjs +18 -0
- package/dist/cjs/format/useUnit.cjs.map +1 -0
- package/dist/cjs/html/index.cjs +33 -0
- package/dist/cjs/index.cjs +17 -0
- package/dist/cjs/localeRouting.cjs +211 -0
- package/dist/cjs/localeRouting.cjs.map +1 -0
- package/dist/cjs/markdown/index.cjs +45 -0
- package/dist/cjs/middleware.cjs +92 -0
- package/dist/cjs/middleware.cjs.map +1 -0
- package/dist/cjs/persistLocale.cjs +51 -0
- package/dist/cjs/persistLocale.cjs.map +1 -0
- package/dist/cjs/requestStorage.cjs +25 -0
- package/dist/cjs/requestStorage.cjs.map +1 -0
- package/dist/cjs/resolveLocale.cjs +21 -0
- package/dist/cjs/resolveLocale.cjs.map +1 -0
- package/dist/cjs/useDictionary.cjs +33 -0
- package/dist/cjs/useDictionary.cjs.map +1 -0
- package/dist/cjs/useIntlayer.cjs +31 -0
- package/dist/cjs/useIntlayer.cjs.map +1 -0
- package/dist/cjs/useLocale.cjs +33 -0
- package/dist/cjs/useLocale.cjs.map +1 -0
- package/dist/esm/IntlayerProvider.mjs +35 -0
- package/dist/esm/IntlayerProvider.mjs.map +1 -0
- package/dist/esm/context.mjs +21 -0
- package/dist/esm/context.mjs.map +1 -0
- package/dist/esm/format/index.mjs +11 -0
- package/dist/esm/format/useCompact.mjs +17 -0
- package/dist/esm/format/useCompact.mjs.map +1 -0
- package/dist/esm/format/useCurrency.mjs +17 -0
- package/dist/esm/format/useCurrency.mjs.map +1 -0
- package/dist/esm/format/useDate.mjs +26 -0
- package/dist/esm/format/useDate.mjs.map +1 -0
- package/dist/esm/format/useIntl.mjs +23 -0
- package/dist/esm/format/useIntl.mjs.map +1 -0
- package/dist/esm/format/useList.mjs +17 -0
- package/dist/esm/format/useList.mjs.map +1 -0
- package/dist/esm/format/useNumber.mjs +20 -0
- package/dist/esm/format/useNumber.mjs.map +1 -0
- package/dist/esm/format/usePercentage.mjs +17 -0
- package/dist/esm/format/usePercentage.mjs.map +1 -0
- package/dist/esm/format/useRelativeTime.mjs +17 -0
- package/dist/esm/format/useRelativeTime.mjs.map +1 -0
- package/dist/esm/format/useUnit.mjs +17 -0
- package/dist/esm/format/useUnit.mjs.map +1 -0
- package/dist/esm/html/index.mjs +3 -0
- package/dist/esm/index.mjs +9 -0
- package/dist/esm/localeRouting.mjs +210 -0
- package/dist/esm/localeRouting.mjs.map +1 -0
- package/dist/esm/markdown/index.mjs +3 -0
- package/dist/esm/middleware.mjs +91 -0
- package/dist/esm/middleware.mjs.map +1 -0
- package/dist/esm/persistLocale.mjs +49 -0
- package/dist/esm/persistLocale.mjs.map +1 -0
- package/dist/esm/requestStorage.mjs +22 -0
- package/dist/esm/requestStorage.mjs.map +1 -0
- package/dist/esm/resolveLocale.mjs +20 -0
- package/dist/esm/resolveLocale.mjs.map +1 -0
- package/dist/esm/useDictionary.mjs +32 -0
- package/dist/esm/useDictionary.mjs.map +1 -0
- package/dist/esm/useIntlayer.mjs +30 -0
- package/dist/esm/useIntlayer.mjs.map +1 -0
- package/dist/esm/useLocale.mjs +32 -0
- package/dist/esm/useLocale.mjs.map +1 -0
- package/dist/types/IntlayerProvider.d.ts +39 -0
- package/dist/types/IntlayerProvider.d.ts.map +1 -0
- package/dist/types/context.d.ts +31 -0
- package/dist/types/context.d.ts.map +1 -0
- package/dist/types/format/index.d.ts +10 -0
- package/dist/types/format/useCompact.d.ts +5 -0
- package/dist/types/format/useCompact.d.ts.map +1 -0
- package/dist/types/format/useCurrency.d.ts +5 -0
- package/dist/types/format/useCurrency.d.ts.map +1 -0
- package/dist/types/format/useDate.d.ts +8 -0
- package/dist/types/format/useDate.d.ts.map +1 -0
- package/dist/types/format/useIntl.d.ts +15 -0
- package/dist/types/format/useIntl.d.ts.map +1 -0
- package/dist/types/format/useList.d.ts +5 -0
- package/dist/types/format/useList.d.ts.map +1 -0
- package/dist/types/format/useNumber.d.ts +8 -0
- package/dist/types/format/useNumber.d.ts.map +1 -0
- package/dist/types/format/usePercentage.d.ts +5 -0
- package/dist/types/format/usePercentage.d.ts.map +1 -0
- package/dist/types/format/useRelativeTime.d.ts +5 -0
- package/dist/types/format/useRelativeTime.d.ts.map +1 -0
- package/dist/types/format/useUnit.d.ts +5 -0
- package/dist/types/format/useUnit.d.ts.map +1 -0
- package/dist/types/html/index.d.ts +2 -0
- package/dist/types/index.d.ts +8 -0
- package/dist/types/localeRouting.d.ts +75 -0
- package/dist/types/localeRouting.d.ts.map +1 -0
- package/dist/types/markdown/index.d.ts +2 -0
- package/dist/types/middleware.d.ts +49 -0
- package/dist/types/middleware.d.ts.map +1 -0
- package/dist/types/persistLocale.d.ts +16 -0
- package/dist/types/persistLocale.d.ts.map +1 -0
- package/dist/types/requestStorage.d.ts +21 -0
- package/dist/types/requestStorage.d.ts.map +1 -0
- package/dist/types/resolveLocale.d.ts +16 -0
- package/dist/types/resolveLocale.d.ts.map +1 -0
- package/dist/types/useDictionary.d.ts +24 -0
- package/dist/types/useDictionary.d.ts.map +1 -0
- package/dist/types/useIntlayer.d.ts +21 -0
- package/dist/types/useIntlayer.d.ts.map +1 -0
- package/dist/types/useLocale.d.ts +25 -0
- package/dist/types/useLocale.d.ts.map +1 -0
- package/package.json +129 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { getCanonicalPath, getDomainHostname, getDomainOrigin, getLocaleFromDomain, getRewriteRules, isProxyStorageLocaleEnabled, localeDetector, resolveLocalizedPath, resolveProxyMode } from "@intlayer/core/localization";
|
|
2
|
+
import { ROUTING_MODE } from "@intlayer/config/defaultValues";
|
|
3
|
+
import { getCookie, getLocaleFromStorageServer } from "@intlayer/core/utils";
|
|
4
|
+
|
|
5
|
+
//#region src/localeRouting.ts
|
|
6
|
+
/** Matches a pathname ending with a file extension (`/logo.svg`). */
|
|
7
|
+
const STATIC_ASSET_PATTERN = /\.[a-zA-Z0-9]+$/;
|
|
8
|
+
const PASS = { kind: "pass" };
|
|
9
|
+
/**
|
|
10
|
+
* Decodes a pathname so it can be matched against the rewrite rules, which are
|
|
11
|
+
* written with the characters the locale actually uses (`/doc/релизы`) while
|
|
12
|
+
* the browser sends them percent-encoded. A malformed escape is kept as is.
|
|
13
|
+
*/
|
|
14
|
+
const decodePathname = (pathname) => {
|
|
15
|
+
try {
|
|
16
|
+
return decodeURI(pathname);
|
|
17
|
+
} catch {
|
|
18
|
+
return pathname;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Removes a trailing slash, except on the root path. A redirect to `/fr/`
|
|
23
|
+
* would otherwise ping-pong with any trailing-slash normalisation downstream.
|
|
24
|
+
*/
|
|
25
|
+
const trimTrailingSlash = (path) => path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
|
|
26
|
+
/**
|
|
27
|
+
* Removes `/{locale}` from the start of a pathname that carries that prefix.
|
|
28
|
+
*/
|
|
29
|
+
const stripLocalePrefix = (pathname, locale) => pathname.slice(`/${locale}`.length) || "/";
|
|
30
|
+
/**
|
|
31
|
+
* Builds the locale-routing resolver of a Remix application.
|
|
32
|
+
*
|
|
33
|
+
* Decides, for each request, whether to serve it as is, serve it from another
|
|
34
|
+
* internal path, or redirect it — mirroring the Intlayer proxies of
|
|
35
|
+
* `next-intlayer` and `vite-intlayer`. Unlike them, an internal rewrite hands
|
|
36
|
+
* the router the path *without* its locale prefix: the Remix router has no
|
|
37
|
+
* trailing-slash normalisation to work around, and this lets an application
|
|
38
|
+
* declare each route once (`/about`) whatever the routing mode, the locale
|
|
39
|
+
* being read from the request context instead of a route param.
|
|
40
|
+
*
|
|
41
|
+
* @param configuration - The `internationalization` and `routing` configuration.
|
|
42
|
+
* @param options - Runtime options.
|
|
43
|
+
* @returns A pure function deciding the routing of a request.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* const resolveLocaleRouting = createLocaleRouting(configuration);
|
|
48
|
+
*
|
|
49
|
+
* resolveLocaleRouting({ url: new URL('http://host/fr/about'), headers });
|
|
50
|
+
* // { kind: 'rewrite', path: '/about', locale: 'fr' }
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
const createLocaleRouting = (configuration, options = {}) => {
|
|
54
|
+
const { isDevServer = true, ignore } = options;
|
|
55
|
+
const { locales, defaultLocale } = configuration.internationalization;
|
|
56
|
+
const { basePath = "", mode = ROUTING_MODE, rewrite, domains, enableProxy } = configuration.routing ?? {};
|
|
57
|
+
const proxyMode = resolveProxyMode(enableProxy);
|
|
58
|
+
const canUseStorageLocale = isProxyStorageLocaleEnabled(proxyMode, isDevServer);
|
|
59
|
+
const isSearchParamsMode = mode === "search-params";
|
|
60
|
+
const noPrefix = mode === "no-prefix" || isSearchParamsMode;
|
|
61
|
+
const prefixDefault = mode === "prefix-all";
|
|
62
|
+
const rewriteRules = getRewriteRules(rewrite, "url");
|
|
63
|
+
const normalizedBasePath = trimTrailingSlash(basePath && !basePath.startsWith("/") ? `/${basePath}` : basePath);
|
|
64
|
+
const isSupportedLocale = (value) => value !== void 0 && locales.includes(value);
|
|
65
|
+
/**
|
|
66
|
+
* Locale carried by the first path segment (`/fr/about` → `fr`).
|
|
67
|
+
*/
|
|
68
|
+
const getPathLocale = (pathname) => {
|
|
69
|
+
const firstSegment = pathname.split("/")[1];
|
|
70
|
+
return isSupportedLocale(firstSegment) ? firstSegment : void 0;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Locale a localized ("pretty") path belongs to. `/a-propos` only exists
|
|
74
|
+
* because a rewrite rule maps it to French, so it declares its locale as
|
|
75
|
+
* explicitly as an `/fr` prefix would; rules whose localized path equals the
|
|
76
|
+
* canonical one carry no signal and are skipped.
|
|
77
|
+
*/
|
|
78
|
+
const getRewriteLocale = (pathname) => rewriteRules ? locales.find((candidate) => getCanonicalPath(pathname, candidate, rewriteRules) !== pathname) : void 0;
|
|
79
|
+
/**
|
|
80
|
+
* Locale persisted by the client (cookie / header), when it may be used as
|
|
81
|
+
* a routing source.
|
|
82
|
+
*/
|
|
83
|
+
const getStorageLocale = (headers) => canUseStorageLocale ? getLocaleFromStorageServer({
|
|
84
|
+
getCookie: (name) => getCookie(name, headers.get("cookie") ?? void 0),
|
|
85
|
+
getHeader: (name) => headers.get(name)
|
|
86
|
+
}) : void 0;
|
|
87
|
+
/**
|
|
88
|
+
* Best locale for a request that names none: storage, then
|
|
89
|
+
* `Accept-Language`, then the default locale.
|
|
90
|
+
*/
|
|
91
|
+
const detectLocale = (headers) => {
|
|
92
|
+
const locale = getStorageLocale(headers) ?? localeDetector({ "accept-language": headers.get("accept-language") ?? void 0 }, locales, defaultLocale);
|
|
93
|
+
return isSupportedLocale(locale) ? locale : defaultLocale;
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* Query string of a URL, with the `locale` param set in `search-params` mode.
|
|
97
|
+
*/
|
|
98
|
+
const withLocaleSearch = (search, locale) => {
|
|
99
|
+
if (!isSearchParamsMode) return search;
|
|
100
|
+
const params = new URLSearchParams(search);
|
|
101
|
+
params.set("locale", locale);
|
|
102
|
+
return `?${params.toString()}`;
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* Public path of an application path for a locale: base path, then the
|
|
106
|
+
* locale prefix when the routing mode shows one for that locale.
|
|
107
|
+
*/
|
|
108
|
+
const toPublicPath = (locale, path, search) => {
|
|
109
|
+
const prefixedPath = !noPrefix && (prefixDefault || locale !== defaultLocale) ? `/${locale}${path === "/" ? "" : path}` : path;
|
|
110
|
+
return `${normalizedBasePath}${trimTrailingSlash(prefixedPath)}${withLocaleSearch(search, locale)}`;
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Internal path handed to the router: base path plus the canonical path.
|
|
114
|
+
*/
|
|
115
|
+
const toInternalPath = (path, search) => `${normalizedBasePath}${path}${search}`;
|
|
116
|
+
const rewriteTo = (path, search, locale) => ({
|
|
117
|
+
kind: "rewrite",
|
|
118
|
+
path: encodeURI(toInternalPath(path, search)),
|
|
119
|
+
locale
|
|
120
|
+
});
|
|
121
|
+
/**
|
|
122
|
+
* Same-origin redirect. A target equal to the request itself is served in
|
|
123
|
+
* place instead, so a configuration mismatch can never loop.
|
|
124
|
+
*/
|
|
125
|
+
const redirectTo = (location, current, persistLocale) => {
|
|
126
|
+
const encodedLocation = encodeURI(location);
|
|
127
|
+
if (encodedLocation === current) return PASS;
|
|
128
|
+
return persistLocale ? {
|
|
129
|
+
kind: "redirect",
|
|
130
|
+
location: encodedLocation,
|
|
131
|
+
status: 302,
|
|
132
|
+
persistLocale
|
|
133
|
+
} : {
|
|
134
|
+
kind: "redirect",
|
|
135
|
+
location: encodedLocation,
|
|
136
|
+
status: 302
|
|
137
|
+
};
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* `no-prefix` and `search-params` modes: the URL never shows a prefix.
|
|
141
|
+
*/
|
|
142
|
+
const handleNoPrefix = ({ url, headers }, pathname, current) => {
|
|
143
|
+
const pathLocale = getPathLocale(pathname);
|
|
144
|
+
if (pathLocale) {
|
|
145
|
+
const canonicalPath = getCanonicalPath(stripLocalePrefix(pathname, pathLocale), pathLocale, rewriteRules);
|
|
146
|
+
return redirectTo(toPublicPath(pathLocale, canonicalPath, url.search), current, pathLocale);
|
|
147
|
+
}
|
|
148
|
+
if (isSearchParamsMode) {
|
|
149
|
+
const searchLocale = url.searchParams.get("locale") ?? void 0;
|
|
150
|
+
const locale = getStorageLocale(headers) ?? (isSupportedLocale(searchLocale) ? searchLocale : void 0) ?? detectLocale(headers);
|
|
151
|
+
const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);
|
|
152
|
+
return searchLocale === locale ? rewriteTo(canonicalPath, url.search, locale) : redirectTo(`${normalizedBasePath}${pathname}${withLocaleSearch(url.search, locale)}`, current);
|
|
153
|
+
}
|
|
154
|
+
const locale = getRewriteLocale(pathname) ?? detectLocale(headers);
|
|
155
|
+
return rewriteTo(getCanonicalPath(pathname, locale, rewriteRules), url.search, locale);
|
|
156
|
+
};
|
|
157
|
+
/**
|
|
158
|
+
* Prefix modes, URL without a locale prefix: redirect to the localized URL
|
|
159
|
+
* when the mode shows a prefix for the resolved locale, serve it otherwise.
|
|
160
|
+
*/
|
|
161
|
+
const handleMissingPathLocale = ({ url, headers }, pathname, current) => {
|
|
162
|
+
const locale = getRewriteLocale(pathname) ?? detectLocale(headers);
|
|
163
|
+
const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);
|
|
164
|
+
if (prefixDefault || locale !== defaultLocale) {
|
|
165
|
+
const { path: localizedPath } = resolveLocalizedPath(canonicalPath, locale, rewriteRules);
|
|
166
|
+
return redirectTo(toPublicPath(locale, localizedPath, url.search), current);
|
|
167
|
+
}
|
|
168
|
+
return rewriteTo(canonicalPath, url.search, locale);
|
|
169
|
+
};
|
|
170
|
+
/**
|
|
171
|
+
* Prefix modes, URL with a locale prefix: normalise it to its localized
|
|
172
|
+
* form, strip the prefix of the default locale when the mode hides it, and
|
|
173
|
+
* serve the canonical path.
|
|
174
|
+
*/
|
|
175
|
+
const handleExistingPathLocale = ({ url }, pathname, pathLocale, current) => {
|
|
176
|
+
const rawPath = stripLocalePrefix(pathname, pathLocale);
|
|
177
|
+
const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);
|
|
178
|
+
const { path: localizedPath, isRewritten } = resolveLocalizedPath(canonicalPath, pathLocale, rewriteRules);
|
|
179
|
+
if (isRewritten && localizedPath !== rawPath) return redirectTo(toPublicPath(pathLocale, localizedPath, url.search), current);
|
|
180
|
+
if (!prefixDefault && pathLocale === defaultLocale) return redirectTo(toPublicPath(pathLocale, localizedPath, url.search), current, pathLocale);
|
|
181
|
+
return rewriteTo(canonicalPath, url.search, pathLocale);
|
|
182
|
+
};
|
|
183
|
+
return (request) => {
|
|
184
|
+
if (proxyMode === "disabled" || ignore?.(request)) return PASS;
|
|
185
|
+
const { url } = request;
|
|
186
|
+
const fullPathname = decodePathname(url.pathname);
|
|
187
|
+
if (normalizedBasePath && fullPathname !== normalizedBasePath && !fullPathname.startsWith(`${normalizedBasePath}/`)) return PASS;
|
|
188
|
+
const pathname = fullPathname.slice(normalizedBasePath.length) || "/";
|
|
189
|
+
const current = `${url.pathname}${url.search}`;
|
|
190
|
+
const pathLocale = getPathLocale(pathname);
|
|
191
|
+
if (STATIC_ASSET_PATTERN.test(pathname)) return pathLocale ? rewriteTo(stripLocalePrefix(pathname, pathLocale), url.search) : PASS;
|
|
192
|
+
if (noPrefix) return handleNoPrefix(request, pathname, current);
|
|
193
|
+
const localeDomain = pathLocale && domains?.[pathLocale];
|
|
194
|
+
if (localeDomain && getDomainHostname(localeDomain) !== url.hostname) return {
|
|
195
|
+
kind: "redirect",
|
|
196
|
+
location: `${getDomainOrigin(localeDomain)}${encodeURI(stripLocalePrefix(pathname, pathLocale))}${url.search}`,
|
|
197
|
+
status: 301
|
|
198
|
+
};
|
|
199
|
+
if (!pathLocale) {
|
|
200
|
+
const domainLocale = getLocaleFromDomain(url.hostname, domains);
|
|
201
|
+
if (domainLocale) return rewriteTo(getCanonicalPath(pathname, domainLocale, rewriteRules), url.search, domainLocale);
|
|
202
|
+
return handleMissingPathLocale(request, pathname, current);
|
|
203
|
+
}
|
|
204
|
+
return handleExistingPathLocale(request, pathname, pathLocale, current);
|
|
205
|
+
};
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
//#endregion
|
|
209
|
+
export { createLocaleRouting };
|
|
210
|
+
//# sourceMappingURL=localeRouting.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"localeRouting.mjs","names":[],"sources":["../../src/localeRouting.ts"],"sourcesContent":["import { ROUTING_MODE } from '@intlayer/config/defaultValues';\nimport {\n getCanonicalPath,\n getDomainHostname,\n getDomainOrigin,\n getLocaleFromDomain,\n getRewriteRules,\n isProxyStorageLocaleEnabled,\n localeDetector,\n resolveLocalizedPath,\n resolveProxyMode,\n} from '@intlayer/core/localization';\nimport { getCookie, getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * The part of an incoming request the locale routing is decided from.\n */\nexport type LocaleRoutingRequest = {\n url: URL;\n headers: Headers;\n};\n\n/**\n * What the locale routing decided for a request.\n *\n * - `pass` — leave the request untouched (proxy disabled, ignored path).\n * - `rewrite` — keep serving the request, but from `path` (locale prefix\n * stripped, rewrite rule resolved to its canonical path). `locale` is the\n * locale the request resolved to, absent for a static asset.\n * - `redirect` — answer with a redirect to `location`. `persistLocale` asks\n * for the locale to be stored on the response so the follow-up request\n * resolves the same locale.\n */\nexport type LocaleRoutingAction =\n | { kind: 'pass' }\n | { kind: 'rewrite'; path: string; locale?: Locale }\n | {\n kind: 'redirect';\n location: string;\n status: 301 | 302;\n persistLocale?: Locale;\n };\n\nexport type LocaleRoutingOptions = {\n /**\n * Whether a development server is serving the app. In `enableProxy: auto`\n * mode, a development server ignores the stored locale (cookie / header)\n * when deciding where a request goes, so a stale cookie cannot keep pulling\n * every navigation to another locale while developing.\n *\n * @default process.env.NODE_ENV === 'development'\n */\n isDevServer?: boolean;\n /**\n * Requests to leave untouched, in addition to static assets.\n */\n ignore?: (request: LocaleRoutingRequest) => boolean;\n};\n\nexport type LocaleRoutingConfiguration = Pick<\n IntlayerConfig,\n 'internationalization' | 'routing'\n>;\n\n/** Matches a pathname ending with a file extension (`/logo.svg`). */\nconst STATIC_ASSET_PATTERN = /\\.[a-zA-Z0-9]+$/;\n\nconst PASS: LocaleRoutingAction = { kind: 'pass' };\n\n/**\n * Decodes a pathname so it can be matched against the rewrite rules, which are\n * written with the characters the locale actually uses (`/doc/релизы`) while\n * the browser sends them percent-encoded. A malformed escape is kept as is.\n */\nconst decodePathname = (pathname: string): string => {\n try {\n return decodeURI(pathname);\n } catch {\n return pathname;\n }\n};\n\n/**\n * Removes a trailing slash, except on the root path. A redirect to `/fr/`\n * would otherwise ping-pong with any trailing-slash normalisation downstream.\n */\nconst trimTrailingSlash = (path: string): string =>\n path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;\n\n/**\n * Removes `/{locale}` from the start of a pathname that carries that prefix.\n */\nconst stripLocalePrefix = (pathname: string, locale: Locale): string =>\n pathname.slice(`/${locale}`.length) || '/';\n\n/**\n * Builds the locale-routing resolver of a Remix application.\n *\n * Decides, for each request, whether to serve it as is, serve it from another\n * internal path, or redirect it — mirroring the Intlayer proxies of\n * `next-intlayer` and `vite-intlayer`. Unlike them, an internal rewrite hands\n * the router the path *without* its locale prefix: the Remix router has no\n * trailing-slash normalisation to work around, and this lets an application\n * declare each route once (`/about`) whatever the routing mode, the locale\n * being read from the request context instead of a route param.\n *\n * @param configuration - The `internationalization` and `routing` configuration.\n * @param options - Runtime options.\n * @returns A pure function deciding the routing of a request.\n *\n * @example\n * ```ts\n * const resolveLocaleRouting = createLocaleRouting(configuration);\n *\n * resolveLocaleRouting({ url: new URL('http://host/fr/about'), headers });\n * // { kind: 'rewrite', path: '/about', locale: 'fr' }\n * ```\n */\nexport const createLocaleRouting = (\n configuration: LocaleRoutingConfiguration,\n options: LocaleRoutingOptions = {}\n): ((request: LocaleRoutingRequest) => LocaleRoutingAction) => {\n const { isDevServer = process.env.NODE_ENV === 'development', ignore } =\n options;\n const { locales, defaultLocale } = configuration.internationalization;\n const {\n basePath = '',\n mode = ROUTING_MODE,\n rewrite,\n domains,\n enableProxy,\n } = configuration.routing ?? {};\n\n const proxyMode = resolveProxyMode(enableProxy);\n const canUseStorageLocale = isProxyStorageLocaleEnabled(\n proxyMode,\n isDevServer\n );\n\n const isSearchParamsMode = mode === 'search-params';\n const noPrefix = mode === 'no-prefix' || isSearchParamsMode;\n const prefixDefault = mode === 'prefix-all';\n const rewriteRules = getRewriteRules(rewrite, 'url');\n const normalizedBasePath = trimTrailingSlash(\n basePath && !basePath.startsWith('/') ? `/${basePath}` : basePath\n );\n\n const isSupportedLocale = (value: string | undefined): value is Locale =>\n value !== undefined && locales.includes(value as Locale);\n\n /**\n * Locale carried by the first path segment (`/fr/about` → `fr`).\n */\n const getPathLocale = (pathname: string): Locale | undefined => {\n const firstSegment = pathname.split('/')[1];\n\n return isSupportedLocale(firstSegment) ? firstSegment : undefined;\n };\n\n /**\n * Locale a localized (\"pretty\") path belongs to. `/a-propos` only exists\n * because a rewrite rule maps it to French, so it declares its locale as\n * explicitly as an `/fr` prefix would; rules whose localized path equals the\n * canonical one carry no signal and are skipped.\n */\n const getRewriteLocale = (pathname: string): Locale | undefined =>\n rewriteRules\n ? locales.find(\n (candidate) =>\n getCanonicalPath(pathname, candidate, rewriteRules) !== pathname\n )\n : undefined;\n\n /**\n * Locale persisted by the client (cookie / header), when it may be used as\n * a routing source.\n */\n const getStorageLocale = (headers: Headers): Locale | undefined =>\n canUseStorageLocale\n ? getLocaleFromStorageServer({\n getCookie: (name) =>\n getCookie(name, headers.get('cookie') ?? undefined),\n getHeader: (name) => headers.get(name),\n })\n : undefined;\n\n /**\n * Best locale for a request that names none: storage, then\n * `Accept-Language`, then the default locale.\n */\n const detectLocale = (headers: Headers): Locale => {\n const locale =\n getStorageLocale(headers) ??\n localeDetector(\n { 'accept-language': headers.get('accept-language') ?? undefined },\n locales,\n defaultLocale\n );\n\n return isSupportedLocale(locale) ? locale : defaultLocale;\n };\n\n /**\n * Query string of a URL, with the `locale` param set in `search-params` mode.\n */\n const withLocaleSearch = (search: string, locale: Locale): string => {\n if (!isSearchParamsMode) return search;\n\n const params = new URLSearchParams(search);\n params.set('locale', locale);\n\n return `?${params.toString()}`;\n };\n\n /**\n * Public path of an application path for a locale: base path, then the\n * locale prefix when the routing mode shows one for that locale.\n */\n const toPublicPath = (\n locale: Locale,\n path: string,\n search: string\n ): string => {\n const showPrefix = !noPrefix && (prefixDefault || locale !== defaultLocale);\n const prefixedPath = showPrefix\n ? `/${locale}${path === '/' ? '' : path}`\n : path;\n\n return `${normalizedBasePath}${trimTrailingSlash(prefixedPath)}${withLocaleSearch(search, locale)}`;\n };\n\n /**\n * Internal path handed to the router: base path plus the canonical path.\n */\n const toInternalPath = (path: string, search: string): string =>\n `${normalizedBasePath}${path}${search}`;\n\n const rewriteTo = (\n path: string,\n search: string,\n locale?: Locale\n ): LocaleRoutingAction => ({\n kind: 'rewrite',\n path: encodeURI(toInternalPath(path, search)),\n locale,\n });\n\n /**\n * Same-origin redirect. A target equal to the request itself is served in\n * place instead, so a configuration mismatch can never loop.\n */\n const redirectTo = (\n location: string,\n current: string,\n persistLocale?: Locale\n ): LocaleRoutingAction => {\n const encodedLocation = encodeURI(location);\n\n if (encodedLocation === current) return PASS;\n\n return persistLocale\n ? {\n kind: 'redirect',\n location: encodedLocation,\n status: 302,\n persistLocale,\n }\n : { kind: 'redirect', location: encodedLocation, status: 302 };\n };\n\n /**\n * `no-prefix` and `search-params` modes: the URL never shows a prefix.\n */\n const handleNoPrefix = (\n { url, headers }: LocaleRoutingRequest,\n pathname: string,\n current: string\n ): LocaleRoutingAction => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const canonicalPath = getCanonicalPath(\n stripLocalePrefix(pathname, pathLocale),\n pathLocale,\n rewriteRules\n );\n\n // Stripping the prefix drops the only locale signal from the URL, so the\n // locale is persisted for the follow-up request.\n return redirectTo(\n toPublicPath(pathLocale, canonicalPath, url.search),\n current,\n pathLocale\n );\n }\n\n if (isSearchParamsMode) {\n const searchLocale = url.searchParams.get('locale') ?? undefined;\n const locale =\n getStorageLocale(headers) ??\n (isSupportedLocale(searchLocale) ? searchLocale : undefined) ??\n detectLocale(headers);\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n return searchLocale === locale\n ? rewriteTo(canonicalPath, url.search, locale)\n : redirectTo(\n `${normalizedBasePath}${pathname}${withLocaleSearch(url.search, locale)}`,\n current\n );\n }\n\n const locale = getRewriteLocale(pathname) ?? detectLocale(headers);\n\n return rewriteTo(\n getCanonicalPath(pathname, locale, rewriteRules),\n url.search,\n locale\n );\n };\n\n /**\n * Prefix modes, URL without a locale prefix: redirect to the localized URL\n * when the mode shows a prefix for the resolved locale, serve it otherwise.\n */\n const handleMissingPathLocale = (\n { url, headers }: LocaleRoutingRequest,\n pathname: string,\n current: string\n ): LocaleRoutingAction => {\n // A localized path names its own locale and outranks storage and\n // `Accept-Language`, otherwise `/a-propos` read as `en` matches no rule.\n const locale = getRewriteLocale(pathname) ?? detectLocale(headers);\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n if (prefixDefault || locale !== defaultLocale) {\n const { path: localizedPath } = resolveLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n\n return redirectTo(\n toPublicPath(locale, localizedPath, url.search),\n current\n );\n }\n\n return rewriteTo(canonicalPath, url.search, locale);\n };\n\n /**\n * Prefix modes, URL with a locale prefix: normalise it to its localized\n * form, strip the prefix of the default locale when the mode hides it, and\n * serve the canonical path.\n */\n const handleExistingPathLocale = (\n { url }: LocaleRoutingRequest,\n pathname: string,\n pathLocale: Locale,\n current: string\n ): LocaleRoutingAction => {\n const rawPath = stripLocalePrefix(pathname, pathLocale);\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n const { path: localizedPath, isRewritten } = resolveLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n\n // `/fr/about` → `/fr/a-propos`\n if (isRewritten && localizedPath !== rawPath) {\n return redirectTo(\n toPublicPath(pathLocale, localizedPath, url.search),\n current\n );\n }\n\n // `/en/about` → `/about`. The locale is persisted: the target no longer\n // names it, and detection could otherwise resolve another one.\n if (!prefixDefault && pathLocale === defaultLocale) {\n return redirectTo(\n toPublicPath(pathLocale, localizedPath, url.search),\n current,\n pathLocale\n );\n }\n\n return rewriteTo(canonicalPath, url.search, pathLocale);\n };\n\n return (request): LocaleRoutingAction => {\n if (proxyMode === 'disabled' || ignore?.(request)) return PASS;\n\n const { url } = request;\n const fullPathname = decodePathname(url.pathname);\n\n if (\n normalizedBasePath &&\n fullPathname !== normalizedBasePath &&\n !fullPathname.startsWith(`${normalizedBasePath}/`)\n ) {\n return PASS;\n }\n\n const pathname = fullPathname.slice(normalizedBasePath.length) || '/';\n const current = `${url.pathname}${url.search}`;\n const pathLocale = getPathLocale(pathname);\n\n // Static assets are served from their unprefixed path, untouched otherwise.\n if (STATIC_ASSET_PATTERN.test(pathname)) {\n return pathLocale\n ? rewriteTo(stripLocalePrefix(pathname, pathLocale), url.search)\n : PASS;\n }\n\n if (noPrefix) return handleNoPrefix(request, pathname, current);\n\n // `host/zh/about` → `https://host.zh/about` when `zh` has its own domain.\n // Domain mapping is stable configuration, hence a cacheable 301.\n const localeDomain = pathLocale && domains?.[pathLocale];\n\n if (localeDomain && getDomainHostname(localeDomain) !== url.hostname) {\n return {\n kind: 'redirect',\n location: `${getDomainOrigin(localeDomain)}${encodeURI(stripLocalePrefix(pathname, pathLocale))}${url.search}`,\n status: 301,\n };\n }\n\n // `host.zh/about` → `/about` as `zh`: the hostname alone names the locale.\n if (!pathLocale) {\n const domainLocale = getLocaleFromDomain(url.hostname, domains);\n\n if (domainLocale) {\n return rewriteTo(\n getCanonicalPath(pathname, domainLocale, rewriteRules),\n url.search,\n domainLocale\n );\n }\n\n return handleMissingPathLocale(request, pathname, current);\n }\n\n return handleExistingPathLocale(request, pathname, pathLocale, current);\n };\n};\n"],"mappings":"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"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { compileMarkdown, installIntlayerMarkdown, installIntlayerMarkdownDynamic, parseMarkdown, renderMarkdown, useMarkdown, useMarkdownRenderer } from "vanilla-intlayer/markdown";
|
|
2
|
+
|
|
3
|
+
export { compileMarkdown, installIntlayerMarkdown, installIntlayerMarkdownDynamic, parseMarkdown, renderMarkdown, useMarkdown, useMarkdownRenderer };
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { INTLAYER_CONTEXT_PROPERTY, Intlayer } from "./context.mjs";
|
|
2
|
+
import { createLocaleRouting } from "./localeRouting.mjs";
|
|
3
|
+
import { withLocaleHeaders, writeLocaleHeaders } from "./persistLocale.mjs";
|
|
4
|
+
import { requestStorage } from "./requestStorage.mjs";
|
|
5
|
+
import { internationalization, routing } from "@intlayer/config/built";
|
|
6
|
+
import { getConfiguration } from "@intlayer/config/node";
|
|
7
|
+
import { getLocaleFromRequest } from "@intlayer/core/localization";
|
|
8
|
+
import { prepareIntlayer } from "@intlayer/engine/build";
|
|
9
|
+
|
|
10
|
+
//#region src/middleware.ts
|
|
11
|
+
/**
|
|
12
|
+
* Builds the redirect response of a locale-routing decision.
|
|
13
|
+
*
|
|
14
|
+
* Built by hand rather than with `Response.redirect`, whose headers are
|
|
15
|
+
* immutable and could not carry the locale cookie.
|
|
16
|
+
*/
|
|
17
|
+
const createRedirectResponse = (action) => {
|
|
18
|
+
const headers = new Headers({ location: action.location });
|
|
19
|
+
if (action.persistLocale) writeLocaleHeaders(headers, action.persistLocale, { includeCookie: true });
|
|
20
|
+
return new Response(null, {
|
|
21
|
+
status: action.status,
|
|
22
|
+
headers
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Remix 3 router middleware handling the internationalization layer:
|
|
27
|
+
* locale routing (redirects and internal rewrites, as `next-intlayer` and
|
|
28
|
+
* `vite-intlayer` do), locale resolution and locale persistence.
|
|
29
|
+
*
|
|
30
|
+
* Locale routing follows `routing.mode`. In the prefix modes, `/fr/about` is
|
|
31
|
+
* served from the `/about` route as French, `/about` is redirected to the
|
|
32
|
+
* localized URL of the detected locale (cookie / header, then
|
|
33
|
+
* `Accept-Language`) unless that locale needs no prefix, and `routing.rewrite`
|
|
34
|
+
* rules are applied both ways (`/fr/about` → `/fr/a-propos`). The router
|
|
35
|
+
* therefore matches every locale against the same unprefixed routes, and
|
|
36
|
+
* `routing.enableProxy: false` turns the routing off while keeping the
|
|
37
|
+
* locale resolution.
|
|
38
|
+
*
|
|
39
|
+
* The resolved locale is exposed as `context.get(Intlayer)` /
|
|
40
|
+
* `context.intlayer`, and the rest of the request runs inside an
|
|
41
|
+
* `AsyncLocalStorage` scope bound to the request context, so the hooks of this
|
|
42
|
+
* package (`useLocale`, `useIntlayer`, `useDictionary`) read that state from
|
|
43
|
+
* anywhere downstream — route handlers, views, Remix UI components — with the
|
|
44
|
+
* same signature as `react-intlayer`.
|
|
45
|
+
*
|
|
46
|
+
* @param options - Locale-routing options.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```ts
|
|
50
|
+
* import { createRouter } from 'remix/router';
|
|
51
|
+
* import { intlayer, useIntlayer } from 'remix-intlayer';
|
|
52
|
+
*
|
|
53
|
+
* const router = createRouter({ middleware: [intlayer()] });
|
|
54
|
+
*
|
|
55
|
+
* // Serves `/`, `/fr`, `/es`… — the locale comes from the request context.
|
|
56
|
+
* router.get('/', () => {
|
|
57
|
+
* const { title } = useIntlayer('home');
|
|
58
|
+
* return new Response(title);
|
|
59
|
+
* });
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
const intlayer = (options = {}) => {
|
|
63
|
+
const configuration = getConfiguration();
|
|
64
|
+
prepareIntlayer(configuration);
|
|
65
|
+
const resolveLocaleRouting = createLocaleRouting({
|
|
66
|
+
internationalization: configuration.internationalization ?? internationalization,
|
|
67
|
+
routing: configuration.routing ?? routing
|
|
68
|
+
}, options);
|
|
69
|
+
return async (context, next) => {
|
|
70
|
+
const action = resolveLocaleRouting(context);
|
|
71
|
+
if (action.kind === "redirect") return createRedirectResponse(action);
|
|
72
|
+
let routedLocale;
|
|
73
|
+
if (action.kind === "rewrite") {
|
|
74
|
+
context.url = new URL(action.path, context.url);
|
|
75
|
+
routedLocale = action.locale;
|
|
76
|
+
}
|
|
77
|
+
const locale = routedLocale ?? await getLocaleFromRequest(context);
|
|
78
|
+
if (routedLocale) writeLocaleHeaders(context.headers, routedLocale);
|
|
79
|
+
context.set(Intlayer, {
|
|
80
|
+
locale,
|
|
81
|
+
defaultLocale: configuration.internationalization?.defaultLocale ?? internationalization.defaultLocale,
|
|
82
|
+
availableLocales: configuration.internationalization?.locales ?? internationalization.locales
|
|
83
|
+
}, { property: INTLAYER_CONTEXT_PROPERTY });
|
|
84
|
+
const response = await requestStorage.run(context, next);
|
|
85
|
+
return routedLocale ? withLocaleHeaders(response, routedLocale) : response;
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
//#endregion
|
|
90
|
+
export { intlayer };
|
|
91
|
+
//# sourceMappingURL=middleware.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.mjs","names":[],"sources":["../../src/middleware.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { getLocaleFromRequest } from '@intlayer/core/localization';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { Middleware } from 'remix/router';\nimport {\n INTLAYER_CONTEXT_PROPERTY,\n Intlayer,\n type IntlayerState,\n} from './context';\nimport {\n createLocaleRouting,\n type LocaleRoutingAction,\n type LocaleRoutingOptions,\n} from './localeRouting';\nimport { withLocaleHeaders, writeLocaleHeaders } from './persistLocale';\nimport { requestStorage } from './requestStorage';\n\nexport type IntlayerMiddlewareOptions = LocaleRoutingOptions;\n\n/**\n * Builds the redirect response of a locale-routing decision.\n *\n * Built by hand rather than with `Response.redirect`, whose headers are\n * immutable and could not carry the locale cookie.\n */\nconst createRedirectResponse = (\n action: Extract<LocaleRoutingAction, { kind: 'redirect' }>\n): Response => {\n const headers = new Headers({ location: action.location });\n\n if (action.persistLocale) {\n writeLocaleHeaders(headers, action.persistLocale, { includeCookie: true });\n }\n\n return new Response(null, { status: action.status, headers });\n};\n\n/**\n * Remix 3 router middleware handling the internationalization layer:\n * locale routing (redirects and internal rewrites, as `next-intlayer` and\n * `vite-intlayer` do), locale resolution and locale persistence.\n *\n * Locale routing follows `routing.mode`. In the prefix modes, `/fr/about` is\n * served from the `/about` route as French, `/about` is redirected to the\n * localized URL of the detected locale (cookie / header, then\n * `Accept-Language`) unless that locale needs no prefix, and `routing.rewrite`\n * rules are applied both ways (`/fr/about` → `/fr/a-propos`). The router\n * therefore matches every locale against the same unprefixed routes, and\n * `routing.enableProxy: false` turns the routing off while keeping the\n * locale resolution.\n *\n * The resolved locale is exposed as `context.get(Intlayer)` /\n * `context.intlayer`, and the rest of the request runs inside an\n * `AsyncLocalStorage` scope bound to the request context, so the hooks of this\n * package (`useLocale`, `useIntlayer`, `useDictionary`) read that state from\n * anywhere downstream — route handlers, views, Remix UI components — with the\n * same signature as `react-intlayer`.\n *\n * @param options - Locale-routing options.\n *\n * @example\n * ```ts\n * import { createRouter } from 'remix/router';\n * import { intlayer, useIntlayer } from 'remix-intlayer';\n *\n * const router = createRouter({ middleware: [intlayer()] });\n *\n * // Serves `/`, `/fr`, `/es`… — the locale comes from the request context.\n * router.get('/', () => {\n * const { title } = useIntlayer('home');\n * return new Response(title);\n * });\n * ```\n */\nexport const intlayer = (\n options: IntlayerMiddlewareOptions = {}\n): Middleware<{\n key: typeof Intlayer;\n value: IntlayerState;\n property: typeof INTLAYER_CONTEXT_PROPERTY;\n}> => {\n // Ensures the generated dictionaries exist when the server starts without a\n // prior `intlayer build`. Fire-and-forget, like the other server integrations.\n const configuration = getConfiguration();\n prepareIntlayer(configuration);\n\n const resolveLocaleRouting = createLocaleRouting(\n {\n internationalization:\n configuration.internationalization ?? internationalization,\n routing: configuration.routing ?? routing,\n },\n options\n );\n\n return async (context, next) => {\n const action = resolveLocaleRouting(context);\n\n if (action.kind === 'redirect') return createRedirectResponse(action);\n\n let routedLocale: Locale | undefined;\n\n if (action.kind === 'rewrite') {\n // The router matches against `context.url`, so reassigning it is the\n // internal rewrite. The original request stays untouched.\n context.url = new URL(action.path, context.url);\n routedLocale = action.locale;\n }\n\n const locale =\n routedLocale ?? ((await getLocaleFromRequest(context)) as Locale);\n\n if (routedLocale) {\n // Propagates the locale downstream through the configured storage\n // header, like the Next.js and Vite proxies do.\n writeLocaleHeaders(context.headers, routedLocale);\n }\n\n context.set(\n Intlayer,\n {\n locale: locale as DeclaredLocales,\n defaultLocale: (configuration.internationalization?.defaultLocale ??\n internationalization.defaultLocale) as DeclaredLocales,\n availableLocales: (configuration.internationalization?.locales ??\n internationalization.locales) as DeclaredLocales[],\n },\n { property: INTLAYER_CONTEXT_PROPERTY }\n );\n\n const response = await requestStorage.run(context, next);\n\n return routedLocale ? withLocaleHeaders(response, routedLocale) : response;\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,0BACJ,WACa;CACb,MAAM,UAAU,IAAI,QAAQ,EAAE,UAAU,OAAO,SAAS,CAAC;CAEzD,IAAI,OAAO,eACT,mBAAmB,SAAS,OAAO,eAAe,EAAE,eAAe,KAAK,CAAC;CAG3E,OAAO,IAAI,SAAS,MAAM;EAAE,QAAQ,OAAO;EAAQ;CAAQ,CAAC;AAC9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,YACX,UAAqC,CAAC,MAKlC;CAGJ,MAAM,gBAAgB,iBAAiB;CACvC,gBAAgB,aAAa;CAE7B,MAAM,uBAAuB,oBAC3B;EACE,sBACE,cAAc,wBAAwB;EACxC,SAAS,cAAc,WAAW;CACpC,GACA,OACF;CAEA,OAAO,OAAO,SAAS,SAAS;EAC9B,MAAM,SAAS,qBAAqB,OAAO;EAE3C,IAAI,OAAO,SAAS,YAAY,OAAO,uBAAuB,MAAM;EAEpE,IAAI;EAEJ,IAAI,OAAO,SAAS,WAAW;GAG7B,QAAQ,MAAM,IAAI,IAAI,OAAO,MAAM,QAAQ,GAAG;GAC9C,eAAe,OAAO;EACxB;EAEA,MAAM,SACJ,gBAAkB,MAAM,qBAAqB,OAAO;EAEtD,IAAI,cAGF,mBAAmB,QAAQ,SAAS,YAAY;EAGlD,QAAQ,IACN,UACA;GACU;GACR,eAAgB,cAAc,sBAAsB,iBAClD,qBAAqB;GACvB,kBAAmB,cAAc,sBAAsB,WACrD,qBAAqB;EACzB,GACA,EAAE,UAAU,0BAA0B,CACxC;EAEA,MAAM,WAAW,MAAM,eAAe,IAAI,SAAS,IAAI;EAEvD,OAAO,eAAe,kBAAkB,UAAU,YAAY,IAAI;CACpE;AACF"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { setLocaleInStorageServer } from "@intlayer/core/utils";
|
|
2
|
+
import { SetCookie } from "remix/headers";
|
|
3
|
+
|
|
4
|
+
//#region src/persistLocale.ts
|
|
5
|
+
/**
|
|
6
|
+
* Serializes a locale cookie as a `Set-Cookie` header value.
|
|
7
|
+
*/
|
|
8
|
+
const serializeCookie = (name, value, attributes) => new SetCookie({
|
|
9
|
+
name,
|
|
10
|
+
value,
|
|
11
|
+
path: attributes.path,
|
|
12
|
+
domain: attributes.domain,
|
|
13
|
+
expires: attributes.expires === void 0 ? void 0 : new Date(attributes.expires),
|
|
14
|
+
secure: attributes.secure,
|
|
15
|
+
httpOnly: attributes.httpOnly,
|
|
16
|
+
sameSite: attributes.sameSite ? attributes.sameSite.charAt(0).toUpperCase() + attributes.sameSite.slice(1) : void 0
|
|
17
|
+
}).toString();
|
|
18
|
+
/**
|
|
19
|
+
* Writes the locale into the storage headers configured in `routing.storage`
|
|
20
|
+
* (custom header, and the cookie when `includeCookie` is set).
|
|
21
|
+
*/
|
|
22
|
+
const writeLocaleHeaders = (headers, locale, { includeCookie = false } = {}) => setLocaleInStorageServer(locale, {
|
|
23
|
+
setHeader: (name, value) => headers.set(name, value),
|
|
24
|
+
setCookieStore: includeCookie ? (name, value, attributes) => headers.append("set-cookie", serializeCookie(name, value, attributes)) : void 0
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* Returns the response with the locale headers set. A response whose headers
|
|
28
|
+
* are immutable (`Response.redirect`, `Response.error`) is re-created.
|
|
29
|
+
*/
|
|
30
|
+
const withLocaleHeaders = (response, locale) => {
|
|
31
|
+
const localeHeaders = new Headers();
|
|
32
|
+
writeLocaleHeaders(localeHeaders, locale);
|
|
33
|
+
try {
|
|
34
|
+
for (const [name, value] of localeHeaders) response.headers.set(name, value);
|
|
35
|
+
return response;
|
|
36
|
+
} catch {
|
|
37
|
+
const headers = new Headers(response.headers);
|
|
38
|
+
for (const [name, value] of localeHeaders) headers.set(name, value);
|
|
39
|
+
return new Response(response.body, {
|
|
40
|
+
status: response.status,
|
|
41
|
+
statusText: response.statusText,
|
|
42
|
+
headers
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
//#endregion
|
|
48
|
+
export { withLocaleHeaders, writeLocaleHeaders };
|
|
49
|
+
//# sourceMappingURL=persistLocale.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"persistLocale.mjs","names":[],"sources":["../../src/persistLocale.ts"],"sourcesContent":["import {\n type CookieBuildAttributes,\n setLocaleInStorageServer,\n} from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { SetCookie } from 'remix/headers';\n\n/**\n * Serializes a locale cookie as a `Set-Cookie` header value.\n */\nconst serializeCookie = (\n name: string,\n value: string,\n attributes: CookieBuildAttributes\n): string =>\n new SetCookie({\n name,\n value,\n path: attributes.path,\n domain: attributes.domain,\n expires:\n attributes.expires === undefined\n ? undefined\n : new Date(attributes.expires),\n secure: attributes.secure,\n httpOnly: attributes.httpOnly,\n sameSite: attributes.sameSite\n ? ((attributes.sameSite.charAt(0).toUpperCase() +\n attributes.sameSite.slice(1)) as 'Strict' | 'Lax' | 'None')\n : undefined,\n }).toString();\n\n/**\n * Writes the locale into the storage headers configured in `routing.storage`\n * (custom header, and the cookie when `includeCookie` is set).\n */\nexport const writeLocaleHeaders = (\n headers: Headers,\n locale: Locale,\n { includeCookie = false }: { includeCookie?: boolean } = {}\n): void =>\n setLocaleInStorageServer(locale, {\n setHeader: (name, value) => headers.set(name, value),\n setCookieStore: includeCookie\n ? (name, value, attributes) =>\n headers.append('set-cookie', serializeCookie(name, value, attributes))\n : undefined,\n });\n\n/**\n * Returns the response with the locale headers set. A response whose headers\n * are immutable (`Response.redirect`, `Response.error`) is re-created.\n */\nexport const withLocaleHeaders = (\n response: Response,\n locale: Locale\n): Response => {\n // Written apart first: `setLocaleInStorageServer` swallows setter errors,\n // so an immutable target has to be detected on the copy.\n const localeHeaders = new Headers();\n writeLocaleHeaders(localeHeaders, locale);\n\n try {\n for (const [name, value] of localeHeaders) {\n response.headers.set(name, value);\n }\n\n return response;\n } catch {\n const headers = new Headers(response.headers);\n\n for (const [name, value] of localeHeaders) {\n headers.set(name, value);\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n};\n"],"mappings":";;;;;;;AAUA,MAAM,mBACJ,MACA,OACA,eAEA,IAAI,UAAU;CACZ;CACA;CACA,MAAM,WAAW;CACjB,QAAQ,WAAW;CACnB,SACE,WAAW,YAAY,SACnB,SACA,IAAI,KAAK,WAAW,OAAO;CACjC,QAAQ,WAAW;CACnB,UAAU,WAAW;CACrB,UAAU,WAAW,WACf,WAAW,SAAS,OAAO,CAAC,CAAC,CAAC,YAAY,IAC1C,WAAW,SAAS,MAAM,CAAC,IAC7B;AACN,CAAC,CAAC,CAAC,SAAS;;;;;AAMd,MAAa,sBACX,SACA,QACA,EAAE,gBAAgB,UAAuC,CAAC,MAE1D,yBAAyB,QAAQ;CAC/B,YAAY,MAAM,UAAU,QAAQ,IAAI,MAAM,KAAK;CACnD,gBAAgB,iBACX,MAAM,OAAO,eACZ,QAAQ,OAAO,cAAc,gBAAgB,MAAM,OAAO,UAAU,CAAC,IACvE;AACN,CAAC;;;;;AAMH,MAAa,qBACX,UACA,WACa;CAGb,MAAM,gBAAgB,IAAI,QAAQ;CAClC,mBAAmB,eAAe,MAAM;CAExC,IAAI;EACF,KAAK,MAAM,CAAC,MAAM,UAAU,eAC1B,SAAS,QAAQ,IAAI,MAAM,KAAK;EAGlC,OAAO;CACT,QAAQ;EACN,MAAM,UAAU,IAAI,QAAQ,SAAS,OAAO;EAE5C,KAAK,MAAM,CAAC,MAAM,UAAU,eAC1B,QAAQ,IAAI,MAAM,KAAK;EAGzB,OAAO,IAAI,SAAS,SAAS,MAAM;GACjC,QAAQ,SAAS;GACjB,YAAY,SAAS;GACrB;EACF,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Intlayer } from "./context.mjs";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
|
|
4
|
+
//#region src/requestStorage.ts
|
|
5
|
+
/**
|
|
6
|
+
* Request context of the request being handled, made available to every
|
|
7
|
+
* function running inside the `intlayer()` middleware scope — route handlers,
|
|
8
|
+
* views, Remix UI components rendered from them — without passing it around.
|
|
9
|
+
*/
|
|
10
|
+
const requestStorage = new AsyncLocalStorage();
|
|
11
|
+
/**
|
|
12
|
+
* Returns the Intlayer state of the request being handled, if any.
|
|
13
|
+
*/
|
|
14
|
+
const getIntlayerState = () => requestStorage.getStore()?.get(Intlayer);
|
|
15
|
+
/**
|
|
16
|
+
* Returns the locale of the request being handled, if any.
|
|
17
|
+
*/
|
|
18
|
+
const getRequestLocale = () => getIntlayerState()?.locale;
|
|
19
|
+
|
|
20
|
+
//#endregion
|
|
21
|
+
export { getIntlayerState, getRequestLocale, requestStorage };
|
|
22
|
+
//# sourceMappingURL=requestStorage.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"requestStorage.mjs","names":[],"sources":["../../src/requestStorage.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { RequestContext } from 'remix/router';\nimport { Intlayer, type IntlayerState } from './context';\n\n/**\n * Request context of the request being handled, made available to every\n * function running inside the `intlayer()` middleware scope — route handlers,\n * views, Remix UI components rendered from them — without passing it around.\n */\nexport const requestStorage = new AsyncLocalStorage<RequestContext<any, any>>();\n\n/**\n * Returns the Intlayer state of the request being handled, if any.\n */\nexport const getIntlayerState = (): IntlayerState | undefined =>\n requestStorage.getStore()?.get(Intlayer) as IntlayerState | undefined;\n\n/**\n * Returns the locale of the request being handled, if any.\n */\nexport const getRequestLocale = (): DeclaredLocales | undefined =>\n getIntlayerState()?.locale;\n"],"mappings":";;;;;;;;;AAUA,MAAa,iBAAiB,IAAI,kBAA4C;;;;AAK9E,MAAa,yBACX,eAAe,SAAS,CAAC,EAAE,IAAI,QAAQ;;;;AAKzC,MAAa,yBACX,iBAAiB,CAAC,EAAE"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { IntlayerProvider } from "./IntlayerProvider.mjs";
|
|
2
|
+
import { Intlayer } from "./middleware.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/resolveLocale.ts
|
|
5
|
+
/**
|
|
6
|
+
* A component `Handle` carries its context store under `context`, whereas a
|
|
7
|
+
* `RequestContext` exposes `get`/`set` directly.
|
|
8
|
+
*/
|
|
9
|
+
const isHandle = (source) => "context" in source && typeof source.context?.get === "function";
|
|
10
|
+
/**
|
|
11
|
+
* Reads the locale published to the given source, if any.
|
|
12
|
+
*/
|
|
13
|
+
const resolveLocale = (source) => {
|
|
14
|
+
if (isHandle(source)) return source.context.get(IntlayerProvider)?.locale;
|
|
15
|
+
return source.get(Intlayer)?.locale;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
//#endregion
|
|
19
|
+
export { resolveLocale };
|
|
20
|
+
//# sourceMappingURL=resolveLocale.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolveLocale.mjs","names":[],"sources":["../../src/resolveLocale.ts"],"sourcesContent":["import type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { RequestContext } from 'remix/router';\nimport type { Handle } from 'remix/ui';\nimport { IntlayerProvider } from './IntlayerProvider';\nimport { Intlayer, type IntlayerState } from './middleware';\n\n/**\n * Where a hook reads the current locale from:\n * - a Remix router `RequestContext`, populated by the `intlayer()` middleware\n * - a Remix UI component `Handle`, populated by an ancestor `IntlayerProvider`\n */\nexport type IntlayerSource = RequestContext<any, any> | Handle<any, any>;\n\n/**\n * A component `Handle` carries its context store under `context`, whereas a\n * `RequestContext` exposes `get`/`set` directly.\n */\nconst isHandle = (source: IntlayerSource): source is Handle<any, any> =>\n 'context' in source &&\n typeof (source as Handle<any, any>).context?.get === 'function';\n\n/**\n * Reads the locale published to the given source, if any.\n */\nexport const resolveLocale = (\n source: IntlayerSource\n): DeclaredLocales | undefined => {\n if (isHandle(source)) {\n return source.context.get(IntlayerProvider)?.locale;\n }\n\n return (source.get(Intlayer) as IntlayerState | undefined)?.locale;\n};\n"],"mappings":";;;;;;;;AAiBA,MAAM,YAAY,WAChB,aAAa,UACb,OAAQ,OAA4B,SAAS,QAAQ;;;;AAKvD,MAAa,iBACX,WACgC;CAChC,IAAI,SAAS,MAAM,GACjB,OAAO,OAAO,QAAQ,IAAI,gBAAgB,CAAC,EAAE;CAG/C,OAAQ,OAAO,IAAI,QAAQ,CAAC,EAAgC;AAC9D"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { getRequestLocale } from "./requestStorage.mjs";
|
|
2
|
+
import { resolveDictionaryArgument } from "@intlayer/core/dictionaryManipulator";
|
|
3
|
+
import { getDictionary } from "@intlayer/core/interpreter";
|
|
4
|
+
|
|
5
|
+
//#region src/useDictionary.ts
|
|
6
|
+
/**
|
|
7
|
+
* Transforms an imported dictionary (or qualified dictionary group) and returns
|
|
8
|
+
* its content for the locale of the request being handled.
|
|
9
|
+
*
|
|
10
|
+
* The second argument is either a locale or a selector object
|
|
11
|
+
* (`{ item }`, `{ variant }`, optionally with `locale`); it takes precedence
|
|
12
|
+
* over the request locale.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* import homeContent from './home.content';
|
|
17
|
+
*
|
|
18
|
+
* router.get('/', () => {
|
|
19
|
+
* const { title } = useDictionary(homeContent);
|
|
20
|
+
* return new Response(title);
|
|
21
|
+
* });
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
const useDictionary = (dictionary, localeOrSelector) => getDictionary(dictionary, resolveDictionaryArgument({
|
|
25
|
+
localeOrSelector,
|
|
26
|
+
contextLocale: getRequestLocale(),
|
|
27
|
+
dictionaryKey: dictionary.key
|
|
28
|
+
}));
|
|
29
|
+
|
|
30
|
+
//#endregion
|
|
31
|
+
export { useDictionary };
|
|
32
|
+
//# sourceMappingURL=useDictionary.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useDictionary.mjs","names":[],"sources":["../../src/useDictionary.ts"],"sourcesContent":["import { resolveDictionaryArgument } from '@intlayer/core/dictionaryManipulator';\nimport { getDictionary } from '@intlayer/core/interpreter';\nimport type {\n Dictionary,\n DictionarySelectorForGroup,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { getRequestLocale } from './requestStorage';\n\n/**\n * Transforms an imported dictionary (or qualified dictionary group) and returns\n * its content for the locale of the request being handled.\n *\n * The second argument is either a locale or a selector object\n * (`{ item }`, `{ variant }`, optionally with `locale`); it takes precedence\n * over the request locale.\n *\n * @example\n * ```ts\n * import homeContent from './home.content';\n *\n * router.get('/', () => {\n * const { title } = useDictionary(homeContent);\n * return new Response(title);\n * });\n * ```\n */\nexport const useDictionary = <\n const T extends Dictionary | QualifiedDictionaryGroup,\n const A extends\n | LocalesValues\n | DictionarySelectorForGroup<T> = DeclaredLocales,\n>(\n dictionary: T,\n localeOrSelector?: A\n) =>\n getDictionary<T, A>(\n dictionary,\n resolveDictionaryArgument({\n localeOrSelector,\n contextLocale: getRequestLocale(),\n dictionaryKey: dictionary.key,\n }) as A\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,iBAMX,YACA,qBAEA,cACE,YACA,0BAA0B;CACxB;CACA,eAAe,iBAAiB;CAChC,eAAe,WAAW;AAC5B,CAAC,CACH"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { getRequestLocale } from "./requestStorage.mjs";
|
|
2
|
+
import { resolveDictionaryArgument } from "@intlayer/core/dictionaryManipulator";
|
|
3
|
+
import { getIntlayer } from "@intlayer/core/interpreter";
|
|
4
|
+
|
|
5
|
+
//#region src/useIntlayer.ts
|
|
6
|
+
/**
|
|
7
|
+
* Picks one dictionary by its key and returns its content for the locale of
|
|
8
|
+
* the request being handled.
|
|
9
|
+
*
|
|
10
|
+
* The second argument is either a locale or a selector object
|
|
11
|
+
* (`{ item }`, `{ variant }`, optionally with `locale`); it takes precedence
|
|
12
|
+
* over the request locale.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* router.get('/', () => {
|
|
17
|
+
* const { title } = useIntlayer('home');
|
|
18
|
+
* return new Response(title);
|
|
19
|
+
* });
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
const useIntlayer = (key, localeOrSelector) => getIntlayer(key, resolveDictionaryArgument({
|
|
23
|
+
localeOrSelector,
|
|
24
|
+
contextLocale: getRequestLocale(),
|
|
25
|
+
dictionaryKey: key
|
|
26
|
+
}));
|
|
27
|
+
|
|
28
|
+
//#endregion
|
|
29
|
+
export { useIntlayer };
|
|
30
|
+
//# sourceMappingURL=useIntlayer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useIntlayer.mjs","names":[],"sources":["../../src/useIntlayer.ts"],"sourcesContent":["import { resolveDictionaryArgument } from '@intlayer/core/dictionaryManipulator';\nimport { getIntlayer } from '@intlayer/core/interpreter';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionarySelectorForKey,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { getRequestLocale } from './requestStorage';\n\n/**\n * Picks one dictionary by its key and returns its content for the locale of\n * the request being handled.\n *\n * The second argument is either a locale or a selector object\n * (`{ item }`, `{ variant }`, optionally with `locale`); it takes precedence\n * over the request locale.\n *\n * @example\n * ```ts\n * router.get('/', () => {\n * const { title } = useIntlayer('home');\n * return new Response(title);\n * });\n * ```\n */\nexport const useIntlayer = <\n const T extends DictionaryKeys,\n const A extends LocalesValues | DictionarySelectorForKey<T> = DeclaredLocales,\n>(\n key: T,\n localeOrSelector?: A\n) =>\n getIntlayer<T, A>(\n key,\n resolveDictionaryArgument({\n localeOrSelector,\n contextLocale: getRequestLocale(),\n dictionaryKey: key as string,\n }) as A\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,eAIX,KACA,qBAEA,YACE,KACA,0BAA0B;CACxB;CACA,eAAe,iBAAiB;CAChC,eAAe;AACjB,CAAC,CACH"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { getIntlayerState } from "./requestStorage.mjs";
|
|
2
|
+
import { internationalization } from "@intlayer/config/built";
|
|
3
|
+
|
|
4
|
+
//#region src/useLocale.ts
|
|
5
|
+
const { defaultLocale, locales: availableLocales } = internationalization;
|
|
6
|
+
/**
|
|
7
|
+
* Returns the locale of the request being handled, with the configured
|
|
8
|
+
* default and available locales.
|
|
9
|
+
*
|
|
10
|
+
* Falls back to the default locale outside of a request, i.e. when the
|
|
11
|
+
* `intlayer()` middleware did not run.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* router.get('/', () => {
|
|
16
|
+
* const { locale, availableLocales } = useLocale();
|
|
17
|
+
* return Response.json({ locale, availableLocales });
|
|
18
|
+
* });
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
const useLocale = () => {
|
|
22
|
+
const state = getIntlayerState();
|
|
23
|
+
return {
|
|
24
|
+
locale: state?.locale ?? defaultLocale,
|
|
25
|
+
defaultLocale: state?.defaultLocale ?? defaultLocale,
|
|
26
|
+
availableLocales: state?.availableLocales ?? availableLocales
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
//#endregion
|
|
31
|
+
export { useLocale };
|
|
32
|
+
//# sourceMappingURL=useLocale.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useLocale.mjs","names":[],"sources":["../../src/useLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport { getIntlayerState, getRequestLocale } from './requestStorage';\n\nexport type UseLocaleResult = {\n locale: DeclaredLocales;\n defaultLocale: DeclaredLocales;\n availableLocales: DeclaredLocales[];\n};\n\nconst { defaultLocale, locales: availableLocales } = internationalization;\n\n/**\n * Returns the locale of the request being handled, with the configured\n * default and available locales.\n *\n * Falls back to the default locale outside of a request, i.e. when the\n * `intlayer()` middleware did not run.\n *\n * @example\n * ```ts\n * router.get('/', () => {\n * const { locale, availableLocales } = useLocale();\n * return Response.json({ locale, availableLocales });\n * });\n * ```\n */\nexport const useLocale = (): UseLocaleResult => {\n const state = getIntlayerState();\n\n return {\n locale: state?.locale ?? (defaultLocale as DeclaredLocales),\n defaultLocale:\n state?.defaultLocale ?? (defaultLocale as DeclaredLocales),\n availableLocales:\n state?.availableLocales ?? (availableLocales as DeclaredLocales[]),\n };\n};\n"],"mappings":";;;;AAUA,MAAM,EAAE,eAAe,SAAS,qBAAqB;;;;;;;;;;;;;;;;AAiBrD,MAAa,kBAAmC;CAC9C,MAAM,QAAQ,iBAAiB;CAE/B,OAAO;EACL,QAAQ,OAAO,UAAW;EAC1B,eACE,OAAO,iBAAkB;EAC3B,kBACE,OAAO,oBAAqB;CAChC;AACF"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { DeclaredLocales, LocalesValues } from "@intlayer/types/module_augmentation";
|
|
2
|
+
import { Handle, RemixNode } from "remix/ui";
|
|
3
|
+
//#region src/IntlayerProvider.d.ts
|
|
4
|
+
export type IntlayerProviderProps = {
|
|
5
|
+
/** Locale to render the subtree with. Defaults to the configured default locale. */
|
|
6
|
+
locale?: LocalesValues;
|
|
7
|
+
children?: RemixNode;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Context value published by {@link IntlayerProvider} to its descendants.
|
|
11
|
+
*/
|
|
12
|
+
export type IntlayerProviderContext = {
|
|
13
|
+
locale: DeclaredLocales;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Remix UI component that publishes the locale to every descendant component,
|
|
17
|
+
* so the hooks of this package can read it from their `Handle`.
|
|
18
|
+
*
|
|
19
|
+
* Nested providers shadow outer ones, following the Remix UI context rules.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```tsx
|
|
23
|
+
* router.get('/', (context) =>
|
|
24
|
+
* context.render(
|
|
25
|
+
* <IntlayerProvider locale={context.intlayer.locale}>
|
|
26
|
+
* <HomePage />
|
|
27
|
+
* </IntlayerProvider>
|
|
28
|
+
* )
|
|
29
|
+
* );
|
|
30
|
+
*
|
|
31
|
+
* function HomePage(handle: Handle) {
|
|
32
|
+
* const { title } = useIntlayer('home', handle);
|
|
33
|
+
* return () => <h1>{title}</h1>;
|
|
34
|
+
* }
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export declare const IntlayerProvider: (handle: Handle<IntlayerProviderProps, IntlayerProviderContext>) => (() => RemixNode);
|
|
38
|
+
//#endregion
|
|
39
|
+
//# sourceMappingURL=IntlayerProvider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IntlayerProvider.d.ts","names":[],"sources":["../../src/IntlayerProvider.ts"],"mappings":";;;YAOY;;EAEV,SAAS;EACT,WAAW;;;;;YAMD;EACV,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;qBAyBG,mBAAgB,QACnB,OAAO,uBAAuB,oCAC9B"}
|