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
15 changes: 9 additions & 6 deletions packages/angular/build/src/utils/server-rendering/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export function generateAngularServerAppEngineManifest(
for (const locale of i18nOptions.inlineLocales) {
const { subPath } = i18nOptions.locales[locale];
const importPath = `${subPath ? `${subPath}/` : ''}${MAIN_SERVER_OUTPUT_FILENAME}`;
entryPoints[subPath] = `() => import('./${importPath}')`;
entryPoints[subPath] = `() => import(${JSON.stringify(`./${importPath}`)})`;
supportedLocales[locale] = subPath;
}
} else {
Expand All @@ -85,12 +85,12 @@ export function generateAngularServerAppEngineManifest(

const manifestContent = `
export default {
basePath: '${basePath}',
basePath: ${JSON.stringify(basePath)},
allowedHosts: ${JSON.stringify(allowedHosts, undefined, 2)},
supportedLocales: ${JSON.stringify(supportedLocales, undefined, 2)},
entryPoints: {
${Object.entries(entryPoints)
.map(([key, value]) => `'${key}': ${value}`)
.map(([key, value]) => `${JSON.stringify(key)}: ${value}`)
.join(',\n ')}
},
};
Expand Down Expand Up @@ -162,8 +162,11 @@ export function generateAngularServerAppManifest(
// which can result in an incorrect byte length.
const size = runInThisContext(`new TextEncoder().encode(\`${escapedContent}\`).byteLength`);

// Asset paths are derived from route paths and can contain arbitrary characters, so they are
// serialized rather than interpolated into the generated executable manifest.
serverAssets[file.path] =
`{size: ${size}, hash: '${file.hash}', text: () => import('./${jsChunkFilePath}').then(m => m.default)}`;
`{size: ${size}, hash: ${JSON.stringify(file.hash)}, ` +
`text: () => import(${JSON.stringify(`./${jsChunkFilePath}`)}).then(m => m.default)}`;
}
}

Expand All @@ -178,13 +181,13 @@ export function generateAngularServerAppManifest(
export default {
bootstrap: () => import('./main.server.mjs').then(m => m.default),
inlineCriticalCss: ${inlineCriticalCss},
baseHref: '${baseHref}',
baseHref: ${JSON.stringify(baseHref)},
locale: ${JSON.stringify(locale)},
routes: ${JSON.stringify(routes, undefined, 2)},
entryPointToBrowserMapping: ${JSON.stringify(entryPointToBrowserMapping, undefined, 2)},
assets: {
${Object.entries(serverAssets)
.map(([key, value]) => `'${key}': ${value}`)
.map(([key, value]) => `${JSON.stringify(key)}: ${value}`)
.join(',\n ')}
},
};
Expand Down
77 changes: 77 additions & 0 deletions packages/angular/build/src/utils/server-rendering/manifest_spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

import type { Metafile } from 'esbuild';
import { BuildOutputFileType } from '../../tools/esbuild/bundler-context';
import { createOutputFile } from '../../tools/esbuild/utils';
import { generateAngularServerAppManifest } from './manifest';

describe('generateAngularServerAppManifest', () => {
const dummyMetafile = { inputs: {}, outputs: {} } as unknown as Metafile;

/**
* Evaluates a generated manifest, which both asserts that it is syntactically valid JavaScript and
* gives access to the values it declares. The dynamic imports it contains are never invoked.
*/
function evaluateManifest(manifestContent: string): unknown {
return new Function(manifestContent.replace('export default', 'return'))();
}
Comment on lines +21 to +23

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using a simple string replacement manifestContent.replace('export default', 'return') will replace the first occurrence of 'export default'. If any serialized asset paths, routes, or other content in the manifest happen to contain the substring 'export default', the replacement will occur there instead of the actual export statement, leading to syntax or evaluation errors. Using a regular expression with the multiline flag (/m) and anchoring to the start of the line (^) makes this replacement much more robust.

  function evaluateManifest(manifestContent: string): unknown {\n    return new Function(manifestContent.replace(/^\\s*export default/m, 'return'))();\n  }


function generateManifest(
htmlOutputFiles: Record<string, string>,
baseHref = '/',
): ReturnType<typeof generateAngularServerAppManifest> {
const additionalHtmlOutputFiles = new Map(
Object.entries(htmlOutputFiles).map(([path, content]) => [
path,
createOutputFile(path, content, BuildOutputFileType.Browser),
]),
);

return generateAngularServerAppManifest(
additionalHtmlOutputFiles,
[],
false,
undefined,
undefined,
baseHref,
new Set(),
dummyMetafile,
undefined,
);
}

it('should serialize asset paths which contain JavaScript string delimiters', () => {
const assetPath = "catalog/customer's-choice/index.html";
const { manifestContent } = generateManifest({
[assetPath]: '<main>Featured</main>',
});

expect(evaluateManifest(manifestContent)).toEqual(
jasmine.objectContaining({
assets: {
[assetPath]: jasmine.objectContaining({
size: 21,
hash: jasmine.any(String),
text: jasmine.any(Function),
}),
},
}),
);
});

it('should serialize a base href which contains JavaScript string delimiters', () => {
const { manifestContent } = generateManifest({ 'index.html': '<main></main>' }, "/o'brien/");

expect(evaluateManifest(manifestContent)).toEqual(
jasmine.objectContaining({
baseHref: "/o'brien/",
}),
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export default async function () {
path: 'ssg/:id',
renderMode: RenderMode.Prerender,
headers: { 'x-custom': 'ssg-with-params' },
getPrerenderParams: async() => [{id: 'one'}, {id: 'two'}],
getPrerenderParams: async() => [{id: 'one'}, {id: 'two'}, {id: "customer's-choice"}],
},
{
path: 'ssr',
Expand Down Expand Up @@ -115,6 +115,7 @@ export default async function () {
'ssg/index.html': 'ssg works!',
'ssg/one/index.html': 'ssg-with-params works!',
'ssg/two/index.html': 'ssg-with-params works!',
"ssg/customer's-choice/index.html": 'ssg-with-params works!',
};

for (const [filePath, fileMatch] of Object.entries(expects)) {
Expand Down
Loading