@verbaly/next 0.67.0 → 0.69.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 CHANGED
@@ -46,6 +46,9 @@ import { getRequestLocale, getVerbalyProps } from '@verbaly/next/server';
46
46
  import { VerbalyProvider } from '@verbaly/next/client';
47
47
  import { localeDirection } from 'verbaly';
48
48
 
49
+ // the language comes from the cookie and Accept-Language, so the shell renders per request
50
+ export const instant = false;
51
+
49
52
  export default async function RootLayout({ children }: { children: React.ReactNode }) {
50
53
  const locale = await getRequestLocale();
51
54
  const props = await getVerbalyProps();
@@ -59,6 +62,8 @@ export default async function RootLayout({ children }: { children: React.ReactNo
59
62
  }
60
63
  ```
61
64
 
65
+ `export const instant = false` is for `cacheComponents`, which `create-next-app` turns on: a layout that reads the request outside `<Suspense>` fails the build there, and a language chosen by cookie is exactly that. Without `cacheComponents`, leave the line out. To keep pages static instead, put the language in the URL (step 5).
66
+
62
67
  **3. Write text**: Server Components use `getT()`:
63
68
 
64
69
  ```tsx
@@ -70,6 +75,28 @@ export default async function Page() {
70
75
  }
71
76
  ```
72
77
 
78
+ Rich text in a Server Component is the same `<Trans>` as in React, from `@verbaly/next/server`: it renders in the request's language with no provider.
79
+
80
+ ```tsx
81
+ import { Trans } from '@verbaly/next/server';
82
+
83
+ <Trans>
84
+ Read the <a href="/terms">terms</a> before you go on
85
+ </Trans>;
86
+ ```
87
+
88
+ Outside a page, where there is no request to read (an OG image, a sitemap, an email), name the language. That call never reads the request, so the route stays static:
89
+
90
+ ```ts
91
+ // app/og/route.ts
92
+ import { getT } from '@verbaly/next/server';
93
+
94
+ export async function GET() {
95
+ const t = await getT({ locale: 'es' });
96
+ return Response.json({ title: t('home.lead') });
97
+ }
98
+ ```
99
+
73
100
  Client Components use the React bindings (re-exported from `@verbaly/next/client`):
74
101
 
75
102
  ```tsx
@@ -135,7 +162,11 @@ export default async function LocaleLayout({ children, params }) {
135
162
  Without `setRequestLocale`, Verbaly negotiates from the cookie and `Accept-Language`, and that read
136
163
  is what makes the route dynamic. With it, no header is read at all.
137
164
 
138
- That's it. `next dev` extracts your messages live (catalogs + `verbaly.d.ts` stay fresh) and says in the terminal what it would otherwise do quietly: a hand edit of a text your code owns, a key written with two texts, a translation that is now older than its source. `next build` blocks on missing translations once it has compiled, so `next typegen`, which loads the same config, never meets the gate. Dev and build show the same words: a text written in the code wins over the catalog in both.
165
+ **Keys are typed.** `getT()` and `useT()` check every key and its params against your catalog, and `getRequestLocale()` returns one of your locales, so `ogLocale[await getRequestLocale()]` needs no cast. The types live in `.verbaly/types.d.ts`, next to the generated modules and never committed; TypeScript skips a dot folder, so Verbaly adds that file to the `include` of your `tsconfig.json`, the way Next adds `.next/types`. On a fresh clone, `next typegen && tsc --noEmit` writes them before it checks them.
166
+
167
+ That's it. `next dev` extracts your messages live (catalogs and types stay fresh) and says in the terminal what it would otherwise do quietly: a hand edit of a text your code owns, a key written with two texts, a translation that is now older than its source. Each one is said once, and again if it goes away and comes back; a long list stays a few lines, and a catalog saved half-typed pauses live extraction with a one-line reason instead of stopping the server. `next build` blocks on missing translations once it has compiled, so `next typegen`, which loads the same config, never meets the gate, with Yarn PnP too. Both say once when they start if a file outside your `include` writes a `` t`…` ``, which no build translates: in a project without `src/`, add `components/` there. The report prints once, above Next's own failure line. Dev and build show the same words: a text written in the code wins over the catalog in both.
168
+
169
+ The gate rides on `compiler.runAfterProductionCompile`, and `withVerbaly` keeps any hook of your own there (yours runs first). A wrapper applied **outside** `withVerbaly` that replaces that hook instead of calling the one it got would switch the gate off, so keep `withVerbaly` outermost or compose the hook.
139
170
 
140
171
  ## 📖 Options
141
172
 
package/dist/index.cjs CHANGED
@@ -1,25 +1,38 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let node_fs = require("node:fs");
3
+ let node_module = require("node:module");
3
4
  let node_path = require("node:path");
4
5
  //#region src/report.ts
5
- const said = /* @__PURE__ */ new Set();
6
- function once(id, line) {
7
- if (said.has(id)) return;
8
- said.add(id);
9
- console.warn(`[verbaly] ${line}`);
10
- }
11
- function reportDev(compiler, cfg, registry, replaced, previous, outdated) {
12
- const messages = registry.messages();
13
- const rel = (file) => (0, node_path.relative)(cfg.root, file).replaceAll("\\", "/");
14
- for (const key of replaced) {
15
- const msg = messages.get(key);
16
- if (!msg || previous && previous.get(key) !== msg.message) continue;
17
- once(`replaced:${key}`, previous ? `${cfg.sourceLocale}.json: your edit of "${key}" was replaced, its text lives in ${rel(msg.file)}: change it there` : `${cfg.sourceLocale}.json: "${key}" took the text written in ${rel(msg.file)}, the code owns it`);
6
+ const reporters = /* @__PURE__ */ new Map();
7
+ const brokenState = /* @__PURE__ */ new Set();
8
+ function reportDev(compiler, cfg, result, previous) {
9
+ let reporter = reporters.get(cfg.root);
10
+ if (!reporter) {
11
+ reporter = compiler.createDevReporter(cfg.root);
12
+ reporters.set(cfg.root, reporter);
13
+ }
14
+ const replaced = [];
15
+ const code = [];
16
+ for (const finding of result.findings) {
17
+ if (finding.kind === "collision" || finding.kind === "renamed") code.push(finding);
18
+ if (finding.kind !== "replaced") continue;
19
+ if (previous && previous.get(finding.key) !== finding.site.message) continue;
20
+ replaced.push({
21
+ ...finding,
22
+ edited: previous !== void 0
23
+ });
18
24
  }
19
- for (const entry of compiler.collisionEntries(registry)) once(`collision:${entry.key}`, compiler.formatCollision(entry, cfg.root).trim());
20
- for (const { name, file } of registry.missed()) once(`missed:${file}:${name}`, `${rel(file)}: ${name}\`…\` is never extracted, so it stays in the source language: name it t`);
21
- for (const { locale, key } of outdated) once(`outdated:${locale}:${key}`, `${locale}: "${key}" was translated from an older source text, update it or approve it`);
22
- return new Map([...messages].map(([key, msg]) => [key, msg.message]));
25
+ reporter.report("replaced", replaced);
26
+ reporter.report("code", code);
27
+ const outdated = result.state ? compiler.outdatedTranslations(cfg, result.catalogs, result.state.fingerprints) : [];
28
+ reporter.report("outdated", outdated.map((entry) => ({
29
+ kind: "outdated",
30
+ ...entry
31
+ })));
32
+ if (result.stateProblem && !brokenState.has(cfg.root)) console.warn(`[verbaly] ${result.stateProblem}, so drafts are not tracked`);
33
+ if (result.stateProblem) brokenState.add(cfg.root);
34
+ else brokenState.delete(cfg.root);
35
+ return new Map([...result.registry.messages()].map(([key, msg]) => [key, msg.message]));
23
36
  }
24
37
  //#endregion
25
38
  //#region src/codegen.ts
@@ -34,21 +47,14 @@ function writeIfChanged(file, content) {
34
47
  (0, node_fs.writeFileSync)(file, content);
35
48
  return true;
36
49
  }
37
- let stateWarned = false;
38
- function syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, previous) {
39
- const { added, replaced } = compiler.syncCatalogs(cfg, catalogs, registry);
40
- for (const locale of Object.keys(added)) compiler.writeCatalog(cfg, locale, catalogs[locale] ?? {});
41
- compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
42
- writeGeneratedModules(compiler, cfg, catalogs, requestOptions);
43
- let outdated = [];
44
- try {
45
- const state = compiler.updateState(cfg, catalogs);
46
- outdated = compiler.outdatedTranslations(cfg, catalogs, state.fingerprints);
47
- } catch (error) {
48
- if (!stateWarned) console.warn(`${compiler.formatCliError(error)}, so drafts are not tracked`);
49
- stateWarned = true;
50
- }
51
- return reportDev(compiler, cfg, registry, replaced, previous, outdated);
50
+ async function syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, previous) {
51
+ const result = await compiler.syncProject(cfg, {
52
+ registry,
53
+ catalogs,
54
+ write: "changed"
55
+ });
56
+ writeGeneratedModules(compiler, cfg, result.catalogs, requestOptions);
57
+ return reportDev(compiler, cfg, result, previous);
52
58
  }
53
59
  function writeGeneratedModules(compiler, cfg, catalogs, requestOptions = {}) {
54
60
  const dir = generatedDir(cfg.root);
@@ -90,9 +96,10 @@ function startWatcher(compiler, cfg, requestOptions, startTexts) {
90
96
  }
91
97
  running = true;
92
98
  try {
93
- texts = syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions, texts);
99
+ texts = await syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions, texts);
94
100
  } catch (error) {
95
- console.warn("[verbaly] live extraction failed:", error);
101
+ const reason = compiler.formatCliError(error).replace(/^\[verbaly\] /, "");
102
+ console.warn(`[verbaly] live extraction paused: ${reason}`);
96
103
  } finally {
97
104
  running = false;
98
105
  if (queued) {
@@ -144,13 +151,15 @@ function withVerbaly(nextConfig, options = {}) {
144
151
  const cfg = await compiler.loadConfig(root, verbalyConfig);
145
152
  const catalogs = compiler.loadCatalogs(cfg);
146
153
  const registry = await compiler.extractProject(cfg);
154
+ await compiler.reportOutsideInclude(cfg);
147
155
  let gate;
148
156
  if (phase === DEV_PHASE) {
149
- const texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);
157
+ const texts = await syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);
150
158
  startWatcher(compiler, cfg, requestOptions, texts);
151
159
  } else {
152
160
  compiler.syncCatalogs(cfg, catalogs, registry);
153
161
  writeGeneratedModules(compiler, cfg, catalogs, requestOptions);
162
+ compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
154
163
  if (phase === BUILD_PHASE) {
155
164
  const runGate = () => compiler.runBuildGate(cfg, registry, failOnMissing);
156
165
  if (hasAfterCompileHook(cfg.root)) gate = runGate;
@@ -165,11 +174,19 @@ function withVerbaly(nextConfig, options = {}) {
165
174
  return composeConfig(base, cfg.root, scope, gate);
166
175
  };
167
176
  }
177
+ const HOOK_FILE = "next/dist/build/after-production-compile.js";
168
178
  function hasAfterCompileHook(root) {
169
179
  for (let dir = root;; dir = (0, node_path.dirname)(dir)) {
170
180
  const next = (0, node_path.join)(dir, "node_modules", "next");
171
- if ((0, node_fs.existsSync)((0, node_path.join)(next, "package.json"))) return (0, node_fs.existsSync)((0, node_path.join)(next, "dist", "build", "after-production-compile.js"));
172
- if ((0, node_path.dirname)(dir) === dir) return false;
181
+ if ((0, node_fs.existsSync)((0, node_path.join)(next, "package.json"))) return (0, node_fs.existsSync)((0, node_path.join)(dir, "node_modules", HOOK_FILE));
182
+ if ((0, node_path.dirname)(dir) === dir) break;
183
+ }
184
+ if (!process.versions.pnp) return false;
185
+ try {
186
+ (0, node_module.createRequire)((0, node_path.join)(root, "package.json")).resolve(HOOK_FILE);
187
+ return true;
188
+ } catch {
189
+ return false;
173
190
  }
174
191
  }
175
192
  function composeConfig(base, root, scope, gate) {
@@ -192,7 +209,12 @@ function composeConfig(base, root, scope, gate) {
192
209
  ...userCompiler,
193
210
  async runAfterProductionCompile(metadata) {
194
211
  await userCompiler?.runAfterProductionCompile?.(metadata);
195
- gate();
212
+ try {
213
+ gate();
214
+ } catch (error) {
215
+ console.error(error.message);
216
+ throw new Error("[verbaly] build blocked, the reason is printed above");
217
+ }
196
218
  }
197
219
  } },
198
220
  turbopack: {
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["relative","join","readFileSync","readdirSync","relative","basename","dirname","join","existsSync"],"sources":["../src/report.ts","../src/codegen.ts","../src/watch.ts","../src/index.ts"],"sourcesContent":["import type { ResolvedConfig } from '@verbaly/compiler';\nimport { relative } from 'node:path';\nimport type { Compiler, Registry } from './codegen';\n\n// a dev server re-runs per keystroke: keyed on what it is about, never on the text being typed\nconst said = new Set<string>();\n\nfunction once(id: string, line: string): void {\n if (said.has(id)) return;\n said.add(id);\n console.warn(`[verbaly] ${line}`);\n}\n\n// the code texts of the last run tell an edit in the code from an edit in the catalog\nexport type CodeTexts = Map<string, string>;\n\nexport function reportDev(\n compiler: Compiler,\n cfg: ResolvedConfig,\n registry: Registry,\n replaced: string[],\n previous: CodeTexts | undefined,\n outdated: { locale: string; key: string }[],\n): CodeTexts {\n const messages = registry.messages();\n const rel = (file: string): string => relative(cfg.root, file).replaceAll('\\\\', '/');\n for (const key of replaced) {\n const msg = messages.get(key);\n // the code changed this text since the last run, which is how a text it owns is edited\n if (!msg || (previous && previous.get(key) !== msg.message)) continue;\n once(\n `replaced:${key}`,\n previous\n ? `${cfg.sourceLocale}.json: your edit of \"${key}\" was replaced, its text lives in ${rel(msg.file)}: change it there`\n : `${cfg.sourceLocale}.json: \"${key}\" took the text written in ${rel(msg.file)}, the code owns it`,\n );\n }\n for (const entry of compiler.collisionEntries(registry)) {\n once(`collision:${entry.key}`, compiler.formatCollision(entry, cfg.root).trim());\n }\n for (const { name, file } of registry.missed()) {\n once(\n `missed:${file}:${name}`,\n `${rel(file)}: ${name}\\`…\\` is never extracted, so it stays in the source language: name it t`,\n );\n }\n for (const { locale, key } of outdated) {\n once(\n `outdated:${locale}:${key}`,\n `${locale}: \"${key}\" was translated from an older source text, update it or approve it`,\n );\n }\n return new Map([...messages].map(([key, msg]) => [key, msg.message]));\n}\n\n// test hook: the set is module state, and each test starts from a server that said nothing\nexport function resetReported(): void {\n said.clear();\n}\n","import type { Catalogs, ResolvedConfig } from '@verbaly/compiler';\nimport { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { reportDev, type CodeTexts } from './report';\n\nexport type Compiler = typeof import('@verbaly/compiler');\nexport type Registry = Awaited<ReturnType<Compiler['extractProject']>>;\n\nexport interface RequestOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\nexport const GENERATED_DIR = '.verbaly';\n\nexport function generatedDir(root: string): string {\n return join(root, GENERATED_DIR);\n}\n\n// content compare: identical rewrites must not retrigger the bundler\nfunction writeIfChanged(file: string, content: string): boolean {\n try {\n if (readFileSync(file, 'utf8') === content) return false;\n } catch {\n // new file\n }\n writeFileSync(file, content);\n return true;\n}\n\nlet stateWarned = false;\n\n// dev pipeline shared by withVerbaly and the watcher: catalogs, dts, runtime modules, state\nexport function syncAndWrite(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: Registry,\n requestOptions: RequestOptions,\n previous?: CodeTexts,\n): CodeTexts {\n const { added, replaced } = compiler.syncCatalogs(cfg, catalogs, registry);\n for (const locale of Object.keys(added)) {\n compiler.writeCatalog(cfg, locale, catalogs[locale] ?? {});\n }\n compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n let outdated: { locale: string; key: string }[] = [];\n try {\n // a pruned key takes its draft along, and an edited source text marks its translations\n const state = compiler.updateState(cfg, catalogs);\n outdated = compiler.outdatedTranslations(cfg, catalogs, state.fingerprints);\n } catch (error) {\n // a broken sidecar must not stop next dev: say it once and keep serving\n if (!stateWarned) console.warn(`${compiler.formatCliError(error)}, so drafts are not tracked`);\n stateWarned = true;\n }\n return reportDev(compiler, cfg, registry, replaced, previous, outdated);\n}\n\n// real-file replacement for virtual:verbaly: Turbopack has no virtual modules\nexport function writeGeneratedModules(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n requestOptions: RequestOptions = {},\n): boolean {\n const dir = generatedDir(cfg.root);\n const localeDir = join(dir, 'locale');\n mkdirSync(localeDir, { recursive: true });\n\n let changed = writeIfChanged(join(dir, '.gitignore'), '*\\n');\n\n // these files are the client module here, so bundle.exclude has to be applied on this path too\n const client = compiler.clientCatalogs(cfg, catalogs);\n const runtime = compiler.generateRuntimeModule(cfg, {\n localeImport: (locale) => `./locale/${locale}.js`,\n extraExports: `export const requestOptions = ${JSON.stringify(requestOptions)};\\n`,\n icu: cfg.icu ?? compiler.needsIcu(client),\n relative: cfg.relative ?? compiler.needsRelative(client),\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n changed = writeIfChanged(join(dir, 'index.js'), runtime) || changed;\n\n const expected = new Set(cfg.locales.map((locale) => `${locale}.js`));\n for (const locale of cfg.locales) {\n changed =\n writeIfChanged(\n join(localeDir, `${locale}.js`),\n compiler.generateLocaleModule(client[locale] ?? {}),\n ) || changed;\n }\n for (const file of readdirSync(localeDir)) {\n if (!expected.has(file)) {\n rmSync(join(localeDir, file));\n changed = true;\n }\n }\n return changed;\n}\n","import type { ResolvedConfig } from '@verbaly/compiler';\nimport { basename, relative } from 'node:path';\nimport { GENERATED_DIR, syncAndWrite, type Compiler, type RequestOptions } from './codegen';\nimport type { CodeTexts } from './report';\n\n// one watcher per project root: next.config can be evaluated more than once\nconst active = new Map<string, () => void>();\n\nexport function startWatcher(\n compiler: Compiler,\n cfg: ResolvedConfig,\n requestOptions: RequestOptions,\n startTexts?: CodeTexts,\n): () => void {\n const existing = active.get(cfg.root);\n if (existing) return existing;\n\n const catalogDir = relative(cfg.root, cfg.dir).replaceAll('\\\\', '/');\n let timer: ReturnType<typeof setTimeout> | undefined;\n let running = false;\n let queued = false;\n let texts = startTexts;\n\n async function refresh(): Promise<void> {\n if (running) {\n queued = true;\n return;\n }\n running = true;\n try {\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, texts);\n } catch (error) {\n console.warn('[verbaly] live extraction failed:', error);\n } finally {\n running = false;\n if (queued) {\n queued = false;\n schedule();\n }\n }\n }\n\n function schedule(): void {\n clearTimeout(timer);\n timer = setTimeout(() => void refresh(), 150);\n }\n\n const keep = catalogDir.split('/')[0];\n const close = compiler.watchTree(cfg.root, { keep, persistent: false }, (filename) => {\n if (!filename) return;\n const file = filename.replaceAll('\\\\', '/');\n if (\n file.startsWith(`${GENERATED_DIR}/`) ||\n file.startsWith('.next/') ||\n file.includes('node_modules/') ||\n file.endsWith('.d.ts')\n ) {\n return;\n }\n // a dotfile there is the state sidecar this pipeline writes: it changes no message\n const isCatalog =\n file.startsWith(`${catalogDir}/`) && file.endsWith('.json') && !basename(file).startsWith('.');\n if (isCatalog || compiler.SOURCE_FILE_RE.test(file)) schedule();\n });\n\n const dispose = (): void => {\n clearTimeout(timer);\n close();\n active.delete(cfg.root);\n };\n active.set(cfg.root, dispose);\n return dispose;\n}\n\n// test hook\nexport function stopWatcher(root: string): void {\n active.get(root)?.();\n}\n","import type { PluginOptions } from '@verbaly/compiler';\nimport { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport {\n GENERATED_DIR,\n generatedDir,\n syncAndWrite,\n writeGeneratedModules,\n type Compiler,\n type RequestOptions,\n} from './codegen';\nimport type { LoaderOptions } from './loader';\nimport { startWatcher } from './watch';\n\nexport type { VerbalyConfig } from '@verbaly/compiler';\nexport type { RequestOptions } from './codegen';\n\nexport interface NextVerbalyOptions extends PluginOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\n// structural NextConfig subset (compat asserted in tests): no index signatures, Next has none\nexport interface WebpackConfigLike {\n resolve?: { alias?: Record<string, unknown>; [key: string]: unknown };\n module?: { rules?: unknown[]; [key: string]: unknown };\n plugins?: unknown[];\n [key: string]: unknown;\n}\n\ninterface WebpackContextLike {\n webpack?: {\n NormalModuleReplacementPlugin: new (test: RegExp, resource: string) => unknown;\n };\n}\n\n// context param is `never` so Next's real webpack fn (specific context type) stays assignable\nexport type WebpackFn = (config: WebpackConfigLike, context: never) => unknown;\n\nexport interface TurbopackLike {\n resolveAlias?: Record<string, unknown>;\n rules?: Record<string, unknown>;\n}\n\n// metadata is `never` for the same reason as the webpack context: Next's own type stays assignable\nexport interface CompilerLike {\n runAfterProductionCompile?: (metadata: never) => Promise<void>;\n}\n\nexport interface NextConfigLike {\n webpack?: WebpackFn | null;\n turbopack?: TurbopackLike;\n compiler?: CompilerLike;\n}\n\n// constraint is object, not NextConfigLike: an all-optional target rejects by weak-type\nexport type NextConfigInput<C extends object> =\n C | ((phase: string, context: { defaultConfig?: unknown }) => C | Promise<C>);\n\n// next/constants values: literal to keep this module import-free of next\nconst DEV_PHASE = 'phase-development-server';\nconst BUILD_PHASE = 'phase-production-build';\n// next experimental-analyze compiles the app as well, so it needs the generated modules on disk\nconst ANALYZE_PHASE = 'phase-analyze';\n\nconst LOADER = '@verbaly/next/loader';\n// matched via condition.path: a bare extension glob also hits Next's App Router entry\nconst SOURCE_PATH_RE = /\\.[cm]?[jt]sx?$/;\n\nexport function withVerbaly<C extends object>(\n nextConfig?: NextConfigInput<C>,\n options: NextVerbalyOptions = {},\n): (phase: string, context?: { defaultConfig?: unknown }) => Promise<C> {\n const { failOnMissing, cookie, fallback, ...verbalyConfig } = options;\n const requestOptions: RequestOptions = { cookie, fallback };\n\n return async (phase, context = {}) => {\n const base: C =\n typeof nextConfig === 'function'\n ? await nextConfig(phase, context)\n : (nextConfig ?? ({} as C));\n const root = verbalyConfig.root ?? process.cwd();\n\n // production server / export: everything is bundled, so no FS work, config only\n if (phase !== DEV_PHASE && phase !== BUILD_PHASE && phase !== ANALYZE_PHASE) {\n return composeConfig(base, root);\n }\n\n // dynamic: the compiler is ESM-only and this entry is also consumed as CJS\n const compiler: Compiler = await import('@verbaly/compiler');\n\n const cfg = await compiler.loadConfig(root, verbalyConfig);\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n let gate: (() => void) | undefined;\n\n if (phase === DEV_PHASE) {\n const texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);\n startWatcher(compiler, cfg, requestOptions, texts);\n } else {\n // the code's text ships, as it does in dev: a catalog edit of a text it owns never wins\n compiler.syncCatalogs(cfg, catalogs, registry);\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n if (phase === BUILD_PHASE) {\n const runGate = (): void => compiler.runBuildGate(cfg, registry, failOnMissing);\n // typegen loads this config in the build phase too, and only a real build runs the hook\n if (hasAfterCompileHook(cfg.root)) gate = runGate;\n else runGate();\n }\n }\n\n // the loader rewrites exactly what extract reads: a file outside include keeps its t`…`\n const scope: LoaderOptions = { root: cfg.root, include: cfg.include, exclude: cfg.exclude };\n return composeConfig(base, cfg.root, scope, gate);\n };\n}\n\n// next build calls compiler.runAfterProductionCompile since 15.4; NODE_PATH may name another next\nfunction hasAfterCompileHook(root: string): boolean {\n for (let dir = root; ; dir = dirname(dir)) {\n const next = join(dir, 'node_modules', 'next');\n if (existsSync(join(next, 'package.json'))) {\n return existsSync(join(next, 'dist', 'build', 'after-production-compile.js'));\n }\n if (dirname(dir) === dir) return false;\n }\n}\n\nfunction composeConfig<C extends object>(\n base: C,\n root: string,\n scope?: LoaderOptions,\n gate?: () => void,\n): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack, compiler: userCompiler } = base as NextConfigLike;\n const loader = scope ? { loader: LOADER, options: scope } : LOADER;\n\n const rules: Record<string, unknown> = { ...turbopack?.rules };\n const verbalyRule = {\n condition: { all: [{ not: 'foreign' }, { path: SOURCE_PATH_RE }] },\n loaders: [loader],\n };\n const existing = rules['*'];\n rules['*'] = existing\n ? [...(Array.isArray(existing) ? existing : [existing]), verbalyRule]\n : verbalyRule;\n\n return {\n ...base,\n ...(gate && {\n compiler: {\n ...userCompiler,\n // after the compile, so next typegen, which loads this config too, never meets the gate\n async runAfterProductionCompile(metadata: never) {\n await userCompiler?.runAfterProductionCompile?.(metadata);\n gate();\n },\n },\n }),\n turbopack: {\n ...turbopack,\n resolveAlias: {\n ...turbopack?.resolveAlias,\n 'virtual:verbaly': `./${GENERATED_DIR}/index.js`,\n },\n rules,\n },\n webpack(config: WebpackConfigLike, context: unknown) {\n // webpack 5 parses 'virtual:' as a URI scheme, so resolve.alias never fires\n const { webpack: webpackInstance } = (context ?? {}) as WebpackContextLike;\n if (webpackInstance?.NormalModuleReplacementPlugin) {\n config.plugins ??= [];\n config.plugins.push(\n new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule),\n );\n }\n config.resolve ??= {};\n config.resolve.alias ??= {};\n (config.resolve.alias as Record<string, unknown>)['virtual:verbaly'] = runtimeModule;\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push({\n test: SOURCE_PATH_RE,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [typeof loader === 'string' ? { loader } : loader],\n });\n return userWebpack ? userWebpack(config, context as never) : config;\n },\n } as C;\n}\n"],"mappings":";;;;AAKA,MAAM,uBAAO,IAAI,IAAY;AAE7B,SAAS,KAAK,IAAY,MAAoB;CAC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irname","join","existsSync"],"sources":["../src/report.ts","../src/codegen.ts","../src/watch.ts","../src/index.ts"],"sourcesContent":["import type { DevReporter, Finding, ResolvedConfig, SyncProjectResult } from '@verbaly/compiler';\nimport type { Compiler } from './codegen';\n\n// one per project: next.config can be evaluated more than once, and the watcher outlives it\nconst reporters = new Map<string, DevReporter>();\nconst brokenState = new Set<string>();\n\n// the code texts of the last run tell an edit in the code from an edit in the catalog\nexport type CodeTexts = Map<string, string>;\n\nexport function reportDev(\n compiler: Compiler,\n cfg: ResolvedConfig,\n result: SyncProjectResult,\n previous: CodeTexts | undefined,\n): CodeTexts {\n let reporter = reporters.get(cfg.root);\n if (!reporter) {\n reporter = compiler.createDevReporter(cfg.root);\n reporters.set(cfg.root, reporter);\n }\n const replaced: Finding[] = [];\n const code: Finding[] = [];\n for (const finding of result.findings) {\n if (finding.kind === 'collision' || finding.kind === 'renamed') code.push(finding);\n if (finding.kind !== 'replaced') continue;\n // the code changed this text since the last run, which is how a text it owns is edited\n if (previous && previous.get(finding.key) !== finding.site.message) continue;\n replaced.push({ ...finding, edited: previous !== undefined });\n }\n reporter.report('replaced', replaced);\n reporter.report('code', code);\n const outdated = result.state\n ? compiler.outdatedTranslations(cfg, result.catalogs, result.state.fingerprints)\n : [];\n reporter.report(\n 'outdated',\n outdated.map((entry): Finding => ({ kind: 'outdated', ...entry })),\n );\n\n // a broken sidecar must not stop next dev: said once, and again if it breaks after a fix\n if (result.stateProblem && !brokenState.has(cfg.root)) {\n console.warn(`[verbaly] ${result.stateProblem}, so drafts are not tracked`);\n }\n if (result.stateProblem) brokenState.add(cfg.root);\n else brokenState.delete(cfg.root);\n\n return new Map([...result.registry.messages()].map(([key, msg]) => [key, msg.message]));\n}\n\n// test hook: each test starts from a server that said nothing\nexport function resetReported(): void {\n reporters.clear();\n brokenState.clear();\n}\n","import type { Catalogs, ResolvedConfig } from '@verbaly/compiler';\nimport { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { reportDev, type CodeTexts } from './report';\n\nexport type Compiler = typeof import('@verbaly/compiler');\nexport type Registry = Awaited<ReturnType<Compiler['extractProject']>>;\n\nexport interface RequestOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\nexport const GENERATED_DIR = '.verbaly';\n\nexport function generatedDir(root: string): string {\n return join(root, GENERATED_DIR);\n}\n\n// content compare: identical rewrites must not retrigger the bundler\nfunction writeIfChanged(file: string, content: string): boolean {\n try {\n if (readFileSync(file, 'utf8') === content) return false;\n } catch {\n // new file\n }\n writeFileSync(file, content);\n return true;\n}\n\n// dev pipeline shared by withVerbaly and the watcher: the compiler's sync, then the runtime modules\nexport async function syncAndWrite(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: Registry,\n requestOptions: RequestOptions,\n previous?: CodeTexts,\n): Promise<CodeTexts> {\n // 'changed': a catalog nothing happened to keeps the formatting its author gave it\n const result = await compiler.syncProject(cfg, { registry, catalogs, write: 'changed' });\n writeGeneratedModules(compiler, cfg, result.catalogs, requestOptions);\n return reportDev(compiler, cfg, result, previous);\n}\n\n// real-file replacement for virtual:verbaly: Turbopack has no virtual modules\nexport function writeGeneratedModules(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n requestOptions: RequestOptions = {},\n): boolean {\n const dir = generatedDir(cfg.root);\n const localeDir = join(dir, 'locale');\n mkdirSync(localeDir, { recursive: true });\n\n let changed = writeIfChanged(join(dir, '.gitignore'), '*\\n');\n\n // these files are the client module here, so bundle.exclude has to be applied on this path too\n const client = compiler.clientCatalogs(cfg, catalogs);\n const runtime = compiler.generateRuntimeModule(cfg, {\n localeImport: (locale) => `./locale/${locale}.js`,\n extraExports: `export const requestOptions = ${JSON.stringify(requestOptions)};\\n`,\n icu: cfg.icu ?? compiler.needsIcu(client),\n relative: cfg.relative ?? compiler.needsRelative(client),\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n changed = writeIfChanged(join(dir, 'index.js'), runtime) || changed;\n\n const expected = new Set(cfg.locales.map((locale) => `${locale}.js`));\n for (const locale of cfg.locales) {\n changed =\n writeIfChanged(\n join(localeDir, `${locale}.js`),\n compiler.generateLocaleModule(client[locale] ?? {}),\n ) || changed;\n }\n for (const file of readdirSync(localeDir)) {\n if (!expected.has(file)) {\n rmSync(join(localeDir, file));\n changed = true;\n }\n }\n return changed;\n}\n","import type { ResolvedConfig } from '@verbaly/compiler';\nimport { basename, relative } from 'node:path';\nimport { GENERATED_DIR, syncAndWrite, type Compiler, type RequestOptions } from './codegen';\nimport type { CodeTexts } from './report';\n\n// one watcher per project root: next.config can be evaluated more than once\nconst active = new Map<string, () => void>();\n\nexport function startWatcher(\n compiler: Compiler,\n cfg: ResolvedConfig,\n requestOptions: RequestOptions,\n startTexts?: CodeTexts,\n): () => void {\n const existing = active.get(cfg.root);\n if (existing) return existing;\n\n const catalogDir = relative(cfg.root, cfg.dir).replaceAll('\\\\', '/');\n let timer: ReturnType<typeof setTimeout> | undefined;\n let running = false;\n let queued = false;\n let texts = startTexts;\n\n async function refresh(): Promise<void> {\n if (running) {\n queued = true;\n return;\n }\n running = true;\n try {\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n texts = await syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, texts);\n } catch (error) {\n // a catalog saved half-typed is broken JSON for a moment: one line, never a stack trace\n const reason = compiler.formatCliError(error).replace(/^\\[verbaly\\] /, '');\n console.warn(`[verbaly] live extraction paused: ${reason}`);\n } finally {\n running = false;\n if (queued) {\n queued = false;\n schedule();\n }\n }\n }\n\n function schedule(): void {\n clearTimeout(timer);\n timer = setTimeout(() => void refresh(), 150);\n }\n\n const keep = catalogDir.split('/')[0];\n const close = compiler.watchTree(cfg.root, { keep, persistent: false }, (filename) => {\n if (!filename) return;\n const file = filename.replaceAll('\\\\', '/');\n if (\n file.startsWith(`${GENERATED_DIR}/`) ||\n file.startsWith('.next/') ||\n file.includes('node_modules/') ||\n file.endsWith('.d.ts')\n ) {\n return;\n }\n // a dotfile there is the state sidecar this pipeline writes: it changes no message\n const isCatalog =\n file.startsWith(`${catalogDir}/`) && file.endsWith('.json') && !basename(file).startsWith('.');\n if (isCatalog || compiler.SOURCE_FILE_RE.test(file)) schedule();\n });\n\n const dispose = (): void => {\n clearTimeout(timer);\n close();\n active.delete(cfg.root);\n };\n active.set(cfg.root, dispose);\n return dispose;\n}\n\n// test hook\nexport function stopWatcher(root: string): void {\n active.get(root)?.();\n}\n","import type { PluginOptions } from '@verbaly/compiler';\nimport { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport {\n GENERATED_DIR,\n generatedDir,\n syncAndWrite,\n writeGeneratedModules,\n type Compiler,\n type RequestOptions,\n} from './codegen';\nimport type { LoaderOptions } from './loader';\nimport { startWatcher } from './watch';\n\nexport type { VerbalyConfig } from '@verbaly/compiler';\nexport type { RequestOptions } from './codegen';\n\nexport interface NextVerbalyOptions extends PluginOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\n// structural NextConfig subset (compat asserted in tests): no index signatures, Next has none\nexport interface WebpackConfigLike {\n resolve?: { alias?: Record<string, unknown>; [key: string]: unknown };\n module?: { rules?: unknown[]; [key: string]: unknown };\n plugins?: unknown[];\n [key: string]: unknown;\n}\n\ninterface WebpackContextLike {\n webpack?: {\n NormalModuleReplacementPlugin: new (test: RegExp, resource: string) => unknown;\n };\n}\n\n// context param is `never` so Next's real webpack fn (specific context type) stays assignable\nexport type WebpackFn = (config: WebpackConfigLike, context: never) => unknown;\n\nexport interface TurbopackLike {\n resolveAlias?: Record<string, unknown>;\n rules?: Record<string, unknown>;\n}\n\n// metadata is `never` for the same reason as the webpack context: Next's own type stays assignable\nexport interface CompilerLike {\n runAfterProductionCompile?: (metadata: never) => Promise<void>;\n}\n\nexport interface NextConfigLike {\n webpack?: WebpackFn | null;\n turbopack?: TurbopackLike;\n compiler?: CompilerLike;\n}\n\n// constraint is object, not NextConfigLike: an all-optional target rejects by weak-type\nexport type NextConfigInput<C extends object> =\n C | ((phase: string, context: { defaultConfig?: unknown }) => C | Promise<C>);\n\n// next/constants values: literal to keep this module import-free of next\nconst DEV_PHASE = 'phase-development-server';\nconst BUILD_PHASE = 'phase-production-build';\n// next experimental-analyze compiles the app as well, so it needs the generated modules on disk\nconst ANALYZE_PHASE = 'phase-analyze';\n\nconst LOADER = '@verbaly/next/loader';\n// matched via condition.path: a bare extension glob also hits Next's App Router entry\nconst SOURCE_PATH_RE = /\\.[cm]?[jt]sx?$/;\n\nexport function withVerbaly<C extends object>(\n nextConfig?: NextConfigInput<C>,\n options: NextVerbalyOptions = {},\n): (phase: string, context?: { defaultConfig?: unknown }) => Promise<C> {\n const { failOnMissing, cookie, fallback, ...verbalyConfig } = options;\n const requestOptions: RequestOptions = { cookie, fallback };\n\n return async (phase, context = {}) => {\n const base: C =\n typeof nextConfig === 'function'\n ? await nextConfig(phase, context)\n : (nextConfig ?? ({} as C));\n const root = verbalyConfig.root ?? process.cwd();\n\n // production server / export: everything is bundled, so no FS work, config only\n if (phase !== DEV_PHASE && phase !== BUILD_PHASE && phase !== ANALYZE_PHASE) {\n return composeConfig(base, root);\n }\n\n // dynamic: the compiler is ESM-only and this entry is also consumed as CJS\n const compiler: Compiler = await import('@verbaly/compiler');\n\n const cfg = await compiler.loadConfig(root, verbalyConfig);\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n // once per phase, from the config: a loader result can come from Turbopack's cache\n await compiler.reportOutsideInclude(cfg);\n let gate: (() => void) | undefined;\n\n if (phase === DEV_PHASE) {\n const texts = await syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);\n startWatcher(compiler, cfg, requestOptions, texts);\n } else {\n // the code's text ships, as it does in dev: a catalog edit of a text it owns never wins\n compiler.syncCatalogs(cfg, catalogs, registry);\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n // next build and next typegen check types, and .verbaly/ is never committed\n compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});\n if (phase === BUILD_PHASE) {\n const runGate = (): void => compiler.runBuildGate(cfg, registry, failOnMissing);\n // typegen loads this config in the build phase too, and only a real build runs the hook\n if (hasAfterCompileHook(cfg.root)) gate = runGate;\n else runGate();\n }\n }\n\n // the loader rewrites exactly what extract reads: a file outside include keeps its t`…`\n const scope: LoaderOptions = { root: cfg.root, include: cfg.include, exclude: cfg.exclude };\n return composeConfig(base, cfg.root, scope, gate);\n };\n}\n\nconst HOOK_FILE = 'next/dist/build/after-production-compile.js';\n\n// next build calls compiler.runAfterProductionCompile since 15.4; NODE_PATH may name another next\nfunction hasAfterCompileHook(root: string): boolean {\n for (let dir = root; ; dir = dirname(dir)) {\n const next = join(dir, 'node_modules', 'next');\n if (existsSync(join(next, 'package.json')))\n return existsSync(join(dir, 'node_modules', HOOK_FILE));\n if (dirname(dir) === dir) break;\n }\n // Yarn PnP has no node_modules, and its resolver finds the project's own next, never NODE_PATH's\n if (!process.versions.pnp) return false;\n try {\n createRequire(join(root, 'package.json')).resolve(HOOK_FILE);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction composeConfig<C extends object>(\n base: C,\n root: string,\n scope?: LoaderOptions,\n gate?: () => void,\n): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack, compiler: userCompiler } = base as NextConfigLike;\n const loader = scope ? { loader: LOADER, options: scope } : LOADER;\n\n const rules: Record<string, unknown> = { ...turbopack?.rules };\n const verbalyRule = {\n condition: { all: [{ not: 'foreign' }, { path: SOURCE_PATH_RE }] },\n loaders: [loader],\n };\n const existing = rules['*'];\n rules['*'] = existing\n ? [...(Array.isArray(existing) ? existing : [existing]), verbalyRule]\n : verbalyRule;\n\n return {\n ...base,\n ...(gate && {\n compiler: {\n ...userCompiler,\n // after the compile, so next typegen, which loads this config too, never meets the gate\n async runAfterProductionCompile(metadata: never) {\n await userCompiler?.runAfterProductionCompile?.(metadata);\n try {\n gate();\n } catch (error) {\n // Next prints a failed hook twice: the report goes out once, and the throw stays short\n console.error((error as Error).message);\n // eslint-disable-next-line preserve-caught-error -- a cause would print the report again\n throw new Error('[verbaly] build blocked, the reason is printed above');\n }\n },\n },\n }),\n turbopack: {\n ...turbopack,\n resolveAlias: {\n ...turbopack?.resolveAlias,\n 'virtual:verbaly': `./${GENERATED_DIR}/index.js`,\n },\n rules,\n },\n webpack(config: WebpackConfigLike, context: unknown) {\n // webpack 5 parses 'virtual:' as a URI scheme, so resolve.alias never fires\n const { webpack: webpackInstance } = (context ?? {}) as WebpackContextLike;\n if (webpackInstance?.NormalModuleReplacementPlugin) {\n config.plugins ??= [];\n config.plugins.push(\n new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule),\n );\n }\n config.resolve ??= {};\n config.resolve.alias ??= {};\n (config.resolve.alias as Record<string, unknown>)['virtual:verbaly'] = runtimeModule;\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push({\n test: SOURCE_PATH_RE,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [typeof loader === 'string' ? { loader } : loader],\n });\n return userWebpack ? userWebpack(config, context as never) : config;\n },\n } as C;\n}\n"],"mappings":";;;;;AAIA,MAAM,4BAAY,IAAI,IAAyB;AAC/C,MAAM,8BAAc,IAAI,IAAY;AAKpC,SAAgB,UACd,UACA,KACA,QACA,UACW;CACX,IAAI,WAAW,UAAU,IAAI,IAAI,IAAI;CACrC,IAAI,CAAC,UAAU;EACb,WAAW,SAAS,kBAAkB,IAAI,IAAI;EAC9C,UAAU,IAAI,IAAI,MAAM,QAAQ;CAClC;CACA,MAAM,WAAsB,CAAC;CAC7B,MAAM,OAAkB,CAAC;CACzB,KAAK,MAAM,WAAW,OAAO,UAAU;EACrC,IAAI,QAAQ,SAAS,eAAe,QAAQ,SAAS,WAAW,KAAK,KAAK,OAAO;EACjF,IAAI,QAAQ,SAAS,YAAY;EAEjC,IAAI,YAAY,SAAS,IAAI,QAAQ,GA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AI,QAAQ,EACV,UAAU;GACR,GAAG;GAEH,MAAM,0BAA0B,UAAiB;IAC/C,MAAM,cAAc,4BAA4B,QAAQ;IACxD,IAAI;KACF,KAAK;IACP,SAAS,OAAO;KAEd,QAAQ,MAAO,MAAgB,OAAO;KAEtC,MAAM,IAAI,MAAM,sDAAsD;IACxE;GACF;EACF,EACF;EACA,WAAW;GACT,GAAG;GACH,cAAc;IACZ,GAAG,WAAW;IACd,mBAAmB,KAAK,cAAc;GACxC;GACA;EACF;EACA,QAAQ,QAA2B,SAAkB;GAEnD,MAAM,EAAE,SAAS,oBAAqB,WAAW,CAAC;GAClD,IAAI,iBAAiB,+BAA+B;IAClD,OAAO,YAAY,CAAC;IACpB,OAAO,QAAQ,KACb,IAAI,gBAAgB,8BAA8B,qBAAqB,aAAa,CACtF;GACF;GACA,OAAO,YAAY,CAAC;GACpB,OAAO,QAAQ,UAAU,CAAC;GAC1B,OAAQ,QAAQ,MAAkC,qBAAqB;GACvE,OAAO,WAAW,CAAC;GACnB,OAAO,OAAO,UAAU,CAAC;GACzB,OAAO,OAAO,MAAM,KAAK;IACvB,MAAM;IACN,SAAS;IACT,SAAS;IACT,KAAK,CAAC,OAAO,WAAW,WAAW,EAAE,OAAO,IAAI,MAAM;GACxD,CAAC;GACD,OAAO,cAAc,YAAY,QAAQ,OAAgB,IAAI;EAC/D;CACF;AACF"}
package/dist/index.js CHANGED
@@ -1,24 +1,37 @@
1
+ import { createRequire } from "node:module";
1
2
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
3
  import { basename, dirname, join, relative } from "node:path";
3
4
  //#region src/report.ts
4
- const said = /* @__PURE__ */ new Set();
5
- function once(id, line) {
6
- if (said.has(id)) return;
7
- said.add(id);
8
- console.warn(`[verbaly] ${line}`);
9
- }
10
- function reportDev(compiler, cfg, registry, replaced, previous, outdated) {
11
- const messages = registry.messages();
12
- const rel = (file) => relative(cfg.root, file).replaceAll("\\", "/");
13
- for (const key of replaced) {
14
- const msg = messages.get(key);
15
- if (!msg || previous && previous.get(key) !== msg.message) continue;
16
- once(`replaced:${key}`, previous ? `${cfg.sourceLocale}.json: your edit of "${key}" was replaced, its text lives in ${rel(msg.file)}: change it there` : `${cfg.sourceLocale}.json: "${key}" took the text written in ${rel(msg.file)}, the code owns it`);
5
+ const reporters = /* @__PURE__ */ new Map();
6
+ const brokenState = /* @__PURE__ */ new Set();
7
+ function reportDev(compiler, cfg, result, previous) {
8
+ let reporter = reporters.get(cfg.root);
9
+ if (!reporter) {
10
+ reporter = compiler.createDevReporter(cfg.root);
11
+ reporters.set(cfg.root, reporter);
12
+ }
13
+ const replaced = [];
14
+ const code = [];
15
+ for (const finding of result.findings) {
16
+ if (finding.kind === "collision" || finding.kind === "renamed") code.push(finding);
17
+ if (finding.kind !== "replaced") continue;
18
+ if (previous && previous.get(finding.key) !== finding.site.message) continue;
19
+ replaced.push({
20
+ ...finding,
21
+ edited: previous !== void 0
22
+ });
17
23
  }
18
- for (const entry of compiler.collisionEntries(registry)) once(`collision:${entry.key}`, compiler.formatCollision(entry, cfg.root).trim());
19
- for (const { name, file } of registry.missed()) once(`missed:${file}:${name}`, `${rel(file)}: ${name}\`…\` is never extracted, so it stays in the source language: name it t`);
20
- for (const { locale, key } of outdated) once(`outdated:${locale}:${key}`, `${locale}: "${key}" was translated from an older source text, update it or approve it`);
21
- return new Map([...messages].map(([key, msg]) => [key, msg.message]));
24
+ reporter.report("replaced", replaced);
25
+ reporter.report("code", code);
26
+ const outdated = result.state ? compiler.outdatedTranslations(cfg, result.catalogs, result.state.fingerprints) : [];
27
+ reporter.report("outdated", outdated.map((entry) => ({
28
+ kind: "outdated",
29
+ ...entry
30
+ })));
31
+ if (result.stateProblem && !brokenState.has(cfg.root)) console.warn(`[verbaly] ${result.stateProblem}, so drafts are not tracked`);
32
+ if (result.stateProblem) brokenState.add(cfg.root);
33
+ else brokenState.delete(cfg.root);
34
+ return new Map([...result.registry.messages()].map(([key, msg]) => [key, msg.message]));
22
35
  }
23
36
  //#endregion
24
37
  //#region src/codegen.ts
@@ -33,21 +46,14 @@ function writeIfChanged(file, content) {
33
46
  writeFileSync(file, content);
34
47
  return true;
35
48
  }
36
- let stateWarned = false;
37
- function syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, previous) {
38
- const { added, replaced } = compiler.syncCatalogs(cfg, catalogs, registry);
39
- for (const locale of Object.keys(added)) compiler.writeCatalog(cfg, locale, catalogs[locale] ?? {});
40
- compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
41
- writeGeneratedModules(compiler, cfg, catalogs, requestOptions);
42
- let outdated = [];
43
- try {
44
- const state = compiler.updateState(cfg, catalogs);
45
- outdated = compiler.outdatedTranslations(cfg, catalogs, state.fingerprints);
46
- } catch (error) {
47
- if (!stateWarned) console.warn(`${compiler.formatCliError(error)}, so drafts are not tracked`);
48
- stateWarned = true;
49
- }
50
- return reportDev(compiler, cfg, registry, replaced, previous, outdated);
49
+ async function syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, previous) {
50
+ const result = await compiler.syncProject(cfg, {
51
+ registry,
52
+ catalogs,
53
+ write: "changed"
54
+ });
55
+ writeGeneratedModules(compiler, cfg, result.catalogs, requestOptions);
56
+ return reportDev(compiler, cfg, result, previous);
51
57
  }
52
58
  function writeGeneratedModules(compiler, cfg, catalogs, requestOptions = {}) {
53
59
  const dir = generatedDir(cfg.root);
@@ -89,9 +95,10 @@ function startWatcher(compiler, cfg, requestOptions, startTexts) {
89
95
  }
90
96
  running = true;
91
97
  try {
92
- texts = syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions, texts);
98
+ texts = await syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions, texts);
93
99
  } catch (error) {
94
- console.warn("[verbaly] live extraction failed:", error);
100
+ const reason = compiler.formatCliError(error).replace(/^\[verbaly\] /, "");
101
+ console.warn(`[verbaly] live extraction paused: ${reason}`);
95
102
  } finally {
96
103
  running = false;
97
104
  if (queued) {
@@ -143,13 +150,15 @@ function withVerbaly(nextConfig, options = {}) {
143
150
  const cfg = await compiler.loadConfig(root, verbalyConfig);
144
151
  const catalogs = compiler.loadCatalogs(cfg);
145
152
  const registry = await compiler.extractProject(cfg);
153
+ await compiler.reportOutsideInclude(cfg);
146
154
  let gate;
147
155
  if (phase === DEV_PHASE) {
148
- const texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);
156
+ const texts = await syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);
149
157
  startWatcher(compiler, cfg, requestOptions, texts);
150
158
  } else {
151
159
  compiler.syncCatalogs(cfg, catalogs, registry);
152
160
  writeGeneratedModules(compiler, cfg, catalogs, requestOptions);
161
+ compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
153
162
  if (phase === BUILD_PHASE) {
154
163
  const runGate = () => compiler.runBuildGate(cfg, registry, failOnMissing);
155
164
  if (hasAfterCompileHook(cfg.root)) gate = runGate;
@@ -164,11 +173,19 @@ function withVerbaly(nextConfig, options = {}) {
164
173
  return composeConfig(base, cfg.root, scope, gate);
165
174
  };
166
175
  }
176
+ const HOOK_FILE = "next/dist/build/after-production-compile.js";
167
177
  function hasAfterCompileHook(root) {
168
178
  for (let dir = root;; dir = dirname(dir)) {
169
179
  const next = join(dir, "node_modules", "next");
170
- if (existsSync(join(next, "package.json"))) return existsSync(join(next, "dist", "build", "after-production-compile.js"));
171
- if (dirname(dir) === dir) return false;
180
+ if (existsSync(join(next, "package.json"))) return existsSync(join(dir, "node_modules", HOOK_FILE));
181
+ if (dirname(dir) === dir) break;
182
+ }
183
+ if (!process.versions.pnp) return false;
184
+ try {
185
+ createRequire(join(root, "package.json")).resolve(HOOK_FILE);
186
+ return true;
187
+ } catch {
188
+ return false;
172
189
  }
173
190
  }
174
191
  function composeConfig(base, root, scope, gate) {
@@ -191,7 +208,12 @@ function composeConfig(base, root, scope, gate) {
191
208
  ...userCompiler,
192
209
  async runAfterProductionCompile(metadata) {
193
210
  await userCompiler?.runAfterProductionCompile?.(metadata);
194
- gate();
211
+ try {
212
+ gate();
213
+ } catch (error) {
214
+ console.error(error.message);
215
+ throw new Error("[verbaly] build blocked, the reason is printed above");
216
+ }
195
217
  }
196
218
  } },
197
219
  turbopack: {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/report.ts","../src/codegen.ts","../src/watch.ts","../src/index.ts"],"sourcesContent":["import type { ResolvedConfig } from '@verbaly/compiler';\nimport { relative } from 'node:path';\nimport type { Compiler, Registry } from './codegen';\n\n// a dev server re-runs per keystroke: keyed on what it is about, never on the text being typed\nconst said = new Set<string>();\n\nfunction once(id: string, line: string): void {\n if (said.has(id)) return;\n said.add(id);\n console.warn(`[verbaly] ${line}`);\n}\n\n// the code texts of the last run tell an edit in the code from an edit in the catalog\nexport type CodeTexts = Map<string, string>;\n\nexport function reportDev(\n compiler: Compiler,\n cfg: ResolvedConfig,\n registry: Registry,\n replaced: string[],\n previous: CodeTexts | undefined,\n outdated: { locale: string; key: string }[],\n): CodeTexts {\n const messages = registry.messages();\n const rel = (file: string): string => relative(cfg.root, file).replaceAll('\\\\', '/');\n for (const key of replaced) {\n const msg = messages.get(key);\n // the code changed this text since the last run, which is how a text it owns is edited\n if (!msg || (previous && previous.get(key) !== msg.message)) continue;\n once(\n `replaced:${key}`,\n previous\n ? `${cfg.sourceLocale}.json: your edit of \"${key}\" was replaced, its text lives in ${rel(msg.file)}: change it there`\n : `${cfg.sourceLocale}.json: \"${key}\" took the text written in ${rel(msg.file)}, the code owns it`,\n );\n }\n for (const entry of compiler.collisionEntries(registry)) {\n once(`collision:${entry.key}`, compiler.formatCollision(entry, cfg.root).trim());\n }\n for (const { name, file } of registry.missed()) {\n once(\n `missed:${file}:${name}`,\n `${rel(file)}: ${name}\\`…\\` is never extracted, so it stays in the source language: name it t`,\n );\n }\n for (const { locale, key } of outdated) {\n once(\n `outdated:${locale}:${key}`,\n `${locale}: \"${key}\" was translated from an older source text, update it or approve it`,\n );\n }\n return new Map([...messages].map(([key, msg]) => [key, msg.message]));\n}\n\n// test hook: the set is module state, and each test starts from a server that said nothing\nexport function resetReported(): void {\n said.clear();\n}\n","import type { Catalogs, ResolvedConfig } from '@verbaly/compiler';\nimport { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { reportDev, type CodeTexts } from './report';\n\nexport type Compiler = typeof import('@verbaly/compiler');\nexport type Registry = Awaited<ReturnType<Compiler['extractProject']>>;\n\nexport interface RequestOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\nexport const GENERATED_DIR = '.verbaly';\n\nexport function generatedDir(root: string): string {\n return join(root, GENERATED_DIR);\n}\n\n// content compare: identical rewrites must not retrigger the bundler\nfunction writeIfChanged(file: string, content: string): boolean {\n try {\n if (readFileSync(file, 'utf8') === content) return false;\n } catch {\n // new file\n }\n writeFileSync(file, content);\n return true;\n}\n\nlet stateWarned = false;\n\n// dev pipeline shared by withVerbaly and the watcher: catalogs, dts, runtime modules, state\nexport function syncAndWrite(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: Registry,\n requestOptions: RequestOptions,\n previous?: CodeTexts,\n): CodeTexts {\n const { added, replaced } = compiler.syncCatalogs(cfg, catalogs, registry);\n for (const locale of Object.keys(added)) {\n compiler.writeCatalog(cfg, locale, catalogs[locale] ?? {});\n }\n compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n let outdated: { locale: string; key: string }[] = [];\n try {\n // a pruned key takes its draft along, and an edited source text marks its translations\n const state = compiler.updateState(cfg, catalogs);\n outdated = compiler.outdatedTranslations(cfg, catalogs, state.fingerprints);\n } catch (error) {\n // a broken sidecar must not stop next dev: say it once and keep serving\n if (!stateWarned) console.warn(`${compiler.formatCliError(error)}, so drafts are not tracked`);\n stateWarned = true;\n }\n return reportDev(compiler, cfg, registry, replaced, previous, outdated);\n}\n\n// real-file replacement for virtual:verbaly: Turbopack has no virtual modules\nexport function writeGeneratedModules(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n requestOptions: RequestOptions = {},\n): boolean {\n const dir = generatedDir(cfg.root);\n const localeDir = join(dir, 'locale');\n mkdirSync(localeDir, { recursive: true });\n\n let changed = writeIfChanged(join(dir, '.gitignore'), '*\\n');\n\n // these files are the client module here, so bundle.exclude has to be applied on this path too\n const client = compiler.clientCatalogs(cfg, catalogs);\n const runtime = compiler.generateRuntimeModule(cfg, {\n localeImport: (locale) => `./locale/${locale}.js`,\n extraExports: `export const requestOptions = ${JSON.stringify(requestOptions)};\\n`,\n icu: cfg.icu ?? compiler.needsIcu(client),\n relative: cfg.relative ?? compiler.needsRelative(client),\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n changed = writeIfChanged(join(dir, 'index.js'), runtime) || changed;\n\n const expected = new Set(cfg.locales.map((locale) => `${locale}.js`));\n for (const locale of cfg.locales) {\n changed =\n writeIfChanged(\n join(localeDir, `${locale}.js`),\n compiler.generateLocaleModule(client[locale] ?? {}),\n ) || changed;\n }\n for (const file of readdirSync(localeDir)) {\n if (!expected.has(file)) {\n rmSync(join(localeDir, file));\n changed = true;\n }\n }\n return changed;\n}\n","import type { ResolvedConfig } from '@verbaly/compiler';\nimport { basename, relative } from 'node:path';\nimport { GENERATED_DIR, syncAndWrite, type Compiler, type RequestOptions } from './codegen';\nimport type { CodeTexts } from './report';\n\n// one watcher per project root: next.config can be evaluated more than once\nconst active = new Map<string, () => void>();\n\nexport function startWatcher(\n compiler: Compiler,\n cfg: ResolvedConfig,\n requestOptions: RequestOptions,\n startTexts?: CodeTexts,\n): () => void {\n const existing = active.get(cfg.root);\n if (existing) return existing;\n\n const catalogDir = relative(cfg.root, cfg.dir).replaceAll('\\\\', '/');\n let timer: ReturnType<typeof setTimeout> | undefined;\n let running = false;\n let queued = false;\n let texts = startTexts;\n\n async function refresh(): Promise<void> {\n if (running) {\n queued = true;\n return;\n }\n running = true;\n try {\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, texts);\n } catch (error) {\n console.warn('[verbaly] live extraction failed:', error);\n } finally {\n running = false;\n if (queued) {\n queued = false;\n schedule();\n }\n }\n }\n\n function schedule(): void {\n clearTimeout(timer);\n timer = setTimeout(() => void refresh(), 150);\n }\n\n const keep = catalogDir.split('/')[0];\n const close = compiler.watchTree(cfg.root, { keep, persistent: false }, (filename) => {\n if (!filename) return;\n const file = filename.replaceAll('\\\\', '/');\n if (\n file.startsWith(`${GENERATED_DIR}/`) ||\n file.startsWith('.next/') ||\n file.includes('node_modules/') ||\n file.endsWith('.d.ts')\n ) {\n return;\n }\n // a dotfile there is the state sidecar this pipeline writes: it changes no message\n const isCatalog =\n file.startsWith(`${catalogDir}/`) && file.endsWith('.json') && !basename(file).startsWith('.');\n if (isCatalog || compiler.SOURCE_FILE_RE.test(file)) schedule();\n });\n\n const dispose = (): void => {\n clearTimeout(timer);\n close();\n active.delete(cfg.root);\n };\n active.set(cfg.root, dispose);\n return dispose;\n}\n\n// test hook\nexport function stopWatcher(root: string): void {\n active.get(root)?.();\n}\n","import type { PluginOptions } from '@verbaly/compiler';\nimport { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport {\n GENERATED_DIR,\n generatedDir,\n syncAndWrite,\n writeGeneratedModules,\n type Compiler,\n type RequestOptions,\n} from './codegen';\nimport type { LoaderOptions } from './loader';\nimport { startWatcher } from './watch';\n\nexport type { VerbalyConfig } from '@verbaly/compiler';\nexport type { RequestOptions } from './codegen';\n\nexport interface NextVerbalyOptions extends PluginOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\n// structural NextConfig subset (compat asserted in tests): no index signatures, Next has none\nexport interface WebpackConfigLike {\n resolve?: { alias?: Record<string, unknown>; [key: string]: unknown };\n module?: { rules?: unknown[]; [key: string]: unknown };\n plugins?: unknown[];\n [key: string]: unknown;\n}\n\ninterface WebpackContextLike {\n webpack?: {\n NormalModuleReplacementPlugin: new (test: RegExp, resource: string) => unknown;\n };\n}\n\n// context param is `never` so Next's real webpack fn (specific context type) stays assignable\nexport type WebpackFn = (config: WebpackConfigLike, context: never) => unknown;\n\nexport interface TurbopackLike {\n resolveAlias?: Record<string, unknown>;\n rules?: Record<string, unknown>;\n}\n\n// metadata is `never` for the same reason as the webpack context: Next's own type stays assignable\nexport interface CompilerLike {\n runAfterProductionCompile?: (metadata: never) => Promise<void>;\n}\n\nexport interface NextConfigLike {\n webpack?: WebpackFn | null;\n turbopack?: TurbopackLike;\n compiler?: CompilerLike;\n}\n\n// constraint is object, not NextConfigLike: an all-optional target rejects by weak-type\nexport type NextConfigInput<C extends object> =\n C | ((phase: string, context: { defaultConfig?: unknown }) => C | Promise<C>);\n\n// next/constants values: literal to keep this module import-free of next\nconst DEV_PHASE = 'phase-development-server';\nconst BUILD_PHASE = 'phase-production-build';\n// next experimental-analyze compiles the app as well, so it needs the generated modules on disk\nconst ANALYZE_PHASE = 'phase-analyze';\n\nconst LOADER = '@verbaly/next/loader';\n// matched via condition.path: a bare extension glob also hits Next's App Router entry\nconst SOURCE_PATH_RE = /\\.[cm]?[jt]sx?$/;\n\nexport function withVerbaly<C extends object>(\n nextConfig?: NextConfigInput<C>,\n options: NextVerbalyOptions = {},\n): (phase: string, context?: { defaultConfig?: unknown }) => Promise<C> {\n const { failOnMissing, cookie, fallback, ...verbalyConfig } = options;\n const requestOptions: RequestOptions = { cookie, fallback };\n\n return async (phase, context = {}) => {\n const base: C =\n typeof nextConfig === 'function'\n ? await nextConfig(phase, context)\n : (nextConfig ?? ({} as C));\n const root = verbalyConfig.root ?? process.cwd();\n\n // production server / export: everything is bundled, so no FS work, config only\n if (phase !== DEV_PHASE && phase !== BUILD_PHASE && phase !== ANALYZE_PHASE) {\n return composeConfig(base, root);\n }\n\n // dynamic: the compiler is ESM-only and this entry is also consumed as CJS\n const compiler: Compiler = await import('@verbaly/compiler');\n\n const cfg = await compiler.loadConfig(root, verbalyConfig);\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n let gate: (() => void) | undefined;\n\n if (phase === DEV_PHASE) {\n const texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);\n startWatcher(compiler, cfg, requestOptions, texts);\n } else {\n // the code's text ships, as it does in dev: a catalog edit of a text it owns never wins\n compiler.syncCatalogs(cfg, catalogs, registry);\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n if (phase === BUILD_PHASE) {\n const runGate = (): void => compiler.runBuildGate(cfg, registry, failOnMissing);\n // typegen loads this config in the build phase too, and only a real build runs the hook\n if (hasAfterCompileHook(cfg.root)) gate = runGate;\n else runGate();\n }\n }\n\n // the loader rewrites exactly what extract reads: a file outside include keeps its t`…`\n const scope: LoaderOptions = { root: cfg.root, include: cfg.include, exclude: cfg.exclude };\n return composeConfig(base, cfg.root, scope, gate);\n };\n}\n\n// next build calls compiler.runAfterProductionCompile since 15.4; NODE_PATH may name another next\nfunction hasAfterCompileHook(root: string): boolean {\n for (let dir = root; ; dir = dirname(dir)) {\n const next = join(dir, 'node_modules', 'next');\n if (existsSync(join(next, 'package.json'))) {\n return existsSync(join(next, 'dist', 'build', 'after-production-compile.js'));\n }\n if (dirname(dir) === dir) return false;\n }\n}\n\nfunction composeConfig<C extends object>(\n base: C,\n root: string,\n scope?: LoaderOptions,\n gate?: () => void,\n): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack, compiler: userCompiler } = base as NextConfigLike;\n const loader = scope ? { loader: LOADER, options: scope } : LOADER;\n\n const rules: Record<string, unknown> = { ...turbopack?.rules };\n const verbalyRule = {\n condition: { all: [{ not: 'foreign' }, { path: SOURCE_PATH_RE }] },\n loaders: [loader],\n };\n const existing = rules['*'];\n rules['*'] = existing\n ? [...(Array.isArray(existing) ? existing : [existing]), verbalyRule]\n : verbalyRule;\n\n return {\n ...base,\n ...(gate && {\n compiler: {\n ...userCompiler,\n // after the compile, so next typegen, which loads this config too, never meets the gate\n async runAfterProductionCompile(metadata: never) {\n await userCompiler?.runAfterProductionCompile?.(metadata);\n gate();\n },\n },\n }),\n turbopack: {\n ...turbopack,\n resolveAlias: {\n ...turbopack?.resolveAlias,\n 'virtual:verbaly': `./${GENERATED_DIR}/index.js`,\n },\n rules,\n },\n webpack(config: WebpackConfigLike, context: unknown) {\n // webpack 5 parses 'virtual:' as a URI scheme, so resolve.alias never fires\n const { webpack: webpackInstance } = (context ?? {}) as WebpackContextLike;\n if (webpackInstance?.NormalModuleReplacementPlugin) {\n config.plugins ??= [];\n config.plugins.push(\n new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule),\n );\n }\n config.resolve ??= {};\n config.resolve.alias ??= {};\n (config.resolve.alias as Record<string, unknown>)['virtual:verbaly'] = runtimeModule;\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push({\n test: SOURCE_PATH_RE,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [typeof loader === 'string' ? { loader } : loader],\n });\n return userWebpack ? userWebpack(config, context as never) : config;\n },\n } as C;\n}\n"],"mappings":";;;AAKA,MAAM,uBAAO,IAAI,IAAY;AAE7B,SAAS,KAAK,IAAY,MAAoB;CAC5C,IAAI,KAAK,IAAI,EAAE,GAAG;CAClB,KAAK,IAAI,EAAE;CACX,QAAQ,KAAK,aAAa,MAAM;AAClC;AAKA,SAAgB,UACd,UACA,KACA,UACA,UACA,UACA,UACW;CACX,MAAM,WAAW,SAAS,SAAS;CACnC,MAAM,OAAO,SAAyB,SAAS,IAAI,MAAM,IAAI,CAAC,CAAC,WAAW,MAAM,GAAG;CACnF,KAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,MAAM,SAAS,IAAI,GAAG;EAE5B,IAAI,CAAC,OAAQ,YAAY,SAAS,IAAI,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YAAY,CAAC;GACpB,OAAO,QAAQ,UAAU,CAAC;GAC1B,OAAQ,QAAQ,MAAkC,qBAAqB;GACvE,OAAO,WAAW,CAAC;GACnB,OAAO,OAAO,UAAU,CAAC;GACzB,OAAO,OAAO,MAAM,KAAK;IACvB,MAAM;IACN,SAAS;IACT,SAAS;IACT,KAAK,CAAC,OAAO,WAAW,WAAW,EAAE,OAAO,IAAI,MAAM;GACxD,CAAC;GACD,OAAO,cAAc,YAAY,QAAQ,OAAgB,IAAI;EAC/D;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/report.ts","../src/codegen.ts","../src/watch.ts","../src/index.ts"],"sourcesContent":["import type { DevReporter, Finding, ResolvedConfig, SyncProjectResult } from '@verbaly/compiler';\nimport type { Compiler } from './codegen';\n\n// one per project: next.config can be evaluated more than once, and the watcher outlives it\nconst reporters = new Map<string, DevReporter>();\nconst brokenState = new Set<string>();\n\n// the code texts of the last run tell an edit in the code from an edit in the catalog\nexport type CodeTexts = Map<string, string>;\n\nexport function reportDev(\n compiler: Compiler,\n cfg: ResolvedConfig,\n result: SyncProjectResult,\n previous: CodeTexts | undefined,\n): CodeTexts {\n let reporter = reporters.get(cfg.root);\n if (!reporter) {\n reporter = compiler.createDevReporter(cfg.root);\n reporters.set(cfg.root, reporter);\n }\n const replaced: Finding[] = [];\n const code: Finding[] = [];\n for (const finding of result.findings) {\n if (finding.kind === 'collision' || finding.kind === 'renamed') code.push(finding);\n if (finding.kind !== 'replaced') continue;\n // the code changed this text since the last run, which is how a text it owns is edited\n if (previous && previous.get(finding.key) !== finding.site.message) continue;\n replaced.push({ ...finding, edited: previous !== undefined });\n }\n reporter.report('replaced', replaced);\n reporter.report('code', code);\n const outdated = result.state\n ? compiler.outdatedTranslations(cfg, result.catalogs, result.state.fingerprints)\n : [];\n reporter.report(\n 'outdated',\n outdated.map((entry): Finding => ({ kind: 'outdated', ...entry })),\n );\n\n // a broken sidecar must not stop next dev: said once, and again if it breaks after a fix\n if (result.stateProblem && !brokenState.has(cfg.root)) {\n console.warn(`[verbaly] ${result.stateProblem}, so drafts are not tracked`);\n }\n if (result.stateProblem) brokenState.add(cfg.root);\n else brokenState.delete(cfg.root);\n\n return new Map([...result.registry.messages()].map(([key, msg]) => [key, msg.message]));\n}\n\n// test hook: each test starts from a server that said nothing\nexport function resetReported(): void {\n reporters.clear();\n brokenState.clear();\n}\n","import type { Catalogs, ResolvedConfig } from '@verbaly/compiler';\nimport { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { reportDev, type CodeTexts } from './report';\n\nexport type Compiler = typeof import('@verbaly/compiler');\nexport type Registry = Awaited<ReturnType<Compiler['extractProject']>>;\n\nexport interface RequestOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\nexport const GENERATED_DIR = '.verbaly';\n\nexport function generatedDir(root: string): string {\n return join(root, GENERATED_DIR);\n}\n\n// content compare: identical rewrites must not retrigger the bundler\nfunction writeIfChanged(file: string, content: string): boolean {\n try {\n if (readFileSync(file, 'utf8') === content) return false;\n } catch {\n // new file\n }\n writeFileSync(file, content);\n return true;\n}\n\n// dev pipeline shared by withVerbaly and the watcher: the compiler's sync, then the runtime modules\nexport async function syncAndWrite(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: Registry,\n requestOptions: RequestOptions,\n previous?: CodeTexts,\n): Promise<CodeTexts> {\n // 'changed': a catalog nothing happened to keeps the formatting its author gave it\n const result = await compiler.syncProject(cfg, { registry, catalogs, write: 'changed' });\n writeGeneratedModules(compiler, cfg, result.catalogs, requestOptions);\n return reportDev(compiler, cfg, result, previous);\n}\n\n// real-file replacement for virtual:verbaly: Turbopack has no virtual modules\nexport function writeGeneratedModules(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n requestOptions: RequestOptions = {},\n): boolean {\n const dir = generatedDir(cfg.root);\n const localeDir = join(dir, 'locale');\n mkdirSync(localeDir, { recursive: true });\n\n let changed = writeIfChanged(join(dir, '.gitignore'), '*\\n');\n\n // these files are the client module here, so bundle.exclude has to be applied on this path too\n const client = compiler.clientCatalogs(cfg, catalogs);\n const runtime = compiler.generateRuntimeModule(cfg, {\n localeImport: (locale) => `./locale/${locale}.js`,\n extraExports: `export const requestOptions = ${JSON.stringify(requestOptions)};\\n`,\n icu: cfg.icu ?? compiler.needsIcu(client),\n relative: cfg.relative ?? compiler.needsRelative(client),\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n changed = writeIfChanged(join(dir, 'index.js'), runtime) || changed;\n\n const expected = new Set(cfg.locales.map((locale) => `${locale}.js`));\n for (const locale of cfg.locales) {\n changed =\n writeIfChanged(\n join(localeDir, `${locale}.js`),\n compiler.generateLocaleModule(client[locale] ?? {}),\n ) || changed;\n }\n for (const file of readdirSync(localeDir)) {\n if (!expected.has(file)) {\n rmSync(join(localeDir, file));\n changed = true;\n }\n }\n return changed;\n}\n","import type { ResolvedConfig } from '@verbaly/compiler';\nimport { basename, relative } from 'node:path';\nimport { GENERATED_DIR, syncAndWrite, type Compiler, type RequestOptions } from './codegen';\nimport type { CodeTexts } from './report';\n\n// one watcher per project root: next.config can be evaluated more than once\nconst active = new Map<string, () => void>();\n\nexport function startWatcher(\n compiler: Compiler,\n cfg: ResolvedConfig,\n requestOptions: RequestOptions,\n startTexts?: CodeTexts,\n): () => void {\n const existing = active.get(cfg.root);\n if (existing) return existing;\n\n const catalogDir = relative(cfg.root, cfg.dir).replaceAll('\\\\', '/');\n let timer: ReturnType<typeof setTimeout> | undefined;\n let running = false;\n let queued = false;\n let texts = startTexts;\n\n async function refresh(): Promise<void> {\n if (running) {\n queued = true;\n return;\n }\n running = true;\n try {\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n texts = await syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, texts);\n } catch (error) {\n // a catalog saved half-typed is broken JSON for a moment: one line, never a stack trace\n const reason = compiler.formatCliError(error).replace(/^\\[verbaly\\] /, '');\n console.warn(`[verbaly] live extraction paused: ${reason}`);\n } finally {\n running = false;\n if (queued) {\n queued = false;\n schedule();\n }\n }\n }\n\n function schedule(): void {\n clearTimeout(timer);\n timer = setTimeout(() => void refresh(), 150);\n }\n\n const keep = catalogDir.split('/')[0];\n const close = compiler.watchTree(cfg.root, { keep, persistent: false }, (filename) => {\n if (!filename) return;\n const file = filename.replaceAll('\\\\', '/');\n if (\n file.startsWith(`${GENERATED_DIR}/`) ||\n file.startsWith('.next/') ||\n file.includes('node_modules/') ||\n file.endsWith('.d.ts')\n ) {\n return;\n }\n // a dotfile there is the state sidecar this pipeline writes: it changes no message\n const isCatalog =\n file.startsWith(`${catalogDir}/`) && file.endsWith('.json') && !basename(file).startsWith('.');\n if (isCatalog || compiler.SOURCE_FILE_RE.test(file)) schedule();\n });\n\n const dispose = (): void => {\n clearTimeout(timer);\n close();\n active.delete(cfg.root);\n };\n active.set(cfg.root, dispose);\n return dispose;\n}\n\n// test hook\nexport function stopWatcher(root: string): void {\n active.get(root)?.();\n}\n","import type { PluginOptions } from '@verbaly/compiler';\nimport { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport {\n GENERATED_DIR,\n generatedDir,\n syncAndWrite,\n writeGeneratedModules,\n type Compiler,\n type RequestOptions,\n} from './codegen';\nimport type { LoaderOptions } from './loader';\nimport { startWatcher } from './watch';\n\nexport type { VerbalyConfig } from '@verbaly/compiler';\nexport type { RequestOptions } from './codegen';\n\nexport interface NextVerbalyOptions extends PluginOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\n// structural NextConfig subset (compat asserted in tests): no index signatures, Next has none\nexport interface WebpackConfigLike {\n resolve?: { alias?: Record<string, unknown>; [key: string]: unknown };\n module?: { rules?: unknown[]; [key: string]: unknown };\n plugins?: unknown[];\n [key: string]: unknown;\n}\n\ninterface WebpackContextLike {\n webpack?: {\n NormalModuleReplacementPlugin: new (test: RegExp, resource: string) => unknown;\n };\n}\n\n// context param is `never` so Next's real webpack fn (specific context type) stays assignable\nexport type WebpackFn = (config: WebpackConfigLike, context: never) => unknown;\n\nexport interface TurbopackLike {\n resolveAlias?: Record<string, unknown>;\n rules?: Record<string, unknown>;\n}\n\n// metadata is `never` for the same reason as the webpack context: Next's own type stays assignable\nexport interface CompilerLike {\n runAfterProductionCompile?: (metadata: never) => Promise<void>;\n}\n\nexport interface NextConfigLike {\n webpack?: WebpackFn | null;\n turbopack?: TurbopackLike;\n compiler?: CompilerLike;\n}\n\n// constraint is object, not NextConfigLike: an all-optional target rejects by weak-type\nexport type NextConfigInput<C extends object> =\n C | ((phase: string, context: { defaultConfig?: unknown }) => C | Promise<C>);\n\n// next/constants values: literal to keep this module import-free of next\nconst DEV_PHASE = 'phase-development-server';\nconst BUILD_PHASE = 'phase-production-build';\n// next experimental-analyze compiles the app as well, so it needs the generated modules on disk\nconst ANALYZE_PHASE = 'phase-analyze';\n\nconst LOADER = '@verbaly/next/loader';\n// matched via condition.path: a bare extension glob also hits Next's App Router entry\nconst SOURCE_PATH_RE = /\\.[cm]?[jt]sx?$/;\n\nexport function withVerbaly<C extends object>(\n nextConfig?: NextConfigInput<C>,\n options: NextVerbalyOptions = {},\n): (phase: string, context?: { defaultConfig?: unknown }) => Promise<C> {\n const { failOnMissing, cookie, fallback, ...verbalyConfig } = options;\n const requestOptions: RequestOptions = { cookie, fallback };\n\n return async (phase, context = {}) => {\n const base: C =\n typeof nextConfig === 'function'\n ? await nextConfig(phase, context)\n : (nextConfig ?? ({} as C));\n const root = verbalyConfig.root ?? process.cwd();\n\n // production server / export: everything is bundled, so no FS work, config only\n if (phase !== DEV_PHASE && phase !== BUILD_PHASE && phase !== ANALYZE_PHASE) {\n return composeConfig(base, root);\n }\n\n // dynamic: the compiler is ESM-only and this entry is also consumed as CJS\n const compiler: Compiler = await import('@verbaly/compiler');\n\n const cfg = await compiler.loadConfig(root, verbalyConfig);\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n // once per phase, from the config: a loader result can come from Turbopack's cache\n await compiler.reportOutsideInclude(cfg);\n let gate: (() => void) | undefined;\n\n if (phase === DEV_PHASE) {\n const texts = await syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);\n startWatcher(compiler, cfg, requestOptions, texts);\n } else {\n // the code's text ships, as it does in dev: a catalog edit of a text it owns never wins\n compiler.syncCatalogs(cfg, catalogs, registry);\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n // next build and next typegen check types, and .verbaly/ is never committed\n compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});\n if (phase === BUILD_PHASE) {\n const runGate = (): void => compiler.runBuildGate(cfg, registry, failOnMissing);\n // typegen loads this config in the build phase too, and only a real build runs the hook\n if (hasAfterCompileHook(cfg.root)) gate = runGate;\n else runGate();\n }\n }\n\n // the loader rewrites exactly what extract reads: a file outside include keeps its t`…`\n const scope: LoaderOptions = { root: cfg.root, include: cfg.include, exclude: cfg.exclude };\n return composeConfig(base, cfg.root, scope, gate);\n };\n}\n\nconst HOOK_FILE = 'next/dist/build/after-production-compile.js';\n\n// next build calls compiler.runAfterProductionCompile since 15.4; NODE_PATH may name another next\nfunction hasAfterCompileHook(root: string): boolean {\n for (let dir = root; ; dir = dirname(dir)) {\n const next = join(dir, 'node_modules', 'next');\n if (existsSync(join(next, 'package.json')))\n return existsSync(join(dir, 'node_modules', HOOK_FILE));\n if (dirname(dir) === dir) break;\n }\n // Yarn PnP has no node_modules, and its resolver finds the project's own next, never NODE_PATH's\n if (!process.versions.pnp) return false;\n try {\n createRequire(join(root, 'package.json')).resolve(HOOK_FILE);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction composeConfig<C extends object>(\n base: C,\n root: string,\n scope?: LoaderOptions,\n gate?: () => void,\n): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack, compiler: userCompiler } = base as NextConfigLike;\n const loader = scope ? { loader: LOADER, options: scope } : LOADER;\n\n const rules: Record<string, unknown> = { ...turbopack?.rules };\n const verbalyRule = {\n condition: { all: [{ not: 'foreign' }, { path: SOURCE_PATH_RE }] },\n loaders: [loader],\n };\n const existing = rules['*'];\n rules['*'] = existing\n ? [...(Array.isArray(existing) ? existing : [existing]), verbalyRule]\n : verbalyRule;\n\n return {\n ...base,\n ...(gate && {\n compiler: {\n ...userCompiler,\n // after the compile, so next typegen, which loads this config too, never meets the gate\n async runAfterProductionCompile(metadata: never) {\n await userCompiler?.runAfterProductionCompile?.(metadata);\n try {\n gate();\n } catch (error) {\n // Next prints a failed hook twice: the report goes out once, and the throw stays short\n console.error((error as Error).message);\n // eslint-disable-next-line preserve-caught-error -- a cause would print the report again\n throw new Error('[verbaly] build blocked, the reason is printed above');\n }\n },\n },\n }),\n turbopack: {\n ...turbopack,\n resolveAlias: {\n ...turbopack?.resolveAlias,\n 'virtual:verbaly': `./${GENERATED_DIR}/index.js`,\n },\n rules,\n },\n webpack(config: WebpackConfigLike, context: unknown) {\n // webpack 5 parses 'virtual:' as a URI scheme, so resolve.alias never fires\n const { webpack: webpackInstance } = (context ?? {}) as WebpackContextLike;\n if (webpackInstance?.NormalModuleReplacementPlugin) {\n config.plugins ??= [];\n config.plugins.push(\n new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule),\n );\n }\n config.resolve ??= {};\n config.resolve.alias ??= {};\n (config.resolve.alias as Record<string, unknown>)['virtual:verbaly'] = runtimeModule;\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push({\n test: SOURCE_PATH_RE,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [typeof loader === 'string' ? { loader } : loader],\n });\n return userWebpack ? userWebpack(config, context as never) : config;\n },\n } as C;\n}\n"],"mappings":";;;;AAIA,MAAM,4BAAY,IAAI,IAAyB;AAC/C,MAAM,8BAAc,IAAI,IAAY;AAKpC,SAAgB,UACd,UACA,KACA,QACA,UACW;CACX,IAAI,WAAW,UAAU,IAAI,I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;KAEtC,MAAM,IAAI,MAAM,sDAAsD;IACxE;GACF;EACF,EACF;EACA,WAAW;GACT,GAAG;GACH,cAAc;IACZ,GAAG,WAAW;IACd,mBAAmB,KAAK,cAAc;GACxC;GACA;EACF;EACA,QAAQ,QAA2B,SAAkB;GAEnD,MAAM,EAAE,SAAS,oBAAqB,WAAW,CAAC;GAClD,IAAI,iBAAiB,+BAA+B;IAClD,OAAO,YAAY,CAAC;IACpB,OAAO,QAAQ,KACb,IAAI,gBAAgB,8BAA8B,qBAAqB,aAAa,CACtF;GACF;GACA,OAAO,YAAY,CAAC;GACpB,OAAO,QAAQ,UAAU,CAAC;GAC1B,OAAQ,QAAQ,MAAkC,qBAAqB;GACvE,OAAO,WAAW,CAAC;GACnB,OAAO,OAAO,UAAU,CAAC;GACzB,OAAO,OAAO,MAAM,KAAK;IACvB,MAAM;IACN,SAAS;IACT,SAAS;IACT,KAAK,CAAC,OAAO,WAAW,WAAW,EAAE,OAAO,IAAI,MAAM;GACxD,CAAC;GACD,OAAO,cAAc,YAAY,QAAQ,OAAgB,IAAI;EAC/D;CACF;AACF"}
package/dist/server.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- import { TFunction, Verbaly } from "verbaly";
1
+ import { TransProps } from "@verbaly/react/server";
2
+ import * as React from "react";
3
+ import { Locale, Translate, Verbaly } from "verbaly";
2
4
  //#region src/server.d.ts
3
5
  export declare function setRequestLocale(locale: string): void;
4
6
  export interface AlternatesOptions {
@@ -10,8 +12,12 @@ export declare function getAlternates(options: AlternatesOptions): {
10
12
  languages: Record<string, string>;
11
13
  };
12
14
  export declare function getVerbaly(): Promise<Verbaly>;
13
- export declare function getT(): Promise<TFunction>;
14
- export declare function getRequestLocale(): Promise<string>;
15
+ export interface GetTOptions {
16
+ locale?: string;
17
+ }
18
+ export declare function getT(options?: GetTOptions): Promise<Translate>;
19
+ export declare function getRequestLocale(): Promise<Locale>;
20
+ export declare function Trans(props: TransProps): Promise<React.ReactElement>;
15
21
  export interface VerbalyProviderProps {
16
22
  locale: string;
17
23
  messages?: Record<string, string>;
package/dist/server.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { renderTrans } from "@verbaly/react/server";
1
2
  import { cookies, headers } from "next/headers";
2
3
  import * as React from "react";
3
4
  import { LOCALE_STORAGE_KEY, alternateLinks, localeFromPath, resolveRequestLocale, warnOnce } from "verbaly";
@@ -24,6 +25,16 @@ function declaredLocale() {
24
25
  if (match) return match;
25
26
  warnOnce(`setRequestLocale was given a locale the project does not have, so it was ignored`);
26
27
  }
28
+ function namedLocale(raw) {
29
+ const match = localeFromPath({
30
+ supported: locales,
31
+ path: `/${raw}`
32
+ });
33
+ if (match) return match;
34
+ warnOnce(`getT was asked for a locale the project does not have, so it answers in the source`);
35
+ return sourceLocale;
36
+ }
37
+ const instanceFor = perRequest((locale) => createRequestInstance(locale));
27
38
  async function negotiate() {
28
39
  const cookieName = requestOptions?.cookie ?? LOCALE_STORAGE_KEY;
29
40
  const headerStore = await headers();
@@ -64,12 +75,16 @@ function getAlternates(options) {
64
75
  async function getVerbaly() {
65
76
  return (await getRequestState()).instance;
66
77
  }
67
- async function getT() {
78
+ async function getT(options = {}) {
79
+ if (options.locale !== void 0) return (await instanceFor(namedLocale(options.locale))).t;
68
80
  return (await getRequestState()).instance.t;
69
81
  }
70
82
  async function getRequestLocale() {
71
83
  return (await getRequestState()).locale;
72
84
  }
85
+ async function Trans(props) {
86
+ return renderTrans(props.instance ?? await getVerbaly(), props);
87
+ }
73
88
  async function getVerbalyProps() {
74
89
  const { locale } = await getRequestState();
75
90
  if (locale === sourceLocale) return { locale };
@@ -79,6 +94,6 @@ async function getVerbalyProps() {
79
94
  };
80
95
  }
81
96
  //#endregion
82
- export { getAlternates, getRequestLocale, getT, getVerbaly, getVerbalyProps, setRequestLocale };
97
+ export { Trans, getAlternates, getRequestLocale, getT, getVerbaly, getVerbalyProps, setRequestLocale };
83
98
 
84
99
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["import { cookies, headers } from 'next/headers';\nimport * as React from 'react';\nimport {\n alternateLinks,\n localeFromPath,\n LOCALE_STORAGE_KEY,\n resolveRequestLocale,\n warnOnce,\n type AlternateLink,\n type TFunction,\n type Verbaly,\n} from 'verbaly';\nimport {\n createRequestInstance,\n loadMessages,\n locales,\n requestOptions,\n routing,\n sourceLocale,\n} from 'virtual:verbaly';\n\ninterface RequestState {\n locale: string;\n instance: Verbaly;\n}\n\n// React.cache = per-request dedupe in RSC; identity fallback keeps plain-node tests runnable\nconst perRequest: <T extends (...args: never[]) => unknown>(fn: T) => T =\n (React as { cache?: <T>(fn: T) => T }).cache ?? ((fn) => fn);\n\ninterface LocaleHolder {\n locale?: string;\n}\n\nconst scopedHolder = perRequest((): LocaleHolder => ({}));\nconst moduleHolder: LocaleHolder = {};\n\n// React.cache only holds inside a request, and outside one there is a single request to hold for\nfunction holder(): LocaleHolder {\n const scoped = scopedHolder();\n return scoped === scopedHolder() ? scoped : moduleHolder;\n}\n\n// call it from the layout with the [locale] segment: reading headers() kills static rendering\nexport function setRequestLocale(locale: string): void {\n // a segment says the url carries the locale, and no-prefix tells every url helper it does not\n if (routing === 'no-prefix') {\n warnOnce(\n `setRequestLocale got a locale segment while routing is \"no-prefix\": if your urls start ` +\n `with the locale, set routing to 'prefix-all' or 'prefix-except-source' in your verbaly config`,\n );\n }\n holder().locale = locale;\n}\n\n// a route segment is a url segment, so it narrows like one: a slug must never become a locale\nfunction declaredLocale(): string | undefined {\n const raw = holder().locale;\n if (raw === undefined) return undefined;\n const match = localeFromPath({ supported: locales, path: `/${raw}` });\n if (match) return match;\n warnOnce(`setRequestLocale was given a locale the project does not have, so it was ignored`);\n return undefined;\n}\n\n// only reached when no segment declared it: this read is what opts a route out of static\nasync function negotiate(): Promise<string> {\n const cookieName = requestOptions?.cookie ?? LOCALE_STORAGE_KEY;\n const headerStore = await headers();\n const cookieValue = cookieName === false ? undefined : (await cookies()).get(cookieName)?.value;\n return resolveRequestLocale({\n supported: locales,\n routing,\n cookie: cookieValue,\n header: headerStore.get('accept-language'),\n fallback: requestOptions?.fallback ?? sourceLocale,\n });\n}\n\nconst getRequestState = perRequest(async (): Promise<RequestState> => {\n const locale = declaredLocale() ?? (await negotiate());\n return { locale, instance: await createRequestInstance(locale) };\n});\n\nexport interface AlternatesOptions {\n path: string;\n baseUrl?: string;\n}\n\n// the hreflang set for generateMetadata, in the shape Next's alternates field takes\nexport function getAlternates(options: AlternatesOptions): {\n canonical?: string;\n languages: Record<string, string>;\n} {\n const links: AlternateLink[] = alternateLinks({\n supported: locales,\n sourceLocale,\n routing,\n path: options.path,\n baseUrl: options.baseUrl,\n });\n const languages: Record<string, string> = {};\n for (const link of links) languages[link.hreflang] = link.href;\n const self = localeFromPath({ supported: locales, path: options.path }) ?? sourceLocale;\n return { canonical: languages[self], languages };\n}\n\n// request-scoped instance: never the virtual:verbaly singleton (locale would leak between requests)\nexport async function getVerbaly(): Promise<Verbaly> {\n return (await getRequestState()).instance;\n}\n\nexport async function getT(): Promise<TFunction> {\n return (await getRequestState()).instance.t;\n}\n\nexport async function getRequestLocale(): Promise<string> {\n return (await getRequestState()).locale;\n}\n\nexport interface VerbalyProviderProps {\n locale: string;\n messages?: Record<string, string>;\n}\n\n// messages omitted for the source locale: it already ships inline in the client bundle\nexport async function getVerbalyProps(): Promise<VerbalyProviderProps> {\n const { locale } = await getRequestState();\n if (locale === sourceLocale) return { locale };\n return { locale, messages: await loadMessages(locale) };\n}\n"],"mappings":";;;;;AA2BA,MAAM,aACH,MAAsC,WAAW,OAAO;AAM3D,MAAM,eAAe,kBAAgC,CAAC,EAAE;AACxD,MAAM,eAA6B,CAAC;AAGpC,SAAS,SAAuB;CAC9B,MAAM,SAAS,aAAa;CAC5B,OAAO,WAAW,aAAa,IAAI,SAAS;AAC9C;AAGA,SAAgB,iBAAiB,QAAsB;CAErD,IAAI,YAAY,aACd,SACE,wLAEF;CAEF,OA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iD;CACrE,MAAM,EAAE,WAAW,MAAM,gBAAgB;CACzC,IAAI,WAAW,cAAc,OAAO,EAAE,OAAO;CAC7C,OAAO;EAAE;EAAQ,UAAU,MAAM,aAAa,MAAM;CAAE;AACxD"}
1
+ {"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["import { renderTrans, type TransProps } from '@verbaly/react/server';\nimport { cookies, headers } from 'next/headers';\nimport * as React from 'react';\nimport {\n alternateLinks,\n localeFromPath,\n LOCALE_STORAGE_KEY,\n resolveRequestLocale,\n warnOnce,\n type AlternateLink,\n type Locale,\n type Translate,\n type Verbaly,\n} from 'verbaly';\nimport {\n createRequestInstance,\n loadMessages,\n locales,\n requestOptions,\n routing,\n sourceLocale,\n} from 'virtual:verbaly';\n\ninterface RequestState {\n locale: string;\n instance: Verbaly;\n}\n\n// React.cache = per-request dedupe in RSC; identity fallback keeps plain-node tests runnable\nconst perRequest: <T extends (...args: never[]) => unknown>(fn: T) => T =\n (React as { cache?: <T>(fn: T) => T }).cache ?? ((fn) => fn);\n\ninterface LocaleHolder {\n locale?: string;\n}\n\nconst scopedHolder = perRequest((): LocaleHolder => ({}));\nconst moduleHolder: LocaleHolder = {};\n\n// React.cache only holds inside a request, and outside one there is a single request to hold for\nfunction holder(): LocaleHolder {\n const scoped = scopedHolder();\n return scoped === scopedHolder() ? scoped : moduleHolder;\n}\n\n// call it from the layout with the [locale] segment: reading headers() kills static rendering\nexport function setRequestLocale(locale: string): void {\n // a segment says the url carries the locale, and no-prefix tells every url helper it does not\n if (routing === 'no-prefix') {\n warnOnce(\n `setRequestLocale got a locale segment while routing is \"no-prefix\": if your urls start ` +\n `with the locale, set routing to 'prefix-all' or 'prefix-except-source' in your verbaly config`,\n );\n }\n holder().locale = locale;\n}\n\n// a route segment is a url segment, so it narrows like one: a slug must never become a locale\nfunction declaredLocale(): string | undefined {\n const raw = holder().locale;\n if (raw === undefined) return undefined;\n const match = localeFromPath({ supported: locales, path: `/${raw}` });\n if (match) return match;\n warnOnce(`setRequestLocale was given a locale the project does not have, so it was ignored`);\n return undefined;\n}\n\n// a locale asked for by name narrows the same way, and one the project lacks falls to the source\nfunction namedLocale(raw: string): string {\n const match = localeFromPath({ supported: locales, path: `/${raw}` });\n if (match) return match;\n warnOnce(`getT was asked for a locale the project does not have, so it answers in the source`);\n return sourceLocale;\n}\n\n// one instance per locale and request: an OG image, a sitemap or an email asks without headers()\nconst instanceFor = perRequest((locale: string) => createRequestInstance(locale));\n\n// only reached when no segment declared it: this read is what opts a route out of static\nasync function negotiate(): Promise<string> {\n const cookieName = requestOptions?.cookie ?? LOCALE_STORAGE_KEY;\n const headerStore = await headers();\n const cookieValue = cookieName === false ? undefined : (await cookies()).get(cookieName)?.value;\n return resolveRequestLocale({\n supported: locales,\n routing,\n cookie: cookieValue,\n header: headerStore.get('accept-language'),\n fallback: requestOptions?.fallback ?? sourceLocale,\n });\n}\n\nconst getRequestState = perRequest(async (): Promise<RequestState> => {\n const locale = declaredLocale() ?? (await negotiate());\n return { locale, instance: await createRequestInstance(locale) };\n});\n\nexport interface AlternatesOptions {\n path: string;\n baseUrl?: string;\n}\n\n// the hreflang set for generateMetadata, in the shape Next's alternates field takes\nexport function getAlternates(options: AlternatesOptions): {\n canonical?: string;\n languages: Record<string, string>;\n} {\n const links: AlternateLink[] = alternateLinks({\n supported: locales,\n sourceLocale,\n routing,\n path: options.path,\n baseUrl: options.baseUrl,\n });\n const languages: Record<string, string> = {};\n for (const link of links) languages[link.hreflang] = link.href;\n const self = localeFromPath({ supported: locales, path: options.path }) ?? sourceLocale;\n return { canonical: languages[self], languages };\n}\n\n// request-scoped instance: never the virtual:verbaly singleton (locale would leak between requests)\nexport async function getVerbaly(): Promise<Verbaly> {\n return (await getRequestState()).instance;\n}\n\nexport interface GetTOptions {\n locale?: string;\n}\n\n// with a locale it never reads headers(), so a route that only renders it stays static\nexport async function getT(options: GetTOptions = {}): Promise<Translate> {\n if (options.locale !== undefined) return (await instanceFor(namedLocale(options.locale))).t;\n return (await getRequestState()).instance.t;\n}\n\nexport async function getRequestLocale(): Promise<Locale> {\n return (await getRequestState()).locale as Locale;\n}\n\n// a Server Component: the request's instance, so a server render needs no provider\nexport async function Trans(props: TransProps): Promise<React.ReactElement> {\n return renderTrans(props.instance ?? (await getVerbaly()), props);\n}\n\nexport interface VerbalyProviderProps {\n locale: string;\n messages?: Record<string, string>;\n}\n\n// messages omitted for the source locale: it already ships inline in the client bundle\nexport async function getVerbalyProps(): Promise<VerbalyProviderProps> {\n const { locale } = await getRequestState();\n if (locale === sourceLocale) return { locale };\n return { locale, messages: await loadMessages(locale) };\n}\n"],"mappings":";;;;;;AA6BA,MAAM,aACH,MAAsC,WAAW,OAAO;AAM3D,MAAM,eAAe,kBAAgC,CAAC,EAAE;AACxD,MAAM,eAA6B,CAAC;AAGpC,SAAS,SAAuB;CAC9B,MAAM,SAAS,aAAa;CAC5B,OAAO,WAAW,aAAa,IAAI,SAAS;AAC9C;AAGA,SAAgB,iBAAiB,QAAsB;CAErD,IAAI,YAAY,aACd,SACE,wLAEF;CAEF,OAAO,CAAC,CAAC,SAAS;AACpB;AAGA,SAAS,iBAAqC;CAC5C,MAAM,MAAM,OAAO,CAAC,CAAC;CACrB,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAA;CAC9B,MAAM,QAAQ,eAAe;EAAE,WAAW;EAAS,MAAM,IAAI;CAAM,CAAC;CACpE,IAAI,OAAO,OAAO;CAClB,SAAS,kFAAkF;AAE7F;AAGA,SAAS,YAAY,KAAqB;CACxC,MAAM,QAAQ,eAAe;EAAE,WAAW;EAAS,MAAM,IAAI;CAAM,CAAC;CACpE,IAAI,OAAO,OAAO;CAClB,SAAS,oFAAoF;CAC7F,OAAO;AACT;AAGA,MAAM,cAAc,YAAY,WAAmB,sBAAsB,MAAM,CAAC;AAGhF,eAAe,YAA6B;CAC1C,MAAM,aAAa,gBAAgB,UAAU;CAC7C,MAAM,cAAc,MAAM,QAAQ;CAClC,MAAM,cAAc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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verbaly/next",
3
- "version": "0.67.0",
3
+ "version": "0.69.0",
4
4
  "description": "Next.js integration for Verbaly: App Router/RSC with per-request locale negotiation, Turbopack and webpack support, flash-free hydration.",
5
5
  "keywords": [
6
6
  "i18n",
@@ -64,23 +64,23 @@
64
64
  "access": "public"
65
65
  },
66
66
  "dependencies": {
67
- "@verbaly/compiler": "^0.67.0"
67
+ "@verbaly/compiler": "^0.69.0"
68
68
  },
69
69
  "peerDependencies": {
70
- "@verbaly/react": "^0.67.0",
70
+ "@verbaly/react": "^0.69.0",
71
71
  "next": "^15.0.0 || ^16.0.0",
72
72
  "react": "^18.0.0 || ^19.0.0",
73
- "verbaly": "^0.67.0"
73
+ "verbaly": "^0.69.0"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@types/react": "^19.3.0",
77
77
  "@types/react-dom": "^19.3.0",
78
- "@verbaly/react": "^0.67.0",
78
+ "@verbaly/react": "^0.69.0",
79
79
  "happy-dom": "^20.14.5",
80
- "next": "^16.3.8",
80
+ "next": "^16.4.0",
81
81
  "react": "^19.3.0",
82
82
  "react-dom": "^19.3.0",
83
- "verbaly": "^0.67.0"
83
+ "verbaly": "^0.69.0"
84
84
  },
85
85
  "scripts": {
86
86
  "build": "tsdown",