import type { Plugin, ModuleInfo, OutputBundle } from "rollup"; /** Shape of the ..translations.json asset emitted into the rollup bundle. */ export interface TranslationsAsset { messages: Array>; } /** Suffix used for translations assets (e.g. .translations.json, dashboard.translations.json). */ export const TRANSLATIONS_SUFFIX = ".translations.json"; /** Module that `t()` must be imported from for its messages to be collected. */ const SN_TRANSLATE_MODULE = "sn-translate"; function walk( node: unknown, visitor: (node: Record) => void, ): void { if (!node || typeof node !== "object") return; const n = node as Record; visitor(n); for (const key of Object.keys(n)) { const child = n[key]; if (Array.isArray(child)) { for (const item of child) { if ( item && typeof item === "object" && (item as { type?: unknown }).type ) { walk(item, visitor); } } } else if ( child && typeof child === "object" && (child as { type?: unknown }).type ) { walk(child, visitor); } } } /** * Derive a per-page translations filename from the HTML asset in the bundle. * e.g. admin/settings.html → admin/settings.translations.json * Returns undefined when no HTML asset exists (single-entry / non-HTML builds). */ const translationsNameFromHtml = (bundle: OutputBundle): string | undefined => { const html = Object.values(bundle).find( (o) => o.type === "asset" && o.fileName.endsWith(".html"), ); if (!html) return undefined; return html.fileName.replace(/\.html$/, TRANSLATIONS_SUFFIX); }; /** * Rollup plugin that collects every string literal passed to `t()` imported * from `sn-translate` and emits them as a `.translations.json` asset in the * bundle so downstream plugins (e.g. snTranslateRecords in @servicenow/sdk-repack) * can consume them without shared closure state. * * In multi-entry builds each HTML page gets its own translations file * (e.g. dashboard.translations.json) so that only that page's messages * are injected into its HTML. Identical messages across pages naturally * coalesce via explicitId in the downstream static-content-plugin. */ export function collectSnTranslate(): Plugin { const messages = new Set(); const objectMessages = new Map>(); return { name: "collect-sn-translate", buildStart() { messages.clear(); objectMessages.clear(); }, moduleParsed(moduleInfo: ModuleInfo) { // Rolldown (the bundler behind Vite 8) does not implement ModuleInfo#ast. // ModuleInfo#code and PluginContext#parse are implemented by both Rollup // and Rolldown, so parse on demand rather than reading a prebuilt AST. // The substring check keeps that extra parse off every unrelated module. const code = moduleInfo.code; if (!code || !code.includes(SN_TRANSLATE_MODULE)) return; const ast = this.parse(code) as unknown as { body: Array>; }; // Find local name(s) of `t` imported from sn-translate const tNames = new Set(); for (const node of ast.body) { if ( node["type"] === "ImportDeclaration" && (node["source"] as { value?: unknown })["value"] === SN_TRANSLATE_MODULE ) { const specifiers = node["specifiers"] as Array< Record >; for (const specifier of specifiers) { if ( specifier["type"] === "ImportSpecifier" && (specifier["imported"] as { name?: unknown })["name"] === "t" ) { tNames.add((specifier["local"] as { name: string })["name"]); } } } } if (tNames.size === 0) return; // Collect every unique first arg to t() in this module walk(ast, (node) => { const args = node["arguments"] as | Array> | undefined; const firstArg = args?.[0]; const callee = node["callee"] as Record | undefined; if ( node["type"] !== "CallExpression" || callee?.["type"] !== "Identifier" || !tNames.has(callee["name"] as string) ) { return; } if (firstArg?.["type"] === "Literal" && firstArg["value"]) { messages.add(firstArg["value"] as string); } else if (firstArg?.["type"] === "ObjectExpression") { const properties = firstArg["properties"] as | Array> | undefined; if (!properties) return; const obj: Record = {}; for (const prop of properties) { if (prop["type"] !== "Property") continue; const key = prop["key"] as Record; const val = prop["value"] as Record; // Identifier keys (unquoted) use .name; Literal keys (quoted) use .value const k = key["type"] === "Identifier" ? (key["name"] as string) : (key["value"] as string); const v = val["value"] as string; if (k !== undefined && typeof v === "string") obj[k] = v; } if (Object.keys(obj).length > 0) objectMessages.set(JSON.stringify(obj), obj); } }); }, generateBundle(_, bundle) { // Derive a per-page filename from the HTML asset when present // (e.g. admin/settings.html → admin/settings.translations.json). // Falls back to the generic .translations.json for single-entry builds. const fileName = translationsNameFromHtml(bundle) ?? TRANSLATIONS_SUFFIX; const asset: TranslationsAsset = { messages: [...messages, ...objectMessages.values()], }; this.emitFile({ type: "asset", fileName, source: JSON.stringify(asset, null, 2), }); }, }; }