Skip to content
Closed
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
26 changes: 25 additions & 1 deletion packages/angular/build/src/builders/application/execute-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,9 +393,11 @@ export async function executeBuild(
);
}

let localizedNames: Map<string, string> | undefined;
// Perform i18n translation inlining if enabled
if (i18nOptions.shouldInline) {
const result = await inlineI18n(browserMetafile, options, executionResult, initialFiles);
localizedNames = result.renamedFiles;
executionResult.addErrors(result.errors);
executionResult.addWarnings(result.warnings);
executionResult.addPrerenderedRoutes(result.prerenderedRoutes);
Expand Down Expand Up @@ -427,11 +429,32 @@ export async function executeBuild(
);
}

let statsMetafile = browserMetafile;
if (options.stats && localizedNames?.size) {
const names = localizedNames;
statsMetafile = {
...browserMetafile,
outputs: Object.fromEntries(
Object.entries(browserMetafile.outputs).map(([path, output]) => [
names.get(path) ?? path,
{
...output,
imports: output.imports.map((entry) => {
const renamedPath = !entry.external && names.get(entry.path);

return renamedPath ? { ...entry, path: renamedPath } : entry;
}),
},
]),
),
};
}

// Write metafiles if stats option is enabled
if (options.stats) {
executionResult.addOutputFile(
'browser-stats.json',
stableStringify(browserMetafile),
stableStringify(statsMetafile),
BuildOutputFileType.Root,
);

Expand All @@ -458,6 +481,7 @@ export async function executeBuild(
estimatedTransferSizes,
!!ssrOptions,
verbose,
localizedNames,
),
);
}
Expand Down
22 changes: 21 additions & 1 deletion packages/angular/build/src/builders/application/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from '../../tools/esbuild/bundler-execution-result';
import { BuildOutputFileType, InitialFileRecord } from '../../tools/esbuild/bundler-files';
import { I18nInliner } from '../../tools/i18n';
import { createLocalizedOutputHasher } from '../../tools/i18n/i18n-output-hashes';
import { maxInlinerWorkers } from '../../utils/environment-options';
import { loadTranslations } from '../../utils/i18n-options';
import { createTranslationLoader } from '../../utils/load-translations';
Expand Down Expand Up @@ -44,6 +45,7 @@ export async function inlineI18n(
errors: string[];
warnings: string[];
prerenderedRoutes: PrerenderedRoutesRecord;
renamedFiles?: Map<string, string>;
}> {
const { i18nOptions, baseHref, cacheOptions } = options;

Expand All @@ -64,6 +66,7 @@ export async function inlineI18n(
errors: string[];
warnings: string[];
prerenderedRoutes: PrerenderedRoutesRecord;
renamedFiles?: Map<string, string>;
} = {
errors: [],
warnings: [],
Expand Down Expand Up @@ -98,13 +101,30 @@ export async function inlineI18n(
});

const inlinedLocales = await inliner.inlineAll(executionResult.outputFiles, localesToInline);
const hashLocalizedOutputs = options.i18nContentHashing
? createLocalizedOutputHasher(
executionResult.outputFiles,
new Set(
options.globalScripts.filter(({ initial }) => !initial).map(({ name }) => name + '.js'),
),
metafile,
)
: undefined;

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

const {
errors,
Expand All @@ -120,7 +140,7 @@ export async function inlineI18n(
},
[...unModifiedOutputFiles, ...localeOutputFiles],
executionResult.assetFiles,
initialFiles,
localeInitialFiles,
locale,
);

Expand Down
8 changes: 8 additions & 0 deletions packages/angular/build/src/builders/application/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,14 @@ export async function normalizeOptions(
tailwindConfiguration,
postcssConfiguration,
i18nOptions,
// Server and watch builds still use the names produced by the bundler throughout the build.
i18nContentHashing:
i18nOptions.shouldInline &&
outputNames.bundles.includes('[hash]') &&
!serverEntryPoint &&
!watch &&
!outExtension &&
!extensions?.codePlugins?.length,
namedChunks,
budgets: budgets?.length ? budgets : undefined,
publicPath: deployUrl,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,7 @@ function getEsBuildCommonOptions(options: NormalizedApplicationBuildOptions): Bu
// change when translation files have changed. If this is not done the post processed files may have
// different content but would retain identical production file names which would lead to browser caching problems.
let footer;
if (i18nOptions.shouldInline) {
if (i18nOptions.shouldInline && !options.i18nContentHashing) {
// Update file hashes to include translation file content
const i18nHash = Object.values(i18nOptions.locales).reduce(
(data, locale) => data + locale.files.map((file) => file.integrity || '').join('|'),
Expand Down
8 changes: 7 additions & 1 deletion packages/angular/build/src/tools/esbuild/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export function logBuildStats(
estimatedTransferSizes?: Map<string, number>,
ssrOutputEnabled?: boolean,
verbose?: boolean,
displayNames?: ReadonlyMap<string, string>,
): string {
// Remove the i18n subpath in case the build is using i18n.
// en-US/main.js -> main.js
Expand Down Expand Up @@ -69,7 +70,12 @@ export function logBuildStats(
const name = initial.get(file)?.name ?? getChunkNameFromMetafile(metafiles, file);
const stat: BundleStats = {
initial: initial.has(file),
stats: [file, name ?? '-', size, estimatedTransferSizes?.get(file) ?? '-'],
stats: [
displayNames?.get(file) ?? file,
name ?? '-',
size,
estimatedTransferSizes?.get(file) ?? '-',
],
};

if (isPlatformServer) {
Expand Down
160 changes: 160 additions & 0 deletions packages/angular/build/src/tools/i18n/i18n-inliner_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import type { ɵParsedTranslation } from '@angular/localize';
import { transform } from 'esbuild';
import assert from 'node:assert';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
Expand All @@ -20,6 +21,7 @@ import {
createOutputFile,
} from '../esbuild/bundler-files';
import { I18nInliner, type I18nInlinerOptions } from './i18n-inliner';
import { createLocalizedOutputHasher } from './i18n-output-hashes';

/**
* A module that uses a `$localize` message with an explicit message identifier so that the
Expand Down Expand Up @@ -1185,3 +1187,161 @@ describe('I18nInliner', () => {
});
});
});

describe('Localized output hashing', () => {
beforeAll(initializeHash);

function renamed(names: ReadonlyMap<string, string>, file: string): string {
const result = names.get(file);
assert(result, 'Expected renamed output file: ' + file);

return result;
}

function outputMetadata(
...entries: [string, [string, 'import-statement' | 'dynamic-import', boolean?][]][]
): Parameters<typeof createLocalizedOutputHasher>[2] {
return {
inputs: {},
outputs: Object.fromEntries(
entries.map(([file, imports]) => [
file,
{
bytes: 0,
inputs: {},
exports: [],
imports: imports.map(([path, kind, external]) => ({ path, kind, external })),
},
]),
),
};
}

it('invalidates a cycle and its importers without invalidating a separate cycle', () => {
const original = [
browserFile('first-AAAAAAAA.js', 'console.log($localize`A`); import "./second-BBBBBBBB.js";'),
browserFile('second-BBBBBBBB.js', 'export {} from "./first-AAAAAAAA.js";'),
browserFile('third-CCCCCCCC.js', 'import "./fourth-DDDDDDDD.js"; console.log($localize`B`);'),
browserFile('fourth-DDDDDDDD.js', 'import "./third-CCCCCCCC.js";'),
browserFile('main-EEEEEEEE.js', 'import(`./second-BBBBBBBB.js`);'),
];
const hash = createLocalizedOutputHasher(
original,
new Set(),
outputMetadata(
['first-AAAAAAAA.js', [['second-BBBBBBBB.js', 'import-statement']]],
['second-BBBBBBBB.js', [['first-AAAAAAAA.js', 'import-statement']]],
['third-CCCCCCCC.js', [['fourth-DDDDDDDD.js', 'import-statement']]],
['fourth-DDDDDDDD.js', [['third-CCCCCCCC.js', 'import-statement']]],
['main-EEEEEEEE.js', [['second-BBBBBBBB.js', 'dynamic-import']]],
),
);
const localize = (text: string) =>
original.map((file) =>
browserFile(
file.path,
file.text
.replace('$localize`A`', JSON.stringify(text))
.replace('$localize`B`', '"Other"'),
),
);

const firstFiles = localize('Before');
const first = hash(firstFiles);
const secondFiles = localize('Après 😀');
const second = hash(secondFiles);

expect(second.size).toBe(5);
for (const path of ['first-AAAAAAAA.js', 'second-BBBBBBBB.js', 'main-EEEEEEEE.js']) {
expect(second.get(path)).not.toBe(first.get(path));
}
for (const path of ['third-CCCCCCCC.js', 'fourth-DDDDDDDD.js']) {
expect(second.get(path)).toBe(first.get(path));
}
expect(findFile(secondFiles, renamed(second, 'first-AAAAAAAA.js')).text).toContain(
renamed(second, 'second-BBBBBBBB.js'),
);
expect(findFile(secondFiles, renamed(second, 'second-BBBBBBBB.js')).text).toContain(
renamed(second, 'first-AAAAAAAA.js'),
);
expect(findFile(secondFiles, renamed(second, 'main-EEEEEEEE.js')).text).toContain(
renamed(second, 'second-BBBBBBBB.js'),
);
});

it('rewrites only actual module specifiers using workspace-relative metadata', () => {
const main = 'app/main-AAAAAAAA.js';
const leaf = 'chunk-BBBBBBBB.js';
const external = 'chunk-CCCCCCCC.js';
const source = `export {a, b} from '../${leaf}'; import(\`../${leaf}\`); import('../${external}'); console.log('../${leaf}');`;
const files = [
browserFile(main, source),
browserFile(leaf, 'export const a = $localize`Hello`, b = 1;'),
browserFile(external, 'export const a = $localize`Hello`;'),
];
const hash = createLocalizedOutputHasher(
files,
new Set(),
outputMetadata(
[
main,
[
['./' + leaf, 'import-statement'],
['./' + leaf, 'dynamic-import'],
[external, 'dynamic-import', true],
],
],
[leaf, []],
[external, []],
),
);
const localized = files.map((file) =>
browserFile(file.path, file.text.replace('$localize`Hello`', '"Bonjour"')),
);

const names = hash(localized);
const newLeaf = renamed(names, leaf);
expect(renamed(names, external)).not.toBe(external);
const mainText = findFile(localized, renamed(names, main)).text;
expect(mainText).toBe(
`export {a, b} from '../${newLeaf}'; import(\`../${newLeaf}\`); import('../${external}'); console.log('../${leaf}');`,
);
});

it('rewrites a worker URL and its source map without rewriting other strings', () => {
const worker = 'worker-aB3_-9cD.js';
const main = 'main-BBBBBBBB.js';
const mainFile = browserFile(
main,
`console.log("${worker}");
new Worker(new URL("${worker}", import.meta.url));
new Worker(new URL(\`./${worker}\`, import.meta.url));`,
);
const sourceMap = browserFile(worker + '.map', JSON.stringify({ version: 3, file: worker }));
const hash = createLocalizedOutputHasher(
[mainFile, browserFile(worker, 'console.log($localize`Hello`);'), sourceMap],
new Set(),
outputMetadata([main, []], [worker, []]),
);
const files = [
mainFile.clone(),
browserFile(
worker,
`console.log("Bonjour");
//# sourceMappingURL=${worker}.map
`,
),
sourceMap.clone(),
];

const names = hash(files);
const newWorker = renamed(names, worker);
expect(newWorker).not.toBe(worker);
const mainText = findFile(files, renamed(names, main)).text;
expect(mainText).toContain(`new URL("${newWorker}"`);
expect(mainText).toContain(`new URL(\`./${newWorker}\``);
expect(mainText).toContain(`console.log("${worker}")`);
expect(findFile(files, newWorker).text).toContain(`sourceMappingURL=${newWorker}.map`);
expect(JSON.parse(findFile(files, newWorker + '.map').text).file).toBe(newWorker);
});
});
Loading
Loading