Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/ThemeTranslations.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ An override file only has to contain the keys it changes; every other key falls
file. A theme also does not have to provide a file for every language.

The build copies these files to `assets/<theme>/i18n/<lang>.json5` in the output, where the
translate loaders pick them up.
server loader picks them up. Like the base files, they are also copied as
`assets/<theme>/i18n/<lang>.<hash>.json` with a content hash in the name; the browser requests
that copy, so a changed translation is never served from the browser cache.

The build also records which themes provide a file for which language, so the browser only
requests override files that exist; a theme without overrides is not requested at all. That
Expand Down
69 changes: 46 additions & 23 deletions src/ngx-translate-loaders/translate-browser.loader.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ describe('TranslateBrowserLoader', () => {
let http: { get: jasmine.Spy };
let loader: TranslateBrowserLoader;
let originalThemes: typeof environment.themes;
let themeLanguages: jasmine.Spy;
let originalProduction: boolean;
let themeLanguageHashes: jasmine.Spy;

/** Match the base i18n request regardless of the production content hash. */
const isBaseRequest = (url: string): boolean => url.startsWith(`${PREFIX}en`) && url.endsWith(SUFFIX);
Expand All @@ -28,19 +29,23 @@ describe('TranslateBrowserLoader', () => {
loader = new TranslateBrowserLoader(transferState as any, http as any, PREFIX, SUFFIX);
// Default to every configured theme having an override, so the merge expectations
// below need no setup; tests that check which files are requested override this.
themeLanguages = spyOn(loader as any, 'themeLanguages').and.callFake(() => {
const declared: Record<string, string[]> = {};
themeLanguageHashes = spyOn(loader as any, 'themeLanguageHashes').and.callFake(() => {
const declared: Record<string, Record<string, string>> = {};
(environment.themes ?? []).forEach((theme: any) => {
declared[theme.name] = ['en'];
declared[theme.name] = { 'en.json5': 'abc123' };
});
return declared;
});
originalThemes = environment.themes;
originalProduction = environment.production;
// other specs may leave production on; the tests below expect unhashed file names unless they set it
environment.production = false;
spyOn(console, 'warn');
});

afterEach(() => {
environment.themes = originalThemes;
environment.production = originalProduction;
});

it('returns the cached translations from the TransferState without any HTTP call', (done) => {
Expand All @@ -61,7 +66,7 @@ describe('TranslateBrowserLoader', () => {
if (isBaseRequest(url)) {
return of(JSON.stringify({ 'home.title': 'Base', 'home.subtitle': 'Base sub' }));
}
if (url === 'assets/custom/i18n/en.json5') {
if (url === 'assets/custom/i18n/en.json') {
return of('{ "home.title": "Custom" }');
}
return throwError(() => new Error('404'));
Expand All @@ -86,13 +91,31 @@ describe('TranslateBrowserLoader', () => {
loader.getTranslation('en').subscribe((messages) => {
expect(messages).toEqual({ 'home.title': 'Base' });
expect(console.warn).toHaveBeenCalledWith(
'[TranslateBrowserLoader] Failed to load theme i18n file assets/custom/i18n/en.json5:',
'[TranslateBrowserLoader] Failed to load theme i18n file assets/custom/i18n/en.json:',
jasmine.any(Error),
);
done();
});
});

it('requests the theme override file by its content hash in production', (done) => {
environment.production = true;
environment.themes = [{ name: 'custom' }];
transferState.get.and.returnValue({});
http.get.and.callFake((url: string) => {
if (url === 'assets/custom/i18n/en.abc123.json') {
return of(JSON.stringify({ 'home.title': 'Custom' }));
}
return of(JSON.stringify({ 'home.title': 'Base' }));
});

loader.getTranslation('en').subscribe((messages) => {
expect(messages).toEqual({ 'home.title': 'Custom' });
expect(http.get).toHaveBeenCalledWith('assets/custom/i18n/en.abc123.json', jasmine.anything());
done();
});
});

it('warns and returns no translations when the base file cannot be loaded', (done) => {
environment.themes = [];
transferState.get.and.returnValue({});
Expand All @@ -112,11 +135,11 @@ describe('TranslateBrowserLoader', () => {
if (isBaseRequest(url)) {
return of(JSON.stringify({ key: 'base' }));
}
if (url === 'assets/parent-theme/i18n/en.json5') {
return of('{ key: "parent" }');
if (url === 'assets/parent-theme/i18n/en.json') {
return of(JSON.stringify({ key: 'parent' }));
}
if (url === 'assets/child-theme/i18n/en.json5') {
return of('{ key: "child" }');
if (url === 'assets/child-theme/i18n/en.json') {
return of(JSON.stringify({ key: 'child' }));
}
return throwError(() => new Error('404'));
});
Expand Down Expand Up @@ -155,12 +178,12 @@ describe('TranslateBrowserLoader', () => {
if (isBaseRequest(url)) {
return of(JSON.stringify({ key: 'base' }));
}
if (url === 'assets/parent-theme/i18n/en.json5') {
return of('{ key: "parent" }');
if (url === 'assets/parent-theme/i18n/en.json') {
return of(JSON.stringify({ key: 'parent' }));
}
if (url === 'assets/sibling-theme/i18n/en.json5') {
if (url === 'assets/sibling-theme/i18n/en.json') {
// sibling has its own value for the same key — must NOT win when parent-theme is active
return of('{ key: "sibling" }');
return of(JSON.stringify({ key: 'sibling' }));
}
return throwError(() => new Error('404'));
});
Expand All @@ -183,10 +206,10 @@ describe('TranslateBrowserLoader', () => {
if (isBaseRequest(url)) {
return of(JSON.stringify({ 'key.a': 'base-a', 'key.b': 'base-b' }));
}
if (url === 'assets/parent-theme/i18n/en.json5') {
if (url === 'assets/parent-theme/i18n/en.json') {
return of('{ "key.a": "parent-a" }');
}
if (url === 'assets/child-theme/i18n/en.json5') {
if (url === 'assets/child-theme/i18n/en.json') {
return of('{ "key.b": "child-b" }');
}
return throwError(() => new Error('404'));
Expand All @@ -202,7 +225,7 @@ describe('TranslateBrowserLoader', () => {
it('does not request any theme override file when the build contains none for the language', (done) => {
// Requesting a file that was never built costs a 404 and delays the first render.
environment.themes = [{ name: 'dspace' }];
themeLanguages.and.returnValue({});
themeLanguageHashes.and.returnValue({});
transferState.get.and.returnValue({});
http.get.and.callFake((url: string) => {
if (isBaseRequest(url)) {
Expand All @@ -214,7 +237,7 @@ describe('TranslateBrowserLoader', () => {
loader.getTranslation('en').subscribe((messages) => {
expect(messages).toEqual({ 'home.title': 'Base' });
expect(http.get).toHaveBeenCalledTimes(1);
expect(http.get).not.toHaveBeenCalledWith('assets/dspace/i18n/en.json5', jasmine.anything());
expect(http.get).not.toHaveBeenCalledWith('assets/dspace/i18n/en.json', jasmine.anything());
done();
});
});
Expand All @@ -225,22 +248,22 @@ describe('TranslateBrowserLoader', () => {
{ name: 'parent-theme' },
];
// Only the ancestor ships an override, so the active child theme must not be requested.
themeLanguages.and.returnValue({ 'parent-theme': ['en'] });
themeLanguageHashes.and.returnValue({ 'parent-theme': { 'en.json5': 'abc123' } });
transferState.get.and.returnValue({});
http.get.and.callFake((url: string) => {
if (isBaseRequest(url)) {
return of(JSON.stringify({ key: 'base' }));
}
if (url === 'assets/parent-theme/i18n/en.json5') {
return of('{ key: "parent" }');
if (url === 'assets/parent-theme/i18n/en.json') {
return of(JSON.stringify({ key: 'parent' }));
}
return throwError(() => new Error('404'));
});

loader.getTranslation('en').subscribe((messages) => {
expect(messages.key).toBe('parent');
expect(http.get).toHaveBeenCalledWith('assets/parent-theme/i18n/en.json5', jasmine.anything());
expect(http.get).not.toHaveBeenCalledWith('assets/child-theme/i18n/en.json5', jasmine.anything());
expect(http.get).toHaveBeenCalledWith('assets/parent-theme/i18n/en.json', jasmine.anything());
expect(http.get).not.toHaveBeenCalledWith('assets/child-theme/i18n/en.json', jasmine.anything());
done();
});
});
Expand Down
22 changes: 12 additions & 10 deletions src/ngx-translate-loaders/translate-browser.loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { AppConfig } from '@dspace/config/app-config.interface';
import { getDefaultThemeConfig } from '@dspace/config/config.util';
import { hasValue } from '@dspace/shared/utils/empty.util';
import { TranslateLoader } from '@ngx-translate/core';
import JSON5 from 'json5';
import {
forkJoin,
Observable,
Expand All @@ -26,7 +25,7 @@ import { resolveActiveThemeChain } from './theme-i18n.util';
* A TranslateLoader for ngx-translate to retrieve i18n messages from the TransferState, or download
* them if they're not available there.
*
* Also fetches per-theme translation overrides from `assets/<theme>/i18n/<lang>.json5` for the
* Also fetches per-theme translation overrides from `assets/<theme>/i18n/<lang>.<hash>.json` for the
* active theme and its ancestors (root → active), merging them on top of the base translations
* so the active theme's keys win. Only the active theme's inheritance chain is loaded — sibling
* themes are excluded to prevent cross-theme key pollution.
Expand Down Expand Up @@ -95,13 +94,16 @@ export class TranslateBrowserLoader implements TranslateLoader {
}

/**
* Fetch the override JSON5 file for the given theme/language.
* Returns an empty object if the file is missing (most themes won't override every language).
* Fetch the override file for the given theme/language (the hashed JSON produced by the build pipeline).
* Returns an empty object if the file can't be loaded.
*/
protected fetchThemeOverride(themeName: string, lang: string): Observable<Record<string, string>> {
const url = `assets/${themeName}/i18n/${lang}.json5`;
const translationHash: string = environment.production
? `.${this.themeLanguageHashes()[themeName]?.[lang + '.json5']}`
: '';
const url = `assets/${themeName}/i18n/${lang}${translationHash}.json`;
return this.http.get(url, { responseType: 'text' }).pipe(
map((text: string) => JSON5.parse(text) as Record<string, string>),
map((json: string) => JSON.parse(json) as Record<string, string>),
catchError((error: unknown) => {
// eslint-disable-next-line no-console
console.warn(`[TranslateBrowserLoader] Failed to load theme i18n file ${url}:`, error);
Expand All @@ -111,17 +113,17 @@ export class TranslateBrowserLoader implements TranslateLoader {
}

/**
* The languages each theme provides an override file for, as collected at build time
* The hashes of the i18n override files of each theme, as collected at build time
*/
protected themeLanguages(): Record<string, string[]> {
return (process.env.themeLanguages as any) ?? {};
protected themeLanguageHashes(): Record<string, Record<string, string>> {
return (process.env.themeLanguageHashes as any) ?? {};
}

/**
* Whether the build contains an i18n override file for this theme and language.
* Requesting a file that isn't there costs a 404 before the merge can complete.
*/
protected hasThemeOverride(themeName: string, lang: string): boolean {
return this.themeLanguages()[themeName]?.includes(lang) === true;
return this.themeLanguageHashes()[themeName]?.[lang + '.json5'] !== undefined;
}
}
19 changes: 8 additions & 11 deletions webpack/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,15 @@ export function getFileHashes(folderPath: string, regExp: RegExp): { [fileName:
}

/**
* Collect the languages each theme provides an i18n override file for, e.g. { custom: ['en'] }
* Calculate the hashes of the i18n override files of each theme, e.g. { custom: { 'en.json5': '<hash>' } }
*
* @param themesPath The path of the folder containing the themes
*/
export function getThemeLanguages(themesPath: string): { [themeName: string]: string[] } {
const extension = '.json5';
const themeLanguages: { [themeName: string]: string[] } = {};
export function getThemeLanguageHashes(themesPath: string): { [themeName: string]: { [fileName: string]: string } } {
const themeHashes: { [themeName: string]: { [fileName: string]: string } } = {};

if (!existsSync(themesPath)) {
return themeLanguages;
return themeHashes;
}

for (const theme of readdirSync(themesPath)) {
Expand All @@ -76,14 +75,12 @@ export function getThemeLanguages(themesPath: string): { [themeName: string]: st
continue;
}

const languages: string[] = readdirSync(i18nPath)
.filter((file: string) => file.endsWith(extension) && statSync(join(i18nPath, file)).isFile())
.map((file: string) => file.slice(0, -extension.length));
const hashes = getFileHashes(i18nPath, /.*\.json5/g);

if (languages.length > 0) {
themeLanguages[theme] = languages;
if (Object.keys(hashes).length > 0) {
themeHashes[theme] = hashes;
}
}

return themeLanguages;
return themeHashes;
}
21 changes: 19 additions & 2 deletions webpack/webpack.common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { EnvironmentPlugin } from 'webpack';
import {
calculateFileHash,
getFileHashes,
getThemeLanguages,
getThemeLanguageHashes,
globalCSSImports,
projectRoot,
} from './helpers';
Expand Down Expand Up @@ -57,6 +57,23 @@ export const copyWebpackOptions = {
}
},
},
{
// theme i18n override files get a content hash as well, like the base files above
from: join(__dirname, '..', 'src', 'themes', '*', 'assets', 'i18n', '*.json5').replace(/\\/g, '/'),
noErrorOnMissing: true,
to({ absoluteFilename }) {
// use [\/|\\] to match both POSIX and Windows separators
const matches = absoluteFilename.match(/.*[\/|\\]themes[\/|\\]([^\/|^\\]+)[\/|\\]assets[\/|\\]i18n[\/|\\](.+)\.json5$/);
if (matches) {
const fileHash: string = process.env.NODE_ENV === 'production' ? `.${calculateFileHash(absoluteFilename)}` : '';
// e.g. themes/custom/assets/i18n/en.json5 will end up in assets/custom/i18n/en.<hash>.json
return join('assets', matches[1], 'i18n', `${matches[2]}${fileHash}.json`);
}
},
transform(content) {
return JSON.stringify(parse(content.toString()));
},
},
{
from: join(__dirname, '..', 'src', 'robots.txt.ejs'),
to: 'assets/robots.txt.ejs',
Expand Down Expand Up @@ -87,7 +104,7 @@ export const commonExports = {
new GenerateDecoratorRegistriesPlugin(),
new EnvironmentPlugin({
languageHashes: getFileHashes(join(__dirname, '..', 'src', 'assets', 'i18n'), /.*\.json5/g),
themeLanguages: getThemeLanguages(join(__dirname, '..', 'src', 'themes')),
themeLanguageHashes: getThemeLanguageHashes(join(__dirname, '..', 'src', 'themes')),
}),
new CopyWebpackPlugin(copyWebpackOptions),
],
Expand Down
Loading