@weglot/translate-react 0.2.1 → 0.3.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/README.md +118 -12
- package/build/metadata/manager.cjs +18 -5
- package/build/metadata/manager.mjs +17 -5
- package/build/metadata/manager.mjs.map +1 -1
- package/build/plugin/next-compiler-loader.cjs +1 -4
- package/build/plugin/next-compiler-loader.mjs +2 -5
- package/build/plugin/next-compiler-loader.mjs.map +1 -1
- package/build/plugin/next-traces.cjs +38 -0
- package/build/plugin/next-traces.mjs +36 -0
- package/build/plugin/next-traces.mjs.map +1 -0
- package/build/plugin/next.cjs +43 -12
- package/build/plugin/next.d.cts.map +1 -1
- package/build/plugin/next.d.mts.map +1 -1
- package/build/plugin/next.mjs +41 -13
- package/build/plugin/next.mjs.map +1 -1
- package/build/plugin/transform/index.cjs +17 -3
- package/build/plugin/transform/index.mjs +17 -3
- package/build/plugin/transform/index.mjs.map +1 -1
- package/build/plugin/transform/msg.cjs +66 -0
- package/build/plugin/transform/msg.mjs +64 -0
- package/build/plugin/transform/msg.mjs.map +1 -0
- package/build/plugin/transform/process-file.cjs +18 -7
- package/build/plugin/transform/process-file.mjs +18 -7
- package/build/plugin/transform/process-file.mjs.map +1 -1
- package/build/plugin/transform/utils.cjs +1 -0
- package/build/plugin/transform/utils.mjs +1 -1
- package/build/plugin/transform/utils.mjs.map +1 -1
- package/build/plugin/unplugin.cjs +6 -7
- package/build/plugin/unplugin.d.cts.map +1 -1
- package/build/plugin/unplugin.d.mts.map +1 -1
- package/build/plugin/unplugin.mjs +7 -8
- package/build/plugin/unplugin.mjs.map +1 -1
- package/build/react/client/index.cjs +2 -0
- package/build/react/client/index.d.cts +2 -1
- package/build/react/client/index.d.mts +2 -1
- package/build/react/client/index.mjs +2 -1
- package/build/react/client/useTranslation.cjs +14 -2
- package/build/react/client/useTranslation.d.cts +0 -35
- package/build/react/client/useTranslation.d.cts.map +1 -1
- package/build/react/client/useTranslation.d.mts +0 -35
- package/build/react/client/useTranslation.d.mts.map +1 -1
- package/build/react/client/useTranslation.mjs +15 -3
- package/build/react/client/useTranslation.mjs.map +1 -1
- package/build/react/server/ServerWeglotProvider.d.cts +2 -2
- package/build/react/server/ServerWeglotProvider.d.mts +2 -2
- package/build/react/server/index.cjs +2 -0
- package/build/react/server/index.d.cts +2 -1
- package/build/react/server/index.d.mts +2 -1
- package/build/react/server/index.mjs +2 -1
- package/build/react/server/useTranslation.cjs +6 -4
- package/build/react/server/useTranslation.d.cts.map +1 -1
- package/build/react/server/useTranslation.d.mts.map +1 -1
- package/build/react/server/useTranslation.mjs +6 -4
- package/build/react/server/useTranslation.mjs.map +1 -1
- package/build/react/server-only/index.cjs +5 -3
- package/build/react/server-only/index.d.cts +2 -3
- package/build/react/server-only/index.d.cts.map +1 -1
- package/build/react/server-only/index.d.mts +2 -3
- package/build/react/server-only/index.d.mts.map +1 -1
- package/build/react/server-only/index.mjs +5 -3
- package/build/react/server-only/index.mjs.map +1 -1
- package/build/react/server-only/translations.cjs +21 -1
- package/build/react/server-only/translations.mjs +22 -2
- package/build/react/server-only/translations.mjs.map +1 -1
- package/build/react/shared/LocaleSwitcher.d.mts +2 -2
- package/build/react/shared/WeglotContext.cjs +18 -2
- package/build/react/shared/WeglotContext.d.cts +1 -0
- package/build/react/shared/WeglotContext.d.cts.map +1 -1
- package/build/react/shared/WeglotContext.d.mts +2 -0
- package/build/react/shared/WeglotContext.d.mts.map +1 -1
- package/build/react/shared/WeglotContext.mjs +18 -2
- package/build/react/shared/WeglotContext.mjs.map +1 -1
- package/build/react/shared/WeglotProvider.cjs +4 -0
- package/build/react/shared/WeglotProvider.d.cts +2 -2
- package/build/react/shared/WeglotProvider.d.cts.map +1 -1
- package/build/react/shared/WeglotProvider.d.mts +2 -2
- package/build/react/shared/WeglotProvider.d.mts.map +1 -1
- package/build/react/shared/WeglotProvider.mjs +4 -0
- package/build/react/shared/WeglotProvider.mjs.map +1 -1
- package/build/react/shared/msg.cjs +50 -0
- package/build/react/shared/msg.d.cts +26 -0
- package/build/react/shared/msg.d.cts.map +1 -0
- package/build/react/shared/msg.d.mts +26 -0
- package/build/react/shared/msg.d.mts.map +1 -0
- package/build/react/shared/msg.mjs +47 -0
- package/build/react/shared/msg.mjs.map +1 -0
- package/build/react/types.d.cts +7 -3
- package/build/react/types.d.cts.map +1 -1
- package/build/react/types.d.mts +7 -3
- package/build/react/types.d.mts.map +1 -1
- package/build/runtime/lru-cache.cjs +38 -0
- package/build/runtime/lru-cache.mjs +38 -0
- package/build/runtime/lru-cache.mjs.map +1 -0
- package/build/runtime/translate-dynamic.cjs +71 -17
- package/build/runtime/translate-dynamic.d.cts +2 -0
- package/build/runtime/translate-dynamic.d.cts.map +1 -1
- package/build/runtime/translate-dynamic.d.mts +2 -0
- package/build/runtime/translate-dynamic.d.mts.map +1 -1
- package/build/runtime/translate-dynamic.mjs +71 -17
- package/build/runtime/translate-dynamic.mjs.map +1 -1
- package/build/translators/weglot/api-client.cjs +4 -1
- package/build/translators/weglot/api-client.mjs +4 -1
- package/build/translators/weglot/api-client.mjs.map +1 -1
- package/build/types.d.cts +7 -1
- package/build/types.d.cts.map +1 -1
- package/build/types.d.mts +7 -1
- package/build/types.d.mts.map +1 -1
- package/build/utils/package-version.cjs +12 -0
- package/build/utils/package-version.mjs +12 -0
- package/build/utils/package-version.mjs.map +1 -0
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -83,13 +83,22 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
83
83
|
}
|
|
84
84
|
```
|
|
85
85
|
|
|
86
|
+
`global-not-found.tsx` renders outside the root layout, so the client
|
|
87
|
+
components it uses stay in the source language. Wrap its content in
|
|
88
|
+
`WeglotProvider` too to translate them.
|
|
89
|
+
|
|
86
90
|
### Generated files
|
|
87
91
|
|
|
88
92
|
- `<sourceRoot>/weglot/cache/<locale>.json`: the translations received from
|
|
89
|
-
Weglot. Commit it to build without calling the API (see
|
|
93
|
+
Weglot. Commit it to build without calling the API (see [Deploying](#deploying)),
|
|
90
94
|
or ignore it and let each build fetch what it lacks.
|
|
91
|
-
-
|
|
92
|
-
|
|
95
|
+
- The dictionaries the app loads, one `<locale>.json` per language, written by
|
|
96
|
+
every build:
|
|
97
|
+
- Vite and Webpack: `public/translations/<locale>.json`. Add it to
|
|
98
|
+
`.gitignore`.
|
|
99
|
+
- Next.js: `<distDir>/<locale>.json` (`.next/` by default), with the rest of
|
|
100
|
+
the build output. Next's trace files list them, so `output: "standalone"`
|
|
101
|
+
and Vercel ship them with the server.
|
|
93
102
|
|
|
94
103
|
### Switching language
|
|
95
104
|
|
|
@@ -129,6 +138,62 @@ identifiers and class names, URLs and file names, `<code>`, `<pre>`, `<script>`,
|
|
|
129
138
|
`<style>`, `<kbd>`, `<samp>` and `<var>`, and anything not readable statically.
|
|
130
139
|
Exclude an element with `translate="no"` or `data-weglot-skip`.
|
|
131
140
|
|
|
141
|
+
Text that only exists at runtime, such as CMS fields, API responses or HTML
|
|
142
|
+
rendered with `dangerouslySetInnerHTML`, is invisible to the compiler. Translate
|
|
143
|
+
it with `@weglot/translate-react/dynamic` (see
|
|
144
|
+
[Runtime translation](#runtime-translation)). It only runs in Server
|
|
145
|
+
Components, calls the Weglot API during the render, and serves the source text
|
|
146
|
+
until Weglot has translated it.
|
|
147
|
+
|
|
148
|
+
### Strings outside JSX: `msg()`
|
|
149
|
+
|
|
150
|
+
The compiler does not follow a string through props or across files. A nav
|
|
151
|
+
array in `nav.ts`, a label passed to `<Menu items={…}>`, an option list built
|
|
152
|
+
in another module: none of these is translated on its own. Mark such strings
|
|
153
|
+
with `msg()` where they are written, and turn them into text with `t()` where
|
|
154
|
+
they are rendered:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
// nav.ts
|
|
158
|
+
import { msg } from "@weglot/translate-react/react";
|
|
159
|
+
|
|
160
|
+
export const NAV = [
|
|
161
|
+
{ href: "/billing", label: msg("Billing") },
|
|
162
|
+
{ href: "/team", label: msg("{count} members") },
|
|
163
|
+
];
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
```tsx
|
|
167
|
+
import { useTranslation } from "@weglot/translate-react/react";
|
|
168
|
+
import { NAV } from "./nav";
|
|
169
|
+
|
|
170
|
+
export function Nav({ members }) {
|
|
171
|
+
const { t } = useTranslation();
|
|
172
|
+
return NAV.map((item) => (
|
|
173
|
+
<a key={item.href} href={item.href} aria-label={t(item.label)}>
|
|
174
|
+
{t(item.label, { count: members })}
|
|
175
|
+
</a>
|
|
176
|
+
));
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`t(message, values?)` returns a plain string, in server and client components
|
|
181
|
+
alike, so it fits attributes and `<option>`. Placeholders use the same ICU
|
|
182
|
+
syntax as the rest of the text; values come from the second argument, or from
|
|
183
|
+
the template literal itself: ``msg(`Invite ${name}`)`` stores `Invite {name}`
|
|
184
|
+
and fills `name` in.
|
|
185
|
+
|
|
186
|
+
`msg()` works in `.ts`, `.js`, `.tsx` and `.jsx` files, with or without
|
|
187
|
+
`useDirective`. Limits:
|
|
188
|
+
|
|
189
|
+
- import it by name from `@weglot/translate-react/react` (`import { msg as m }`
|
|
190
|
+
is fine, `import * as weglot` is not);
|
|
191
|
+
- its argument must be a string or template literal, not a variable;
|
|
192
|
+
- render the result through `t()`: `{item.label}` on its own is an object, not
|
|
193
|
+
text;
|
|
194
|
+
- in development, server components show a `msg()` translation once the dev
|
|
195
|
+
cache has it, after a reload.
|
|
196
|
+
|
|
132
197
|
## Configuration
|
|
133
198
|
|
|
134
199
|
| Option | Type | Default | Description |
|
|
@@ -173,20 +238,36 @@ Languages are not configured here: they come from your Weglot project.
|
|
|
173
238
|
|
|
174
239
|
- `translate` (default): missing translations are generated through the
|
|
175
240
|
Weglot API at build time; the build fails if translation fails.
|
|
176
|
-
- `cache-only`: no
|
|
241
|
+
- `cache-only`: no translation calls; the build fails if the local cache is
|
|
177
242
|
incomplete. Override per build with `WEGLOT_BUILD_MODE=cache-only`.
|
|
178
243
|
|
|
179
244
|
Weglot generates translations with an LLM, so new strings can take a moment:
|
|
180
245
|
the build waits for them up to `translationTimeout`. If some are still not
|
|
181
246
|
ready, the build fails, keeping the ones it received in the local cache, so
|
|
182
|
-
building again picks up where it stopped
|
|
183
|
-
|
|
184
|
-
strings not ready in time show in the source language until the next reload.
|
|
247
|
+
building again picks up where it stopped. In dev, strings not ready in time
|
|
248
|
+
show in the source language until the next reload.
|
|
185
249
|
|
|
186
250
|
A string Weglot will not translate, such as one made only of digits, does not
|
|
187
251
|
fail the build: it is served in the source language with a warning, and asked
|
|
188
252
|
for again on the next build.
|
|
189
253
|
|
|
254
|
+
## Deploying
|
|
255
|
+
|
|
256
|
+
In `translate` mode, a deploy depends on the Weglot API: a slow or failed call
|
|
257
|
+
fails the build. For CI and Vercel, build in `cache-only` mode from a committed
|
|
258
|
+
cache instead:
|
|
259
|
+
|
|
260
|
+
1. Build locally (or in a dedicated CI job) in `translate` mode, and commit
|
|
261
|
+
`<sourceRoot>/weglot/cache/*.json`.
|
|
262
|
+
2. Set `WEGLOT_BUILD_MODE=cache-only` in the deploy environment (on Vercel, as
|
|
263
|
+
an environment variable of the project).
|
|
264
|
+
|
|
265
|
+
The deploy then makes no translation calls. It still reads the languages from
|
|
266
|
+
your Weglot project settings, so keep `WEGLOT_API_KEY` set. A string missing
|
|
267
|
+
from the cache fails the build with `Cache validation failed in cache-only
|
|
268
|
+
mode` and the locales concerned: build once in `translate` mode and commit the
|
|
269
|
+
updated cache.
|
|
270
|
+
|
|
190
271
|
## React API
|
|
191
272
|
|
|
192
273
|
```tsx
|
|
@@ -225,11 +306,20 @@ fragment the way the Weglot proxy splits a page, so inline markup survives.
|
|
|
225
306
|
|
|
226
307
|
Calls made in the same render are batched into one request, and all of them
|
|
227
308
|
return the source text if the API takes longer than 500ms — a slow call never
|
|
228
|
-
holds up a page.
|
|
229
|
-
the
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
309
|
+
holds up a page. Pass `{ timeoutMs }` to change that, or `{ locale }` to
|
|
310
|
+
override the locale for one call. `configureDynamicTranslation({ apiKey })`
|
|
311
|
+
sets the key when it does not come from the environment.
|
|
312
|
+
|
|
313
|
+
**First view.** Content Weglot has never seen is translated on its first
|
|
314
|
+
request, which can take longer than the timeout: that view shows the source
|
|
315
|
+
text. Translations are then kept in memory by the server (the last 10,000;
|
|
316
|
+
set `configureDynamicTranslation({ cacheSize })`), so later renders do not call
|
|
317
|
+
the API. A statically rendered or ISR page that served source text has its
|
|
318
|
+
revalidation cut to one second, so Next renders it again on the next requests
|
|
319
|
+
instead of caching the untranslated page. To avoid the untranslated first
|
|
320
|
+
view, raise `timeoutMs` on pages where waiting is acceptable, or open each new
|
|
321
|
+
page once in every language after publishing it so the translations exist
|
|
322
|
+
before visitors arrive.
|
|
233
323
|
|
|
234
324
|
## Development (this repo)
|
|
235
325
|
|
|
@@ -239,6 +329,22 @@ pnpm --filter @weglot/translate-react test
|
|
|
239
329
|
pnpm --filter @weglot/translate-react build
|
|
240
330
|
```
|
|
241
331
|
|
|
332
|
+
`pnpm test:e2e` packs the package, installs it in the fixture apps of `e2e/`
|
|
333
|
+
(Next 15, Next 16, Vite and webpack) and builds, serves and runs their dev
|
|
334
|
+
servers against a local fake of the Weglot API, so it needs no key. Browser
|
|
335
|
+
checks use Playwright's Chromium: run `pnpm exec playwright install chromium`
|
|
336
|
+
once. The installs are kept in
|
|
337
|
+
`$TMPDIR/weglot-translate-react-e2e` (or `E2E_WORK_DIR`) and reused until the
|
|
338
|
+
package or `e2e/installs/` changes. A known bug is written as `it.fails`
|
|
339
|
+
with its issue number: the PR that fixes it turns it into `it`.
|
|
340
|
+
|
|
341
|
+
`e2e/live.e2e.test.ts` builds the Next fixture against the real Weglot API and
|
|
342
|
+
is skipped without `WEGLOT_E2E_API_KEY`. The `Live API` workflow runs it on
|
|
343
|
+
every pull request and push to master, with the key from the
|
|
344
|
+
`WEGLOT_E2E_API_KEY` repository secret. A staging key also needs the
|
|
345
|
+
`WEGLOT_E2E_SETTINGS_URL` variable set to
|
|
346
|
+
`https://api.weglot.dev/project-settings`.
|
|
347
|
+
|
|
242
348
|
## License
|
|
243
349
|
|
|
244
350
|
Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
|
@@ -61,19 +61,30 @@ async function runWithDbConnection(dbPath, noSync, fn) {
|
|
|
61
61
|
}
|
|
62
62
|
function readEntriesFromDb(db) {
|
|
63
63
|
const entries = {};
|
|
64
|
-
for (const {
|
|
64
|
+
for (const { value } of db.getRange()) {
|
|
65
|
+
const fileEntries = Array.isArray(value) ? value : [value];
|
|
66
|
+
for (const entry of fileEntries) entries[entry.hash] = entry;
|
|
67
|
+
}
|
|
65
68
|
return entries;
|
|
66
69
|
}
|
|
67
70
|
async function loadMetadata(dbPath, noSync = false) {
|
|
68
71
|
return runWithDbConnection(dbPath, noSync, readEntriesFromDb);
|
|
69
72
|
}
|
|
70
73
|
/**
|
|
71
|
-
*
|
|
74
|
+
* Replaces the entries of one file, so a string removed from it does not linger
|
|
75
|
+
* when the database is kept between builds.
|
|
72
76
|
*/
|
|
73
|
-
async function
|
|
77
|
+
async function saveFileMetadata(dbPath, filePath, entries, noSync = false) {
|
|
74
78
|
return runWithDbConnection(dbPath, noSync, (db) => {
|
|
79
|
+
if (entries.length > 0) db.putSync(filePath, entries);
|
|
80
|
+
else if (db.get(filePath) !== void 0) db.removeSync(filePath);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/** Drops the entries of files that no longer exist. */
|
|
84
|
+
async function pruneMetadata(dbPath) {
|
|
85
|
+
return runWithDbConnection(dbPath, true, (db) => {
|
|
75
86
|
db.transactionSync(() => {
|
|
76
|
-
for (const
|
|
87
|
+
for (const key of db.getKeys()) if (!fs.default.existsSync(key)) db.removeSync(key);
|
|
77
88
|
});
|
|
78
89
|
});
|
|
79
90
|
}
|
|
@@ -108,6 +119,7 @@ function cleanupMetadataForEnvironment(metadataDbPath, environment) {
|
|
|
108
119
|
cleanupExistingMetadata(metadataDbPath);
|
|
109
120
|
}
|
|
110
121
|
function getMetadataPath(config) {
|
|
122
|
+
if (config.metadataDir) return config.metadataDir;
|
|
111
123
|
const dirname = config.environment === "development" ? METADATA_DIR_DEV : METADATA_DIR_BUILD;
|
|
112
124
|
return path.default.join(require_path_helpers.getWeglotDir(config), dirname);
|
|
113
125
|
}
|
|
@@ -116,4 +128,5 @@ function getMetadataPath(config) {
|
|
|
116
128
|
exports.cleanupMetadataForEnvironment = cleanupMetadataForEnvironment;
|
|
117
129
|
exports.getMetadataPath = getMetadataPath;
|
|
118
130
|
exports.loadMetadata = loadMetadata;
|
|
119
|
-
exports.
|
|
131
|
+
exports.pruneMetadata = pruneMetadata;
|
|
132
|
+
exports.saveFileMetadata = saveFileMetadata;
|
|
@@ -58,19 +58,30 @@ async function runWithDbConnection(dbPath, noSync, fn) {
|
|
|
58
58
|
}
|
|
59
59
|
function readEntriesFromDb(db) {
|
|
60
60
|
const entries = {};
|
|
61
|
-
for (const {
|
|
61
|
+
for (const { value } of db.getRange()) {
|
|
62
|
+
const fileEntries = Array.isArray(value) ? value : [value];
|
|
63
|
+
for (const entry of fileEntries) entries[entry.hash] = entry;
|
|
64
|
+
}
|
|
62
65
|
return entries;
|
|
63
66
|
}
|
|
64
67
|
async function loadMetadata(dbPath, noSync = false) {
|
|
65
68
|
return runWithDbConnection(dbPath, noSync, readEntriesFromDb);
|
|
66
69
|
}
|
|
67
70
|
/**
|
|
68
|
-
*
|
|
71
|
+
* Replaces the entries of one file, so a string removed from it does not linger
|
|
72
|
+
* when the database is kept between builds.
|
|
69
73
|
*/
|
|
70
|
-
async function
|
|
74
|
+
async function saveFileMetadata(dbPath, filePath, entries, noSync = false) {
|
|
71
75
|
return runWithDbConnection(dbPath, noSync, (db) => {
|
|
76
|
+
if (entries.length > 0) db.putSync(filePath, entries);
|
|
77
|
+
else if (db.get(filePath) !== void 0) db.removeSync(filePath);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/** Drops the entries of files that no longer exist. */
|
|
81
|
+
async function pruneMetadata(dbPath) {
|
|
82
|
+
return runWithDbConnection(dbPath, true, (db) => {
|
|
72
83
|
db.transactionSync(() => {
|
|
73
|
-
for (const
|
|
84
|
+
for (const key of db.getKeys()) if (!fs.existsSync(key)) db.removeSync(key);
|
|
74
85
|
});
|
|
75
86
|
});
|
|
76
87
|
}
|
|
@@ -105,10 +116,11 @@ function cleanupMetadataForEnvironment(metadataDbPath, environment) {
|
|
|
105
116
|
cleanupExistingMetadata(metadataDbPath);
|
|
106
117
|
}
|
|
107
118
|
function getMetadataPath(config) {
|
|
119
|
+
if (config.metadataDir) return config.metadataDir;
|
|
108
120
|
const dirname = config.environment === "development" ? METADATA_DIR_DEV : METADATA_DIR_BUILD;
|
|
109
121
|
return path.join(getWeglotDir(config), dirname);
|
|
110
122
|
}
|
|
111
123
|
|
|
112
124
|
//#endregion
|
|
113
|
-
export { cleanupMetadataForEnvironment, getMetadataPath, loadMetadata,
|
|
125
|
+
export { cleanupMetadataForEnvironment, getMetadataPath, loadMetadata, pruneMetadata, saveFileMetadata };
|
|
114
126
|
//# sourceMappingURL=manager.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.mjs","names":["entries: MetadataSchema"],"sources":["../../src/metadata/manager.ts"],"sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport type { RootDatabase } from \"lmdb\";\nimport type { MetadataSchema, PathConfig, TranslationEntry } from \"../types\";\nimport { getWeglotDir } from \"../utils/path-helpers\";\nimport { logger } from \"../utils/logger\";\n\nconst METADATA_DIR_DEV = \"metadata-dev\";\nconst METADATA_DIR_BUILD = \"metadata-build\";\n\n/**\n * Opens an LMDB environment once per path and process: an open() racing another\n * worker's close() double-frees the env (SIGABRT), killing Turbopack's worker.\n *\n * lmdb is loaded via dynamic import() to prevent bundlers and require hooks\n * from transforming its CJS bundle, which contains syntax they can't handle.\n */\nconst connections = new Map<string, Promise<RootDatabase>>();\n\nfunction openDatabaseConnection(\n dbPath: string,\n noSync: boolean,\n): Promise<RootDatabase> {\n const existing = connections.get(dbPath);\n if (existing) return existing;\n\n const opening = (async () => {\n try {\n fs.mkdirSync(dbPath, { recursive: true });\n const { open } = await import(\"lmdb\");\n return open({\n path: dbPath,\n compression: true,\n noSync,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to open LMDB at ${dbPath}: ${message}`);\n }\n })();\n\n connections.set(dbPath, opening);\n // A failed open must not be cached, or every later operation replays it.\n opening.catch(() => connections.delete(dbPath));\n return opening;\n}\n\n/**\n * Closes the cached connection. Also prevents EBUSY/EPERM on Windows during\n * directory cleanup.\n */\nexport async function closeMetadataDatabase(dbPath: string): Promise<void> {\n const opening = connections.get(dbPath);\n if (!opening) return;\n connections.delete(dbPath);\n\n try {\n const db = await opening;\n await db.close();\n } catch (e) {\n logger.debug(`Error closing database at ${dbPath}: ${e}`);\n }\n}\n\n/**\n * Runs the callback against the connection for this path. The connection is\n * left open for the life of the process; see openDatabaseConnection.\n */\nasync function runWithDbConnection<T>(\n dbPath: string,\n noSync: boolean,\n fn: (db: RootDatabase) => T,\n): Promise<T> {\n const db = await openDatabaseConnection(dbPath, noSync);\n return fn(db);\n}\n\nfunction readEntriesFromDb(db: RootDatabase): MetadataSchema {\n const entries: MetadataSchema = {};\n\n for (const {
|
|
1
|
+
{"version":3,"file":"manager.mjs","names":["entries: MetadataSchema"],"sources":["../../src/metadata/manager.ts"],"sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport type { RootDatabase } from \"lmdb\";\nimport type { MetadataSchema, PathConfig, TranslationEntry } from \"../types\";\nimport { getWeglotDir } from \"../utils/path-helpers\";\nimport { logger } from \"../utils/logger\";\n\nconst METADATA_DIR_DEV = \"metadata-dev\";\nconst METADATA_DIR_BUILD = \"metadata-build\";\n\n/**\n * Opens an LMDB environment once per path and process: an open() racing another\n * worker's close() double-frees the env (SIGABRT), killing Turbopack's worker.\n *\n * lmdb is loaded via dynamic import() to prevent bundlers and require hooks\n * from transforming its CJS bundle, which contains syntax they can't handle.\n */\nconst connections = new Map<string, Promise<RootDatabase>>();\n\nfunction openDatabaseConnection(\n dbPath: string,\n noSync: boolean,\n): Promise<RootDatabase> {\n const existing = connections.get(dbPath);\n if (existing) return existing;\n\n const opening = (async () => {\n try {\n fs.mkdirSync(dbPath, { recursive: true });\n const { open } = await import(\"lmdb\");\n return open({\n path: dbPath,\n compression: true,\n noSync,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to open LMDB at ${dbPath}: ${message}`);\n }\n })();\n\n connections.set(dbPath, opening);\n // A failed open must not be cached, or every later operation replays it.\n opening.catch(() => connections.delete(dbPath));\n return opening;\n}\n\n/**\n * Closes the cached connection. Also prevents EBUSY/EPERM on Windows during\n * directory cleanup.\n */\nexport async function closeMetadataDatabase(dbPath: string): Promise<void> {\n const opening = connections.get(dbPath);\n if (!opening) return;\n connections.delete(dbPath);\n\n try {\n const db = await opening;\n await db.close();\n } catch (e) {\n logger.debug(`Error closing database at ${dbPath}: ${e}`);\n }\n}\n\n/**\n * Runs the callback against the connection for this path. The connection is\n * left open for the life of the process; see openDatabaseConnection.\n */\nasync function runWithDbConnection<T>(\n dbPath: string,\n noSync: boolean,\n fn: (db: RootDatabase) => T,\n): Promise<T> {\n const db = await openDatabaseConnection(dbPath, noSync);\n return fn(db);\n}\n\nfunction readEntriesFromDb(db: RootDatabase): MetadataSchema {\n const entries: MetadataSchema = {};\n\n for (const { value } of db.getRange()) {\n // Databases written before entries were grouped by file hold one entry per key.\n const fileEntries = (Array.isArray(value) ? value : [value]) as TranslationEntry[];\n for (const entry of fileEntries) {\n entries[entry.hash] = entry;\n }\n }\n\n return entries;\n}\n\nexport async function loadMetadata(\n dbPath: string,\n noSync = false,\n): Promise<MetadataSchema> {\n return runWithDbConnection(dbPath, noSync, readEntriesFromDb);\n}\n\n/**\n * Replaces the entries of one file, so a string removed from it does not linger\n * when the database is kept between builds.\n */\nexport async function saveFileMetadata(\n dbPath: string,\n filePath: string,\n entries: TranslationEntry[],\n noSync = false,\n): Promise<void> {\n return runWithDbConnection(dbPath, noSync, (db) => {\n if (entries.length > 0) {\n db.putSync(filePath, entries);\n } else if (db.get(filePath) !== undefined) {\n db.removeSync(filePath);\n }\n });\n}\n\n/** Drops the entries of files that no longer exist. */\nexport async function pruneMetadata(dbPath: string): Promise<void> {\n return runWithDbConnection(dbPath, true, (db) => {\n db.transactionSync(() => {\n for (const key of db.getKeys()) {\n if (!fs.existsSync(key as string)) db.removeSync(key);\n }\n });\n });\n}\n\nexport function cleanupExistingMetadata(metadataDbPath: string): void {\n logger.debug(`Cleaning up metadata database: ${metadataDbPath}`);\n void closeMetadataDatabase(metadataDbPath);\n\n try {\n fs.rmSync(metadataDbPath, { recursive: true, force: true });\n logger.info(`🧹 Cleaned up metadata database: ${metadataDbPath}`);\n } catch (error) {\n const code =\n error instanceof Error && \"code\" in error\n ? (error as NodeJS.ErrnoException).code\n : undefined;\n const message = error instanceof Error ? error.message : String(error);\n\n if (code === \"ENOENT\") {\n logger.debug(\n `Metadata database already deleted or doesn't exist: ${metadataDbPath}`,\n );\n return;\n }\n\n logger.warn(`Failed to cleanup metadata database: ${message}`);\n }\n}\n\n/**\n * Cleared between builds so a stale entry is not paid for, but kept in development\n * where clearing leaves cache-served hashes unresolvable.\n */\nexport function cleanupMetadataForEnvironment(\n metadataDbPath: string,\n environment: PathConfig[\"environment\"],\n): void {\n if (environment === \"development\") {\n logger.debug(`Keeping development metadata database: ${metadataDbPath}`);\n return;\n }\n cleanupExistingMetadata(metadataDbPath);\n}\n\nexport function getMetadataPath(config: PathConfig): string {\n if (config.metadataDir) return config.metadataDir;\n const dirname =\n config.environment === \"development\"\n ? METADATA_DIR_DEV\n : METADATA_DIR_BUILD;\n return path.join(getWeglotDir(config), dirname);\n}\n"],"mappings":";;;;;;AAOA,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;;;;;;;;AAS3B,MAAM,8BAAc,IAAI,KAAoC;AAE5D,SAAS,uBACP,QACA,QACuB;CACvB,MAAM,WAAW,YAAY,IAAI,OAAO;AACxC,KAAI,SAAU,QAAO;CAErB,MAAM,WAAW,YAAY;AAC3B,MAAI;AACF,MAAG,UAAU,QAAQ,EAAE,WAAW,MAAM,CAAC;GACzC,MAAM,EAAE,SAAS,MAAM,OAAO;AAC9B,UAAO,KAAK;IACV,MAAM;IACN,aAAa;IACb;IACD,CAAC;WACK,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,SAAM,IAAI,MAAM,0BAA0B,OAAO,IAAI,UAAU;;KAE/D;AAEJ,aAAY,IAAI,QAAQ,QAAQ;AAEhC,SAAQ,YAAY,YAAY,OAAO,OAAO,CAAC;AAC/C,QAAO;;;;;;AAOT,eAAsB,sBAAsB,QAA+B;CACzE,MAAM,UAAU,YAAY,IAAI,OAAO;AACvC,KAAI,CAAC,QAAS;AACd,aAAY,OAAO,OAAO;AAE1B,KAAI;AAEF,SADW,MAAM,SACR,OAAO;UACT,GAAG;AACV,SAAO,MAAM,6BAA6B,OAAO,IAAI,IAAI;;;;;;;AAQ7D,eAAe,oBACb,QACA,QACA,IACY;AAEZ,QAAO,GADI,MAAM,uBAAuB,QAAQ,OAAO,CAC1C;;AAGf,SAAS,kBAAkB,IAAkC;CAC3D,MAAMA,UAA0B,EAAE;AAElC,MAAK,MAAM,EAAE,WAAW,GAAG,UAAU,EAAE;EAErC,MAAM,cAAe,MAAM,QAAQ,MAAM,GAAG,QAAQ,CAAC,MAAM;AAC3D,OAAK,MAAM,SAAS,YAClB,SAAQ,MAAM,QAAQ;;AAI1B,QAAO;;AAGT,eAAsB,aACpB,QACA,SAAS,OACgB;AACzB,QAAO,oBAAoB,QAAQ,QAAQ,kBAAkB;;;;;;AAO/D,eAAsB,iBACpB,QACA,UACA,SACA,SAAS,OACM;AACf,QAAO,oBAAoB,QAAQ,SAAS,OAAO;AACjD,MAAI,QAAQ,SAAS,EACnB,IAAG,QAAQ,UAAU,QAAQ;WACpB,GAAG,IAAI,SAAS,KAAK,OAC9B,IAAG,WAAW,SAAS;GAEzB;;;AAIJ,eAAsB,cAAc,QAA+B;AACjE,QAAO,oBAAoB,QAAQ,OAAO,OAAO;AAC/C,KAAG,sBAAsB;AACvB,QAAK,MAAM,OAAO,GAAG,SAAS,CAC5B,KAAI,CAAC,GAAG,WAAW,IAAc,CAAE,IAAG,WAAW,IAAI;IAEvD;GACF;;AAGJ,SAAgB,wBAAwB,gBAA8B;AACpE,QAAO,MAAM,kCAAkC,iBAAiB;AAChE,CAAK,sBAAsB,eAAe;AAE1C,KAAI;AACF,KAAG,OAAO,gBAAgB;GAAE,WAAW;GAAM,OAAO;GAAM,CAAC;AAC3D,SAAO,KAAK,oCAAoC,iBAAiB;UAC1D,OAAO;EACd,MAAM,OACJ,iBAAiB,SAAS,UAAU,QAC/B,MAAgC,OACjC;EACN,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AAEtE,MAAI,SAAS,UAAU;AACrB,UAAO,MACL,uDAAuD,iBACxD;AACD;;AAGF,SAAO,KAAK,wCAAwC,UAAU;;;;;;;AAQlE,SAAgB,8BACd,gBACA,aACM;AACN,KAAI,gBAAgB,eAAe;AACjC,SAAO,MAAM,0CAA0C,iBAAiB;AACxE;;AAEF,yBAAwB,eAAe;;AAGzC,SAAgB,gBAAgB,QAA4B;AAC1D,KAAI,OAAO,YAAa,QAAO,OAAO;CACtC,MAAM,UACJ,OAAO,gBAAgB,gBACnB,mBACA;AACN,QAAO,KAAK,KAAK,aAAa,OAAO,EAAE,QAAQ"}
|
|
@@ -22,11 +22,8 @@ async function nextCompilerLoader(source) {
|
|
|
22
22
|
filePath: this.resourcePath,
|
|
23
23
|
config
|
|
24
24
|
});
|
|
25
|
+
await require_manager.saveFileMetadata(config.metadataFilePath, this.resourcePath, result.transformed ? result.newEntries ?? [] : [], config.environment !== "development");
|
|
25
26
|
if (!result.transformed) return callback(null, source);
|
|
26
|
-
if (result.newEntries && result.newEntries.length > 0) {
|
|
27
|
-
await require_manager.saveMetadata(config.metadataFilePath, result.newEntries, config.environment !== "development");
|
|
28
|
-
require_logger.logger.debug(`[Turbopack Loader] Found ${result.newEntries.length} translatable text(s) in ${this.resourcePath}`);
|
|
29
|
-
}
|
|
30
27
|
const validMap = result.map && result.map.sources && Array.isArray(result.map.sources) && result.map.sources.every((s) => typeof s === "string") ? result.map : void 0;
|
|
31
28
|
callback(null, result.code, validMap);
|
|
32
29
|
} catch (error) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { logger } from "../utils/logger.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { saveFileMetadata } from "../metadata/manager.mjs";
|
|
3
3
|
import { transformComponent } from "./transform/index.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/plugin/next-compiler-loader.ts
|
|
@@ -22,11 +22,8 @@ async function nextCompilerLoader(source) {
|
|
|
22
22
|
filePath: this.resourcePath,
|
|
23
23
|
config
|
|
24
24
|
});
|
|
25
|
+
await saveFileMetadata(config.metadataFilePath, this.resourcePath, result.transformed ? result.newEntries ?? [] : [], config.environment !== "development");
|
|
25
26
|
if (!result.transformed) return callback(null, source);
|
|
26
|
-
if (result.newEntries && result.newEntries.length > 0) {
|
|
27
|
-
await saveMetadata(config.metadataFilePath, result.newEntries, config.environment !== "development");
|
|
28
|
-
logger.debug(`[Turbopack Loader] Found ${result.newEntries.length} translatable text(s) in ${this.resourcePath}`);
|
|
29
|
-
}
|
|
30
27
|
const validMap = result.map && result.map.sources && Array.isArray(result.map.sources) && result.map.sources.every((s) => typeof s === "string") ? result.map : void 0;
|
|
31
28
|
callback(null, result.code, validMap);
|
|
32
29
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next-compiler-loader.mjs","names":["config: WeglotConfig & { metadataFilePath: string }"],"sources":["../../src/plugin/next-compiler-loader.ts"],"sourcesContent":["import type { WeglotConfig } from \"../types\";\nimport { transformComponent } from \"./transform\";\nimport { logger } from \"../utils/logger\";\nimport {
|
|
1
|
+
{"version":3,"file":"next-compiler-loader.mjs","names":["config: WeglotConfig & { metadataFilePath: string }"],"sources":["../../src/plugin/next-compiler-loader.ts"],"sourcesContent":["import type { WeglotConfig } from \"../types\";\nimport { transformComponent } from \"./transform\";\nimport { logger } from \"../utils/logger\";\nimport { saveFileMetadata } from \"../metadata/manager\";\n\n/**\n * Turbopack/Webpack loader for automatic translation\n *\n * This loader transforms React components to inject translation calls automatically.\n *\n * For production builds, translations are generated after compilation completes\n * via Next.js's runAfterProductionCompile hook (see next.ts plugin).\n */\nexport default async function nextCompilerLoader(\n this: any,\n source: string,\n): Promise<void> {\n // TODO (AleksandrSl 14/12/2025): Webpack doesn't like callback usage in async function.\n // But async function can return only code, so we have to use promises which is sad. It actually errors only when we catch an error, so it's not an urgent problem\n\n // Ensure we're running in loader context\n if (typeof this.async !== \"function\") {\n throw new Error(\"This module must be run as a loader\");\n }\n const callback = this.async();\n\n try {\n const config: WeglotConfig & { metadataFilePath: string } =\n this.getOptions();\n\n logger.debug(`[Turbopack Loader] Processing: ${this.resourcePath}`);\n\n // Transform the component\n const result = transformComponent({\n code: source,\n filePath: this.resourcePath,\n config,\n });\n\n await saveFileMetadata(\n config.metadataFilePath,\n this.resourcePath,\n result.transformed ? (result.newEntries ?? []) : [],\n config.environment !== \"development\",\n );\n\n if (!result.transformed) {\n return callback(null, source);\n }\n\n // Validate source map before passing to webpack\n // Webpack crashes if sources array contains undefined values\n const validMap =\n result.map &&\n result.map.sources &&\n Array.isArray(result.map.sources) &&\n result.map.sources.every((s: any) => typeof s === \"string\")\n ? result.map\n : undefined;\n\n callback(null, result.code, validMap);\n } catch (error) {\n logger.error(`Compiler failed for ${this.resourcePath}:`);\n logger.error(\n \"Details:\",\n error,\n typeof error === \"object\" && error && \"message\" in error\n ? error.message\n : error,\n error instanceof Error ? error.stack : undefined,\n );\n callback(error as Error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,eAA8B,mBAE5B,QACe;AAKf,KAAI,OAAO,KAAK,UAAU,WACxB,OAAM,IAAI,MAAM,sCAAsC;CAExD,MAAM,WAAW,KAAK,OAAO;AAE7B,KAAI;EACF,MAAMA,SACJ,KAAK,YAAY;AAEnB,SAAO,MAAM,kCAAkC,KAAK,eAAe;EAGnE,MAAM,SAAS,mBAAmB;GAChC,MAAM;GACN,UAAU,KAAK;GACf;GACD,CAAC;AAEF,QAAM,iBACJ,OAAO,kBACP,KAAK,cACL,OAAO,cAAe,OAAO,cAAc,EAAE,GAAI,EAAE,EACnD,OAAO,gBAAgB,cACxB;AAED,MAAI,CAAC,OAAO,YACV,QAAO,SAAS,MAAM,OAAO;EAK/B,MAAM,WACJ,OAAO,OACP,OAAO,IAAI,WACX,MAAM,QAAQ,OAAO,IAAI,QAAQ,IACjC,OAAO,IAAI,QAAQ,OAAO,MAAW,OAAO,MAAM,SAAS,GACvD,OAAO,MACP;AAEN,WAAS,MAAM,OAAO,MAAM,SAAS;UAC9B,OAAO;AACd,SAAO,MAAM,uBAAuB,KAAK,aAAa,GAAG;AACzD,SAAO,MACL,YACA,OACA,OAAO,UAAU,YAAY,SAAS,aAAa,QAC/C,MAAM,UACN,OACJ,iBAAiB,QAAQ,MAAM,QAAQ,OACxC;AACD,WAAS,MAAe"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let node_fs_promises = require("node:fs/promises");
|
|
3
|
+
node_fs_promises = require_rolldown_runtime.__toESM(node_fs_promises);
|
|
4
|
+
let node_path = require("node:path");
|
|
5
|
+
node_path = require_rolldown_runtime.__toESM(node_path);
|
|
6
|
+
|
|
7
|
+
//#region src/plugin/next-traces.ts
|
|
8
|
+
async function findTraceFiles(dir) {
|
|
9
|
+
const entries = await node_fs_promises.default.readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
10
|
+
return (await Promise.all(entries.map((entry) => {
|
|
11
|
+
const fullPath = node_path.default.join(dir, entry.name);
|
|
12
|
+
if (entry.isDirectory()) return findTraceFiles(fullPath);
|
|
13
|
+
return entry.name.endsWith(".nft.json") ? [fullPath] : [];
|
|
14
|
+
}))).flat();
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The server reads the dictionaries from a path built at runtime, which Next's
|
|
18
|
+
* file tracing cannot see, so standalone and Vercel builds would leave them out.
|
|
19
|
+
*/
|
|
20
|
+
async function addDictionariesToTraces(distDir, locales) {
|
|
21
|
+
const dictionaries = (await Promise.all(locales.map(async (locale) => {
|
|
22
|
+
const file = node_path.default.join(distDir, `${locale}.json`);
|
|
23
|
+
return (await node_fs_promises.default.stat(file).catch(() => null))?.isFile() ? file : null;
|
|
24
|
+
}))).filter((file) => file !== null);
|
|
25
|
+
if (dictionaries.length === 0) return;
|
|
26
|
+
const traceFiles = await findTraceFiles(node_path.default.join(distDir, "server"));
|
|
27
|
+
await Promise.all(traceFiles.map(async (traceFile) => {
|
|
28
|
+
const trace = JSON.parse(await node_fs_promises.default.readFile(traceFile, "utf8"));
|
|
29
|
+
if (!Array.isArray(trace.files)) return;
|
|
30
|
+
const files = new Set(trace.files);
|
|
31
|
+
for (const dictionary of dictionaries) files.add(node_path.default.relative(node_path.default.dirname(traceFile), dictionary).split(node_path.default.sep).join("/"));
|
|
32
|
+
trace.files = [...files];
|
|
33
|
+
await node_fs_promises.default.writeFile(traceFile, JSON.stringify(trace));
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
exports.addDictionariesToTraces = addDictionariesToTraces;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
//#region src/plugin/next-traces.ts
|
|
5
|
+
async function findTraceFiles(dir) {
|
|
6
|
+
const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
7
|
+
return (await Promise.all(entries.map((entry) => {
|
|
8
|
+
const fullPath = path.join(dir, entry.name);
|
|
9
|
+
if (entry.isDirectory()) return findTraceFiles(fullPath);
|
|
10
|
+
return entry.name.endsWith(".nft.json") ? [fullPath] : [];
|
|
11
|
+
}))).flat();
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The server reads the dictionaries from a path built at runtime, which Next's
|
|
15
|
+
* file tracing cannot see, so standalone and Vercel builds would leave them out.
|
|
16
|
+
*/
|
|
17
|
+
async function addDictionariesToTraces(distDir, locales) {
|
|
18
|
+
const dictionaries = (await Promise.all(locales.map(async (locale) => {
|
|
19
|
+
const file = path.join(distDir, `${locale}.json`);
|
|
20
|
+
return (await fs.stat(file).catch(() => null))?.isFile() ? file : null;
|
|
21
|
+
}))).filter((file) => file !== null);
|
|
22
|
+
if (dictionaries.length === 0) return;
|
|
23
|
+
const traceFiles = await findTraceFiles(path.join(distDir, "server"));
|
|
24
|
+
await Promise.all(traceFiles.map(async (traceFile) => {
|
|
25
|
+
const trace = JSON.parse(await fs.readFile(traceFile, "utf8"));
|
|
26
|
+
if (!Array.isArray(trace.files)) return;
|
|
27
|
+
const files = new Set(trace.files);
|
|
28
|
+
for (const dictionary of dictionaries) files.add(path.relative(path.dirname(traceFile), dictionary).split(path.sep).join("/"));
|
|
29
|
+
trace.files = [...files];
|
|
30
|
+
await fs.writeFile(traceFile, JSON.stringify(trace));
|
|
31
|
+
}));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
35
|
+
export { addDictionariesToTraces };
|
|
36
|
+
//# sourceMappingURL=next-traces.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"next-traces.mjs","names":[],"sources":["../../src/plugin/next-traces.ts"],"sourcesContent":["import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nasync function findTraceFiles(dir: string): Promise<string[]> {\n const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);\n const nested = await Promise.all(\n entries.map((entry) => {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) return findTraceFiles(fullPath);\n return entry.name.endsWith(\".nft.json\") ? [fullPath] : [];\n }),\n );\n return nested.flat();\n}\n\n/**\n * The server reads the dictionaries from a path built at runtime, which Next's\n * file tracing cannot see, so standalone and Vercel builds would leave them out.\n */\nexport async function addDictionariesToTraces(\n distDir: string,\n locales: string[],\n): Promise<void> {\n const written = await Promise.all(\n locales.map(async (locale) => {\n const file = path.join(distDir, `${locale}.json`);\n return (await fs.stat(file).catch(() => null))?.isFile() ? file : null;\n }),\n );\n const dictionaries = written.filter((file): file is string => file !== null);\n if (dictionaries.length === 0) return;\n const traceFiles = await findTraceFiles(path.join(distDir, \"server\"));\n\n await Promise.all(\n traceFiles.map(async (traceFile) => {\n const trace = JSON.parse(await fs.readFile(traceFile, \"utf8\"));\n if (!Array.isArray(trace.files)) return;\n const files = new Set<string>(trace.files);\n for (const dictionary of dictionaries) {\n files.add(path.relative(path.dirname(traceFile), dictionary).split(path.sep).join(\"/\"));\n }\n trace.files = [...files];\n await fs.writeFile(traceFile, JSON.stringify(trace));\n }),\n );\n}\n"],"mappings":";;;;AAGA,eAAe,eAAe,KAAgC;CAC5D,MAAM,UAAU,MAAM,GAAG,QAAQ,KAAK,EAAE,eAAe,MAAM,CAAC,CAAC,YAAY,EAAE,CAAC;AAQ9E,SAPe,MAAM,QAAQ,IAC3B,QAAQ,KAAK,UAAU;EACrB,MAAM,WAAW,KAAK,KAAK,KAAK,MAAM,KAAK;AAC3C,MAAI,MAAM,aAAa,CAAE,QAAO,eAAe,SAAS;AACxD,SAAO,MAAM,KAAK,SAAS,YAAY,GAAG,CAAC,SAAS,GAAG,EAAE;GACzD,CACH,EACa,MAAM;;;;;;AAOtB,eAAsB,wBACpB,SACA,SACe;CAOf,MAAM,gBANU,MAAM,QAAQ,IAC5B,QAAQ,IAAI,OAAO,WAAW;EAC5B,MAAM,OAAO,KAAK,KAAK,SAAS,GAAG,OAAO,OAAO;AACjD,UAAQ,MAAM,GAAG,KAAK,KAAK,CAAC,YAAY,KAAK,GAAG,QAAQ,GAAG,OAAO;GAClE,CACH,EAC4B,QAAQ,SAAyB,SAAS,KAAK;AAC5E,KAAI,aAAa,WAAW,EAAG;CAC/B,MAAM,aAAa,MAAM,eAAe,KAAK,KAAK,SAAS,SAAS,CAAC;AAErE,OAAM,QAAQ,IACZ,WAAW,IAAI,OAAO,cAAc;EAClC,MAAM,QAAQ,KAAK,MAAM,MAAM,GAAG,SAAS,WAAW,OAAO,CAAC;AAC9D,MAAI,CAAC,MAAM,QAAQ,MAAM,MAAM,CAAE;EACjC,MAAM,QAAQ,IAAI,IAAY,MAAM,MAAM;AAC1C,OAAK,MAAM,cAAc,aACvB,OAAM,IAAI,KAAK,SAAS,KAAK,QAAQ,UAAU,EAAE,WAAW,CAAC,MAAM,KAAK,IAAI,CAAC,KAAK,IAAI,CAAC;AAEzF,QAAM,QAAQ,CAAC,GAAG,MAAM;AACxB,QAAM,GAAG,UAAU,WAAW,KAAK,UAAU,MAAM,CAAC;GACpD,CACH"}
|
package/build/plugin/next.cjs
CHANGED
|
@@ -1,18 +1,27 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
1
2
|
const require_logger = require('../utils/logger.cjs');
|
|
2
3
|
const require_config_factory = require('../utils/config-factory.cjs');
|
|
3
4
|
const require_translation_service = require('../translators/translation-service.cjs');
|
|
4
5
|
const require_manager = require('../metadata/manager.cjs');
|
|
5
6
|
const require_translation_server = require('../translation-server/translation-server.cjs');
|
|
6
7
|
const require_build_translator = require('./build-translator.cjs');
|
|
8
|
+
const require_next_traces = require('./next-traces.cjs');
|
|
7
9
|
const require_cleanup = require('./cleanup.cjs');
|
|
8
10
|
const require_use_i18n = require('./transform/use-i18n.cjs');
|
|
11
|
+
const require_msg = require('./transform/msg.cjs');
|
|
12
|
+
const require_package_version = require('../utils/package-version.cjs');
|
|
13
|
+
let node_fs_promises = require("node:fs/promises");
|
|
14
|
+
node_fs_promises = require_rolldown_runtime.__toESM(node_fs_promises);
|
|
15
|
+
let node_path = require("node:path");
|
|
16
|
+
node_path = require_rolldown_runtime.__toESM(node_path);
|
|
9
17
|
|
|
10
18
|
//#region src/plugin/next.ts
|
|
11
19
|
function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
|
|
12
20
|
const common = {
|
|
13
21
|
sourceRoot: weglotConfig.sourceRoot,
|
|
14
22
|
weglotDir: weglotConfig.weglotDir,
|
|
15
|
-
sourceLocale: weglotConfig.sourceLocale
|
|
23
|
+
sourceLocale: weglotConfig.sourceLocale,
|
|
24
|
+
version: require_package_version.packageVersion()
|
|
16
25
|
};
|
|
17
26
|
const compilerLoader = {
|
|
18
27
|
loader: "@weglot/translate-react/next-compiler-loader",
|
|
@@ -55,17 +64,27 @@ function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
|
|
|
55
64
|
turbopack: {
|
|
56
65
|
pattern: "*.{tsx,jsx}",
|
|
57
66
|
config: {
|
|
58
|
-
condition:
|
|
67
|
+
condition: weglotConfig.useDirective ? { any: [{ content: require_use_i18n.useI18nRegex }, { content: require_msg.msgImportRegex }] } : { content: void 0 },
|
|
59
68
|
loaders: [compilerLoader]
|
|
60
69
|
}
|
|
61
70
|
},
|
|
62
71
|
webpack: {
|
|
63
72
|
enforce: "pre",
|
|
64
|
-
test: /\.(tsx|jsx)$/i,
|
|
73
|
+
test: /\.(tsx|jsx|[cm]?[jt]s)$/i,
|
|
65
74
|
exclude: /node_modules/,
|
|
66
75
|
use: [compilerLoader]
|
|
67
76
|
}
|
|
68
77
|
},
|
|
78
|
+
messages: { turbopack: {
|
|
79
|
+
pattern: "*.{ts,js,mts,mjs}",
|
|
80
|
+
config: hasStableTurboConfig() ? {
|
|
81
|
+
condition: { all: [{ not: "foreign" }, { content: require_msg.msgImportRegex }] },
|
|
82
|
+
loaders: [compilerLoader]
|
|
83
|
+
} : {
|
|
84
|
+
foreign: false,
|
|
85
|
+
default: { loaders: [compilerLoader] }
|
|
86
|
+
}
|
|
87
|
+
} },
|
|
69
88
|
config: {
|
|
70
89
|
turbopack: {
|
|
71
90
|
pattern: "**/virtual/config.mjs",
|
|
@@ -132,10 +151,22 @@ function mergeTurbopackRules(existingRules, newRules) {
|
|
|
132
151
|
function isMainRunner() {
|
|
133
152
|
return !process.env.NEXT_PRIVATE_BUILD_WORKER && !process.env.IS_NEXT_WORKER && !process.env.NEXT_PRIVATE_WORKER;
|
|
134
153
|
}
|
|
154
|
+
async function failOnLostMetadata(metadataFilePath, lastBuildFile) {
|
|
155
|
+
if (Object.keys(await require_manager.loadMetadata(metadataFilePath, true)).length > 0) return;
|
|
156
|
+
const last = await node_fs_promises.default.readFile(lastBuildFile, "utf8").then((content) => JSON.parse(content).entries).catch(() => 0);
|
|
157
|
+
if (last > 0) throw new Error(`No translatable text was found, but the previous build had ${last} entries: the bundler served the files from its cache without the Weglot metadata. Delete ${node_path.default.relative(process.cwd(), node_path.default.dirname(node_path.default.dirname(lastBuildFile)))} and build again.`);
|
|
158
|
+
}
|
|
159
|
+
async function writeLastBuild(metadataFilePath, lastBuildFile) {
|
|
160
|
+
const entries = Object.keys(await require_manager.loadMetadata(metadataFilePath, true)).length;
|
|
161
|
+
await node_fs_promises.default.mkdir(node_path.default.dirname(lastBuildFile), { recursive: true });
|
|
162
|
+
await node_fs_promises.default.writeFile(lastBuildFile, JSON.stringify({ entries }));
|
|
163
|
+
}
|
|
135
164
|
async function withWeglot(nextConfig = {}, weglotOptions) {
|
|
136
165
|
const weglotConfig = require_config_factory.createWeglotConfig(weglotOptions);
|
|
137
166
|
await require_config_factory.resolveProjectLanguages(weglotConfig);
|
|
138
|
-
|
|
167
|
+
const distDir = node_path.default.resolve(nextConfig.distDir ?? ".next");
|
|
168
|
+
if (weglotConfig.environment !== "development") weglotConfig.metadataDir = node_path.default.join(distDir, "cache", "weglot", "metadata-build");
|
|
169
|
+
const metadataFilePath = require_manager.getMetadataPath(weglotConfig);
|
|
139
170
|
const isDev = weglotConfig.environment === "development";
|
|
140
171
|
require_logger.logger.debug(`Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`);
|
|
141
172
|
if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) if (weglotConfig.dev.translationServerUrl) {
|
|
@@ -158,11 +189,6 @@ async function withWeglot(nextConfig = {}, weglotOptions) {
|
|
|
158
189
|
} });
|
|
159
190
|
}
|
|
160
191
|
const translationServerUrl = process.env.WEGLOT_TRANSLATION_SERVER_URL;
|
|
161
|
-
if (isMainRunner()) {
|
|
162
|
-
const environment = weglotConfig.environment;
|
|
163
|
-
require_manager.cleanupMetadataForEnvironment(metadataFilePath, environment);
|
|
164
|
-
require_cleanup.registerCleanupOnCurrentProcess({ cleanup: () => require_manager.cleanupMetadataForEnvironment(metadataFilePath, environment) });
|
|
165
|
-
}
|
|
166
192
|
const existingTurbopackConfig = getTurbopackConfig(nextConfig);
|
|
167
193
|
let mergedRules = mergeTurbopackRules(existingTurbopackConfig.rules ?? {}, Object.values(loaders({
|
|
168
194
|
weglotConfig,
|
|
@@ -184,18 +210,23 @@ async function withWeglot(nextConfig = {}, weglotOptions) {
|
|
|
184
210
|
resolveAlias: mergedResolveAlias
|
|
185
211
|
}
|
|
186
212
|
} };
|
|
187
|
-
const runAfterProductionCompile = async ({ distDir, projectDir }) => {
|
|
213
|
+
const runAfterProductionCompile = async ({ distDir: distDir$1, projectDir }) => {
|
|
188
214
|
if (typeof nextConfig.compiler?.runAfterProductionCompile === "function") await nextConfig.compiler.runAfterProductionCompile({
|
|
189
|
-
distDir,
|
|
215
|
+
distDir: distDir$1,
|
|
190
216
|
projectDir
|
|
191
217
|
});
|
|
192
218
|
require_logger.logger.info("Running post-build translation generation...");
|
|
219
|
+
const lastBuildFile = node_path.default.join(distDir$1, "cache", "weglot", "last-build.json");
|
|
193
220
|
try {
|
|
221
|
+
await require_manager.pruneMetadata(metadataFilePath);
|
|
222
|
+
await failOnLostMetadata(metadataFilePath, lastBuildFile);
|
|
194
223
|
await require_build_translator.processBuildTranslations({
|
|
195
224
|
config: weglotConfig,
|
|
196
|
-
publicOutputPath: distDir,
|
|
225
|
+
publicOutputPath: distDir$1,
|
|
197
226
|
metadataFilePath
|
|
198
227
|
});
|
|
228
|
+
await require_next_traces.addDictionariesToTraces(distDir$1, weglotConfig.targetLocales);
|
|
229
|
+
await writeLastBuild(metadataFilePath, lastBuildFile);
|
|
199
230
|
} catch (error) {
|
|
200
231
|
require_logger.logger.error("Translation generation failed:", error instanceof Error ? error.message : error);
|
|
201
232
|
throw error;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.d.cts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"next.d.cts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAwBY,uBAAA,GAA0B;iBAqOhB,UAAA,aACR,uCACG,0BACd,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.d.mts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"next.d.mts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAwBY,uBAAA,GAA0B;iBAqOhB,UAAA,aACR,uCACG,0BACd,QAAQ"}
|