@weglot/translate-react 0.2.2 → 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 +96 -9
- package/build/plugin/next.cjs +13 -2
- package/build/plugin/next.d.cts.map +1 -1
- package/build/plugin/next.d.mts.map +1 -1
- package/build/plugin/next.mjs +13 -2
- 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 +9 -7
- package/build/plugin/transform/process-file.mjs +9 -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 +3 -2
- package/build/plugin/unplugin.d.cts.map +1 -1
- package/build/plugin/unplugin.d.mts.map +1 -1
- package/build/plugin/unplugin.mjs +3 -2
- 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.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.d.mts +1 -0
- package/build/react/shared/WeglotContext.d.mts.map +1 -1
- package/build/react/shared/WeglotProvider.d.mts +2 -2
- 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/package.json +1 -1
package/README.md
CHANGED
|
@@ -90,10 +90,15 @@ components it uses stay in the source language. Wrap its content in
|
|
|
90
90
|
### Generated files
|
|
91
91
|
|
|
92
92
|
- `<sourceRoot>/weglot/cache/<locale>.json`: the translations received from
|
|
93
|
-
Weglot. Commit it to build without calling the API (see
|
|
93
|
+
Weglot. Commit it to build without calling the API (see [Deploying](#deploying)),
|
|
94
94
|
or ignore it and let each build fetch what it lacks.
|
|
95
|
-
-
|
|
96
|
-
|
|
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.
|
|
97
102
|
|
|
98
103
|
### Switching language
|
|
99
104
|
|
|
@@ -133,6 +138,62 @@ identifiers and class names, URLs and file names, `<code>`, `<pre>`, `<script>`,
|
|
|
133
138
|
`<style>`, `<kbd>`, `<samp>` and `<var>`, and anything not readable statically.
|
|
134
139
|
Exclude an element with `translate="no"` or `data-weglot-skip`.
|
|
135
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
|
+
|
|
136
197
|
## Configuration
|
|
137
198
|
|
|
138
199
|
| Option | Type | Default | Description |
|
|
@@ -177,7 +238,7 @@ Languages are not configured here: they come from your Weglot project.
|
|
|
177
238
|
|
|
178
239
|
- `translate` (default): missing translations are generated through the
|
|
179
240
|
Weglot API at build time; the build fails if translation fails.
|
|
180
|
-
- `cache-only`: no
|
|
241
|
+
- `cache-only`: no translation calls; the build fails if the local cache is
|
|
181
242
|
incomplete. Override per build with `WEGLOT_BUILD_MODE=cache-only`.
|
|
182
243
|
|
|
183
244
|
Weglot generates translations with an LLM, so new strings can take a moment:
|
|
@@ -190,6 +251,23 @@ A string Weglot will not translate, such as one made only of digits, does not
|
|
|
190
251
|
fail the build: it is served in the source language with a warning, and asked
|
|
191
252
|
for again on the next build.
|
|
192
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
|
+
|
|
193
271
|
## React API
|
|
194
272
|
|
|
195
273
|
```tsx
|
|
@@ -228,11 +306,20 @@ fragment the way the Weglot proxy splits a page, so inline markup survives.
|
|
|
228
306
|
|
|
229
307
|
Calls made in the same render are batched into one request, and all of them
|
|
230
308
|
return the source text if the API takes longer than 500ms — a slow call never
|
|
231
|
-
holds up a page.
|
|
232
|
-
the
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
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.
|
|
236
323
|
|
|
237
324
|
## Development (this repo)
|
|
238
325
|
|
package/build/plugin/next.cjs
CHANGED
|
@@ -8,6 +8,7 @@ const require_build_translator = require('./build-translator.cjs');
|
|
|
8
8
|
const require_next_traces = require('./next-traces.cjs');
|
|
9
9
|
const require_cleanup = require('./cleanup.cjs');
|
|
10
10
|
const require_use_i18n = require('./transform/use-i18n.cjs');
|
|
11
|
+
const require_msg = require('./transform/msg.cjs');
|
|
11
12
|
const require_package_version = require('../utils/package-version.cjs');
|
|
12
13
|
let node_fs_promises = require("node:fs/promises");
|
|
13
14
|
node_fs_promises = require_rolldown_runtime.__toESM(node_fs_promises);
|
|
@@ -63,17 +64,27 @@ function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
|
|
|
63
64
|
turbopack: {
|
|
64
65
|
pattern: "*.{tsx,jsx}",
|
|
65
66
|
config: {
|
|
66
|
-
condition:
|
|
67
|
+
condition: weglotConfig.useDirective ? { any: [{ content: require_use_i18n.useI18nRegex }, { content: require_msg.msgImportRegex }] } : { content: void 0 },
|
|
67
68
|
loaders: [compilerLoader]
|
|
68
69
|
}
|
|
69
70
|
},
|
|
70
71
|
webpack: {
|
|
71
72
|
enforce: "pre",
|
|
72
|
-
test: /\.(tsx|jsx)$/i,
|
|
73
|
+
test: /\.(tsx|jsx|[cm]?[jt]s)$/i,
|
|
73
74
|
exclude: /node_modules/,
|
|
74
75
|
use: [compilerLoader]
|
|
75
76
|
}
|
|
76
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
|
+
} },
|
|
77
88
|
config: {
|
|
78
89
|
turbopack: {
|
|
79
90
|
pattern: "**/virtual/config.mjs",
|
|
@@ -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"}
|
package/build/plugin/next.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { processBuildTranslations } from "./build-translator.mjs";
|
|
|
8
8
|
import { addDictionariesToTraces } from "./next-traces.mjs";
|
|
9
9
|
import { registerCleanupOnCurrentProcess } from "./cleanup.mjs";
|
|
10
10
|
import { useI18nRegex } from "./transform/use-i18n.mjs";
|
|
11
|
+
import { msgImportRegex } from "./transform/msg.mjs";
|
|
11
12
|
import { packageVersion } from "../utils/package-version.mjs";
|
|
12
13
|
import fs from "node:fs/promises";
|
|
13
14
|
import path from "node:path";
|
|
@@ -61,17 +62,27 @@ function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
|
|
|
61
62
|
turbopack: {
|
|
62
63
|
pattern: "*.{tsx,jsx}",
|
|
63
64
|
config: {
|
|
64
|
-
condition:
|
|
65
|
+
condition: weglotConfig.useDirective ? { any: [{ content: useI18nRegex }, { content: msgImportRegex }] } : { content: void 0 },
|
|
65
66
|
loaders: [compilerLoader]
|
|
66
67
|
}
|
|
67
68
|
},
|
|
68
69
|
webpack: {
|
|
69
70
|
enforce: "pre",
|
|
70
|
-
test: /\.(tsx|jsx)$/i,
|
|
71
|
+
test: /\.(tsx|jsx|[cm]?[jt]s)$/i,
|
|
71
72
|
exclude: /node_modules/,
|
|
72
73
|
use: [compilerLoader]
|
|
73
74
|
}
|
|
74
75
|
},
|
|
76
|
+
messages: { turbopack: {
|
|
77
|
+
pattern: "*.{ts,js,mts,mjs}",
|
|
78
|
+
config: hasStableTurboConfig() ? {
|
|
79
|
+
condition: { all: [{ not: "foreign" }, { content: msgImportRegex }] },
|
|
80
|
+
loaders: [compilerLoader]
|
|
81
|
+
} : {
|
|
82
|
+
foreign: false,
|
|
83
|
+
default: { loaders: [compilerLoader] }
|
|
84
|
+
}
|
|
85
|
+
} },
|
|
75
86
|
config: {
|
|
76
87
|
turbopack: {
|
|
77
88
|
pattern: "**/virtual/config.mjs",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.mjs","names":["turbopackConfig: Partial<NextConfig>","distDir","webpack: NextJsWebpackConfig"],"sources":["../../src/plugin/next.ts"],"sourcesContent":["import type { NextConfig } from \"next\";\nimport type {\n NextJsWebpackConfig,\n TurbopackOptions,\n WebpackConfigContext,\n} from \"next/dist/server/config-shared\";\nimport {\n createWeglotConfig,\n resolveProjectLanguages,\n} from \"../utils/config-factory\";\nimport { logger } from \"../utils/logger\";\nimport type { WeglotConfig, PartialWeglotConfig } from \"../types\";\nimport { processBuildTranslations } from \"./build-translator\";\nimport { addDictionariesToTraces } from \"./next-traces\";\nimport { startOrGetTranslationServer } from \"../translation-server/translation-server\";\nimport { getMetadataPath, loadMetadata, pruneMetadata } from \"../metadata/manager\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\nimport { TranslationService } from \"../translators\";\nimport { packageVersion } from \"../utils/package-version\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport type WeglotNextPluginOptions = PartialWeglotConfig;\n\ntype RuleKey = \"compiler\" | \"config\" | \"localeServer\" | \"localeClient\";\n\nfunction loaders({\n weglotConfig,\n metadataFilePath,\n translationServerUrl,\n}: {\n weglotConfig: WeglotConfig;\n metadataFilePath: string;\n translationServerUrl?: string;\n}): Record<RuleKey, { turbopack?: any; webpack?: any }> {\n const common = {\n sourceRoot: weglotConfig.sourceRoot,\n weglotDir: weglotConfig.weglotDir,\n sourceLocale: weglotConfig.sourceLocale,\n // Part of the bundlers' cache key, so an upgrade recompiles cached files.\n version: packageVersion(),\n };\n\n // TODO (AleksandrSl 14/12/2025): Type options.\n const compilerLoader = {\n loader: \"@weglot/translate-react/next-compiler-loader\",\n options: {\n ...common,\n useDirective: weglotConfig.useDirective,\n translatableAttributes: weglotConfig.translatableAttributes,\n metadataFilePath,\n },\n };\n\n const configLoader = {\n loader: \"@weglot/translate-react/next-config-loader\",\n options: {\n ...common,\n // The runtime reads these to address the API without a settings call.\n apiLocales: weglotConfig.apiLocales,\n translationEngine: weglotConfig.translationEngine,\n apiBaseUrl: weglotConfig.apiBaseUrl,\n // Turbopack rejects undefined options, left by an absent server URL.\n dev: Object.fromEntries(\n Object.entries({ translationServerUrl, ...weglotConfig.dev }).filter(\n ([, value]) => value !== undefined,\n ),\n ),\n },\n };\n const localeServerLoader = {\n loader: \"@weglot/translate-react/next-locale-server-loader\",\n options: {\n ...common,\n localePersistence: weglotConfig.localePersistence,\n },\n };\n\n const localeClientLoader = {\n loader: \"@weglot/translate-react/next-locale-client-loader\",\n options: {\n ...common,\n localePersistence: weglotConfig.localePersistence,\n },\n };\n\n return {\n compiler: {\n turbopack: {\n pattern: \"*.{tsx,jsx}\",\n config: {\n condition: {\n content: weglotConfig.useDirective ? useI18nRegex : undefined,\n },\n loaders: [compilerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /\\.(tsx|jsx)$/i,\n exclude: /node_modules/,\n use: [compilerLoader],\n },\n },\n\n // Every environment, not just dev: it also carries the locale map and engine,\n // whose placeholders would otherwise reach the browser.\n config: {\n turbopack: {\n pattern: \"**/virtual/config.mjs\",\n config: {\n loaders: [configLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/config\\.mjs$/i,\n use: [configLoader],\n },\n },\n\n localeServer: {\n turbopack: {\n pattern: \"**/virtual/locale/server.mjs\",\n config: {\n loaders: [localeServerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]server\\.mjs$/i,\n use: [localeServerLoader],\n },\n },\n\n localeClient: {\n turbopack: {\n pattern: \"**/virtual/locale/client.mjs\",\n config: {\n loaders: [localeClientLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]client\\.mjs$/i,\n use: [localeClientLoader],\n },\n },\n };\n}\n\n/**\n * Check if Next.js supports stable turbopack config (Next.js 16+)\n */\nfunction hasStableTurboConfig(): boolean {\n try {\n const nextPackage = require(\"next/package.json\");\n const majorVersion = parseInt(nextPackage.version.split(\".\")[0], 10);\n return majorVersion >= 16;\n } catch {\n return false;\n }\n}\n\nfunction getTurbopackConfig(userConfig: NextConfig): TurbopackOptions {\n return (\n (hasStableTurboConfig()\n ? userConfig?.turbopack\n : // @ts-expect-error - experimental.turbo for Next.js <16\n userConfig?.experimental?.turbo) || {}\n );\n}\n\n/**\n * Merge Turbopack rules without mutating original\n */\nfunction mergeTurbopackRules(\n existingRules: Record<string, any>,\n newRules: ({ pattern: string; config: any } | undefined)[],\n): Record<string, any> {\n const mergedRules = { ...existingRules };\n\n for (const newRule of newRules) {\n if (!newRule) continue;\n const { pattern, config } = newRule;\n\n if (mergedRules[pattern]) {\n if (Array.isArray(mergedRules[pattern])) {\n mergedRules[pattern] = [...mergedRules[pattern], config];\n } else {\n mergedRules[pattern] = [mergedRules[pattern], config];\n }\n } else {\n mergedRules[pattern] = config;\n }\n }\n\n return mergedRules;\n}\n\n// Next read config several times. Once in the main runner,\n// and ~ twice in the build workers which cannot get the config otherwise, because it's not serializable.\n// Workers start in separate processed by get most of the env from the main loader\nfunction isMainRunner() {\n return (\n !process.env.NEXT_PRIVATE_BUILD_WORKER &&\n !process.env.IS_NEXT_WORKER &&\n !process.env.NEXT_PRIVATE_WORKER\n );\n}\n\nasync function failOnLostMetadata(metadataFilePath: string, lastBuildFile: string) {\n const entries = Object.keys(await loadMetadata(metadataFilePath, true)).length;\n if (entries > 0) return;\n const last = await fs\n .readFile(lastBuildFile, \"utf8\")\n .then((content) => JSON.parse(content).entries as number)\n .catch(() => 0);\n if (last > 0) {\n throw new Error(\n `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 ${path.relative(process.cwd(), path.dirname(path.dirname(lastBuildFile)))} and build again.`,\n );\n }\n}\n\nasync function writeLastBuild(metadataFilePath: string, lastBuildFile: string) {\n const entries = Object.keys(await loadMetadata(metadataFilePath, true)).length;\n await fs.mkdir(path.dirname(lastBuildFile), { recursive: true });\n await fs.writeFile(lastBuildFile, JSON.stringify({ entries }));\n}\n\nexport async function withWeglot(\n nextConfig: NextConfig = {},\n weglotOptions: WeglotNextPluginOptions,\n): Promise<NextConfig> {\n const weglotConfig = createWeglotConfig(weglotOptions);\n await resolveProjectLanguages(weglotConfig);\n const distDir = path.resolve(nextConfig.distDir ?? \".next\");\n if (weglotConfig.environment !== \"development\") {\n // Kept with the bundler cache: files it serves are not compiled again, so\n // their entries must come from the previous build.\n weglotConfig.metadataDir = path.join(distDir, \"cache\", \"weglot\", \"metadata-build\");\n }\n const metadataFilePath = getMetadataPath(weglotConfig);\n const isDev = weglotConfig.environment === \"development\";\n\n logger.debug(\n `Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`,\n );\n\n // Try to start up the translation server once.\n // We have two barriers, a simple one here and a more complex one inside the startTranslationServer which doesn't start the server if it can find one running.\n // We do not use isMainRunner here, because we need to start the server as early as possible, so the loaders get the translation server url. The main runner in dev mode runs after a dev server process is started.\n if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) {\n if (weglotConfig.dev.translationServerUrl) {\n logger.info(`Using existing translation server URL (${weglotConfig.dev.translationServerUrl}) from config`);\n process.env.WEGLOT_TRANSLATION_SERVER_URL =\n weglotConfig.dev.translationServerUrl;\n } else {\n const translationServer = await startOrGetTranslationServer({\n translationService: new TranslationService(weglotConfig, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n onReady: (port) => {\n logger.info(\n `Translation server started successfully on port: ${port}`,\n );\n },\n config: weglotConfig,\n });\n process.env.WEGLOT_TRANSLATION_SERVER_URL = translationServer.url;\n if (translationServer.server) {\n // We start the server in the same process, so we should be fine without any sync cleanup. Server should be killed with the process.\n registerCleanupOnCurrentProcess({\n asyncCleanup: async () => {\n await translationServer.server.stop();\n },\n });\n }\n }\n }\n\n const translationServerUrl = process.env.WEGLOT_TRANSLATION_SERVER_URL;\n\n const existingTurbopackConfig = getTurbopackConfig(nextConfig);\n let mergedRules = mergeTurbopackRules(\n existingTurbopackConfig.rules ?? {},\n Object.values(\n loaders({ weglotConfig, metadataFilePath, translationServerUrl }),\n ).map((rules) => rules.turbopack),\n );\n\n const existingResolveAlias = existingTurbopackConfig.resolveAlias;\n const mergedResolveAlias = {\n ...existingResolveAlias,\n };\n\n let turbopackConfig: Partial<NextConfig>;\n if (hasStableTurboConfig()) {\n turbopackConfig = {\n turbopack: {\n ...nextConfig.turbopack, // Preserve existing turbopack options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n };\n } else {\n turbopackConfig = {\n experimental: {\n ...nextConfig.experimental, // Preserve ALL experimental options\n // @ts-expect-error - turbo for Next.js <16\n turbo: {\n // @ts-expect-error - turbo for Next.js <16\n ...nextConfig.experimental?.turbo, // Preserve existing turbo options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n },\n };\n }\n\n const runAfterProductionCompile = async ({\n distDir,\n projectDir,\n }: {\n distDir: string;\n projectDir: string;\n }) => {\n if (typeof nextConfig.compiler?.runAfterProductionCompile === \"function\") {\n await nextConfig.compiler.runAfterProductionCompile({\n distDir,\n projectDir,\n });\n }\n\n logger.info(\"Running post-build translation generation...\");\n\n const lastBuildFile = path.join(distDir, \"cache\", \"weglot\", \"last-build.json\");\n try {\n await pruneMetadata(metadataFilePath);\n await failOnLostMetadata(metadataFilePath, lastBuildFile);\n await processBuildTranslations({\n config: weglotConfig,\n publicOutputPath: distDir,\n metadataFilePath,\n });\n await addDictionariesToTraces(distDir, weglotConfig.targetLocales);\n await writeLastBuild(metadataFilePath, lastBuildFile);\n } catch (error) {\n logger.error(\n \"Translation generation failed:\",\n error instanceof Error ? error.message : error,\n );\n throw error;\n }\n };\n\n const webpack: NextJsWebpackConfig = (\n config: any,\n options: WebpackConfigContext,\n ) => {\n // Apply user's webpack config first if it exists\n let modifiedConfig = config;\n if (typeof nextConfig.webpack === \"function\") {\n modifiedConfig = nextConfig.webpack(config, options);\n }\n\n const weglotRules = Object.values(\n loaders({ weglotConfig, metadataFilePath, translationServerUrl }),\n )\n .map((rules) => rules.webpack)\n .filter(Boolean);\n\n // I tried using plugin from unplugin, but with all the loaders stuff it works poorly.\n // Failing with weird errors which appear on the later compilations, probably something with the cache and virtual modules\n modifiedConfig.module.rules.unshift(...weglotRules);\n\n return modifiedConfig;\n };\n\n return {\n ...nextConfig,\n ...turbopackConfig,\n compiler: {\n ...nextConfig.compiler,\n runAfterProductionCompile,\n },\n webpack,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,SAAS,QAAQ,EACf,cACA,kBACA,wBAKsD;CACtD,MAAM,SAAS;EACb,YAAY,aAAa;EACzB,WAAW,aAAa;EACxB,cAAc,aAAa;EAE3B,SAAS,gBAAgB;EAC1B;CAGD,MAAM,iBAAiB;EACrB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,cAAc,aAAa;GAC3B,wBAAwB,aAAa;GACrC;GACD;EACF;CAED,MAAM,eAAe;EACnB,QAAQ;EACR,SAAS;GACP,GAAG;GAEH,YAAY,aAAa;GACzB,mBAAmB,aAAa;GAChC,YAAY,aAAa;GAEzB,KAAK,OAAO,YACV,OAAO,QAAQ;IAAE;IAAsB,GAAG,aAAa;IAAK,CAAC,CAAC,QAC3D,GAAG,WAAW,UAAU,OAC1B,CACF;GACF;EACF;CACD,MAAM,qBAAqB;EACzB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,mBAAmB,aAAa;GACjC;EACF;CAED,MAAM,qBAAqB;EACzB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,mBAAmB,aAAa;GACjC;EACF;AAED,QAAO;EACL,UAAU;GACR,WAAW;IACT,SAAS;IACT,QAAQ;KACN,WAAW,EACT,SAAS,aAAa,eAAe,eAAe,QACrD;KACD,SAAS,CAAC,eAAe;KAC1B;IACF;GACD,SAAS;IACP,SAAS;IACT,MAAM;IACN,SAAS;IACT,KAAK,CAAC,eAAe;IACtB;GACF;EAID,QAAQ;GACN,WAAW;IACT,SAAS;IACT,QAAQ,EACN,SAAS,CAAC,aAAa,EACxB;IACF;GACD,SAAS;IACP,SAAS;IACT,MAAM;IACN,KAAK,CAAC,aAAa;IACpB;GACF;EAED,cAAc;GACZ,WAAW;IACT,SAAS;IACT,QAAQ,EACN,SAAS,CAA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AIlB,iBAAe,OAAO,MAAM,QAAQ,GAAG,YAAY;AAEnD,SAAO;;AAGT,QAAO;EACL,GAAG;EACH,GAAG;EACH,UAAU;GACR,GAAG,WAAW;GACd;GACD;EACD;EACD"}
|
|
1
|
+
{"version":3,"file":"next.mjs","names":["turbopackConfig: Partial<NextConfig>","distDir","webpack: NextJsWebpackConfig"],"sources":["../../src/plugin/next.ts"],"sourcesContent":["import type { NextConfig } from \"next\";\nimport type {\n NextJsWebpackConfig,\n TurbopackOptions,\n WebpackConfigContext,\n} from \"next/dist/server/config-shared\";\nimport {\n createWeglotConfig,\n resolveProjectLanguages,\n} from \"../utils/config-factory\";\nimport { logger } from \"../utils/logger\";\nimport type { WeglotConfig, PartialWeglotConfig } from \"../types\";\nimport { processBuildTranslations } from \"./build-translator\";\nimport { addDictionariesToTraces } from \"./next-traces\";\nimport { startOrGetTranslationServer } from \"../translation-server/translation-server\";\nimport { getMetadataPath, loadMetadata, pruneMetadata } from \"../metadata/manager\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\nimport { msgImportRegex } from \"./transform/msg\";\nimport { TranslationService } from \"../translators\";\nimport { packageVersion } from \"../utils/package-version\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport type WeglotNextPluginOptions = PartialWeglotConfig;\n\ntype RuleKey =\n | \"compiler\"\n | \"messages\"\n | \"config\"\n | \"localeServer\"\n | \"localeClient\";\n\nfunction loaders({\n weglotConfig,\n metadataFilePath,\n translationServerUrl,\n}: {\n weglotConfig: WeglotConfig;\n metadataFilePath: string;\n translationServerUrl?: string;\n}): Record<RuleKey, { turbopack?: any; webpack?: any }> {\n const common = {\n sourceRoot: weglotConfig.sourceRoot,\n weglotDir: weglotConfig.weglotDir,\n sourceLocale: weglotConfig.sourceLocale,\n // Part of the bundlers' cache key, so an upgrade recompiles cached files.\n version: packageVersion(),\n };\n\n // TODO (AleksandrSl 14/12/2025): Type options.\n const compilerLoader = {\n loader: \"@weglot/translate-react/next-compiler-loader\",\n options: {\n ...common,\n useDirective: weglotConfig.useDirective,\n translatableAttributes: weglotConfig.translatableAttributes,\n metadataFilePath,\n },\n };\n\n const configLoader = {\n loader: \"@weglot/translate-react/next-config-loader\",\n options: {\n ...common,\n // The runtime reads these to address the API without a settings call.\n apiLocales: weglotConfig.apiLocales,\n translationEngine: weglotConfig.translationEngine,\n apiBaseUrl: weglotConfig.apiBaseUrl,\n // Turbopack rejects undefined options, left by an absent server URL.\n dev: Object.fromEntries(\n Object.entries({ translationServerUrl, ...weglotConfig.dev }).filter(\n ([, value]) => value !== undefined,\n ),\n ),\n },\n };\n const localeServerLoader = {\n loader: \"@weglot/translate-react/next-locale-server-loader\",\n options: {\n ...common,\n localePersistence: weglotConfig.localePersistence,\n },\n };\n\n const localeClientLoader = {\n loader: \"@weglot/translate-react/next-locale-client-loader\",\n options: {\n ...common,\n localePersistence: weglotConfig.localePersistence,\n },\n };\n\n return {\n compiler: {\n turbopack: {\n pattern: \"*.{tsx,jsx}\",\n config: {\n condition: weglotConfig.useDirective\n ? { any: [{ content: useI18nRegex }, { content: msgImportRegex }] }\n : { content: undefined },\n loaders: [compilerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /\\.(tsx|jsx|[cm]?[jt]s)$/i,\n exclude: /node_modules/,\n use: [compilerLoader],\n },\n },\n\n // .ts/.js files are compiled only for their msg() calls.\n messages: {\n turbopack: {\n pattern: \"*.{ts,js,mts,mjs}\",\n config: hasStableTurboConfig()\n ? {\n condition: {\n all: [{ not: \"foreign\" }, { content: msgImportRegex }],\n },\n loaders: [compilerLoader],\n }\n : { foreign: false, default: { loaders: [compilerLoader] } },\n },\n },\n\n // Every environment, not just dev: it also carries the locale map and engine,\n // whose placeholders would otherwise reach the browser.\n config: {\n turbopack: {\n pattern: \"**/virtual/config.mjs\",\n config: {\n loaders: [configLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/config\\.mjs$/i,\n use: [configLoader],\n },\n },\n\n localeServer: {\n turbopack: {\n pattern: \"**/virtual/locale/server.mjs\",\n config: {\n loaders: [localeServerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]server\\.mjs$/i,\n use: [localeServerLoader],\n },\n },\n\n localeClient: {\n turbopack: {\n pattern: \"**/virtual/locale/client.mjs\",\n config: {\n loaders: [localeClientLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]client\\.mjs$/i,\n use: [localeClientLoader],\n },\n },\n };\n}\n\n/**\n * Check if Next.js supports stable turbopack config (Next.js 16+)\n */\nfunction hasStableTurboConfig(): boolean {\n try {\n const nextPackage = require(\"next/package.json\");\n const majorVersion = parseInt(nextPackage.version.split(\".\")[0], 10);\n return majorVersion >= 16;\n } catch {\n return false;\n }\n}\n\nfunction getTurbopackConfig(userConfig: NextConfig): TurbopackOptions {\n return (\n (hasStableTurboConfig()\n ? userConfig?.turbopack\n : // @ts-expect-error - experimental.turbo for Next.js <16\n userConfig?.experimental?.turbo) || {}\n );\n}\n\n/**\n * Merge Turbopack rules without mutating original\n */\nfunction mergeTurbopackRules(\n existingRules: Record<string, any>,\n newRules: ({ pattern: string; config: any } | undefined)[],\n): Record<string, any> {\n const mergedRules = { ...existingRules };\n\n for (const newRule of newRules) {\n if (!newRule) continue;\n const { pattern, config } = newRule;\n\n if (mergedRules[pattern]) {\n if (Array.isArray(mergedRules[pattern])) {\n mergedRules[pattern] = [...mergedRules[pattern], config];\n } else {\n mergedRules[pattern] = [mergedRules[pattern], config];\n }\n } else {\n mergedRules[pattern] = config;\n }\n }\n\n return mergedRules;\n}\n\n// Next read config several times. Once in the main runner,\n// and ~ twice in the build workers which cannot get the config otherwise, because it's not serializable.\n// Workers start in separate processed by get most of the env from the main loader\nfunction isMainRunner() {\n return (\n !process.env.NEXT_PRIVATE_BUILD_WORKER &&\n !process.env.IS_NEXT_WORKER &&\n !process.env.NEXT_PRIVATE_WORKER\n );\n}\n\nasync function failOnLostMetadata(metadataFilePath: string, lastBuildFile: string) {\n const entries = Object.keys(await loadMetadata(metadataFilePath, true)).length;\n if (entries > 0) return;\n const last = await fs\n .readFile(lastBuildFile, \"utf8\")\n .then((content) => JSON.parse(content).entries as number)\n .catch(() => 0);\n if (last > 0) {\n throw new Error(\n `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 ${path.relative(process.cwd(), path.dirname(path.dirname(lastBuildFile)))} and build again.`,\n );\n }\n}\n\nasync function writeLastBuild(metadataFilePath: string, lastBuildFile: string) {\n const entries = Object.keys(await loadMetadata(metadataFilePath, true)).length;\n await fs.mkdir(path.dirname(lastBuildFile), { recursive: true });\n await fs.writeFile(lastBuildFile, JSON.stringify({ entries }));\n}\n\nexport async function withWeglot(\n nextConfig: NextConfig = {},\n weglotOptions: WeglotNextPluginOptions,\n): Promise<NextConfig> {\n const weglotConfig = createWeglotConfig(weglotOptions);\n await resolveProjectLanguages(weglotConfig);\n const distDir = path.resolve(nextConfig.distDir ?? \".next\");\n if (weglotConfig.environment !== \"development\") {\n // Kept with the bundler cache: files it serves are not compiled again, so\n // their entries must come from the previous build.\n weglotConfig.metadataDir = path.join(distDir, \"cache\", \"weglot\", \"metadata-build\");\n }\n const metadataFilePath = getMetadataPath(weglotConfig);\n const isDev = weglotConfig.environment === \"development\";\n\n logger.debug(\n `Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`,\n );\n\n // Try to start up the translation server once.\n // We have two barriers, a simple one here and a more complex one inside the startTranslationServer which doesn't start the server if it can find one running.\n // We do not use isMainRunner here, because we need to start the server as early as possible, so the loaders get the translation server url. The main runner in dev mode runs after a dev server process is started.\n if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) {\n if (weglotConfig.dev.translationServerUrl) {\n logger.info(`Using existing translation server URL (${weglotConfig.dev.translationServerUrl}) from config`);\n process.env.WEGLOT_TRANSLATION_SERVER_URL =\n weglotConfig.dev.translationServerUrl;\n } else {\n const translationServer = await startOrGetTranslationServer({\n translationService: new TranslationService(weglotConfig, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n onReady: (port) => {\n logger.info(\n `Translation server started successfully on port: ${port}`,\n );\n },\n config: weglotConfig,\n });\n process.env.WEGLOT_TRANSLATION_SERVER_URL = translationServer.url;\n if (translationServer.server) {\n // We start the server in the same process, so we should be fine without any sync cleanup. Server should be killed with the process.\n registerCleanupOnCurrentProcess({\n asyncCleanup: async () => {\n await translationServer.server.stop();\n },\n });\n }\n }\n }\n\n const translationServerUrl = process.env.WEGLOT_TRANSLATION_SERVER_URL;\n\n const existingTurbopackConfig = getTurbopackConfig(nextConfig);\n let mergedRules = mergeTurbopackRules(\n existingTurbopackConfig.rules ?? {},\n Object.values(\n loaders({ weglotConfig, metadataFilePath, translationServerUrl }),\n ).map((rules) => rules.turbopack),\n );\n\n const existingResolveAlias = existingTurbopackConfig.resolveAlias;\n const mergedResolveAlias = {\n ...existingResolveAlias,\n };\n\n let turbopackConfig: Partial<NextConfig>;\n if (hasStableTurboConfig()) {\n turbopackConfig = {\n turbopack: {\n ...nextConfig.turbopack, // Preserve existing turbopack options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n };\n } else {\n turbopackConfig = {\n experimental: {\n ...nextConfig.experimental, // Preserve ALL experimental options\n // @ts-expect-error - turbo for Next.js <16\n turbo: {\n // @ts-expect-error - turbo for Next.js <16\n ...nextConfig.experimental?.turbo, // Preserve existing turbo options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n },\n };\n }\n\n const runAfterProductionCompile = async ({\n distDir,\n projectDir,\n }: {\n distDir: string;\n projectDir: string;\n }) => {\n if (typeof nextConfig.compiler?.runAfterProductionCompile === \"function\") {\n await nextConfig.compiler.runAfterProductionCompile({\n distDir,\n projectDir,\n });\n }\n\n logger.info(\"Running post-build translation generation...\");\n\n const lastBuildFile = path.join(distDir, \"cache\", \"weglot\", \"last-build.json\");\n try {\n await pruneMetadata(metadataFilePath);\n await failOnLostMetadata(metadataFilePath, lastBuildFile);\n await processBuildTranslations({\n config: weglotConfig,\n publicOutputPath: distDir,\n metadataFilePath,\n });\n await addDictionariesToTraces(distDir, weglotConfig.targetLocales);\n await writeLastBuild(metadataFilePath, lastBuildFile);\n } catch (error) {\n logger.error(\n \"Translation generation failed:\",\n error instanceof Error ? error.message : error,\n );\n throw error;\n }\n };\n\n const webpack: NextJsWebpackConfig = (\n config: any,\n options: WebpackConfigContext,\n ) => {\n // Apply user's webpack config first if it exists\n let modifiedConfig = config;\n if (typeof nextConfig.webpack === \"function\") {\n modifiedConfig = nextConfig.webpack(config, options);\n }\n\n const weglotRules = Object.values(\n loaders({ weglotConfig, metadataFilePath, translationServerUrl }),\n )\n .map((rules) => rules.webpack)\n .filter(Boolean);\n\n // I tried using plugin from unplugin, but with all the loaders stuff it works poorly.\n // Failing with weird errors which appear on the later compilations, probably something with the cache and virtual modules\n modifiedConfig.module.rules.unshift(...weglotRules);\n\n return modifiedConfig;\n };\n\n return {\n ...nextConfig,\n ...turbopackConfig,\n compiler: {\n ...nextConfig.compiler,\n runAfterProductionCompile,\n },\n webpack,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiCA,SAAS,QAAQ,EACf,cACA,kBACA,wBAKsD;CACtD,MAAM,SAAS;EACb,YAAY,aAAa;EACzB,WAAW,aAAa;EACxB,cAAc,aAAa;EAE3B,SAAS,gBAAgB;EAC1B;CAGD,MAAM,iBAAiB;EACrB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,cAAc,aAAa;GAC3B,wBAAwB,aAAa;GACrC;GACD;EACF;CAED,MAAM,eAAe;EACnB,QAAQ;EACR,SAAS;GACP,GAAG;GAEH,YAAY,aAAa;GACzB,mBAAmB,aAAa;GAChC,YAAY,aAAa;GAEzB,KAAK,OAAO,YACV,OAAO,QAAQ;IAAE;IAAsB,GAAG,aAAa;IAAK,CAAC,CAAC,QAC3D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,mBAAkB,EAChB,WAAW;EACT,GAAG,WAAW;EACd,OAAO;EACP,cAAc;EACf,EACF;KAED,mBAAkB,EAChB,cAAc;EACZ,GAAG,WAAW;EAEd,OAAO;GAEL,GAAG,WAAW,cAAc;GAC5B,OAAO;GACP,cAAc;GACf;EACF,EACF;CAGH,MAAM,4BAA4B,OAAO,EACvC,oBACA,iBAII;AACJ,MAAI,OAAO,WAAW,UAAU,8BAA8B,WAC5D,OAAM,WAAW,SAAS,0BAA0B;GAClD;GACA;GACD,CAAC;AAGJ,SAAO,KAAK,+CAA+C;EAE3D,MAAM,gBAAgB,KAAK,KAAKC,WAAS,SAAS,UAAU,kBAAkB;AAC9E,MAAI;AACF,SAAM,cAAc,iBAAiB;AACrC,SAAM,mBAAmB,kBAAkB,cAAc;AACzD,SAAM,yBAAyB;IAC7B,QAAQ;IACR,kBAAkBA;IAClB;IACD,CAAC;AACF,SAAM,wBAAwBA,WAAS,aAAa,cAAc;AAClE,SAAM,eAAe,kBAAkB,cAAc;WAC9C,OAAO;AACd,UAAO,MACL,kCACA,iBAAiB,QAAQ,MAAM,UAAU,MAC1C;AACD,SAAM;;;CAIV,MAAMC,WACJ,QACA,YACG;EAEH,IAAI,iBAAiB;AACrB,MAAI,OAAO,WAAW,YAAY,WAChC,kBAAiB,WAAW,QAAQ,QAAQ,QAAQ;EAGtD,MAAM,cAAc,OAAO,OACzB,QAAQ;GAAE;GAAc;GAAkB;GAAsB,CAAC,CAClE,CACE,KAAK,UAAU,MAAM,QAAQ,CAC7B,OAAO,QAAQ;AAIlB,iBAAe,OAAO,MAAM,QAAQ,GAAG,YAAY;AAEnD,SAAO;;AAGT,QAAO;EACL,GAAG;EACH,GAAG;EACH,UAAU;GACR,GAAG,WAAW;GACd;GACD;EACD;EACD"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_logger = require('../../utils/logger.cjs');
|
|
3
3
|
const require_babel_compat = require('./babel-compat.cjs');
|
|
4
|
+
const require_msg = require('./msg.cjs');
|
|
4
5
|
const require_process_file = require('./process-file.cjs');
|
|
5
6
|
let path = require("path");
|
|
6
7
|
path = require_rolldown_runtime.__toESM(path);
|
|
@@ -8,22 +9,35 @@ let _babel_parser = require("@babel/parser");
|
|
|
8
9
|
_babel_parser = require_rolldown_runtime.__toESM(_babel_parser);
|
|
9
10
|
|
|
10
11
|
//#region src/plugin/transform/index.ts
|
|
12
|
+
const JSX_FILE = /\.[jt]sx$/;
|
|
13
|
+
function parserPlugins(filePath) {
|
|
14
|
+
if (JSX_FILE.test(filePath)) return ["jsx", "typescript"];
|
|
15
|
+
if (/\.[cm]?ts$/.test(filePath)) return ["typescript"];
|
|
16
|
+
return ["jsx"];
|
|
17
|
+
}
|
|
11
18
|
/**
|
|
12
19
|
* Transform component code to inject translation calls
|
|
13
20
|
*/
|
|
14
21
|
function transformComponent({ code, filePath, config }) {
|
|
22
|
+
const isJsxFile = JSX_FILE.test(filePath);
|
|
23
|
+
if (!isJsxFile && !require_msg.msgImportRegex.test(code)) return {
|
|
24
|
+
code,
|
|
25
|
+
newEntries: [],
|
|
26
|
+
transformed: false
|
|
27
|
+
};
|
|
15
28
|
const relativeFilePath = path.default.relative(path.default.resolve(config.sourceRoot), filePath).split(path.default.sep).join("/");
|
|
16
29
|
try {
|
|
17
30
|
const ast = _babel_parser.parse(code, {
|
|
18
31
|
sourceType: "module",
|
|
19
|
-
plugins:
|
|
32
|
+
plugins: parserPlugins(filePath)
|
|
20
33
|
});
|
|
21
34
|
require_logger.logger.debug(`Transforming ${filePath}`);
|
|
22
|
-
const translationEntries = require_process_file.processFile(ast, {
|
|
35
|
+
const translationEntries = isJsxFile ? require_process_file.processFile(ast, {
|
|
23
36
|
relativeFilePath,
|
|
24
37
|
needsDirective: config.useDirective,
|
|
25
38
|
translatableAttributes: config.translatableAttributes
|
|
26
|
-
});
|
|
39
|
+
}) : [];
|
|
40
|
+
if (require_msg.msgImportRegex.test(code)) translationEntries.push(...require_msg.processMsgCalls(ast, relativeFilePath));
|
|
27
41
|
const output = require_babel_compat.generate(ast, { sourceMaps: true }, code);
|
|
28
42
|
require_logger.logger.debug(`Transformed ${filePath}. Code: ${output.code}`);
|
|
29
43
|
return {
|
|
@@ -1,26 +1,40 @@
|
|
|
1
1
|
import { logger } from "../../utils/logger.mjs";
|
|
2
2
|
import { generate } from "./babel-compat.mjs";
|
|
3
|
+
import { msgImportRegex, processMsgCalls } from "./msg.mjs";
|
|
3
4
|
import { processFile } from "./process-file.mjs";
|
|
4
5
|
import path from "path";
|
|
5
6
|
import * as parser from "@babel/parser";
|
|
6
7
|
|
|
7
8
|
//#region src/plugin/transform/index.ts
|
|
9
|
+
const JSX_FILE = /\.[jt]sx$/;
|
|
10
|
+
function parserPlugins(filePath) {
|
|
11
|
+
if (JSX_FILE.test(filePath)) return ["jsx", "typescript"];
|
|
12
|
+
if (/\.[cm]?ts$/.test(filePath)) return ["typescript"];
|
|
13
|
+
return ["jsx"];
|
|
14
|
+
}
|
|
8
15
|
/**
|
|
9
16
|
* Transform component code to inject translation calls
|
|
10
17
|
*/
|
|
11
18
|
function transformComponent({ code, filePath, config }) {
|
|
19
|
+
const isJsxFile = JSX_FILE.test(filePath);
|
|
20
|
+
if (!isJsxFile && !msgImportRegex.test(code)) return {
|
|
21
|
+
code,
|
|
22
|
+
newEntries: [],
|
|
23
|
+
transformed: false
|
|
24
|
+
};
|
|
12
25
|
const relativeFilePath = path.relative(path.resolve(config.sourceRoot), filePath).split(path.sep).join("/");
|
|
13
26
|
try {
|
|
14
27
|
const ast = parser.parse(code, {
|
|
15
28
|
sourceType: "module",
|
|
16
|
-
plugins:
|
|
29
|
+
plugins: parserPlugins(filePath)
|
|
17
30
|
});
|
|
18
31
|
logger.debug(`Transforming ${filePath}`);
|
|
19
|
-
const translationEntries = processFile(ast, {
|
|
32
|
+
const translationEntries = isJsxFile ? processFile(ast, {
|
|
20
33
|
relativeFilePath,
|
|
21
34
|
needsDirective: config.useDirective,
|
|
22
35
|
translatableAttributes: config.translatableAttributes
|
|
23
|
-
});
|
|
36
|
+
}) : [];
|
|
37
|
+
if (msgImportRegex.test(code)) translationEntries.push(...processMsgCalls(ast, relativeFilePath));
|
|
24
38
|
const output = generate(ast, { sourceMaps: true }, code);
|
|
25
39
|
logger.debug(`Transformed ${filePath}. Code: ${output.code}`);
|
|
26
40
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/plugin/transform/index.ts"],"sourcesContent":["import * as parser from \"@babel/parser\";\nimport path from \"path\";\nimport type { WeglotConfig, TranslationEntry } from \"../../types\";\nimport { processFile } from \"./process-file\";\nimport { logger } from \"../../utils/logger\";\nimport { generate } from \"./babel-compat\";\n\nexport interface TransformResult {\n code: string;\n map?: any;\n newEntries?: TranslationEntry[];\n transformed: boolean;\n}\n\nexport interface BabelTransformOptions {\n code: string;\n filePath: string;\n config: WeglotConfig;\n}\n\n/**\n * Transform component code to inject translation calls\n */\nexport function transformComponent({\n code,\n filePath,\n config,\n}: BabelTransformOptions): TransformResult {\n // Get relative file path for consistent hashing\n const relativeFilePath = path\n .relative(path.resolve(config.sourceRoot), filePath)\n .split(path.sep)\n // '/' is used as a cross-platform path separator\n .join(\"/\");\n\n try {\n const ast = parser.parse(code, {\n sourceType: \"module\",\n plugins:
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["translationEntries: TranslationEntry[]"],"sources":["../../../src/plugin/transform/index.ts"],"sourcesContent":["import * as parser from \"@babel/parser\";\nimport path from \"path\";\nimport type { WeglotConfig, TranslationEntry } from \"../../types\";\nimport { processFile } from \"./process-file\";\nimport { msgImportRegex, processMsgCalls } from \"./msg\";\nimport { logger } from \"../../utils/logger\";\nimport { generate } from \"./babel-compat\";\n\nexport interface TransformResult {\n code: string;\n map?: any;\n newEntries?: TranslationEntry[];\n transformed: boolean;\n}\n\nexport interface BabelTransformOptions {\n code: string;\n filePath: string;\n config: WeglotConfig;\n}\n\nconst JSX_FILE = /\\.[jt]sx$/;\n\nfunction parserPlugins(filePath: string): parser.ParserPlugin[] {\n if (JSX_FILE.test(filePath)) return [\"jsx\", \"typescript\"];\n if (/\\.[cm]?ts$/.test(filePath)) return [\"typescript\"];\n return [\"jsx\"];\n}\n\n/**\n * Transform component code to inject translation calls\n */\nexport function transformComponent({\n code,\n filePath,\n config,\n}: BabelTransformOptions): TransformResult {\n const isJsxFile = JSX_FILE.test(filePath);\n if (!isJsxFile && !msgImportRegex.test(code)) {\n return { code, newEntries: [], transformed: false };\n }\n\n // Get relative file path for consistent hashing\n const relativeFilePath = path\n .relative(path.resolve(config.sourceRoot), filePath)\n .split(path.sep)\n // '/' is used as a cross-platform path separator\n .join(\"/\");\n\n try {\n const ast = parser.parse(code, {\n sourceType: \"module\",\n plugins: parserPlugins(filePath),\n });\n\n logger.debug(`Transforming ${filePath}`);\n\n const translationEntries: TranslationEntry[] = isJsxFile\n ? processFile(ast, {\n relativeFilePath,\n needsDirective: config.useDirective,\n translatableAttributes: config.translatableAttributes,\n })\n : [];\n if (msgImportRegex.test(code)) {\n translationEntries.push(...processMsgCalls(ast, relativeFilePath));\n }\n\n const output = generate(\n ast,\n {\n sourceMaps: true,\n },\n code,\n );\n\n logger.debug(`Transformed ${filePath}. Code: ${output.code}`);\n\n return {\n code: output.code,\n map: output.map,\n newEntries: translationEntries,\n transformed: translationEntries.length > 0,\n };\n } catch (error) {\n // TODO (AleksandrSl 08/12/2025): Should also log the message\n logger.error(`Failed to transform ${filePath}:`, error);\n // Return original code on error\n return {\n code,\n transformed: false,\n };\n }\n}\n"],"mappings":";;;;;;;;AAqBA,MAAM,WAAW;AAEjB,SAAS,cAAc,UAAyC;AAC9D,KAAI,SAAS,KAAK,SAAS,CAAE,QAAO,CAAC,OAAO,aAAa;AACzD,KAAI,aAAa,KAAK,SAAS,CAAE,QAAO,CAAC,aAAa;AACtD,QAAO,CAAC,MAAM;;;;;AAMhB,SAAgB,mBAAmB,EACjC,MACA,UACA,UACyC;CACzC,MAAM,YAAY,SAAS,KAAK,SAAS;AACzC,KAAI,CAAC,aAAa,CAAC,eAAe,KAAK,KAAK,CAC1C,QAAO;EAAE;EAAM,YAAY,EAAE;EAAE,aAAa;EAAO;CAIrD,MAAM,mBAAmB,KACtB,SAAS,KAAK,QAAQ,OAAO,WAAW,EAAE,SAAS,CACnD,MAAM,KAAK,IAAI,CAEf,KAAK,IAAI;AAEZ,KAAI;EACF,MAAM,MAAM,OAAO,MAAM,MAAM;GAC7B,YAAY;GACZ,SAAS,cAAc,SAAS;GACjC,CAAC;AAEF,SAAO,MAAM,gBAAgB,WAAW;EAExC,MAAMA,qBAAyC,YAC3C,YAAY,KAAK;GACf;GACA,gBAAgB,OAAO;GACvB,wBAAwB,OAAO;GAChC,CAAC,GACF,EAAE;AACN,MAAI,eAAe,KAAK,KAAK,CAC3B,oBAAmB,KAAK,GAAG,gBAAgB,KAAK,iBAAiB,CAAC;EAGpE,MAAM,SAAS,SACb,KACA,EACE,YAAY,MACb,EACD,KACD;AAED,SAAO,MAAM,eAAe,SAAS,UAAU,OAAO,OAAO;AAE7D,SAAO;GACL,MAAM,OAAO;GACb,KAAK,OAAO;GACZ,YAAY;GACZ,aAAa,mBAAmB,SAAS;GAC1C;UACM,OAAO;AAEd,SAAO,MAAM,uBAAuB,SAAS,IAAI,MAAM;AAEvD,SAAO;GACL;GACA,aAAa;GACd"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_logger = require('../../utils/logger.cjs');
|
|
3
|
+
const require_babel_compat = require('./babel-compat.cjs');
|
|
4
|
+
const require_utils = require('./utils.cjs');
|
|
5
|
+
const require_expression_strings = require('./expression-strings.cjs');
|
|
6
|
+
let _babel_types = require("@babel/types");
|
|
7
|
+
_babel_types = require_rolldown_runtime.__toESM(_babel_types);
|
|
8
|
+
|
|
9
|
+
//#region src/plugin/transform/msg.ts
|
|
10
|
+
const MSG_SOURCE = `${require_utils.root}/react`;
|
|
11
|
+
/** Quick pre-parse check that a file may import `msg`. */
|
|
12
|
+
const msgImportRegex = /@weglot\/translate-react\/react["']/;
|
|
13
|
+
function isMsgImport(path) {
|
|
14
|
+
const callee = path.node.callee;
|
|
15
|
+
if (!_babel_types.isIdentifier(callee)) return false;
|
|
16
|
+
const binding = path.scope.getBinding(callee.name);
|
|
17
|
+
if (!binding || binding.kind !== "module") return false;
|
|
18
|
+
const specifier = binding.path;
|
|
19
|
+
if (!specifier.isImportSpecifier()) return false;
|
|
20
|
+
const imported = specifier.node.imported;
|
|
21
|
+
const importedName = _babel_types.isIdentifier(imported) ? imported.name : imported.value;
|
|
22
|
+
const declaration = specifier.parentPath;
|
|
23
|
+
return importedName === "msg" && specifier.node.importKind !== "type" && declaration?.isImportDeclaration() === true && declaration.node.importKind !== "type" && declaration.node.source.value === MSG_SOURCE;
|
|
24
|
+
}
|
|
25
|
+
function readMessage(argument) {
|
|
26
|
+
if (_babel_types.isStringLiteral(argument)) return { text: argument.value };
|
|
27
|
+
if (!_babel_types.isTemplateLiteral(argument)) return null;
|
|
28
|
+
if (argument.expressions.length === 0) {
|
|
29
|
+
const quasi = argument.quasis[0];
|
|
30
|
+
return { text: quasi.value.cooked ?? quasi.value.raw };
|
|
31
|
+
}
|
|
32
|
+
const message = require_expression_strings.templateToMessage(argument);
|
|
33
|
+
if (!message) return null;
|
|
34
|
+
return {
|
|
35
|
+
text: message.text,
|
|
36
|
+
values: _babel_types.objectExpression([...message.variables.map((name) => _babel_types.objectProperty(_babel_types.identifier(name), _babel_types.identifier(name), false, true)), ...[...message.expressions].map(([name, expression]) => _babel_types.objectProperty(_babel_types.identifier(name), expression))])
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Registers every `msg("…")` imported from the package and rewrites it to
|
|
41
|
+
* `msg("…", hash, values?)`, so the runtime descriptor carries its hash.
|
|
42
|
+
*/
|
|
43
|
+
function processMsgCalls(ast, filePath) {
|
|
44
|
+
const entries = [];
|
|
45
|
+
require_babel_compat.traverse(ast, { CallExpression(path) {
|
|
46
|
+
if (path.node.arguments.length !== 1 || !isMsgImport(path)) return;
|
|
47
|
+
const argument = path.node.arguments[0];
|
|
48
|
+
const message = readMessage(argument);
|
|
49
|
+
if (!message || message.text.trim() === "") {
|
|
50
|
+
require_logger.logger.warn(`msg() in ${filePath} needs a string or template literal with text; it is left untranslated.`);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const entry = require_utils.createTranslationEntry("message", message.text, {}, filePath, argument.loc?.start.line, argument.loc?.start.column);
|
|
54
|
+
entries.push(entry);
|
|
55
|
+
path.node.arguments = [
|
|
56
|
+
_babel_types.stringLiteral(message.text),
|
|
57
|
+
_babel_types.stringLiteral(entry.hash),
|
|
58
|
+
...message.values ? [message.values] : []
|
|
59
|
+
];
|
|
60
|
+
} });
|
|
61
|
+
return entries;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
//#endregion
|
|
65
|
+
exports.msgImportRegex = msgImportRegex;
|
|
66
|
+
exports.processMsgCalls = processMsgCalls;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { logger } from "../../utils/logger.mjs";
|
|
2
|
+
import { traverse } from "./babel-compat.mjs";
|
|
3
|
+
import { createTranslationEntry, root } from "./utils.mjs";
|
|
4
|
+
import { templateToMessage } from "./expression-strings.mjs";
|
|
5
|
+
import * as t from "@babel/types";
|
|
6
|
+
|
|
7
|
+
//#region src/plugin/transform/msg.ts
|
|
8
|
+
const MSG_SOURCE = `${root}/react`;
|
|
9
|
+
/** Quick pre-parse check that a file may import `msg`. */
|
|
10
|
+
const msgImportRegex = /@weglot\/translate-react\/react["']/;
|
|
11
|
+
function isMsgImport(path) {
|
|
12
|
+
const callee = path.node.callee;
|
|
13
|
+
if (!t.isIdentifier(callee)) return false;
|
|
14
|
+
const binding = path.scope.getBinding(callee.name);
|
|
15
|
+
if (!binding || binding.kind !== "module") return false;
|
|
16
|
+
const specifier = binding.path;
|
|
17
|
+
if (!specifier.isImportSpecifier()) return false;
|
|
18
|
+
const imported = specifier.node.imported;
|
|
19
|
+
const importedName = t.isIdentifier(imported) ? imported.name : imported.value;
|
|
20
|
+
const declaration = specifier.parentPath;
|
|
21
|
+
return importedName === "msg" && specifier.node.importKind !== "type" && declaration?.isImportDeclaration() === true && declaration.node.importKind !== "type" && declaration.node.source.value === MSG_SOURCE;
|
|
22
|
+
}
|
|
23
|
+
function readMessage(argument) {
|
|
24
|
+
if (t.isStringLiteral(argument)) return { text: argument.value };
|
|
25
|
+
if (!t.isTemplateLiteral(argument)) return null;
|
|
26
|
+
if (argument.expressions.length === 0) {
|
|
27
|
+
const quasi = argument.quasis[0];
|
|
28
|
+
return { text: quasi.value.cooked ?? quasi.value.raw };
|
|
29
|
+
}
|
|
30
|
+
const message = templateToMessage(argument);
|
|
31
|
+
if (!message) return null;
|
|
32
|
+
return {
|
|
33
|
+
text: message.text,
|
|
34
|
+
values: t.objectExpression([...message.variables.map((name) => t.objectProperty(t.identifier(name), t.identifier(name), false, true)), ...[...message.expressions].map(([name, expression]) => t.objectProperty(t.identifier(name), expression))])
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Registers every `msg("…")` imported from the package and rewrites it to
|
|
39
|
+
* `msg("…", hash, values?)`, so the runtime descriptor carries its hash.
|
|
40
|
+
*/
|
|
41
|
+
function processMsgCalls(ast, filePath) {
|
|
42
|
+
const entries = [];
|
|
43
|
+
traverse(ast, { CallExpression(path) {
|
|
44
|
+
if (path.node.arguments.length !== 1 || !isMsgImport(path)) return;
|
|
45
|
+
const argument = path.node.arguments[0];
|
|
46
|
+
const message = readMessage(argument);
|
|
47
|
+
if (!message || message.text.trim() === "") {
|
|
48
|
+
logger.warn(`msg() in ${filePath} needs a string or template literal with text; it is left untranslated.`);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const entry = createTranslationEntry("message", message.text, {}, filePath, argument.loc?.start.line, argument.loc?.start.column);
|
|
52
|
+
entries.push(entry);
|
|
53
|
+
path.node.arguments = [
|
|
54
|
+
t.stringLiteral(message.text),
|
|
55
|
+
t.stringLiteral(entry.hash),
|
|
56
|
+
...message.values ? [message.values] : []
|
|
57
|
+
];
|
|
58
|
+
} });
|
|
59
|
+
return entries;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
//#endregion
|
|
63
|
+
export { msgImportRegex, processMsgCalls };
|
|
64
|
+
//# sourceMappingURL=msg.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"msg.mjs","names":["entries: MessageTranslationEntry[]"],"sources":["../../../src/plugin/transform/msg.ts"],"sourcesContent":["import * as t from \"@babel/types\";\nimport type { NodePath } from \"@babel/traverse\";\nimport type { MessageTranslationEntry } from \"../../types\";\nimport { logger } from \"../../utils/logger\";\nimport { traverse } from \"./babel-compat\";\nimport { templateToMessage } from \"./expression-strings\";\nimport { createTranslationEntry, root } from \"./utils\";\n\nexport const MSG_SOURCE = `${root}/react`;\n\n/** Quick pre-parse check that a file may import `msg`. */\nexport const msgImportRegex = /@weglot\\/translate-react\\/react[\"']/;\n\nfunction isMsgImport(path: NodePath<t.CallExpression>): boolean {\n const callee = path.node.callee;\n if (!t.isIdentifier(callee)) return false;\n\n const binding = path.scope.getBinding(callee.name);\n if (!binding || binding.kind !== \"module\") return false;\n\n const specifier = binding.path;\n if (!specifier.isImportSpecifier()) return false;\n\n const imported = specifier.node.imported;\n const importedName = t.isIdentifier(imported)\n ? imported.name\n : imported.value;\n const declaration = specifier.parentPath;\n\n return (\n importedName === \"msg\" &&\n specifier.node.importKind !== \"type\" &&\n declaration?.isImportDeclaration() === true &&\n declaration.node.importKind !== \"type\" &&\n declaration.node.source.value === MSG_SOURCE\n );\n}\n\nfunction readMessage(\n argument: t.Node,\n): { text: string; values?: t.ObjectExpression } | null {\n if (t.isStringLiteral(argument)) {\n return { text: argument.value };\n }\n\n if (!t.isTemplateLiteral(argument)) return null;\n\n if (argument.expressions.length === 0) {\n const quasi = argument.quasis[0];\n return { text: quasi.value.cooked ?? quasi.value.raw };\n }\n\n const message = templateToMessage(argument);\n if (!message) return null;\n\n return {\n text: message.text,\n values: t.objectExpression([\n ...message.variables.map((name) =>\n t.objectProperty(t.identifier(name), t.identifier(name), false, true),\n ),\n ...[...message.expressions].map(([name, expression]) =>\n t.objectProperty(t.identifier(name), expression),\n ),\n ]),\n };\n}\n\n/**\n * Registers every `msg(\"…\")` imported from the package and rewrites it to\n * `msg(\"…\", hash, values?)`, so the runtime descriptor carries its hash.\n */\nexport function processMsgCalls(\n ast: t.Node,\n filePath: string,\n): MessageTranslationEntry[] {\n const entries: MessageTranslationEntry[] = [];\n\n traverse(ast, {\n CallExpression(path) {\n if (path.node.arguments.length !== 1 || !isMsgImport(path)) return;\n\n const argument = path.node.arguments[0];\n const message = readMessage(argument);\n if (!message || message.text.trim() === \"\") {\n logger.warn(\n `msg() in ${filePath} needs a string or template literal with text; it is left untranslated.`,\n );\n return;\n }\n\n const entry = createTranslationEntry(\n \"message\",\n message.text,\n {},\n filePath,\n argument.loc?.start.line,\n argument.loc?.start.column,\n );\n entries.push(entry);\n\n path.node.arguments = [\n t.stringLiteral(message.text),\n t.stringLiteral(entry.hash),\n ...(message.values ? [message.values] : []),\n ];\n },\n });\n\n return entries;\n}\n"],"mappings":";;;;;;;AAQA,MAAa,aAAa,GAAG,KAAK;;AAGlC,MAAa,iBAAiB;AAE9B,SAAS,YAAY,MAA2C;CAC9D,MAAM,SAAS,KAAK,KAAK;AACzB,KAAI,CAAC,EAAE,aAAa,OAAO,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK,MAAM,WAAW,OAAO,KAAK;AAClD,KAAI,CAAC,WAAW,QAAQ,SAAS,SAAU,QAAO;CAElD,MAAM,YAAY,QAAQ;AAC1B,KAAI,CAAC,UAAU,mBAAmB,CAAE,QAAO;C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AQ,uBACZ,WACA,QAAQ,MACR,EAAE,EACF,UACA,SAAS,KAAK,MAAM,MACpB,SAAS,KAAK,MAAM,OACrB;AACD,UAAQ,KAAK,MAAM;AAEnB,OAAK,KAAK,YAAY;GACpB,EAAE,cAAc,QAAQ,KAAK;GAC7B,EAAE,cAAc,MAAM,KAAK;GAC3B,GAAI,QAAQ,SAAS,CAAC,QAAQ,OAAO,GAAG,EAAE;GAC3C;IAEJ,CAAC;AAEF,QAAO"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_logger = require('../../utils/logger.cjs');
|
|
3
3
|
const require_engine = require('../../translators/weglot/engine.cjs');
|
|
4
|
-
const require_utils = require('./utils.cjs');
|
|
5
|
-
const require_metadata = require('./metadata.cjs');
|
|
6
4
|
const require_babel_compat = require('./babel-compat.cjs');
|
|
5
|
+
const require_utils = require('./utils.cjs');
|
|
7
6
|
const require_expression_strings = require('./expression-strings.cjs');
|
|
7
|
+
const require_metadata = require('./metadata.cjs');
|
|
8
8
|
let _babel_types = require("@babel/types");
|
|
9
9
|
_babel_types = require_rolldown_runtime.__toESM(_babel_types);
|
|
10
10
|
|
|
@@ -239,10 +239,9 @@ function hasMergeableSiblings(children) {
|
|
|
239
239
|
/**
|
|
240
240
|
* Serialize JSX children to a translation string with placeholders
|
|
241
241
|
*/
|
|
242
|
-
function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ new Map()) {
|
|
242
|
+
function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ new Map(), expressions = /* @__PURE__ */ new Map()) {
|
|
243
243
|
let text = "";
|
|
244
244
|
const variables = [];
|
|
245
|
-
const expressions = /* @__PURE__ */ new Map();
|
|
246
245
|
const components = /* @__PURE__ */ new Map();
|
|
247
246
|
for (const child of children) if (child.type === "JSXText") {
|
|
248
247
|
let normalized = require_utils.normalizeWhitespace(child.value);
|
|
@@ -276,7 +275,7 @@ function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ n
|
|
|
276
275
|
const tagName = `${elementName}${count}`;
|
|
277
276
|
translateAttributes(child, state);
|
|
278
277
|
if (shouldTranslate) {
|
|
279
|
-
const nested = serializeJSXChildren(child.children, state, elementCounts);
|
|
278
|
+
const nested = serializeJSXChildren(child.children, state, elementCounts, expressions);
|
|
280
279
|
text += `<${tagName}>${nested.text}</${tagName}>`;
|
|
281
280
|
for (const v of nested.variables) if (!variables.includes(v)) variables.push(v);
|
|
282
281
|
for (const [nestedTag, nestedElement] of nested.components) components.set(nestedTag, nestedElement);
|
|
@@ -403,13 +402,16 @@ function injectTranslationHook(path, component, state) {
|
|
|
403
402
|
state.needsUnifiedImport = true;
|
|
404
403
|
}
|
|
405
404
|
}
|
|
405
|
+
function importsBinding(programPath, name, source) {
|
|
406
|
+
return programPath.node.body.some((statement) => _babel_types.isImportDeclaration(statement) && statement.importKind !== "type" && statement.source.value === source && statement.specifiers.some((specifier) => _babel_types.isImportSpecifier(specifier) && specifier.local.name === name && _babel_types.isIdentifier(specifier.imported, { name }) && specifier.importKind !== "type"));
|
|
407
|
+
}
|
|
406
408
|
/**
|
|
407
409
|
* Add translation imports at the top of the file
|
|
408
410
|
* Called on Program exit after all components have been processed
|
|
409
411
|
*/
|
|
410
412
|
function addTranslationImports(programPath, state) {
|
|
411
|
-
if (state.needsAsyncImport) programPath.node.body.unshift(require_utils.constructServerImport());
|
|
412
|
-
if (state.needsUnifiedImport) programPath.node.body.unshift(require_utils.comstructUnifiedImport());
|
|
413
|
+
if (state.needsAsyncImport && !importsBinding(programPath, "getServerTranslations", require_utils.constructServerImport().source.value)) programPath.node.body.unshift(require_utils.constructServerImport());
|
|
414
|
+
if (state.needsUnifiedImport && !importsBinding(programPath, "useTranslation", require_utils.comstructUnifiedImport().source.value)) programPath.node.body.unshift(require_utils.comstructUnifiedImport());
|
|
413
415
|
}
|
|
414
416
|
/**
|
|
415
417
|
* Handle component function detection and state update
|