Skip to content

Commit 3d6dbd3

Browse files
committed
fix(@angular/build): keep generated locale polyfills cacheable
1 parent 8b26efa commit 3d6dbd3

7 files changed

Lines changed: 127 additions & 41 deletions

File tree

‎packages/angular/build/src/builders/application/i18n.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ export async function inlineI18n(
4545
warnings: string[];
4646
prerenderedRoutes: PrerenderedRoutesRecord;
4747
}> {
48-
const { i18nOptions, baseHref, cacheOptions } = options;
48+
const { i18nOptions, baseHref, cacheOptions, workspaceRoot } = options;
4949

5050
// Create the multi-threaded inliner with common options.
5151
const inliner = new I18nInliner(
@@ -56,6 +56,7 @@ export async function inlineI18n(
5656
: maxInlinerWorkers,
5757
persistentCachePath: cacheOptions.enabled ? cacheOptions.path : undefined,
5858
localizeVersion: i18nOptions.localizeVersion,
59+
workspaceRoot,
5960
},
6061
workerPool,
6162
);

‎packages/angular/build/src/tools/esbuild/application-code-bundle.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
SERVER_APP_MANIFEST_FILENAME,
2020
SERVER_GENERATED_EXTERNALS,
2121
} from '../../utils/server-rendering/manifest';
22+
import { loadLocaleData } from '../i18n/locale-data';
2223
import { AngularCompilationContext } from './angular/compilation-state';
2324
import { createCompilerPlugin } from './angular/compiler-plugin';
2425
import { ComponentStylesheetBundler } from './angular/component-stylesheets';
@@ -706,6 +707,22 @@ function getEsBuildCommonPolyfillsOptions(
706707
if (i18nOptions.shouldInline) {
707708
// Remove localize polyfill when i18n inline transformation have been applied to all the packages.
708709
polyfills = polyfills.filter((path) => !path.startsWith('@angular/localize'));
710+
711+
if (polyfills.length === 0 && !options.watch) {
712+
buildOptions.plugins.push({
713+
name: 'angular-locale-data-hash',
714+
async setup({ initialOptions }) {
715+
// The generated polyfills module only inlines the locale ID and locale data, not messages.
716+
// Account for both in the shared output hash before esbuild assigns the filename.
717+
const data = await Promise.all(
718+
Array.from(i18nOptions.inlineLocales)
719+
.sort()
720+
.map(async (locale) => [locale, (await loadLocaleData(locale, workspaceRoot)).code]),
721+
);
722+
initialOptions.footer = { js: `/**i18n:${calculateHash(JSON.stringify(data))}*/` };
723+
},
724+
});
725+
}
709726
} else if (i18nOptions.hasDefinedSourceLocale) {
710727
// When not inlining and a source locale is present, use the source locale data directly
711728
polyfills.unshift(`angular:locale/data:${i18nOptions.sourceLocale}`);

‎packages/angular/build/src/tools/i18n/i18n-inliner-worker.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import { deserialize } from 'node:v8';
1919
import { parseSync } from 'oxc-parser';
2020
import { traversePostOrder } from '../oxc/traversal';
2121
import { createSharedTranslationProxy } from './i18n-translation-reader';
22-
import { loadLocaleData } from './locale-data';
22+
import { type LoadedLocaleData, loadLocaleData } from './locale-data';
2323

2424
/**
2525
* The options passed to the inliner for each code request
@@ -51,6 +51,7 @@ export interface InlineCodeRequest {
5151
* How to handle missing translations.
5252
*/
5353
missingTranslation?: 'error' | 'warning' | 'ignore';
54+
workspaceRoot?: string;
5455
}
5556

5657
/**
@@ -89,6 +90,7 @@ export interface InlineFileBatchRequest {
8990
* How to handle missing translations.
9091
*/
9192
missingTranslation?: 'error' | 'warning' | 'ignore';
93+
workspaceRoot?: string;
9294

9395
/**
9496
* Whether the file data should be treated as ephemeral and not cached long-term in the Worker.
@@ -152,6 +154,8 @@ const fileDataCache = new Map<string, Promise<CachedFileData>>();
152154
*/
153155
const deserializedTranslations = new Map<string, Promise<Record<string, ɵParsedTranslation>>>();
154156

157+
const localeDataCache = new Map<string, Promise<LoadedLocaleData>>();
158+
155159
/**
156160
* The current inlining generation for this worker.
157161
*/
@@ -286,6 +290,7 @@ export async function inlineFileBatch(
286290
locale,
287291
await loadTranslation(locale, translation),
288292
request.filename,
293+
request.workspaceRoot,
289294
request.missingTranslation,
290295
);
291296

@@ -319,6 +324,7 @@ export async function inlineCode(request: InlineCodeRequest): Promise<InlineCode
319324
request.locale,
320325
await loadTranslation(request.locale, request.translation),
321326
request.filename,
327+
request.workspaceRoot,
322328
request.missingTranslation,
323329
);
324330

@@ -480,6 +486,7 @@ function escapeTemplatePart(part: string): string {
480486
* @param locale The target locale identifier.
481487
* @param translation The translation messages dictionary, or undefined for untranslated locale.
482488
* @param filename The name of the file being transformed.
489+
* @param workspaceRoot The workspace root used to resolve locale data.
483490
* @param missingTranslation How to handle missing translations.
484491
* @returns The transformed code, optional remapped source map, and diagnostics.
485492
*/
@@ -490,6 +497,7 @@ async function inlineLocalize(
490497
locale: string,
491498
translation: Record<string, ɵParsedTranslation> | undefined,
492499
filename: string,
500+
workspaceRoot = process.cwd(),
493501
missingTranslation: 'error' | 'warning' | 'ignore' = 'warning',
494502
) {
495503
const magicString = new MagicString(code);
@@ -502,7 +510,13 @@ async function inlineLocalize(
502510
}
503511

504512
if (metadata.localeInsertSites.length > 0) {
505-
const localeData = await loadLocaleData(locale);
513+
const cacheKey = JSON.stringify([workspaceRoot, locale]);
514+
let pendingLocaleData = localeDataCache.get(cacheKey);
515+
if (!pendingLocaleData) {
516+
pendingLocaleData = loadLocaleData(locale, workspaceRoot);
517+
localeDataCache.set(cacheKey, pendingLocaleData);
518+
}
519+
const localeData = await pendingLocaleData;
506520
if (localeData.error) {
507521
diagnostics.push({ type: 'error', message: localeData.error });
508522
} else if (localeData.warning) {

‎packages/angular/build/src/tools/i18n/i18n-inliner.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ export interface I18nInlinerOptions {
144144
maxConcurrency?: number;
145145
persistentCachePath?: string;
146146
localizeVersion?: string;
147+
workspaceRoot?: string;
147148
}
148149

149150
/**
@@ -308,7 +309,7 @@ export class I18nInliner {
308309
await this.initCache();
309310

310311
const generation = ++this.#generation;
311-
const { missingTranslation, localizeVersion } = this.options;
312+
const { missingTranslation, localizeVersion, workspaceRoot } = this.options;
312313
const localeList = Array.from(locales);
313314

314315
if (localeList.length === 0) {
@@ -353,6 +354,7 @@ export class I18nInliner {
353354
translation: translationIntegrity || translation,
354355
missingTranslation,
355356
localizeVersion,
357+
workspaceRoot,
356358
}),
357359
),
358360
);
@@ -572,6 +574,7 @@ export class I18nInliner {
572574
map: mapBlob,
573575
locales: new Map(batchEntries.map((e) => [e.locale, e.translation])),
574576
missingTranslation: this.options.missingTranslation,
577+
workspaceRoot: this.options.workspaceRoot,
575578
ephemeral,
576579
activeLocales,
577580
generation,
@@ -675,6 +678,7 @@ export class I18nInliner {
675678
filename: templateId,
676679
locale,
677680
missingTranslation: this.options.missingTranslation,
681+
workspaceRoot: this.options.workspaceRoot,
678682
translation: await serializeTranslation(
679683
translation,
680684
translationIntegrity,

‎packages/angular/build/src/tools/i18n/i18n-inliner_spec.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import type { ɵParsedTranslation } from '@angular/localize';
1010
import { transform } from 'esbuild';
11+
import assert from 'node:assert';
1112
import fs from 'node:fs/promises';
1213
import os from 'node:os';
1314
import path from 'node:path';
@@ -1119,6 +1120,37 @@ describe('I18nInliner', () => {
11191120
externalPool = undefined;
11201121
});
11211122

1123+
it('resolves and caches locale data separately for each workspace', async () => {
1124+
const baseTmpDir = process.env['TEST_TMPDIR'];
1125+
assert(baseTmpDir, 'TEST_TMPDIR is not set');
1126+
const tempDir = await fs.mkdtemp(path.join(baseTmpDir, 'i18n-workspaces-'));
1127+
externalPool = new WorkerPool({ maxThreads: 1 });
1128+
1129+
try {
1130+
for (const name of ['first', 'second']) {
1131+
const workspaceRoot = path.join(tempDir, name);
1132+
const localeDir = path.join(workspaceRoot, 'node_modules/@angular/common/locales/global');
1133+
await fs.mkdir(localeDir, { recursive: true });
1134+
const localeData = `globalThis.localeData = "${name}";`;
1135+
await fs.writeFile(path.join(localeDir, 'fr.js'), localeData);
1136+
1137+
inliner = new I18nInliner({ missingTranslation: 'error', workspaceRoot }, externalPool);
1138+
const { outputFiles, errors, warnings } = await inliner.inlineForLocale(
1139+
[browserFile('polyfills.js', '$localize.locale = "___NG_LOCALE_INSERT___";')],
1140+
'fr',
1141+
undefined,
1142+
);
1143+
1144+
expect(errors).toEqual([]);
1145+
expect(warnings).toEqual([]);
1146+
expect(findFile(outputFiles, 'polyfills.js').text).toContain(localeData);
1147+
await inliner.close();
1148+
}
1149+
} finally {
1150+
await fs.rm(tempDir, { recursive: true, force: true });
1151+
}
1152+
});
1153+
11221154
it('uses the supplied workerPool to execute transformation tasks', async () => {
11231155
externalPool = new WorkerPool({ maxThreads: 1 });
11241156
const runSpy = spyOn(externalPool, 'run').and.callThrough();

‎packages/angular/build/src/tools/i18n/locale-data.ts‎

Lines changed: 16 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,6 @@ export interface LoadedLocaleData {
3737
error?: string;
3838
}
3939

40-
const localeDataCache = new Map<string, Promise<LoadedLocaleData>>();
41-
4240
/**
4341
* Resolves the path to the Angular locale data file for a given locale tag.
4442
*
@@ -98,41 +96,28 @@ export function resolveLocaleDataPath(
9896
* @param projectRoot Optional project root for module resolution.
9997
* @returns A promise resolving to the loaded locale data script code and any diagnostic warnings.
10098
*/
101-
export function loadLocaleData(
99+
export async function loadLocaleData(
102100
rawLocaleTag: string,
103101
projectRoot?: string,
104102
): Promise<LoadedLocaleData> {
105-
let cached = localeDataCache.get(rawLocaleTag);
106-
if (!cached) {
107-
cached = (async () => {
108-
const projectResolve = createProjectResolver(projectRoot ?? process.cwd());
109-
const resolution = resolveLocaleDataPath(rawLocaleTag, (potentialPath) => {
110-
try {
111-
return projectResolve(potentialPath);
112-
} catch {
113-
return undefined;
114-
}
115-
});
116-
117-
if (resolution.error) {
118-
return { error: resolution.error };
119-
}
120-
121-
if (resolution.path) {
122-
try {
123-
const code = await readFile(resolution.path, 'utf8');
103+
const projectResolve = createProjectResolver(projectRoot ?? process.cwd());
104+
const resolution = resolveLocaleDataPath(rawLocaleTag, (potentialPath) =>
105+
projectResolve(potentialPath),
106+
);
124107

125-
return { code, warning: resolution.warning };
126-
} catch (e) {
127-
return { error: `Failed to read locale data file: ${(e as Error).message}` };
128-
}
129-
}
108+
if (resolution.error) {
109+
return { error: resolution.error };
110+
}
130111

131-
return { warning: resolution.warning };
132-
})();
112+
if (resolution.path) {
113+
try {
114+
const code = await readFile(resolution.path, 'utf8');
133115

134-
localeDataCache.set(rawLocaleTag, cached);
116+
return { code, warning: resolution.warning };
117+
} catch (e) {
118+
return { error: `Failed to read locale data file: ${(e as Error).message}` };
119+
}
135120
}
136121

137-
return cached;
122+
return { warning: resolution.warning };
138123
}

‎tests/e2e/tests/i18n/ivy-localize-hashes.ts‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,12 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9-
import * as fs from 'node:fs';
10-
import { appendToFile } from '../../utils/fs';
9+
import assert from 'node:assert/strict';
10+
import { readdirSync, readFileSync } from 'node:fs';
11+
import { getGlobalVariable } from '../../utils/env';
12+
import { replaceInFile } from '../../utils/fs';
1113
import { ng } from '../../utils/process';
14+
import { updateJsonFile } from '../../utils/project';
1215
import { langTranslations, setupI18nConfig } from './setup';
1316

1417
const OUTPUT_RE = /^(?<name>(?:main|vendor|\d+))(?:\.|-)(?<hash>[a-z0-9]+)\.js$/i;
@@ -17,11 +20,27 @@ export default async function () {
1720
// Setup i18n tests and config.
1821
await setupI18nConfig();
1922

23+
const esbuild = getGlobalVariable('argv')['esbuild'];
24+
if (esbuild) {
25+
// Test the polyfills bundle that contains only the CLI-generated locale initialization.
26+
await updateJsonFile('angular.json', (workspace) => {
27+
workspace.projects['test-project'].architect['build'].options.polyfills = [];
28+
});
29+
}
30+
2031
// Build each locale and record output file hashes
2132
const hashes = new Map<string, string>();
33+
const polyfills = new Map<string, { name: string; content: string }>();
2234
await ng('build', '--output-hashing=all', '--configuration=development');
2335
for (const { lang, outputPath } of langTranslations) {
24-
for (const entry of fs.readdirSync(outputPath)) {
36+
for (const entry of readdirSync(outputPath)) {
37+
if (esbuild && /^polyfills-[a-z0-9]+\.js$/i.test(entry)) {
38+
polyfills.set(lang, {
39+
name: entry,
40+
content: readFileSync(`${outputPath}/${entry}`, 'utf-8'),
41+
});
42+
}
43+
2544
const match = entry.match(OUTPUT_RE);
2645
if (!match?.groups) {
2746
continue;
@@ -36,13 +55,27 @@ export default async function () {
3655
throw new Error('No output entries found.');
3756
}
3857

39-
// Alter content of a used translation file
40-
await appendToFile('src/locale/messages.fr.xlf', '\n');
58+
if (esbuild) {
59+
assert.equal(polyfills.size, langTranslations.length);
60+
assert.equal(new Set(Array.from(polyfills.values(), ({ name }) => name)).size, 1);
61+
}
62+
63+
// Change a translated message without changing any application source.
64+
await replaceInFile('src/locale/messages.fr.xlf', 'Bonjour', 'Salut');
4165

4266
// Build each locale and ensure hashes are different
4367
await ng('build', '--output-hashing=all', '--configuration=development');
4468
for (const { lang, outputPath } of langTranslations) {
45-
for (const entry of fs.readdirSync(outputPath)) {
69+
const localePolyfills = polyfills.get(lang);
70+
if (localePolyfills) {
71+
assert.equal(
72+
readFileSync(`${outputPath}/${localePolyfills.name}`, 'utf-8'),
73+
localePolyfills.content,
74+
`Expected the generated polyfills to stay cacheable for ${lang}.`,
75+
);
76+
}
77+
78+
for (const entry of readdirSync(outputPath)) {
4679
const match = entry.match(OUTPUT_RE);
4780
if (!match?.groups) {
4881
continue;

0 commit comments

Comments
 (0)