Skip to content

Commit

Permalink
perf: prevent compiling translations with very large values (#880)
Browse files Browse the repository at this point in the history
Co-authored-by: max.kless@googlemail.com <max.kless@googlemail.com>
  • Loading branch information
dhhyi and MaxKless authored Sep 23, 2021
1 parent 46be038 commit 36aebad
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
2 changes: 2 additions & 0 deletions docs/concepts/localization.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ The PWA uses an [ICU Message Format](https://unicode-org.github.io/icu/userguide
Have a look at the spec for [PWATranslateCompiler](../../src/app/core/utils/translate/pwa-translate-compiler.spec.ts) for an overview of supported methods.
> :warning: Translations with large values (> 1000 characters) will not be compiled to improve performance. We recommend using CMS components instead. If you _really_ need to increase this limit, adapt the `MAX_COMPILATION_LENGTH` variable of [PWATranslateCompiler](../../src/app/core/utils/translate/pwa-translate-compiler.ts).
### Localization with Formatted Dates
The date pipe is used as formatter in texts with dates.
Expand Down
18 changes: 16 additions & 2 deletions src/app/core/utils/translate/pwa-translate-compiler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable, Injector } from '@angular/core';
import { Injectable, Injector, isDevMode } from '@angular/core';
import { TranslateCompiler, TranslateService } from '@ngx-translate/core';

import { Translations } from './translations.type';
Expand All @@ -9,6 +9,8 @@ const cache: Record<string, Function> = {};
export class PWATranslateCompiler implements TranslateCompiler {
constructor(private injector: Injector) {}

private static MAX_COMPILATION_LENGTH = 1000;

/**
* regular expression for grabbing everything in the form:
* {{<variable>, plural/select, <case>...<case>}}
Expand Down Expand Up @@ -124,10 +126,22 @@ export class PWATranslateCompiler implements TranslateCompiler {
return template;
}

private sanityCheck(key: string, value: string | Function): boolean {
const sane = typeof value !== 'string' || value.length <= PWATranslateCompiler.MAX_COMPILATION_LENGTH;
if (isDevMode() && !sane) {
console.warn(
'Not compiling translation with key',
key,
'as it is too big! - Use CMS! - This is a development mode only warning and can be ignored if the behavior is intended.'
);
}
return sane;
}

compileTranslations(translations: Translations): Translations {
return Object.entries(translations)
.map<[string, string | Function]>(([key, value]) => {
if (this.checkIfCompileNeeded(value)) {
if (this.sanityCheck(key, value) && this.checkIfCompileNeeded(value)) {
return [key, this.compile(value as string)];
}
return [key, value];
Expand Down

0 comments on commit 36aebad

Please sign in to comment.