-
Notifications
You must be signed in to change notification settings - Fork 12k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(@angular-devkit/build-angular): handle HTTP requests to assets du…
…ring prerendering This commit fixes an issue were during prerendering (SSG) http requests to assets causes prerendering to fail. Closes #25720 (cherry picked from commit 5b35410)
1 parent
a037d6a
commit 192a2ae
Showing
8 changed files
with
309 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
121 changes: 121 additions & 0 deletions
121
packages/angular_devkit/build_angular/src/utils/server-rendering/prerender-server.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
/** | ||
* @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.io/license | ||
*/ | ||
|
||
import { lookup as lookupMimeType } from 'mrmime'; | ||
import { readFile } from 'node:fs/promises'; | ||
import { IncomingMessage, RequestListener, ServerResponse, createServer } from 'node:http'; | ||
import { extname, posix } from 'node:path'; | ||
import { BuildOutputAsset } from '../../tools/esbuild/bundler-execution-result'; | ||
|
||
/** | ||
* Start a server that can handle HTTP requests to assets. | ||
* | ||
* @example | ||
* ```ts | ||
* httpClient.get('/assets/content.json'); | ||
* ``` | ||
* @returns the server address. | ||
*/ | ||
export async function startServer(assets: Readonly<BuildOutputAsset[]>): Promise<{ | ||
address: string; | ||
close?: () => void; | ||
}> { | ||
if (Object.keys(assets).length === 0) { | ||
return { | ||
address: '', | ||
}; | ||
} | ||
|
||
const assetsReversed: Record<string, string> = {}; | ||
for (const { source, destination } of assets) { | ||
assetsReversed[addLeadingSlash(destination.replace(/\\/g, posix.sep))] = source; | ||
} | ||
|
||
const assetsCache: Map<string, { mimeType: string | void; content: Buffer }> = new Map(); | ||
const server = createServer(requestHandler(assetsReversed, assetsCache)); | ||
|
||
await new Promise<void>((resolve) => { | ||
server.listen(0, '127.0.0.1', resolve); | ||
}); | ||
|
||
const serverAddress = server.address(); | ||
let address: string; | ||
if (!serverAddress) { | ||
address = ''; | ||
} else if (typeof serverAddress === 'string') { | ||
address = serverAddress; | ||
} else { | ||
const { port, address: host } = serverAddress; | ||
address = `http://${host}:${port}`; | ||
} | ||
|
||
return { | ||
address, | ||
close: () => { | ||
assetsCache.clear(); | ||
server.unref(); | ||
server.close(); | ||
}, | ||
}; | ||
} | ||
function requestHandler( | ||
assetsReversed: Record<string, string>, | ||
assetsCache: Map<string, { mimeType: string | void; content: Buffer }>, | ||
): RequestListener<typeof IncomingMessage, typeof ServerResponse> { | ||
return (req, res) => { | ||
if (!req.url) { | ||
res.destroy(new Error('Request url was empty.')); | ||
|
||
return; | ||
} | ||
|
||
const { pathname } = new URL(req.url, 'resolve://'); | ||
const asset = assetsReversed[pathname]; | ||
if (!asset) { | ||
res.statusCode = 404; | ||
res.statusMessage = 'Asset not found.'; | ||
res.end(); | ||
|
||
return; | ||
} | ||
|
||
const cachedAsset = assetsCache.get(pathname); | ||
if (cachedAsset) { | ||
const { content, mimeType } = cachedAsset; | ||
if (mimeType) { | ||
res.setHeader('Content-Type', mimeType); | ||
} | ||
|
||
res.end(content); | ||
|
||
return; | ||
} | ||
|
||
readFile(asset) | ||
.then((content) => { | ||
const extension = extname(pathname); | ||
const mimeType = lookupMimeType(extension); | ||
|
||
assetsCache.set(pathname, { | ||
mimeType, | ||
content, | ||
}); | ||
|
||
if (mimeType) { | ||
res.setHeader('Content-Type', mimeType); | ||
} | ||
|
||
res.end(content); | ||
}) | ||
.catch((e) => res.destroy(e)); | ||
}; | ||
} | ||
|
||
function addLeadingSlash(value: string): string { | ||
return value.charAt(0) === '/' ? value : '/' + value; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
83 changes: 83 additions & 0 deletions
83
tests/legacy-cli/e2e/tests/build/prerender/http-requests-assets.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
import { ng } from '../../../utils/process'; | ||
import { getGlobalVariable } from '../../../utils/env'; | ||
import { expectFileToMatch, rimraf, writeMultipleFiles } from '../../../utils/fs'; | ||
import { installWorkspacePackages } from '../../../utils/packages'; | ||
import { useSha } from '../../../utils/project'; | ||
|
||
export default async function () { | ||
// TODO(alanagius): allow this test to run for non snapshots once FW v17.0.0-rc.1 is released on NPM. | ||
const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; | ||
if (!isSnapshotBuild) { | ||
return; | ||
} | ||
|
||
const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; | ||
if (useWebpackBuilder) { | ||
// Not supported by the webpack based builder. | ||
return; | ||
} | ||
|
||
// Forcibly remove in case another test doesn't clean itself up. | ||
await rimraf('node_modules/@angular/ssr'); | ||
await ng('add', '@angular/ssr', '--skip-confirmation'); | ||
await useSha(); | ||
await installWorkspacePackages(); | ||
|
||
await writeMultipleFiles({ | ||
// Add http client and route | ||
'src/app/app.config.ts': ` | ||
import { ApplicationConfig } from '@angular/core'; | ||
import { provideRouter } from '@angular/router'; | ||
import {HomeComponent} from './home/home.component'; | ||
import { provideClientHydration } from '@angular/platform-browser'; | ||
import { provideHttpClient, withFetch } from '@angular/common/http'; | ||
export const appConfig: ApplicationConfig = { | ||
providers: [ | ||
provideRouter([{ | ||
path: '', | ||
component: HomeComponent, | ||
}]), | ||
provideClientHydration(), | ||
provideHttpClient(withFetch()), | ||
], | ||
}; | ||
`, | ||
// Add asset | ||
'src/assets/media.json': JSON.stringify({ dataFromAssets: true }), | ||
// Update component to do an HTTP call to asset. | ||
'src/app/app.component.ts': ` | ||
import { Component, inject } from '@angular/core'; | ||
import { CommonModule } from '@angular/common'; | ||
import { RouterOutlet } from '@angular/router'; | ||
import { HttpClient } from '@angular/common/http'; | ||
@Component({ | ||
selector: 'app-root', | ||
standalone: true, | ||
imports: [CommonModule, RouterOutlet], | ||
template: \` | ||
<p>{{ data | json }}</p> | ||
<router-outlet></router-outlet> | ||
\`, | ||
}) | ||
export class AppComponent { | ||
data: any; | ||
constructor() { | ||
const http = inject(HttpClient); | ||
http.get('/assets/media.json').subscribe((d) => { | ||
this.data = d; | ||
}); | ||
} | ||
} | ||
`, | ||
}); | ||
|
||
await ng('generate', 'component', 'home'); | ||
await ng('build', '--configuration=production', '--prerender'); | ||
await expectFileToMatch( | ||
'dist/test-project/browser/index.html', | ||
/<p>{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/, | ||
); | ||
} |