@better-translate/astro 1.0.0
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/LICENSE +21 -0
- package/README.md +5 -0
- package/dist/chunk-2ZLSODTJ.js +105 -0
- package/dist/chunk-3ERZEJZW.js +27 -0
- package/dist/content.cjs +197 -0
- package/dist/content.d.cts +69 -0
- package/dist/content.d.ts +69 -0
- package/dist/content.js +152 -0
- package/dist/index-B2VGZAji.d.cts +30 -0
- package/dist/index-B2VGZAji.d.ts +30 -0
- package/dist/index.cjs +151 -0
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +11 -0
- package/dist/middleware.cjs +83 -0
- package/dist/middleware.d.cts +25 -0
- package/dist/middleware.d.ts +25 -0
- package/dist/middleware.js +33 -0
- package/package.json +66 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jorge Alvarenga
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# @better-translate/astro
|
|
2
|
+
|
|
3
|
+
`@better-translate/astro` adds request helpers, middleware, and localized content helpers for Astro. Use it with `@better-translate/core` when your Astro app needs request-aware translations.
|
|
4
|
+
|
|
5
|
+
Full docs: [better-translate-placeholder.com/en/docs/adapters/astro](https://better-translate-placeholder.com/en/docs/adapters/astro)
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import {
|
|
2
|
+
readRequestCached
|
|
3
|
+
} from "./chunk-3ERZEJZW.js";
|
|
4
|
+
|
|
5
|
+
// src/server.ts
|
|
6
|
+
import {
|
|
7
|
+
getRequestLocale as getStoredRequestLocale,
|
|
8
|
+
resolveRequestLocale,
|
|
9
|
+
setRequestLocale as setStoredRequestLocale
|
|
10
|
+
} from "@better-translate/core/server";
|
|
11
|
+
function getRequestConfig(factory) {
|
|
12
|
+
return factory;
|
|
13
|
+
}
|
|
14
|
+
function setRequestLocale(locale) {
|
|
15
|
+
setStoredRequestLocale(locale);
|
|
16
|
+
}
|
|
17
|
+
function createServerHelpers(requestConfig) {
|
|
18
|
+
const requestConfigCacheKey = /* @__PURE__ */ Symbol("better-translate-astro-request-config");
|
|
19
|
+
function readRequestConfig() {
|
|
20
|
+
return readRequestCached(requestConfigCacheKey, async () => {
|
|
21
|
+
const resolved = await requestConfig();
|
|
22
|
+
const translator = resolved.translator;
|
|
23
|
+
return {
|
|
24
|
+
locale: resolved.locale,
|
|
25
|
+
translator
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
async function getResolvedLocale(options) {
|
|
30
|
+
const { locale: configLocale, translator } = await readRequestConfig();
|
|
31
|
+
return resolveRequestLocale(translator, {
|
|
32
|
+
locale: options?.config?.locale ?? options?.locale,
|
|
33
|
+
requestLocale: getStoredRequestLocale(),
|
|
34
|
+
configLocale
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
async function getDirection(options) {
|
|
38
|
+
const [{ translator }, locale] = await Promise.all([
|
|
39
|
+
readRequestConfig(),
|
|
40
|
+
getResolvedLocale(options)
|
|
41
|
+
]);
|
|
42
|
+
return translator.getDirection({
|
|
43
|
+
config: typeof options?.config?.rtl === "boolean" ? {
|
|
44
|
+
rtl: options.config.rtl
|
|
45
|
+
} : void 0,
|
|
46
|
+
locale
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async function isRtl(options) {
|
|
50
|
+
return await getDirection(options) === "rtl";
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
async getAvailableLanguages() {
|
|
54
|
+
return (await readRequestConfig()).translator.getAvailableLanguages();
|
|
55
|
+
},
|
|
56
|
+
getDirection,
|
|
57
|
+
async getLocale() {
|
|
58
|
+
return getResolvedLocale();
|
|
59
|
+
},
|
|
60
|
+
async getMessages() {
|
|
61
|
+
const [{ translator }, locale] = await Promise.all([
|
|
62
|
+
readRequestConfig(),
|
|
63
|
+
getResolvedLocale()
|
|
64
|
+
]);
|
|
65
|
+
const loadedMessages = await translator.loadLocale(locale);
|
|
66
|
+
const cachedMessages = translator.getMessages()[locale];
|
|
67
|
+
if (loadedMessages) {
|
|
68
|
+
return loadedMessages;
|
|
69
|
+
}
|
|
70
|
+
if (cachedMessages) {
|
|
71
|
+
return cachedMessages;
|
|
72
|
+
}
|
|
73
|
+
throw new Error(
|
|
74
|
+
`Locale "${locale}" messages are not available. Preload them or register a loader in your Better Translate core config.`
|
|
75
|
+
);
|
|
76
|
+
},
|
|
77
|
+
isRtl,
|
|
78
|
+
async getTranslations(options) {
|
|
79
|
+
const [{ translator }, locale] = await Promise.all([
|
|
80
|
+
readRequestConfig(),
|
|
81
|
+
getResolvedLocale(options)
|
|
82
|
+
]);
|
|
83
|
+
await translator.loadLocale(locale);
|
|
84
|
+
return ((...args) => {
|
|
85
|
+
const [key, translateOptions] = args;
|
|
86
|
+
return translator.t(
|
|
87
|
+
key,
|
|
88
|
+
{
|
|
89
|
+
...translateOptions ?? {},
|
|
90
|
+
locale
|
|
91
|
+
}
|
|
92
|
+
);
|
|
93
|
+
});
|
|
94
|
+
},
|
|
95
|
+
async getTranslator() {
|
|
96
|
+
return (await readRequestConfig()).translator;
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export {
|
|
102
|
+
getRequestConfig,
|
|
103
|
+
setRequestLocale,
|
|
104
|
+
createServerHelpers
|
|
105
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// src/request-cache.ts
|
|
2
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
3
|
+
var requestCacheStorage = new AsyncLocalStorage();
|
|
4
|
+
function getOrCreateRequestCacheStore() {
|
|
5
|
+
const existingStore = requestCacheStorage.getStore();
|
|
6
|
+
if (existingStore) {
|
|
7
|
+
return existingStore;
|
|
8
|
+
}
|
|
9
|
+
const nextStore = {
|
|
10
|
+
cache: /* @__PURE__ */ new Map()
|
|
11
|
+
};
|
|
12
|
+
requestCacheStorage.enterWith(nextStore);
|
|
13
|
+
return nextStore;
|
|
14
|
+
}
|
|
15
|
+
function readRequestCached(key, factory) {
|
|
16
|
+
const store = getOrCreateRequestCacheStore();
|
|
17
|
+
if (store.cache.has(key)) {
|
|
18
|
+
return store.cache.get(key);
|
|
19
|
+
}
|
|
20
|
+
const value = factory();
|
|
21
|
+
store.cache.set(key, value);
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export {
|
|
26
|
+
readRequestCached
|
|
27
|
+
};
|
package/dist/content.cjs
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/content.ts
|
|
21
|
+
var content_exports = {};
|
|
22
|
+
__export(content_exports, {
|
|
23
|
+
ContentDocumentNotFoundError: () => ContentDocumentNotFoundError,
|
|
24
|
+
createContentCollectionHelpers: () => createContentCollectionHelpers
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(content_exports);
|
|
27
|
+
var import_server = require("@better-translate/core/server");
|
|
28
|
+
|
|
29
|
+
// src/request-cache.ts
|
|
30
|
+
var import_node_async_hooks = require("async_hooks");
|
|
31
|
+
var requestCacheStorage = new import_node_async_hooks.AsyncLocalStorage();
|
|
32
|
+
function getOrCreateRequestCacheStore() {
|
|
33
|
+
const existingStore = requestCacheStorage.getStore();
|
|
34
|
+
if (existingStore) {
|
|
35
|
+
return existingStore;
|
|
36
|
+
}
|
|
37
|
+
const nextStore = {
|
|
38
|
+
cache: /* @__PURE__ */ new Map()
|
|
39
|
+
};
|
|
40
|
+
requestCacheStorage.enterWith(nextStore);
|
|
41
|
+
return nextStore;
|
|
42
|
+
}
|
|
43
|
+
function readRequestCached(key, factory) {
|
|
44
|
+
const store = getOrCreateRequestCacheStore();
|
|
45
|
+
if (store.cache.has(key)) {
|
|
46
|
+
return store.cache.get(key);
|
|
47
|
+
}
|
|
48
|
+
const value = factory();
|
|
49
|
+
store.cache.set(key, value);
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/content.ts
|
|
54
|
+
var ContentDocumentNotFoundError = class extends Error {
|
|
55
|
+
fallbackLocale;
|
|
56
|
+
id;
|
|
57
|
+
lookedUpEntryIds;
|
|
58
|
+
requestedLocale;
|
|
59
|
+
constructor(options) {
|
|
60
|
+
super(
|
|
61
|
+
`Content document "${options.id}" was not found for locale "${options.requestedLocale}" or fallback locale "${options.fallbackLocale}".`
|
|
62
|
+
);
|
|
63
|
+
this.name = "ContentDocumentNotFoundError";
|
|
64
|
+
this.id = options.id;
|
|
65
|
+
this.requestedLocale = options.requestedLocale;
|
|
66
|
+
this.fallbackLocale = options.fallbackLocale;
|
|
67
|
+
this.lookedUpEntryIds = options.lookedUpEntryIds;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
function normalizeDocumentId(documentId) {
|
|
71
|
+
const normalizedDocumentId = documentId.trim().replaceAll("\\", "/").replace(/^\/+/, "").replace(/\/+$/, "");
|
|
72
|
+
if (!normalizedDocumentId || normalizedDocumentId === "." || normalizedDocumentId.startsWith("../") || normalizedDocumentId.includes("/../")) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
`Content document id "${documentId}" cannot escape the configured collection root.`
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
return normalizedDocumentId;
|
|
78
|
+
}
|
|
79
|
+
function defaultLocalizeId(locale, documentId) {
|
|
80
|
+
return `${locale}/${documentId}`;
|
|
81
|
+
}
|
|
82
|
+
function createContentCollectionHelpers(requestConfig, options) {
|
|
83
|
+
const requestConfigCacheKey = /* @__PURE__ */ Symbol(
|
|
84
|
+
"better-translate-astro-content-request-config"
|
|
85
|
+
);
|
|
86
|
+
const collectionCacheKey = /* @__PURE__ */ Symbol(
|
|
87
|
+
"better-translate-astro-content-collection"
|
|
88
|
+
);
|
|
89
|
+
const getEntryId = options.getEntryId ?? ((entry) => entry.id);
|
|
90
|
+
const localizeId = options.localizeId ?? defaultLocalizeId;
|
|
91
|
+
function readRequestConfig() {
|
|
92
|
+
return readRequestCached(requestConfigCacheKey, async () => {
|
|
93
|
+
const resolved = await requestConfig();
|
|
94
|
+
const translator = resolved.translator;
|
|
95
|
+
return {
|
|
96
|
+
locale: resolved.locale,
|
|
97
|
+
translator
|
|
98
|
+
};
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
function readCollection() {
|
|
102
|
+
return readRequestCached(collectionCacheKey, async () => {
|
|
103
|
+
const entries = await options.getCollection(options.collection);
|
|
104
|
+
const entryMap = /* @__PURE__ */ new Map();
|
|
105
|
+
for (const entry of entries) {
|
|
106
|
+
entryMap.set(getEntryId(entry), entry);
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
entries,
|
|
110
|
+
entryMap
|
|
111
|
+
};
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
async function getResolvedLocale(requestOptions) {
|
|
115
|
+
const { locale: configLocale, translator } = await readRequestConfig();
|
|
116
|
+
return (0, import_server.resolveRequestLocale)(translator, {
|
|
117
|
+
locale: requestOptions?.locale,
|
|
118
|
+
requestLocale: (0, import_server.getRequestLocale)(),
|
|
119
|
+
configLocale
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
async function listDocuments() {
|
|
123
|
+
const [{ entries }, { translator }] = await Promise.all([
|
|
124
|
+
readCollection(),
|
|
125
|
+
readRequestConfig()
|
|
126
|
+
]);
|
|
127
|
+
const defaultLocalePrefix = `${translator.defaultLocale}/`;
|
|
128
|
+
const documentIds = /* @__PURE__ */ new Set();
|
|
129
|
+
for (const entry of entries) {
|
|
130
|
+
const entryId = getEntryId(entry);
|
|
131
|
+
if (!entryId.startsWith(defaultLocalePrefix)) {
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
documentIds.add(entryId.slice(defaultLocalePrefix.length));
|
|
135
|
+
}
|
|
136
|
+
return [...documentIds].sort();
|
|
137
|
+
}
|
|
138
|
+
async function getDocument(documentId, requestOptions) {
|
|
139
|
+
const normalizedDocumentId = normalizeDocumentId(documentId);
|
|
140
|
+
const [requestedLocale, { translator }, { entryMap }] = await Promise.all([
|
|
141
|
+
getResolvedLocale(requestOptions),
|
|
142
|
+
readRequestConfig(),
|
|
143
|
+
readCollection()
|
|
144
|
+
]);
|
|
145
|
+
const fallbackLocale = translator.fallbackLocale;
|
|
146
|
+
const localeSearchOrder = requestedLocale === fallbackLocale ? [requestedLocale] : [requestedLocale, fallbackLocale];
|
|
147
|
+
const lookedUpEntryIds = [];
|
|
148
|
+
for (const locale of localeSearchOrder) {
|
|
149
|
+
const entryId = localizeId(locale, normalizedDocumentId);
|
|
150
|
+
lookedUpEntryIds.push(entryId);
|
|
151
|
+
const entry = entryMap.get(entryId);
|
|
152
|
+
if (!entry) {
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
data: entry.data,
|
|
157
|
+
entry,
|
|
158
|
+
entryId,
|
|
159
|
+
id: normalizedDocumentId,
|
|
160
|
+
locale,
|
|
161
|
+
requestedLocale,
|
|
162
|
+
usedFallback: locale !== requestedLocale
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
throw new ContentDocumentNotFoundError({
|
|
166
|
+
fallbackLocale,
|
|
167
|
+
id: normalizedDocumentId,
|
|
168
|
+
lookedUpEntryIds,
|
|
169
|
+
requestedLocale
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
async function renderDocument(documentOrId, requestOptions) {
|
|
173
|
+
if (!options.render) {
|
|
174
|
+
throw new Error(
|
|
175
|
+
'renderDocument(...) requires a "render" function in createContentCollectionHelpers(...).'
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
const document = typeof documentOrId === "string" ? await getDocument(documentOrId, requestOptions) : documentOrId;
|
|
179
|
+
return {
|
|
180
|
+
...document,
|
|
181
|
+
rendered: await options.render(document.entry)
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
async getCollection() {
|
|
186
|
+
return (await readCollection()).entries;
|
|
187
|
+
},
|
|
188
|
+
getDocument,
|
|
189
|
+
listDocuments,
|
|
190
|
+
renderDocument
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
194
|
+
0 && (module.exports = {
|
|
195
|
+
ContentDocumentNotFoundError,
|
|
196
|
+
createContentCollectionHelpers
|
|
197
|
+
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { ConfiguredTranslator, TranslationMessages } from '@better-translate/core';
|
|
2
|
+
import { I as InferTranslatorLocale, R as RequestConfigFactory } from './index-B2VGZAji.cjs';
|
|
3
|
+
|
|
4
|
+
type AnyTranslator = ConfiguredTranslator<any, TranslationMessages>;
|
|
5
|
+
type InferEntryData<TEntry> = TEntry extends {
|
|
6
|
+
data: infer TData;
|
|
7
|
+
} ? TData : never;
|
|
8
|
+
interface ContentDocumentOptions<TLocale extends string> {
|
|
9
|
+
locale?: TLocale;
|
|
10
|
+
}
|
|
11
|
+
interface ContentCollectionOptions<TEntry extends {
|
|
12
|
+
data: unknown;
|
|
13
|
+
id: string;
|
|
14
|
+
}, TRenderedDocument> {
|
|
15
|
+
collection: string;
|
|
16
|
+
getCollection: (collection: string) => readonly TEntry[] | Promise<readonly TEntry[]>;
|
|
17
|
+
getEntryId?: (entry: TEntry) => string;
|
|
18
|
+
localizeId?: (locale: string, documentId: string) => string;
|
|
19
|
+
render?: (entry: TEntry) => TRenderedDocument | Promise<TRenderedDocument>;
|
|
20
|
+
}
|
|
21
|
+
interface LocalizedContentDocument<TLocale extends string, TEntry extends {
|
|
22
|
+
data: unknown;
|
|
23
|
+
id: string;
|
|
24
|
+
}> {
|
|
25
|
+
data: InferEntryData<TEntry>;
|
|
26
|
+
entry: TEntry;
|
|
27
|
+
entryId: string;
|
|
28
|
+
id: string;
|
|
29
|
+
locale: TLocale;
|
|
30
|
+
requestedLocale: TLocale;
|
|
31
|
+
usedFallback: boolean;
|
|
32
|
+
}
|
|
33
|
+
interface RenderedContentDocument<TLocale extends string, TEntry extends {
|
|
34
|
+
data: unknown;
|
|
35
|
+
id: string;
|
|
36
|
+
}, TRenderedDocument> extends LocalizedContentDocument<TLocale, TEntry> {
|
|
37
|
+
rendered: TRenderedDocument;
|
|
38
|
+
}
|
|
39
|
+
interface ContentCollectionHelpers<TLocale extends string, TEntry extends {
|
|
40
|
+
data: unknown;
|
|
41
|
+
id: string;
|
|
42
|
+
}, TRenderedDocument> {
|
|
43
|
+
getCollection(): Promise<readonly TEntry[]>;
|
|
44
|
+
getDocument(documentId: string, options?: ContentDocumentOptions<TLocale>): Promise<LocalizedContentDocument<TLocale, TEntry>>;
|
|
45
|
+
listDocuments(): Promise<string[]>;
|
|
46
|
+
renderDocument(documentId: string, options?: ContentDocumentOptions<TLocale>): Promise<RenderedContentDocument<TLocale, TEntry, TRenderedDocument>>;
|
|
47
|
+
renderDocument(document: LocalizedContentDocument<TLocale, TEntry>): Promise<RenderedContentDocument<TLocale, TEntry, TRenderedDocument>>;
|
|
48
|
+
}
|
|
49
|
+
declare class ContentDocumentNotFoundError extends Error {
|
|
50
|
+
readonly fallbackLocale: string;
|
|
51
|
+
readonly id: string;
|
|
52
|
+
readonly lookedUpEntryIds: readonly string[];
|
|
53
|
+
readonly requestedLocale: string;
|
|
54
|
+
constructor(options: {
|
|
55
|
+
fallbackLocale: string;
|
|
56
|
+
id: string;
|
|
57
|
+
lookedUpEntryIds: readonly string[];
|
|
58
|
+
requestedLocale: string;
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
declare function createContentCollectionHelpers<TTranslator extends AnyTranslator, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>, TEntry extends {
|
|
62
|
+
data: unknown;
|
|
63
|
+
id: string;
|
|
64
|
+
} = {
|
|
65
|
+
data: unknown;
|
|
66
|
+
id: string;
|
|
67
|
+
}, TRenderedDocument = unknown>(requestConfig: RequestConfigFactory<TTranslator, TLocale>, options: ContentCollectionOptions<TEntry, TRenderedDocument>): ContentCollectionHelpers<TLocale, TEntry, TRenderedDocument>;
|
|
68
|
+
|
|
69
|
+
export { type ContentCollectionHelpers, type ContentCollectionOptions, ContentDocumentNotFoundError, type ContentDocumentOptions, type LocalizedContentDocument, type RenderedContentDocument, createContentCollectionHelpers };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { ConfiguredTranslator, TranslationMessages } from '@better-translate/core';
|
|
2
|
+
import { I as InferTranslatorLocale, R as RequestConfigFactory } from './index-B2VGZAji.js';
|
|
3
|
+
|
|
4
|
+
type AnyTranslator = ConfiguredTranslator<any, TranslationMessages>;
|
|
5
|
+
type InferEntryData<TEntry> = TEntry extends {
|
|
6
|
+
data: infer TData;
|
|
7
|
+
} ? TData : never;
|
|
8
|
+
interface ContentDocumentOptions<TLocale extends string> {
|
|
9
|
+
locale?: TLocale;
|
|
10
|
+
}
|
|
11
|
+
interface ContentCollectionOptions<TEntry extends {
|
|
12
|
+
data: unknown;
|
|
13
|
+
id: string;
|
|
14
|
+
}, TRenderedDocument> {
|
|
15
|
+
collection: string;
|
|
16
|
+
getCollection: (collection: string) => readonly TEntry[] | Promise<readonly TEntry[]>;
|
|
17
|
+
getEntryId?: (entry: TEntry) => string;
|
|
18
|
+
localizeId?: (locale: string, documentId: string) => string;
|
|
19
|
+
render?: (entry: TEntry) => TRenderedDocument | Promise<TRenderedDocument>;
|
|
20
|
+
}
|
|
21
|
+
interface LocalizedContentDocument<TLocale extends string, TEntry extends {
|
|
22
|
+
data: unknown;
|
|
23
|
+
id: string;
|
|
24
|
+
}> {
|
|
25
|
+
data: InferEntryData<TEntry>;
|
|
26
|
+
entry: TEntry;
|
|
27
|
+
entryId: string;
|
|
28
|
+
id: string;
|
|
29
|
+
locale: TLocale;
|
|
30
|
+
requestedLocale: TLocale;
|
|
31
|
+
usedFallback: boolean;
|
|
32
|
+
}
|
|
33
|
+
interface RenderedContentDocument<TLocale extends string, TEntry extends {
|
|
34
|
+
data: unknown;
|
|
35
|
+
id: string;
|
|
36
|
+
}, TRenderedDocument> extends LocalizedContentDocument<TLocale, TEntry> {
|
|
37
|
+
rendered: TRenderedDocument;
|
|
38
|
+
}
|
|
39
|
+
interface ContentCollectionHelpers<TLocale extends string, TEntry extends {
|
|
40
|
+
data: unknown;
|
|
41
|
+
id: string;
|
|
42
|
+
}, TRenderedDocument> {
|
|
43
|
+
getCollection(): Promise<readonly TEntry[]>;
|
|
44
|
+
getDocument(documentId: string, options?: ContentDocumentOptions<TLocale>): Promise<LocalizedContentDocument<TLocale, TEntry>>;
|
|
45
|
+
listDocuments(): Promise<string[]>;
|
|
46
|
+
renderDocument(documentId: string, options?: ContentDocumentOptions<TLocale>): Promise<RenderedContentDocument<TLocale, TEntry, TRenderedDocument>>;
|
|
47
|
+
renderDocument(document: LocalizedContentDocument<TLocale, TEntry>): Promise<RenderedContentDocument<TLocale, TEntry, TRenderedDocument>>;
|
|
48
|
+
}
|
|
49
|
+
declare class ContentDocumentNotFoundError extends Error {
|
|
50
|
+
readonly fallbackLocale: string;
|
|
51
|
+
readonly id: string;
|
|
52
|
+
readonly lookedUpEntryIds: readonly string[];
|
|
53
|
+
readonly requestedLocale: string;
|
|
54
|
+
constructor(options: {
|
|
55
|
+
fallbackLocale: string;
|
|
56
|
+
id: string;
|
|
57
|
+
lookedUpEntryIds: readonly string[];
|
|
58
|
+
requestedLocale: string;
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
declare function createContentCollectionHelpers<TTranslator extends AnyTranslator, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>, TEntry extends {
|
|
62
|
+
data: unknown;
|
|
63
|
+
id: string;
|
|
64
|
+
} = {
|
|
65
|
+
data: unknown;
|
|
66
|
+
id: string;
|
|
67
|
+
}, TRenderedDocument = unknown>(requestConfig: RequestConfigFactory<TTranslator, TLocale>, options: ContentCollectionOptions<TEntry, TRenderedDocument>): ContentCollectionHelpers<TLocale, TEntry, TRenderedDocument>;
|
|
68
|
+
|
|
69
|
+
export { type ContentCollectionHelpers, type ContentCollectionOptions, ContentDocumentNotFoundError, type ContentDocumentOptions, type LocalizedContentDocument, type RenderedContentDocument, createContentCollectionHelpers };
|
package/dist/content.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import {
|
|
2
|
+
readRequestCached
|
|
3
|
+
} from "./chunk-3ERZEJZW.js";
|
|
4
|
+
|
|
5
|
+
// src/content.ts
|
|
6
|
+
import {
|
|
7
|
+
getRequestLocale as getStoredRequestLocale,
|
|
8
|
+
resolveRequestLocale
|
|
9
|
+
} from "@better-translate/core/server";
|
|
10
|
+
var ContentDocumentNotFoundError = class extends Error {
|
|
11
|
+
fallbackLocale;
|
|
12
|
+
id;
|
|
13
|
+
lookedUpEntryIds;
|
|
14
|
+
requestedLocale;
|
|
15
|
+
constructor(options) {
|
|
16
|
+
super(
|
|
17
|
+
`Content document "${options.id}" was not found for locale "${options.requestedLocale}" or fallback locale "${options.fallbackLocale}".`
|
|
18
|
+
);
|
|
19
|
+
this.name = "ContentDocumentNotFoundError";
|
|
20
|
+
this.id = options.id;
|
|
21
|
+
this.requestedLocale = options.requestedLocale;
|
|
22
|
+
this.fallbackLocale = options.fallbackLocale;
|
|
23
|
+
this.lookedUpEntryIds = options.lookedUpEntryIds;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
function normalizeDocumentId(documentId) {
|
|
27
|
+
const normalizedDocumentId = documentId.trim().replaceAll("\\", "/").replace(/^\/+/, "").replace(/\/+$/, "");
|
|
28
|
+
if (!normalizedDocumentId || normalizedDocumentId === "." || normalizedDocumentId.startsWith("../") || normalizedDocumentId.includes("/../")) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
`Content document id "${documentId}" cannot escape the configured collection root.`
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
return normalizedDocumentId;
|
|
34
|
+
}
|
|
35
|
+
function defaultLocalizeId(locale, documentId) {
|
|
36
|
+
return `${locale}/${documentId}`;
|
|
37
|
+
}
|
|
38
|
+
function createContentCollectionHelpers(requestConfig, options) {
|
|
39
|
+
const requestConfigCacheKey = /* @__PURE__ */ Symbol(
|
|
40
|
+
"better-translate-astro-content-request-config"
|
|
41
|
+
);
|
|
42
|
+
const collectionCacheKey = /* @__PURE__ */ Symbol(
|
|
43
|
+
"better-translate-astro-content-collection"
|
|
44
|
+
);
|
|
45
|
+
const getEntryId = options.getEntryId ?? ((entry) => entry.id);
|
|
46
|
+
const localizeId = options.localizeId ?? defaultLocalizeId;
|
|
47
|
+
function readRequestConfig() {
|
|
48
|
+
return readRequestCached(requestConfigCacheKey, async () => {
|
|
49
|
+
const resolved = await requestConfig();
|
|
50
|
+
const translator = resolved.translator;
|
|
51
|
+
return {
|
|
52
|
+
locale: resolved.locale,
|
|
53
|
+
translator
|
|
54
|
+
};
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function readCollection() {
|
|
58
|
+
return readRequestCached(collectionCacheKey, async () => {
|
|
59
|
+
const entries = await options.getCollection(options.collection);
|
|
60
|
+
const entryMap = /* @__PURE__ */ new Map();
|
|
61
|
+
for (const entry of entries) {
|
|
62
|
+
entryMap.set(getEntryId(entry), entry);
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
entries,
|
|
66
|
+
entryMap
|
|
67
|
+
};
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
async function getResolvedLocale(requestOptions) {
|
|
71
|
+
const { locale: configLocale, translator } = await readRequestConfig();
|
|
72
|
+
return resolveRequestLocale(translator, {
|
|
73
|
+
locale: requestOptions?.locale,
|
|
74
|
+
requestLocale: getStoredRequestLocale(),
|
|
75
|
+
configLocale
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
async function listDocuments() {
|
|
79
|
+
const [{ entries }, { translator }] = await Promise.all([
|
|
80
|
+
readCollection(),
|
|
81
|
+
readRequestConfig()
|
|
82
|
+
]);
|
|
83
|
+
const defaultLocalePrefix = `${translator.defaultLocale}/`;
|
|
84
|
+
const documentIds = /* @__PURE__ */ new Set();
|
|
85
|
+
for (const entry of entries) {
|
|
86
|
+
const entryId = getEntryId(entry);
|
|
87
|
+
if (!entryId.startsWith(defaultLocalePrefix)) {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
documentIds.add(entryId.slice(defaultLocalePrefix.length));
|
|
91
|
+
}
|
|
92
|
+
return [...documentIds].sort();
|
|
93
|
+
}
|
|
94
|
+
async function getDocument(documentId, requestOptions) {
|
|
95
|
+
const normalizedDocumentId = normalizeDocumentId(documentId);
|
|
96
|
+
const [requestedLocale, { translator }, { entryMap }] = await Promise.all([
|
|
97
|
+
getResolvedLocale(requestOptions),
|
|
98
|
+
readRequestConfig(),
|
|
99
|
+
readCollection()
|
|
100
|
+
]);
|
|
101
|
+
const fallbackLocale = translator.fallbackLocale;
|
|
102
|
+
const localeSearchOrder = requestedLocale === fallbackLocale ? [requestedLocale] : [requestedLocale, fallbackLocale];
|
|
103
|
+
const lookedUpEntryIds = [];
|
|
104
|
+
for (const locale of localeSearchOrder) {
|
|
105
|
+
const entryId = localizeId(locale, normalizedDocumentId);
|
|
106
|
+
lookedUpEntryIds.push(entryId);
|
|
107
|
+
const entry = entryMap.get(entryId);
|
|
108
|
+
if (!entry) {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
data: entry.data,
|
|
113
|
+
entry,
|
|
114
|
+
entryId,
|
|
115
|
+
id: normalizedDocumentId,
|
|
116
|
+
locale,
|
|
117
|
+
requestedLocale,
|
|
118
|
+
usedFallback: locale !== requestedLocale
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
throw new ContentDocumentNotFoundError({
|
|
122
|
+
fallbackLocale,
|
|
123
|
+
id: normalizedDocumentId,
|
|
124
|
+
lookedUpEntryIds,
|
|
125
|
+
requestedLocale
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
async function renderDocument(documentOrId, requestOptions) {
|
|
129
|
+
if (!options.render) {
|
|
130
|
+
throw new Error(
|
|
131
|
+
'renderDocument(...) requires a "render" function in createContentCollectionHelpers(...).'
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
const document = typeof documentOrId === "string" ? await getDocument(documentOrId, requestOptions) : documentOrId;
|
|
135
|
+
return {
|
|
136
|
+
...document,
|
|
137
|
+
rendered: await options.render(document.entry)
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
async getCollection() {
|
|
142
|
+
return (await readCollection()).entries;
|
|
143
|
+
},
|
|
144
|
+
getDocument,
|
|
145
|
+
listDocuments,
|
|
146
|
+
renderDocument
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
export {
|
|
150
|
+
ContentDocumentNotFoundError,
|
|
151
|
+
createContentCollectionHelpers
|
|
152
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { ConfiguredTranslator, TranslationMessages, TranslationLanguageMetadata, TranslationConfig, TranslationDirection, DeepPartialMessages } from '@better-translate/core';
|
|
2
|
+
|
|
3
|
+
type AnyTranslator = ConfiguredTranslator<any, TranslationMessages>;
|
|
4
|
+
type InferTranslatorLocale<TTranslator> = TTranslator extends ConfiguredTranslator<infer TLocale, TranslationMessages> ? TLocale : never;
|
|
5
|
+
type InferTranslatorMessages<TTranslator> = TTranslator extends ConfiguredTranslator<string, infer TMessages> ? TMessages : TranslationMessages;
|
|
6
|
+
interface BetterTranslateRequestConfig<TTranslator extends AnyTranslator, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>> {
|
|
7
|
+
locale?: TLocale;
|
|
8
|
+
translator: TTranslator;
|
|
9
|
+
}
|
|
10
|
+
type RequestConfigFactory<TTranslator extends AnyTranslator, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>> = () => BetterTranslateRequestConfig<TTranslator, TLocale> | Promise<BetterTranslateRequestConfig<TTranslator, TLocale>>;
|
|
11
|
+
type RequestDirectionOptions<TLocale extends string> = {
|
|
12
|
+
locale?: TLocale;
|
|
13
|
+
config?: TranslationConfig<TLocale>;
|
|
14
|
+
};
|
|
15
|
+
interface ServerHelpers<TRequestLocale extends string, TTranslator extends AnyTranslator> {
|
|
16
|
+
getAvailableLanguages(): Promise<readonly TranslationLanguageMetadata<InferTranslatorLocale<TTranslator>>[]>;
|
|
17
|
+
getDirection(options?: RequestDirectionOptions<InferTranslatorLocale<TTranslator>>): Promise<TranslationDirection>;
|
|
18
|
+
getLocale(): Promise<TRequestLocale>;
|
|
19
|
+
getMessages(): Promise<DeepPartialMessages<InferTranslatorMessages<TTranslator>> | InferTranslatorMessages<TTranslator>>;
|
|
20
|
+
isRtl(options?: RequestDirectionOptions<InferTranslatorLocale<TTranslator>>): Promise<boolean>;
|
|
21
|
+
getTranslations(options?: {
|
|
22
|
+
locale?: InferTranslatorLocale<TTranslator>;
|
|
23
|
+
}): Promise<TTranslator["t"]>;
|
|
24
|
+
getTranslator(): Promise<TTranslator>;
|
|
25
|
+
}
|
|
26
|
+
declare function getRequestConfig<TTranslator extends AnyTranslator, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>>(factory: RequestConfigFactory<TTranslator, TLocale>): RequestConfigFactory<TTranslator, TLocale>;
|
|
27
|
+
declare function setRequestLocale<TLocale extends string>(locale: TLocale | undefined): void;
|
|
28
|
+
declare function createServerHelpers<TTranslator extends AnyTranslator, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>>(requestConfig: RequestConfigFactory<TTranslator, TLocale>): ServerHelpers<TLocale, TTranslator>;
|
|
29
|
+
|
|
30
|
+
export { type BetterTranslateRequestConfig as B, type InferTranslatorLocale as I, type RequestConfigFactory as R, type ServerHelpers as S, createServerHelpers as c, getRequestConfig as g, setRequestLocale as s };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { ConfiguredTranslator, TranslationMessages, TranslationLanguageMetadata, TranslationConfig, TranslationDirection, DeepPartialMessages } from '@better-translate/core';
|
|
2
|
+
|
|
3
|
+
type AnyTranslator = ConfiguredTranslator<any, TranslationMessages>;
|
|
4
|
+
type InferTranslatorLocale<TTranslator> = TTranslator extends ConfiguredTranslator<infer TLocale, TranslationMessages> ? TLocale : never;
|
|
5
|
+
type InferTranslatorMessages<TTranslator> = TTranslator extends ConfiguredTranslator<string, infer TMessages> ? TMessages : TranslationMessages;
|
|
6
|
+
interface BetterTranslateRequestConfig<TTranslator extends AnyTranslator, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>> {
|
|
7
|
+
locale?: TLocale;
|
|
8
|
+
translator: TTranslator;
|
|
9
|
+
}
|
|
10
|
+
type RequestConfigFactory<TTranslator extends AnyTranslator, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>> = () => BetterTranslateRequestConfig<TTranslator, TLocale> | Promise<BetterTranslateRequestConfig<TTranslator, TLocale>>;
|
|
11
|
+
type RequestDirectionOptions<TLocale extends string> = {
|
|
12
|
+
locale?: TLocale;
|
|
13
|
+
config?: TranslationConfig<TLocale>;
|
|
14
|
+
};
|
|
15
|
+
interface ServerHelpers<TRequestLocale extends string, TTranslator extends AnyTranslator> {
|
|
16
|
+
getAvailableLanguages(): Promise<readonly TranslationLanguageMetadata<InferTranslatorLocale<TTranslator>>[]>;
|
|
17
|
+
getDirection(options?: RequestDirectionOptions<InferTranslatorLocale<TTranslator>>): Promise<TranslationDirection>;
|
|
18
|
+
getLocale(): Promise<TRequestLocale>;
|
|
19
|
+
getMessages(): Promise<DeepPartialMessages<InferTranslatorMessages<TTranslator>> | InferTranslatorMessages<TTranslator>>;
|
|
20
|
+
isRtl(options?: RequestDirectionOptions<InferTranslatorLocale<TTranslator>>): Promise<boolean>;
|
|
21
|
+
getTranslations(options?: {
|
|
22
|
+
locale?: InferTranslatorLocale<TTranslator>;
|
|
23
|
+
}): Promise<TTranslator["t"]>;
|
|
24
|
+
getTranslator(): Promise<TTranslator>;
|
|
25
|
+
}
|
|
26
|
+
declare function getRequestConfig<TTranslator extends AnyTranslator, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>>(factory: RequestConfigFactory<TTranslator, TLocale>): RequestConfigFactory<TTranslator, TLocale>;
|
|
27
|
+
declare function setRequestLocale<TLocale extends string>(locale: TLocale | undefined): void;
|
|
28
|
+
declare function createServerHelpers<TTranslator extends AnyTranslator, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>>(requestConfig: RequestConfigFactory<TTranslator, TLocale>): ServerHelpers<TLocale, TTranslator>;
|
|
29
|
+
|
|
30
|
+
export { type BetterTranslateRequestConfig as B, type InferTranslatorLocale as I, type RequestConfigFactory as R, type ServerHelpers as S, createServerHelpers as c, getRequestConfig as g, setRequestLocale as s };
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
createServerHelpers: () => createServerHelpers,
|
|
24
|
+
getRequestConfig: () => getRequestConfig,
|
|
25
|
+
setRequestLocale: () => setRequestLocale
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(index_exports);
|
|
28
|
+
|
|
29
|
+
// src/server.ts
|
|
30
|
+
var import_server = require("@better-translate/core/server");
|
|
31
|
+
|
|
32
|
+
// src/request-cache.ts
|
|
33
|
+
var import_node_async_hooks = require("async_hooks");
|
|
34
|
+
var requestCacheStorage = new import_node_async_hooks.AsyncLocalStorage();
|
|
35
|
+
function getOrCreateRequestCacheStore() {
|
|
36
|
+
const existingStore = requestCacheStorage.getStore();
|
|
37
|
+
if (existingStore) {
|
|
38
|
+
return existingStore;
|
|
39
|
+
}
|
|
40
|
+
const nextStore = {
|
|
41
|
+
cache: /* @__PURE__ */ new Map()
|
|
42
|
+
};
|
|
43
|
+
requestCacheStorage.enterWith(nextStore);
|
|
44
|
+
return nextStore;
|
|
45
|
+
}
|
|
46
|
+
function readRequestCached(key, factory) {
|
|
47
|
+
const store = getOrCreateRequestCacheStore();
|
|
48
|
+
if (store.cache.has(key)) {
|
|
49
|
+
return store.cache.get(key);
|
|
50
|
+
}
|
|
51
|
+
const value = factory();
|
|
52
|
+
store.cache.set(key, value);
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// src/server.ts
|
|
57
|
+
function getRequestConfig(factory) {
|
|
58
|
+
return factory;
|
|
59
|
+
}
|
|
60
|
+
function setRequestLocale(locale) {
|
|
61
|
+
(0, import_server.setRequestLocale)(locale);
|
|
62
|
+
}
|
|
63
|
+
function createServerHelpers(requestConfig) {
|
|
64
|
+
const requestConfigCacheKey = /* @__PURE__ */ Symbol("better-translate-astro-request-config");
|
|
65
|
+
function readRequestConfig() {
|
|
66
|
+
return readRequestCached(requestConfigCacheKey, async () => {
|
|
67
|
+
const resolved = await requestConfig();
|
|
68
|
+
const translator = resolved.translator;
|
|
69
|
+
return {
|
|
70
|
+
locale: resolved.locale,
|
|
71
|
+
translator
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
async function getResolvedLocale(options) {
|
|
76
|
+
const { locale: configLocale, translator } = await readRequestConfig();
|
|
77
|
+
return (0, import_server.resolveRequestLocale)(translator, {
|
|
78
|
+
locale: options?.config?.locale ?? options?.locale,
|
|
79
|
+
requestLocale: (0, import_server.getRequestLocale)(),
|
|
80
|
+
configLocale
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
async function getDirection(options) {
|
|
84
|
+
const [{ translator }, locale] = await Promise.all([
|
|
85
|
+
readRequestConfig(),
|
|
86
|
+
getResolvedLocale(options)
|
|
87
|
+
]);
|
|
88
|
+
return translator.getDirection({
|
|
89
|
+
config: typeof options?.config?.rtl === "boolean" ? {
|
|
90
|
+
rtl: options.config.rtl
|
|
91
|
+
} : void 0,
|
|
92
|
+
locale
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
async function isRtl(options) {
|
|
96
|
+
return await getDirection(options) === "rtl";
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
async getAvailableLanguages() {
|
|
100
|
+
return (await readRequestConfig()).translator.getAvailableLanguages();
|
|
101
|
+
},
|
|
102
|
+
getDirection,
|
|
103
|
+
async getLocale() {
|
|
104
|
+
return getResolvedLocale();
|
|
105
|
+
},
|
|
106
|
+
async getMessages() {
|
|
107
|
+
const [{ translator }, locale] = await Promise.all([
|
|
108
|
+
readRequestConfig(),
|
|
109
|
+
getResolvedLocale()
|
|
110
|
+
]);
|
|
111
|
+
const loadedMessages = await translator.loadLocale(locale);
|
|
112
|
+
const cachedMessages = translator.getMessages()[locale];
|
|
113
|
+
if (loadedMessages) {
|
|
114
|
+
return loadedMessages;
|
|
115
|
+
}
|
|
116
|
+
if (cachedMessages) {
|
|
117
|
+
return cachedMessages;
|
|
118
|
+
}
|
|
119
|
+
throw new Error(
|
|
120
|
+
`Locale "${locale}" messages are not available. Preload them or register a loader in your Better Translate core config.`
|
|
121
|
+
);
|
|
122
|
+
},
|
|
123
|
+
isRtl,
|
|
124
|
+
async getTranslations(options) {
|
|
125
|
+
const [{ translator }, locale] = await Promise.all([
|
|
126
|
+
readRequestConfig(),
|
|
127
|
+
getResolvedLocale(options)
|
|
128
|
+
]);
|
|
129
|
+
await translator.loadLocale(locale);
|
|
130
|
+
return ((...args) => {
|
|
131
|
+
const [key, translateOptions] = args;
|
|
132
|
+
return translator.t(
|
|
133
|
+
key,
|
|
134
|
+
{
|
|
135
|
+
...translateOptions ?? {},
|
|
136
|
+
locale
|
|
137
|
+
}
|
|
138
|
+
);
|
|
139
|
+
});
|
|
140
|
+
},
|
|
141
|
+
async getTranslator() {
|
|
142
|
+
return (await readRequestConfig()).translator;
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
147
|
+
0 && (module.exports = {
|
|
148
|
+
createServerHelpers,
|
|
149
|
+
getRequestConfig,
|
|
150
|
+
setRequestLocale
|
|
151
|
+
});
|
package/dist/index.d.cts
ADDED
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/middleware.ts
|
|
21
|
+
var middleware_exports = {};
|
|
22
|
+
__export(middleware_exports, {
|
|
23
|
+
createBetterTranslateMiddleware: () => createBetterTranslateMiddleware
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(middleware_exports);
|
|
26
|
+
var import_server2 = require("@better-translate/core/server");
|
|
27
|
+
|
|
28
|
+
// src/request-cache.ts
|
|
29
|
+
var import_node_async_hooks = require("async_hooks");
|
|
30
|
+
var requestCacheStorage = new import_node_async_hooks.AsyncLocalStorage();
|
|
31
|
+
function getOrCreateRequestCacheStore() {
|
|
32
|
+
const existingStore = requestCacheStorage.getStore();
|
|
33
|
+
if (existingStore) {
|
|
34
|
+
return existingStore;
|
|
35
|
+
}
|
|
36
|
+
const nextStore = {
|
|
37
|
+
cache: /* @__PURE__ */ new Map()
|
|
38
|
+
};
|
|
39
|
+
requestCacheStorage.enterWith(nextStore);
|
|
40
|
+
return nextStore;
|
|
41
|
+
}
|
|
42
|
+
function readRequestCached(key, factory) {
|
|
43
|
+
const store = getOrCreateRequestCacheStore();
|
|
44
|
+
if (store.cache.has(key)) {
|
|
45
|
+
return store.cache.get(key);
|
|
46
|
+
}
|
|
47
|
+
const value = factory();
|
|
48
|
+
store.cache.set(key, value);
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/server.ts
|
|
53
|
+
var import_server = require("@better-translate/core/server");
|
|
54
|
+
function setRequestLocale(locale) {
|
|
55
|
+
(0, import_server.setRequestLocale)(locale);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/middleware.ts
|
|
59
|
+
function createBetterTranslateMiddleware(requestConfig, options) {
|
|
60
|
+
const requestConfigCacheKey = /* @__PURE__ */ Symbol(
|
|
61
|
+
"better-translate-astro-middleware-request-config"
|
|
62
|
+
);
|
|
63
|
+
function readConfig() {
|
|
64
|
+
return readRequestCached(requestConfigCacheKey, () => requestConfig());
|
|
65
|
+
}
|
|
66
|
+
return async (context, next) => {
|
|
67
|
+
const resolvedConfig = await readConfig();
|
|
68
|
+
const requestedLocale = await options?.resolveLocale?.(context) ?? context.currentLocale;
|
|
69
|
+
const locale = (0, import_server2.resolveRequestLocale)(resolvedConfig.translator, {
|
|
70
|
+
locale: requestedLocale,
|
|
71
|
+
configLocale: resolvedConfig.locale
|
|
72
|
+
});
|
|
73
|
+
setRequestLocale(locale);
|
|
74
|
+
context.locals.betterTranslate = {
|
|
75
|
+
locale
|
|
76
|
+
};
|
|
77
|
+
return next();
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
81
|
+
0 && (module.exports = {
|
|
82
|
+
createBetterTranslateMiddleware
|
|
83
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ConfiguredTranslator, TranslationMessages } from '@better-translate/core';
|
|
2
|
+
import { I as InferTranslatorLocale, R as RequestConfigFactory } from './index-B2VGZAji.cjs';
|
|
3
|
+
|
|
4
|
+
interface BetterTranslateLocals<TLocale extends string = string> {
|
|
5
|
+
betterTranslate?: {
|
|
6
|
+
locale: TLocale;
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
interface BetterTranslateMiddlewareContext<TLocale extends string = string, TLocals extends Record<string, unknown> = Record<string, unknown>> {
|
|
10
|
+
currentLocale?: string;
|
|
11
|
+
locals: TLocals & BetterTranslateLocals<TLocale>;
|
|
12
|
+
params?: Record<string, string | undefined>;
|
|
13
|
+
preferredLocale?: string;
|
|
14
|
+
preferredLocaleList?: string[];
|
|
15
|
+
request: Request;
|
|
16
|
+
url: URL;
|
|
17
|
+
}
|
|
18
|
+
type BetterTranslateMiddlewareNext = () => Response | Promise<Response>;
|
|
19
|
+
type BetterTranslateMiddlewareHandler<TLocale extends string = string, TLocals extends Record<string, unknown> = Record<string, unknown>> = (context: BetterTranslateMiddlewareContext<TLocale, TLocals>, next: BetterTranslateMiddlewareNext) => Response | Promise<Response>;
|
|
20
|
+
interface CreateBetterTranslateMiddlewareOptions<TLocale extends string, TLocals extends Record<string, unknown> = Record<string, unknown>> {
|
|
21
|
+
resolveLocale?: (context: BetterTranslateMiddlewareContext<TLocale, TLocals>) => TLocale | string | undefined | Promise<TLocale | string | undefined>;
|
|
22
|
+
}
|
|
23
|
+
declare function createBetterTranslateMiddleware<TTranslator extends ConfiguredTranslator<any, TranslationMessages>, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>, TLocals extends Record<string, unknown> = Record<string, unknown>>(requestConfig: RequestConfigFactory<TTranslator, TLocale>, options?: CreateBetterTranslateMiddlewareOptions<TLocale, TLocals>): BetterTranslateMiddlewareHandler<TLocale, TLocals>;
|
|
24
|
+
|
|
25
|
+
export { type BetterTranslateLocals, type BetterTranslateMiddlewareContext, type BetterTranslateMiddlewareHandler, type BetterTranslateMiddlewareNext, type CreateBetterTranslateMiddlewareOptions, createBetterTranslateMiddleware };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ConfiguredTranslator, TranslationMessages } from '@better-translate/core';
|
|
2
|
+
import { I as InferTranslatorLocale, R as RequestConfigFactory } from './index-B2VGZAji.js';
|
|
3
|
+
|
|
4
|
+
interface BetterTranslateLocals<TLocale extends string = string> {
|
|
5
|
+
betterTranslate?: {
|
|
6
|
+
locale: TLocale;
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
interface BetterTranslateMiddlewareContext<TLocale extends string = string, TLocals extends Record<string, unknown> = Record<string, unknown>> {
|
|
10
|
+
currentLocale?: string;
|
|
11
|
+
locals: TLocals & BetterTranslateLocals<TLocale>;
|
|
12
|
+
params?: Record<string, string | undefined>;
|
|
13
|
+
preferredLocale?: string;
|
|
14
|
+
preferredLocaleList?: string[];
|
|
15
|
+
request: Request;
|
|
16
|
+
url: URL;
|
|
17
|
+
}
|
|
18
|
+
type BetterTranslateMiddlewareNext = () => Response | Promise<Response>;
|
|
19
|
+
type BetterTranslateMiddlewareHandler<TLocale extends string = string, TLocals extends Record<string, unknown> = Record<string, unknown>> = (context: BetterTranslateMiddlewareContext<TLocale, TLocals>, next: BetterTranslateMiddlewareNext) => Response | Promise<Response>;
|
|
20
|
+
interface CreateBetterTranslateMiddlewareOptions<TLocale extends string, TLocals extends Record<string, unknown> = Record<string, unknown>> {
|
|
21
|
+
resolveLocale?: (context: BetterTranslateMiddlewareContext<TLocale, TLocals>) => TLocale | string | undefined | Promise<TLocale | string | undefined>;
|
|
22
|
+
}
|
|
23
|
+
declare function createBetterTranslateMiddleware<TTranslator extends ConfiguredTranslator<any, TranslationMessages>, TLocale extends InferTranslatorLocale<TTranslator> = InferTranslatorLocale<TTranslator>, TLocals extends Record<string, unknown> = Record<string, unknown>>(requestConfig: RequestConfigFactory<TTranslator, TLocale>, options?: CreateBetterTranslateMiddlewareOptions<TLocale, TLocals>): BetterTranslateMiddlewareHandler<TLocale, TLocals>;
|
|
24
|
+
|
|
25
|
+
export { type BetterTranslateLocals, type BetterTranslateMiddlewareContext, type BetterTranslateMiddlewareHandler, type BetterTranslateMiddlewareNext, type CreateBetterTranslateMiddlewareOptions, createBetterTranslateMiddleware };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {
|
|
2
|
+
setRequestLocale
|
|
3
|
+
} from "./chunk-2ZLSODTJ.js";
|
|
4
|
+
import {
|
|
5
|
+
readRequestCached
|
|
6
|
+
} from "./chunk-3ERZEJZW.js";
|
|
7
|
+
|
|
8
|
+
// src/middleware.ts
|
|
9
|
+
import { resolveRequestLocale } from "@better-translate/core/server";
|
|
10
|
+
function createBetterTranslateMiddleware(requestConfig, options) {
|
|
11
|
+
const requestConfigCacheKey = /* @__PURE__ */ Symbol(
|
|
12
|
+
"better-translate-astro-middleware-request-config"
|
|
13
|
+
);
|
|
14
|
+
function readConfig() {
|
|
15
|
+
return readRequestCached(requestConfigCacheKey, () => requestConfig());
|
|
16
|
+
}
|
|
17
|
+
return async (context, next) => {
|
|
18
|
+
const resolvedConfig = await readConfig();
|
|
19
|
+
const requestedLocale = await options?.resolveLocale?.(context) ?? context.currentLocale;
|
|
20
|
+
const locale = resolveRequestLocale(resolvedConfig.translator, {
|
|
21
|
+
locale: requestedLocale,
|
|
22
|
+
configLocale: resolvedConfig.locale
|
|
23
|
+
});
|
|
24
|
+
setRequestLocale(locale);
|
|
25
|
+
context.locals.betterTranslate = {
|
|
26
|
+
locale
|
|
27
|
+
};
|
|
28
|
+
return next();
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export {
|
|
32
|
+
createBetterTranslateMiddleware
|
|
33
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@better-translate/astro",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Astro integration package for Better Translate.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "./dist/index.cjs",
|
|
9
|
+
"module": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js",
|
|
15
|
+
"require": "./dist/index.cjs"
|
|
16
|
+
},
|
|
17
|
+
"./middleware": {
|
|
18
|
+
"types": "./dist/middleware.d.ts",
|
|
19
|
+
"import": "./dist/middleware.js",
|
|
20
|
+
"require": "./dist/middleware.cjs"
|
|
21
|
+
},
|
|
22
|
+
"./content": {
|
|
23
|
+
"types": "./dist/content.d.ts",
|
|
24
|
+
"import": "./dist/content.js",
|
|
25
|
+
"require": "./dist/content.cjs"
|
|
26
|
+
},
|
|
27
|
+
"./package.json": "./package.json"
|
|
28
|
+
},
|
|
29
|
+
"files": ["dist", "LICENSE", "README.md"],
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "tsup src/index.ts src/middleware.ts src/content.ts --format esm,cjs --dts --clean",
|
|
32
|
+
"check-types": "tsc --noEmit",
|
|
33
|
+
"test": "bun test tests/runtime",
|
|
34
|
+
"test:types": "tsc -p tests/types/tsconfig.json --noEmit"
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"repository": {
|
|
40
|
+
"type": "git",
|
|
41
|
+
"url": "git+https://github.com/jralvarenga/better-translate.git",
|
|
42
|
+
"directory": "packages/astro"
|
|
43
|
+
},
|
|
44
|
+
"homepage": "https://github.com/jralvarenga/better-translate/tree/main/packages/astro#readme",
|
|
45
|
+
"bugs": {
|
|
46
|
+
"url": "https://github.com/jralvarenga/better-translate/issues"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@better-translate/core": "workspace:^"
|
|
50
|
+
},
|
|
51
|
+
"peerDependencies": {
|
|
52
|
+
"astro": "^5.0.0 || ^6.0.0"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@repo/typescript-config": "*"
|
|
56
|
+
},
|
|
57
|
+
"keywords": [
|
|
58
|
+
"astro",
|
|
59
|
+
"i18n",
|
|
60
|
+
"l10n",
|
|
61
|
+
"markdown",
|
|
62
|
+
"mdx",
|
|
63
|
+
"translations",
|
|
64
|
+
"typescript"
|
|
65
|
+
]
|
|
66
|
+
}
|