Skip to content

Commit bb6e7f6

Browse files
committed
fix(@angular/build): preserve unaffected localized chunk URLs
1 parent 2c6e8b9 commit bb6e7f6

8 files changed

Lines changed: 720 additions & 6 deletions

File tree

‎packages/angular/build/src/builders/application/execute-build.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -393,9 +393,11 @@ export async function executeBuild(
393393
);
394394
}
395395

396+
let localizedNames: Map<string, string> | undefined;
396397
// Perform i18n translation inlining if enabled
397398
if (i18nOptions.shouldInline) {
398399
const result = await inlineI18n(browserMetafile, options, executionResult, initialFiles);
400+
localizedNames = result.renamedFiles;
399401
executionResult.addErrors(result.errors);
400402
executionResult.addWarnings(result.warnings);
401403
executionResult.addPrerenderedRoutes(result.prerenderedRoutes);
@@ -427,11 +429,32 @@ export async function executeBuild(
427429
);
428430
}
429431

432+
let statsMetafile = browserMetafile;
433+
if (options.stats && localizedNames?.size) {
434+
const names = localizedNames;
435+
statsMetafile = {
436+
...browserMetafile,
437+
outputs: Object.fromEntries(
438+
Object.entries(browserMetafile.outputs).map(([path, output]) => [
439+
names.get(path) ?? path,
440+
{
441+
...output,
442+
imports: output.imports.map((entry) => {
443+
const renamedPath = !entry.external && names.get(entry.path);
444+
445+
return renamedPath ? { ...entry, path: renamedPath } : entry;
446+
}),
447+
},
448+
]),
449+
),
450+
};
451+
}
452+
430453
// Write metafiles if stats option is enabled
431454
if (options.stats) {
432455
executionResult.addOutputFile(
433456
'browser-stats.json',
434-
stableStringify(browserMetafile),
457+
stableStringify(statsMetafile),
435458
BuildOutputFileType.Root,
436459
);
437460

@@ -458,6 +481,7 @@ export async function executeBuild(
458481
estimatedTransferSizes,
459482
!!ssrOptions,
460483
verbose,
484+
localizedNames,
461485
),
462486
);
463487
}

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

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
} from '../../tools/esbuild/bundler-execution-result';
1818
import { BuildOutputFileType, InitialFileRecord } from '../../tools/esbuild/bundler-files';
1919
import { I18nInliner } from '../../tools/i18n';
20+
import { createLocalizedOutputHasher } from '../../tools/i18n/i18n-output-hashes';
2021
import { maxInlinerWorkers } from '../../utils/environment-options';
2122
import { loadTranslations } from '../../utils/i18n-options';
2223
import { createTranslationLoader } from '../../utils/load-translations';
@@ -44,6 +45,7 @@ export async function inlineI18n(
4445
errors: string[];
4546
warnings: string[];
4647
prerenderedRoutes: PrerenderedRoutesRecord;
48+
renamedFiles?: Map<string, string>;
4749
}> {
4850
const { i18nOptions, baseHref, cacheOptions } = options;
4951

@@ -64,6 +66,7 @@ export async function inlineI18n(
6466
errors: string[];
6567
warnings: string[];
6668
prerenderedRoutes: PrerenderedRoutesRecord;
69+
renamedFiles?: Map<string, string>;
6770
} = {
6871
errors: [],
6972
warnings: [],
@@ -98,13 +101,30 @@ export async function inlineI18n(
98101
});
99102

100103
const inlinedLocales = await inliner.inlineAll(executionResult.outputFiles, localesToInline);
104+
const hashLocalizedOutputs = options.i18nContentHashing
105+
? createLocalizedOutputHasher(
106+
executionResult.outputFiles,
107+
new Set(
108+
options.globalScripts.filter(({ initial }) => !initial).map(({ name }) => name + '.js'),
109+
),
110+
metafile,
111+
)
112+
: undefined;
101113

102114
for (const locale of i18nOptions.inlineLocales) {
103115
const localeInlineResult = inlinedLocales.get(locale);
104116
assert(localeInlineResult !== undefined, 'Inlined result must exist for locale: ' + locale);
105117
const localeOutputFiles = localeInlineResult.outputFiles;
106118
inlineResult.errors.push(...localeInlineResult.errors);
107119
inlineResult.warnings.push(...localeInlineResult.warnings);
120+
const renamedFiles = hashLocalizedOutputs?.(localeOutputFiles);
121+
// As with the pre-localization build summary, report a single set of output names.
122+
inlineResult.renamedFiles ??= renamedFiles;
123+
const localeInitialFiles = renamedFiles?.size
124+
? new Map(
125+
Array.from(initialFiles, ([path, record]) => [renamedFiles.get(path) ?? path, record]),
126+
)
127+
: initialFiles;
108128

109129
const {
110130
errors,
@@ -120,7 +140,7 @@ export async function inlineI18n(
120140
},
121141
[...unModifiedOutputFiles, ...localeOutputFiles],
122142
executionResult.assetFiles,
123-
initialFiles,
143+
localeInitialFiles,
124144
locale,
125145
);
126146

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,14 @@ export async function normalizeOptions(
544544
tailwindConfiguration,
545545
postcssConfiguration,
546546
i18nOptions,
547+
// Server and watch builds still use the names produced by the bundler throughout the build.
548+
i18nContentHashing:
549+
i18nOptions.shouldInline &&
550+
outputNames.bundles.includes('[hash]') &&
551+
!serverEntryPoint &&
552+
!watch &&
553+
!outExtension &&
554+
!extensions?.codePlugins?.length,
547555
namedChunks,
548556
budgets: budgets?.length ? budgets : undefined,
549557
publicPath: deployUrl,

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -572,7 +572,7 @@ function getEsBuildCommonOptions(options: NormalizedApplicationBuildOptions): Bu
572572
// change when translation files have changed. If this is not done the post processed files may have
573573
// different content but would retain identical production file names which would lead to browser caching problems.
574574
let footer;
575-
if (i18nOptions.shouldInline) {
575+
if (i18nOptions.shouldInline && !options.i18nContentHashing) {
576576
// Update file hashes to include translation file content
577577
const i18nHash = Object.values(i18nOptions.locales).reduce(
578578
(data, locale) => data + locale.files.map((file) => file.integrity || '').join('|'),

‎packages/angular/build/src/tools/esbuild/utils.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export function logBuildStats(
3030
estimatedTransferSizes?: Map<string, number>,
3131
ssrOutputEnabled?: boolean,
3232
verbose?: boolean,
33+
displayNames?: ReadonlyMap<string, string>,
3334
): string {
3435
// Remove the i18n subpath in case the build is using i18n.
3536
// en-US/main.js -> main.js
@@ -69,7 +70,12 @@ export function logBuildStats(
6970
const name = initial.get(file)?.name ?? getChunkNameFromMetafile(metafiles, file);
7071
const stat: BundleStats = {
7172
initial: initial.has(file),
72-
stats: [file, name ?? '-', size, estimatedTransferSizes?.get(file) ?? '-'],
73+
stats: [
74+
displayNames?.get(file) ?? file,
75+
name ?? '-',
76+
size,
77+
estimatedTransferSizes?.get(file) ?? '-',
78+
],
7379
};
7480

7581
if (isPlatformServer) {

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

Lines changed: 160 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';
@@ -20,6 +21,7 @@ import {
2021
createOutputFile,
2122
} from '../esbuild/bundler-files';
2223
import { I18nInliner, type I18nInlinerOptions } from './i18n-inliner';
24+
import { createLocalizedOutputHasher } from './i18n-output-hashes';
2325

2426
/**
2527
* A module that uses a `$localize` message with an explicit message identifier so that the
@@ -1185,3 +1187,161 @@ describe('I18nInliner', () => {
11851187
});
11861188
});
11871189
});
1190+
1191+
describe('Localized output hashing', () => {
1192+
beforeAll(initializeHash);
1193+
1194+
function renamed(names: ReadonlyMap<string, string>, file: string): string {
1195+
const result = names.get(file);
1196+
assert(result, 'Expected renamed output file: ' + file);
1197+
1198+
return result;
1199+
}
1200+
1201+
function outputMetadata(
1202+
...entries: [string, [string, 'import-statement' | 'dynamic-import', boolean?][]][]
1203+
): Parameters<typeof createLocalizedOutputHasher>[2] {
1204+
return {
1205+
inputs: {},
1206+
outputs: Object.fromEntries(
1207+
entries.map(([file, imports]) => [
1208+
file,
1209+
{
1210+
bytes: 0,
1211+
inputs: {},
1212+
exports: [],
1213+
imports: imports.map(([path, kind, external]) => ({ path, kind, external })),
1214+
},
1215+
]),
1216+
),
1217+
};
1218+
}
1219+
1220+
it('invalidates a cycle and its importers without invalidating a separate cycle', () => {
1221+
const original = [
1222+
browserFile('first-AAAAAAAA.js', 'console.log($localize`A`); import "./second-BBBBBBBB.js";'),
1223+
browserFile('second-BBBBBBBB.js', 'export {} from "./first-AAAAAAAA.js";'),
1224+
browserFile('third-CCCCCCCC.js', 'import "./fourth-DDDDDDDD.js"; console.log($localize`B`);'),
1225+
browserFile('fourth-DDDDDDDD.js', 'import "./third-CCCCCCCC.js";'),
1226+
browserFile('main-EEEEEEEE.js', 'import(`./second-BBBBBBBB.js`);'),
1227+
];
1228+
const hash = createLocalizedOutputHasher(
1229+
original,
1230+
new Set(),
1231+
outputMetadata(
1232+
['first-AAAAAAAA.js', [['second-BBBBBBBB.js', 'import-statement']]],
1233+
['second-BBBBBBBB.js', [['first-AAAAAAAA.js', 'import-statement']]],
1234+
['third-CCCCCCCC.js', [['fourth-DDDDDDDD.js', 'import-statement']]],
1235+
['fourth-DDDDDDDD.js', [['third-CCCCCCCC.js', 'import-statement']]],
1236+
['main-EEEEEEEE.js', [['second-BBBBBBBB.js', 'dynamic-import']]],
1237+
),
1238+
);
1239+
const localize = (text: string) =>
1240+
original.map((file) =>
1241+
browserFile(
1242+
file.path,
1243+
file.text
1244+
.replace('$localize`A`', JSON.stringify(text))
1245+
.replace('$localize`B`', '"Other"'),
1246+
),
1247+
);
1248+
1249+
const firstFiles = localize('Before');
1250+
const first = hash(firstFiles);
1251+
const secondFiles = localize('Après 😀');
1252+
const second = hash(secondFiles);
1253+
1254+
expect(second.size).toBe(5);
1255+
for (const path of ['first-AAAAAAAA.js', 'second-BBBBBBBB.js', 'main-EEEEEEEE.js']) {
1256+
expect(second.get(path)).not.toBe(first.get(path));
1257+
}
1258+
for (const path of ['third-CCCCCCCC.js', 'fourth-DDDDDDDD.js']) {
1259+
expect(second.get(path)).toBe(first.get(path));
1260+
}
1261+
expect(findFile(secondFiles, renamed(second, 'first-AAAAAAAA.js')).text).toContain(
1262+
renamed(second, 'second-BBBBBBBB.js'),
1263+
);
1264+
expect(findFile(secondFiles, renamed(second, 'second-BBBBBBBB.js')).text).toContain(
1265+
renamed(second, 'first-AAAAAAAA.js'),
1266+
);
1267+
expect(findFile(secondFiles, renamed(second, 'main-EEEEEEEE.js')).text).toContain(
1268+
renamed(second, 'second-BBBBBBBB.js'),
1269+
);
1270+
});
1271+
1272+
it('rewrites only actual module specifiers using workspace-relative metadata', () => {
1273+
const main = 'app/main-AAAAAAAA.js';
1274+
const leaf = 'chunk-BBBBBBBB.js';
1275+
const external = 'chunk-CCCCCCCC.js';
1276+
const source = `export {a, b} from '../${leaf}'; import(\`../${leaf}\`); import('../${external}'); console.log('../${leaf}');`;
1277+
const files = [
1278+
browserFile(main, source),
1279+
browserFile(leaf, 'export const a = $localize`Hello`, b = 1;'),
1280+
browserFile(external, 'export const a = $localize`Hello`;'),
1281+
];
1282+
const hash = createLocalizedOutputHasher(
1283+
files,
1284+
new Set(),
1285+
outputMetadata(
1286+
[
1287+
main,
1288+
[
1289+
['./' + leaf, 'import-statement'],
1290+
['./' + leaf, 'dynamic-import'],
1291+
[external, 'dynamic-import', true],
1292+
],
1293+
],
1294+
[leaf, []],
1295+
[external, []],
1296+
),
1297+
);
1298+
const localized = files.map((file) =>
1299+
browserFile(file.path, file.text.replace('$localize`Hello`', '"Bonjour"')),
1300+
);
1301+
1302+
const names = hash(localized);
1303+
const newLeaf = renamed(names, leaf);
1304+
expect(renamed(names, external)).not.toBe(external);
1305+
const mainText = findFile(localized, renamed(names, main)).text;
1306+
expect(mainText).toBe(
1307+
`export {a, b} from '../${newLeaf}'; import(\`../${newLeaf}\`); import('../${external}'); console.log('../${leaf}');`,
1308+
);
1309+
});
1310+
1311+
it('rewrites a worker URL and its source map without rewriting other strings', () => {
1312+
const worker = 'worker-aB3_-9cD.js';
1313+
const main = 'main-BBBBBBBB.js';
1314+
const mainFile = browserFile(
1315+
main,
1316+
`console.log("${worker}");
1317+
new Worker(new URL("${worker}", import.meta.url));
1318+
new Worker(new URL(\`./${worker}\`, import.meta.url));`,
1319+
);
1320+
const sourceMap = browserFile(worker + '.map', JSON.stringify({ version: 3, file: worker }));
1321+
const hash = createLocalizedOutputHasher(
1322+
[mainFile, browserFile(worker, 'console.log($localize`Hello`);'), sourceMap],
1323+
new Set(),
1324+
outputMetadata([main, []], [worker, []]),
1325+
);
1326+
const files = [
1327+
mainFile.clone(),
1328+
browserFile(
1329+
worker,
1330+
`console.log("Bonjour");
1331+
//# sourceMappingURL=${worker}.map
1332+
`,
1333+
),
1334+
sourceMap.clone(),
1335+
];
1336+
1337+
const names = hash(files);
1338+
const newWorker = renamed(names, worker);
1339+
expect(newWorker).not.toBe(worker);
1340+
const mainText = findFile(files, renamed(names, main)).text;
1341+
expect(mainText).toContain(`new URL("${newWorker}"`);
1342+
expect(mainText).toContain(`new URL(\`./${newWorker}\``);
1343+
expect(mainText).toContain(`console.log("${worker}")`);
1344+
expect(findFile(files, newWorker).text).toContain(`sourceMappingURL=${newWorker}.map`);
1345+
expect(JSON.parse(findFile(files, newWorker + '.map').text).file).toBe(newWorker);
1346+
});
1347+
});

0 commit comments

Comments
 (0)