@weglot/translate-react 0.2.1 → 0.2.2

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.
Files changed (46) hide show
  1. package/README.md +22 -3
  2. package/build/metadata/manager.cjs +18 -5
  3. package/build/metadata/manager.mjs +17 -5
  4. package/build/metadata/manager.mjs.map +1 -1
  5. package/build/plugin/next-compiler-loader.cjs +1 -4
  6. package/build/plugin/next-compiler-loader.mjs +2 -5
  7. package/build/plugin/next-compiler-loader.mjs.map +1 -1
  8. package/build/plugin/next-traces.cjs +38 -0
  9. package/build/plugin/next-traces.mjs +36 -0
  10. package/build/plugin/next-traces.mjs.map +1 -0
  11. package/build/plugin/next.cjs +30 -10
  12. package/build/plugin/next.d.cts.map +1 -1
  13. package/build/plugin/next.d.mts.map +1 -1
  14. package/build/plugin/next.mjs +28 -11
  15. package/build/plugin/next.mjs.map +1 -1
  16. package/build/plugin/transform/process-file.cjs +9 -0
  17. package/build/plugin/transform/process-file.mjs +9 -0
  18. package/build/plugin/transform/process-file.mjs.map +1 -1
  19. package/build/plugin/unplugin.cjs +3 -5
  20. package/build/plugin/unplugin.mjs +4 -6
  21. package/build/plugin/unplugin.mjs.map +1 -1
  22. package/build/react/server/ServerWeglotProvider.d.cts +2 -2
  23. package/build/react/server/ServerWeglotProvider.d.mts +2 -2
  24. package/build/react/shared/LocaleSwitcher.d.mts +2 -2
  25. package/build/react/shared/WeglotContext.cjs +18 -2
  26. package/build/react/shared/WeglotContext.d.cts +1 -0
  27. package/build/react/shared/WeglotContext.d.cts.map +1 -1
  28. package/build/react/shared/WeglotContext.d.mts +1 -0
  29. package/build/react/shared/WeglotContext.d.mts.map +1 -1
  30. package/build/react/shared/WeglotContext.mjs +18 -2
  31. package/build/react/shared/WeglotContext.mjs.map +1 -1
  32. package/build/react/shared/WeglotProvider.cjs +4 -0
  33. package/build/react/shared/WeglotProvider.d.cts +2 -2
  34. package/build/react/shared/WeglotProvider.d.cts.map +1 -1
  35. package/build/react/shared/WeglotProvider.d.mts +2 -2
  36. package/build/react/shared/WeglotProvider.d.mts.map +1 -1
  37. package/build/react/shared/WeglotProvider.mjs +4 -0
  38. package/build/react/shared/WeglotProvider.mjs.map +1 -1
  39. package/build/types.d.cts +7 -1
  40. package/build/types.d.cts.map +1 -1
  41. package/build/types.d.mts +7 -1
  42. package/build/types.d.mts.map +1 -1
  43. package/build/utils/package-version.cjs +12 -0
  44. package/build/utils/package-version.mjs +12 -0
  45. package/build/utils/package-version.mjs.map +1 -0
  46. package/package.json +4 -2
package/README.md CHANGED
@@ -83,6 +83,10 @@ 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
@@ -179,9 +183,8 @@ Languages are not configured here: they come from your Weglot project.
179
183
  Weglot generates translations with an LLM, so new strings can take a moment:
180
184
  the build waits for them up to `translationTimeout`. If some are still not
181
185
  ready, the build fails, keeping the ones it received in the local cache, so
182
- building again picks up where it stopped (with Next.js, delete the `.next`
183
- folder first). In dev,
184
- strings not ready in time show in the source language until the next reload.
186
+ building again picks up where it stopped. In dev, strings not ready in time
187
+ show in the source language until the next reload.
185
188
 
186
189
  A string Weglot will not translate, such as one made only of digits, does not
187
190
  fail the build: it is served in the source language with a warning, and asked
@@ -239,6 +242,22 @@ pnpm --filter @weglot/translate-react test
239
242
  pnpm --filter @weglot/translate-react build
240
243
  ```
241
244
 
245
+ `pnpm test:e2e` packs the package, installs it in the fixture apps of `e2e/`
246
+ (Next 15, Next 16, Vite and webpack) and builds, serves and runs their dev
247
+ servers against a local fake of the Weglot API, so it needs no key. Browser
248
+ checks use Playwright's Chromium: run `pnpm exec playwright install chromium`
249
+ once. The installs are kept in
250
+ `$TMPDIR/weglot-translate-react-e2e` (or `E2E_WORK_DIR`) and reused until the
251
+ package or `e2e/installs/` changes. A known bug is written as `it.fails`
252
+ with its issue number: the PR that fixes it turns it into `it`.
253
+
254
+ `e2e/live.e2e.test.ts` builds the Next fixture against the real Weglot API and
255
+ is skipped without `WEGLOT_E2E_API_KEY`. The `Live API` workflow runs it on
256
+ every pull request and push to master, with the key from the
257
+ `WEGLOT_E2E_API_KEY` repository secret. A staging key also needs the
258
+ `WEGLOT_E2E_SETTINGS_URL` variable set to
259
+ `https://api.weglot.dev/project-settings`.
260
+
242
261
  ## License
243
262
 
244
263
  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 { key, value } of db.getRange()) entries[key] = value;
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
- * Persists translation entries to LMDB in a single atomic transaction.
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 saveMetadata(dbPath, entries, noSync = false) {
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 entry of entries) db.putSync(entry.hash, entry);
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.saveMetadata = saveMetadata;
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 { key, value } of db.getRange()) entries[key] = value;
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
- * Persists translation entries to LMDB in a single atomic transaction.
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 saveMetadata(dbPath, entries, noSync = false) {
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 entry of entries) db.putSync(entry.hash, entry);
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, saveMetadata };
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 { key, value } of db.getRange()) {\n entries[key as string] = value as TranslationEntry;\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 * Persists translation entries to LMDB in a single atomic transaction.\n */\nexport async function saveMetadata(\n dbPath: string,\n entries: TranslationEntry[],\n noSync = false,\n): Promise<void> {\n return runWithDbConnection(dbPath, noSync, (db) => {\n db.transactionSync(() => {\n for (const entry of entries) {\n db.putSync(entry.hash, entry);\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 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,OA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O,KAAK,KAAK,aAAa,OAAO,EAAE,QAAQ"}
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,QAA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Ae;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 { saveMetadata } from "../metadata/manager.mjs";
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 { saveMetadata } 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 // If no transformation occurred, return original source\n if (!result.transformed) {\n return callback(null, source);\n }\n\n // Update metadata with new entries\n if (result.newEntries && result.newEntries.length > 0) {\n await saveMetadata(\n config.metadataFilePath,\n result.newEntries,\n config.environment !== \"development\",\n );\n\n logger.debug(\n `[Turbopack Loader] Found ${result.newEntries.length} translatable text(s) in ${this.resourcePath}`,\n );\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;AAGF,MAAI,CAAC,OAAO,YACV,QAAO,SAAS,MAAM,OAAO;AAI/B,MAAI,OAAO,cAAc,OAAO,WAAW,SAAS,GAAG;AACrD,SAAM,aACJ,OAAO,kBACP,OAAO,YACP,OAAO,gBAAgB,cACxB;AAED,UAAO,MACL,4BAA4B,OAAO,WAAW,OAAO,2BAA2B,KAAK,eACtF;;EAKH,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"}
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"}
@@ -1,18 +1,26 @@
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_package_version = require('../utils/package-version.cjs');
12
+ let node_fs_promises = require("node:fs/promises");
13
+ node_fs_promises = require_rolldown_runtime.__toESM(node_fs_promises);
14
+ let node_path = require("node:path");
15
+ node_path = require_rolldown_runtime.__toESM(node_path);
9
16
 
10
17
  //#region src/plugin/next.ts
11
18
  function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
12
19
  const common = {
13
20
  sourceRoot: weglotConfig.sourceRoot,
14
21
  weglotDir: weglotConfig.weglotDir,
15
- sourceLocale: weglotConfig.sourceLocale
22
+ sourceLocale: weglotConfig.sourceLocale,
23
+ version: require_package_version.packageVersion()
16
24
  };
17
25
  const compilerLoader = {
18
26
  loader: "@weglot/translate-react/next-compiler-loader",
@@ -132,10 +140,22 @@ function mergeTurbopackRules(existingRules, newRules) {
132
140
  function isMainRunner() {
133
141
  return !process.env.NEXT_PRIVATE_BUILD_WORKER && !process.env.IS_NEXT_WORKER && !process.env.NEXT_PRIVATE_WORKER;
134
142
  }
143
+ async function failOnLostMetadata(metadataFilePath, lastBuildFile) {
144
+ if (Object.keys(await require_manager.loadMetadata(metadataFilePath, true)).length > 0) return;
145
+ const last = await node_fs_promises.default.readFile(lastBuildFile, "utf8").then((content) => JSON.parse(content).entries).catch(() => 0);
146
+ 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.`);
147
+ }
148
+ async function writeLastBuild(metadataFilePath, lastBuildFile) {
149
+ const entries = Object.keys(await require_manager.loadMetadata(metadataFilePath, true)).length;
150
+ await node_fs_promises.default.mkdir(node_path.default.dirname(lastBuildFile), { recursive: true });
151
+ await node_fs_promises.default.writeFile(lastBuildFile, JSON.stringify({ entries }));
152
+ }
135
153
  async function withWeglot(nextConfig = {}, weglotOptions) {
136
154
  const weglotConfig = require_config_factory.createWeglotConfig(weglotOptions);
137
155
  await require_config_factory.resolveProjectLanguages(weglotConfig);
138
- let metadataFilePath = require_manager.getMetadataPath(weglotConfig);
156
+ const distDir = node_path.default.resolve(nextConfig.distDir ?? ".next");
157
+ if (weglotConfig.environment !== "development") weglotConfig.metadataDir = node_path.default.join(distDir, "cache", "weglot", "metadata-build");
158
+ const metadataFilePath = require_manager.getMetadataPath(weglotConfig);
139
159
  const isDev = weglotConfig.environment === "development";
140
160
  require_logger.logger.debug(`Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`);
141
161
  if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) if (weglotConfig.dev.translationServerUrl) {
@@ -158,11 +178,6 @@ async function withWeglot(nextConfig = {}, weglotOptions) {
158
178
  } });
159
179
  }
160
180
  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
181
  const existingTurbopackConfig = getTurbopackConfig(nextConfig);
167
182
  let mergedRules = mergeTurbopackRules(existingTurbopackConfig.rules ?? {}, Object.values(loaders({
168
183
  weglotConfig,
@@ -184,18 +199,23 @@ async function withWeglot(nextConfig = {}, weglotOptions) {
184
199
  resolveAlias: mergedResolveAlias
185
200
  }
186
201
  } };
187
- const runAfterProductionCompile = async ({ distDir, projectDir }) => {
202
+ const runAfterProductionCompile = async ({ distDir: distDir$1, projectDir }) => {
188
203
  if (typeof nextConfig.compiler?.runAfterProductionCompile === "function") await nextConfig.compiler.runAfterProductionCompile({
189
- distDir,
204
+ distDir: distDir$1,
190
205
  projectDir
191
206
  });
192
207
  require_logger.logger.info("Running post-build translation generation...");
208
+ const lastBuildFile = node_path.default.join(distDir$1, "cache", "weglot", "last-build.json");
193
209
  try {
210
+ await require_manager.pruneMetadata(metadataFilePath);
211
+ await failOnLostMetadata(metadataFilePath, lastBuildFile);
194
212
  await require_build_translator.processBuildTranslations({
195
213
  config: weglotConfig,
196
- publicOutputPath: distDir,
214
+ publicOutputPath: distDir$1,
197
215
  metadataFilePath
198
216
  });
217
+ await require_next_traces.addDictionariesToTraces(distDir$1, weglotConfig.targetLocales);
218
+ await writeLastBuild(metadataFilePath, lastBuildFile);
199
219
  } catch (error) {
200
220
  require_logger.logger.error("Translation generation failed:", error instanceof Error ? error.message : error);
201
221
  throw error;
@@ -1 +1 @@
1
- {"version":3,"file":"next.d.cts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAmBY,uBAAA,GAA0B;iBA2LhB,UAAA,aACR,uCACG,0BACd,QAAQ"}
1
+ {"version":3,"file":"next.d.cts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAuBY,uBAAA,GAA0B;iBAiNhB,UAAA,aACR,uCACG,0BACd,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"next.d.mts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAmBY,uBAAA,GAA0B;iBA2LhB,UAAA,aACR,uCACG,0BACd,QAAQ"}
1
+ {"version":3,"file":"next.d.mts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAuBY,uBAAA,GAA0B;iBAiNhB,UAAA,aACR,uCACG,0BACd,QAAQ"}
@@ -2,18 +2,23 @@ import { __require } from "../_virtual/rolldown_runtime.mjs";
2
2
  import { logger } from "../utils/logger.mjs";
3
3
  import { createWeglotConfig, resolveProjectLanguages } from "../utils/config-factory.mjs";
4
4
  import { TranslationService } from "../translators/translation-service.mjs";
5
- import { cleanupMetadataForEnvironment, getMetadataPath } from "../metadata/manager.mjs";
5
+ import { getMetadataPath, loadMetadata, pruneMetadata } from "../metadata/manager.mjs";
6
6
  import { startOrGetTranslationServer } from "../translation-server/translation-server.mjs";
7
7
  import { processBuildTranslations } from "./build-translator.mjs";
8
+ import { addDictionariesToTraces } from "./next-traces.mjs";
8
9
  import { registerCleanupOnCurrentProcess } from "./cleanup.mjs";
9
10
  import { useI18nRegex } from "./transform/use-i18n.mjs";
11
+ import { packageVersion } from "../utils/package-version.mjs";
12
+ import fs from "node:fs/promises";
13
+ import path from "node:path";
10
14
 
11
15
  //#region src/plugin/next.ts
12
16
  function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
13
17
  const common = {
14
18
  sourceRoot: weglotConfig.sourceRoot,
15
19
  weglotDir: weglotConfig.weglotDir,
16
- sourceLocale: weglotConfig.sourceLocale
20
+ sourceLocale: weglotConfig.sourceLocale,
21
+ version: packageVersion()
17
22
  };
18
23
  const compilerLoader = {
19
24
  loader: "@weglot/translate-react/next-compiler-loader",
@@ -133,10 +138,22 @@ function mergeTurbopackRules(existingRules, newRules) {
133
138
  function isMainRunner() {
134
139
  return !process.env.NEXT_PRIVATE_BUILD_WORKER && !process.env.IS_NEXT_WORKER && !process.env.NEXT_PRIVATE_WORKER;
135
140
  }
141
+ async function failOnLostMetadata(metadataFilePath, lastBuildFile) {
142
+ if (Object.keys(await loadMetadata(metadataFilePath, true)).length > 0) return;
143
+ const last = await fs.readFile(lastBuildFile, "utf8").then((content) => JSON.parse(content).entries).catch(() => 0);
144
+ 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 ${path.relative(process.cwd(), path.dirname(path.dirname(lastBuildFile)))} and build again.`);
145
+ }
146
+ async function writeLastBuild(metadataFilePath, lastBuildFile) {
147
+ const entries = Object.keys(await loadMetadata(metadataFilePath, true)).length;
148
+ await fs.mkdir(path.dirname(lastBuildFile), { recursive: true });
149
+ await fs.writeFile(lastBuildFile, JSON.stringify({ entries }));
150
+ }
136
151
  async function withWeglot(nextConfig = {}, weglotOptions) {
137
152
  const weglotConfig = createWeglotConfig(weglotOptions);
138
153
  await resolveProjectLanguages(weglotConfig);
139
- let metadataFilePath = getMetadataPath(weglotConfig);
154
+ const distDir = path.resolve(nextConfig.distDir ?? ".next");
155
+ if (weglotConfig.environment !== "development") weglotConfig.metadataDir = path.join(distDir, "cache", "weglot", "metadata-build");
156
+ const metadataFilePath = getMetadataPath(weglotConfig);
140
157
  const isDev = weglotConfig.environment === "development";
141
158
  logger.debug(`Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`);
142
159
  if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) if (weglotConfig.dev.translationServerUrl) {
@@ -159,11 +176,6 @@ async function withWeglot(nextConfig = {}, weglotOptions) {
159
176
  } });
160
177
  }
161
178
  const translationServerUrl = process.env.WEGLOT_TRANSLATION_SERVER_URL;
162
- if (isMainRunner()) {
163
- const environment = weglotConfig.environment;
164
- cleanupMetadataForEnvironment(metadataFilePath, environment);
165
- registerCleanupOnCurrentProcess({ cleanup: () => cleanupMetadataForEnvironment(metadataFilePath, environment) });
166
- }
167
179
  const existingTurbopackConfig = getTurbopackConfig(nextConfig);
168
180
  let mergedRules = mergeTurbopackRules(existingTurbopackConfig.rules ?? {}, Object.values(loaders({
169
181
  weglotConfig,
@@ -185,18 +197,23 @@ async function withWeglot(nextConfig = {}, weglotOptions) {
185
197
  resolveAlias: mergedResolveAlias
186
198
  }
187
199
  } };
188
- const runAfterProductionCompile = async ({ distDir, projectDir }) => {
200
+ const runAfterProductionCompile = async ({ distDir: distDir$1, projectDir }) => {
189
201
  if (typeof nextConfig.compiler?.runAfterProductionCompile === "function") await nextConfig.compiler.runAfterProductionCompile({
190
- distDir,
202
+ distDir: distDir$1,
191
203
  projectDir
192
204
  });
193
205
  logger.info("Running post-build translation generation...");
206
+ const lastBuildFile = path.join(distDir$1, "cache", "weglot", "last-build.json");
194
207
  try {
208
+ await pruneMetadata(metadataFilePath);
209
+ await failOnLostMetadata(metadataFilePath, lastBuildFile);
195
210
  await processBuildTranslations({
196
211
  config: weglotConfig,
197
- publicOutputPath: distDir,
212
+ publicOutputPath: distDir$1,
198
213
  metadataFilePath
199
214
  });
215
+ await addDictionariesToTraces(distDir$1, weglotConfig.targetLocales);
216
+ await writeLastBuild(metadataFilePath, lastBuildFile);
200
217
  } catch (error) {
201
218
  logger.error("Translation generation failed:", error instanceof Error ? error.message : error);
202
219
  throw error;
@@ -1 +1 @@
1
- {"version":3,"file":"next.mjs","names":["turbopackConfig: Partial<NextConfig>","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 { startOrGetTranslationServer } from \"../translation-server/translation-server\";\nimport { cleanupMetadataForEnvironment, getMetadataPath } from \"../metadata/manager\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\nimport { TranslationService } from \"../translators\";\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 };\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\nexport async function withWeglot(\n nextConfig: NextConfig = {},\n weglotOptions: WeglotNextPluginOptions,\n): Promise<NextConfig> {\n const weglotConfig = createWeglotConfig(weglotOptions);\n await resolveProjectLanguages(weglotConfig);\n let 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 if (isMainRunner()) {\n const environment = weglotConfig.environment;\n cleanupMetadataForEnvironment(metadataFilePath, environment);\n\n registerCleanupOnCurrentProcess({\n cleanup: () => cleanupMetadataForEnvironment(metadataFilePath, environment),\n });\n }\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 try {\n await processBuildTranslations({\n config: weglotConfig,\n publicOutputPath: distDir,\n metadataFilePath,\n });\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":";;;;;;;;;;;AAuBA,SAAS,QAAQ,EACf,cACA,kBACA,wBAKsD;CACtD,MAAM,SAAS;EACb,YAA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BAAiB,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
+ {"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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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"}
@@ -299,7 +299,16 @@ function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ n
299
299
  function transformVoidElement(node, state) {
300
300
  translateAttributes(node, state);
301
301
  }
302
+ /** Digits, punctuation and placeholders alone come back from the API unchanged. */
303
+ function hasWords(children) {
304
+ return children.some((child) => {
305
+ if (child.type === "JSXText") return /\p{L}/u.test(child.value);
306
+ if (child.type === "JSXExpressionContainer") return child.expression.type === "StringLiteral" && /\p{L}/u.test(child.expression.value);
307
+ return child.type === "JSXElement" && !require_utils.isVoidElement(child) && !shouldSkipTranslationForElement(child) && hasWords(child.children);
308
+ });
309
+ }
302
310
  function getTranslationScope(node, state) {
311
+ if (!hasWords(node.children)) return null;
303
312
  if (hasMixedContent(node)) {
304
313
  const serialized = serializeJSXChildren(node.children, state);
305
314
  const text$1 = serialized.text.trim();