import type { Plugin, ModuleInfo, NormalizedOutputOptions, OutputAsset, } from "rollup"; import { rollup } from "rollup"; import { collectSnTranslate, type TranslationsAsset, } from "../../src/sn-translate"; const TRANSLATIONS_SUFFIX = ".translations.json"; type ModuleParsedHook = ( this: { parse: (code: string) => unknown }, info: ModuleInfo, ) => void | Promise; // The plugin parses ModuleInfo#code via PluginContext#parse, which both Rollup // and Rolldown implement, so the hook needs a context supplying `parse`. Take // it from a real Rollup plugin context rather than importing rollup/parseAst, // which this jest project's "node" moduleResolution cannot resolve. Rolldown's // (oxc) parser produces the same shapes for the nodes read below, but cannot be // exercised here: it and vite are ESM-only and this jest project runs as CJS. const rollupCtx = { parse: (_code: string): unknown => { throw new Error("rollup parser not captured yet"); }, }; beforeAll(async () => { const bundle = await rollup({ input: "virtual:entry", plugins: [ { name: "capture-parse", resolveId: (id) => (id === "virtual:entry" ? id : null), load: (id) => (id === "virtual:entry" ? "export default 1;" : null), moduleParsed() { const ctx = this; rollupCtx.parse = (code: string) => ctx.parse(code); }, }, ], }); await bundle.close(); }); type GenerateBundleHook = ( this: { emitFile: (file: { type: string; fileName: string; source: string; }) => string; }, options: NormalizedOutputOptions, bundle: Record, ) => void | Promise; // Build a minimal ModuleInfo from source code using rollup's own parser async function makeModuleInfo(code: string): Promise { let capturedInfo: ModuleInfo | undefined; const bundle = await rollup({ input: "virtual:entry", plugins: [ { name: "virtual", resolveId(id) { if (id === "virtual:entry" || id === "virtual:sn-translate") return id; return null; }, load(id) { if (id === "virtual:entry") return code; if (id === "virtual:sn-translate") return "export const t = (s) => s;"; return null; }, moduleParsed(info) { if (info.id === "virtual:entry") capturedInfo = info; }, }, ], }); await bundle.close(); if (!capturedInfo) throw new Error("Module info not captured"); return capturedInfo; } // Run the full rollup pipeline and capture the emitted translations asset async function buildAndGetTranslations( code: string, ): Promise { let translationsSource: string | undefined; const bundle = await rollup({ input: "virtual:entry", plugins: [ { name: "virtual", resolveId(id) { if (id === "virtual:entry" || id === "virtual:sn-translate") return id; return null; }, load(id) { if (id === "virtual:entry") return code; if (id === "virtual:sn-translate") return "export const t = (s) => s;"; return null; }, }, collectSnTranslate(), ], }); const { output } = await bundle.generate({ format: "es" }); await bundle.close(); for (const chunk of output) { if (chunk.type === "asset" && chunk.fileName === TRANSLATIONS_SUFFIX) { translationsSource = chunk.source as string; } } if (!translationsSource) throw new Error(`${TRANSLATIONS_SUFFIX} not emitted`); return JSON.parse(translationsSource) as TranslationsAsset; } describe("collectSnTranslate", () => { describe("plugin shape", () => { test("returns a rollup Plugin named collect-sn-translate", () => { const plugin = collectSnTranslate(); expect(plugin.name).toBe("collect-sn-translate"); }); test("has moduleParsed and generateBundle hooks", () => { const plugin = collectSnTranslate(); expect(typeof plugin.moduleParsed).toBe("function"); expect(typeof plugin.generateBundle).toBe("function"); }); }); describe("emitted .translations.json asset", () => { test("emits .translations.json with empty messages when no sn-translate import", async () => { const asset = await buildAndGetTranslations( `console.log('no translations here');`, ); expect(asset.messages).toEqual([]); }); test("emits the collected message string", async () => { const asset = await buildAndGetTranslations( `import { t } from 'sn-translate'; t('Hello world');`, ); expect(asset.messages).toEqual(["Hello world"]); }); test("emits multiple distinct messages", async () => { const asset = await buildAndGetTranslations( `import { t } from 'sn-translate'; t('First message'); t('Second message');`, ); expect(asset.messages).toEqual(["First message", "Second message"]); }); test("deduplicates identical message strings", async () => { const asset = await buildAndGetTranslations( `import { t } from 'sn-translate'; t('Hello world'); t('Hello world');`, ); expect(asset.messages).toEqual(["Hello world"]); }); test("handles t aliased to a different local name", async () => { const asset = await buildAndGetTranslations( `import { t as translate } from 'sn-translate'; translate('Aliased');`, ); expect(asset.messages).toEqual(["Aliased"]); }); test("ignores t() calls with non-literal first arguments", async () => { const asset = await buildAndGetTranslations( `import { t } from 'sn-translate'; const key = 'dynamic'; t(key);`, ); expect(asset.messages).toEqual([]); }); test("ignores imports of t from other packages", async () => { const asset = await buildAndGetTranslations( `import { t } from 'other-package'; t('Not from sn-translate');`, ); expect(asset.messages).toEqual([]); }); test("preserves messages with single-quote characters", async () => { const asset = await buildAndGetTranslations( `import { t } from 'sn-translate'; t("This isn't a translated string");`, ); expect(asset.messages).toEqual(["This isn't a translated string"]); }); test("collects object arg with quoted string keys", async () => { const asset = await buildAndGetTranslations( `import { t } from 'sn-translate'; t({ "code": "abc-123", "message": "Hello world", "comment": "A greeting" });`, ); expect(asset.messages).toEqual([ { code: "abc-123", message: "Hello world", comment: "A greeting" }, ]); }); test("collects object arg with unquoted identifier keys", async () => { const asset = await buildAndGetTranslations( `import { t } from 'sn-translate'; t({ code: "abc-123", message: "Hello world" });`, ); expect(asset.messages).toEqual([ { code: "abc-123", message: "Hello world" }, ]); }); test("deduplicates identical object args", async () => { const asset = await buildAndGetTranslations( `import { t } from 'sn-translate'; t({ code: "abc-123", message: "Hello world" }); t({ code: "abc-123", message: "Hello world" });`, ); expect(asset.messages).toEqual([ { code: "abc-123", message: "Hello world" }, ]); }); test("collects both string and object args from same module", async () => { const asset = await buildAndGetTranslations( `import { t } from 'sn-translate'; t('Plain string'); t({ code: "obj-001", message: "Object message" });`, ); expect(asset.messages).toEqual([ "Plain string", { code: "obj-001", message: "Object message" }, ]); }); test("emits well-formed JSON", async () => { const bundle = await rollup({ input: "virtual:entry", plugins: [ { name: "virtual", resolveId(id) { if (id === "virtual:entry") return id; return null; }, load(id) { if (id === "virtual:entry") return `export default 42;`; return null; }, }, collectSnTranslate(), ], }); const { output } = await bundle.generate({ format: "es" }); await bundle.close(); const asset = output.find( (c): c is OutputAsset => c.type === "asset" && c.fileName === TRANSLATIONS_SUFFIX, ); expect(asset).toBeDefined(); expect(() => JSON.parse(asset!.source as string)).not.toThrow(); }); }); describe("per-page translations naming", () => { test("uses HTML asset stem when present in the bundle", async () => { const plugin = collectSnTranslate(); const hook = plugin.moduleParsed as ModuleParsedHook; const generateBundle = plugin.generateBundle as GenerateBundleHook; const info = await makeModuleInfo( `import { t } from 'sn-translate'; t('Hello');`, ); await hook.call(rollupCtx, info); const emitted: { fileName: string; source: string }[] = []; await generateBundle.call( { emitFile(file) { emitted.push({ fileName: file.fileName, source: file.source }); return ""; }, }, {} as NormalizedOutputOptions, { "dashboard.html": { type: "asset", fileName: "dashboard.html", source: "", }, }, ); expect(emitted).toHaveLength(1); expect(emitted[0].fileName).toBe("dashboard.translations.json"); }); test("preserves subdirectory from HTML asset path", async () => { const plugin = collectSnTranslate(); const hook = plugin.moduleParsed as ModuleParsedHook; const generateBundle = plugin.generateBundle as GenerateBundleHook; const info = await makeModuleInfo( `import { t } from 'sn-translate'; t('Save');`, ); await hook.call(rollupCtx, info); const emitted: { fileName: string }[] = []; await generateBundle.call( { emitFile(file) { emitted.push({ fileName: file.fileName }); return ""; }, }, {} as NormalizedOutputOptions, { "admin/settings.html": { type: "asset", fileName: "admin/settings.html", source: "", }, }, ); expect(emitted[0].fileName).toBe("admin/settings.translations.json"); }); test("preserves deeply nested directory from HTML asset path", async () => { const plugin = collectSnTranslate(); const hook = plugin.moduleParsed as ModuleParsedHook; const generateBundle = plugin.generateBundle as GenerateBundleHook; const info = await makeModuleInfo( `import { t } from 'sn-translate'; t('Deep');`, ); await hook.call(rollupCtx, info); const emitted: { fileName: string }[] = []; await generateBundle.call( { emitFile(file) { emitted.push({ fileName: file.fileName }); return ""; }, }, {} as NormalizedOutputOptions, { "admin/pages/settings.html": { type: "asset", fileName: "admin/pages/settings.html", source: "", }, }, ); expect(emitted[0].fileName).toBe( "admin/pages/settings.translations.json", ); }); test("falls back to default name when no HTML asset exists", async () => { const plugin = collectSnTranslate(); const hook = plugin.moduleParsed as ModuleParsedHook; const generateBundle = plugin.generateBundle as GenerateBundleHook; const info = await makeModuleInfo( `import { t } from 'sn-translate'; t('Msg');`, ); await hook.call(rollupCtx, info); const emitted: { fileName: string }[] = []; await generateBundle.call( { emitFile(file) { emitted.push({ fileName: file.fileName }); return ""; }, }, {} as NormalizedOutputOptions, {}, ); expect(emitted[0].fileName).toBe(TRANSLATIONS_SUFFIX); }); }); describe("moduleParsed hook in isolation", () => { // Tests that verify AST-walking behaviour directly via the hook, // covering the deduplication across separate moduleParsed calls. test("deduplicates the same message seen in two separate moduleParsed calls", async () => { const plugin = collectSnTranslate(); const hook = plugin.moduleParsed as ModuleParsedHook; const emitted: string[] = []; const generateBundle = plugin.generateBundle as GenerateBundleHook; const info1 = await makeModuleInfo( `import { t } from 'sn-translate'; t('Shared');`, ); const info2 = await makeModuleInfo( `import { t } from 'sn-translate'; t('Shared');`, ); await hook.call(rollupCtx, info1); await hook.call(rollupCtx, info2); await generateBundle.call( { emitFile(file) { emitted.push(file.source); return ""; }, }, {} as NormalizedOutputOptions, {}, ); const asset = JSON.parse(emitted[0]) as TranslationsAsset; expect(asset.messages).toEqual(["Shared"]); }); }); // Rolldown (the bundler behind Vite 8) throws // "UNSUPPORTED: ModuleInfo#ast" on any access to ModuleInfo#ast, so the // plugin must parse ModuleInfo#code instead. See src/sn-translate/index.ts. describe("rolldown / Vite 8 compatibility", () => { // Mirrors Rolldown's transformModuleInfo: `code` is real, `ast` throws. const rolldownModuleInfo = (code: string): ModuleInfo => ({ id: "virtual:entry", code, get ast(): never { throw new Error("UNSUPPORTED: ModuleInfo#ast"); }, }) as unknown as ModuleInfo; const collect = async ( info: ModuleInfo, ctx: { parse: (code: string) => unknown }, ): Promise => { const plugin = collectSnTranslate(); await (plugin.moduleParsed as ModuleParsedHook).call(ctx, info); const emitted: string[] = []; await (plugin.generateBundle as GenerateBundleHook).call( { emitFile(file) { emitted.push(file.source); return ""; }, }, {} as NormalizedOutputOptions, {}, ); return JSON.parse(emitted[0]) as TranslationsAsset; }; test("never reads ModuleInfo#ast", async () => { const asset = await collect( rolldownModuleInfo(`import { t } from 'sn-translate'; t('From code');`), rollupCtx, ); expect(asset.messages).toEqual(["From code"]); }); test("does not throw when ModuleInfo#code is null", async () => { const info = { id: "external", code: null } as unknown as ModuleInfo; await expect(collect(info, rollupCtx)).resolves.toEqual({ messages: [] }); }); test("collects string and object messages from ModuleInfo#code", async () => { const asset = await collect( rolldownModuleInfo( `import { t } from 'sn-translate'; import { t as translate } from 'sn-translate'; t('Hello world'); translate('Aliased'); t({ code: "abc-123", message: "Hello world" });`, ), rollupCtx, ); expect(asset.messages).toEqual([ "Hello world", "Aliased", { code: "abc-123", message: "Hello world" }, ]); }); test("skips parsing modules that never mention sn-translate", async () => { const parse = jest.fn(rollupCtx.parse); const asset = await collect( rolldownModuleInfo(`export const answer = 42;`), { parse }, ); expect(parse).not.toHaveBeenCalled(); expect(asset.messages).toEqual([]); }); }); });