|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.dev/license |
| 7 | + */ |
| 8 | + |
| 9 | +import { ApplicationRef, StaticProvider, Type } from '@angular/core'; |
| 10 | +import { BootstrapContext } from '@angular/platform-browser'; |
| 11 | +import { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/platform-server'; |
| 12 | +import * as fs from 'node:fs'; |
| 13 | +import { dirname, join, normalize, resolve } from 'node:path'; |
| 14 | +import { URL } from 'node:url'; |
| 15 | +import { CommonEngineInlineCriticalCssProcessor } from './inline-css-processor'; |
| 16 | +import { |
| 17 | + noopRunMethodAndMeasurePerf, |
| 18 | + printPerformanceLogs, |
| 19 | + runMethodAndMeasurePerf, |
| 20 | +} from './peformance-profiler'; |
| 21 | + |
| 22 | +const SSG_MARKER_REGEXP = /ng-server-context=["']\w*\|?ssg\|?\w*["']/; |
| 23 | + |
| 24 | +export interface CommonEngineOptions { |
| 25 | + /** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */ |
| 26 | + bootstrap?: Type<{}> | ((context: BootstrapContext) => Promise<ApplicationRef>); |
| 27 | + |
| 28 | + /** A set of platform level providers for all requests. */ |
| 29 | + providers?: StaticProvider[]; |
| 30 | + |
| 31 | + /** Enable request performance profiling data collection and printing the results in the server console. */ |
| 32 | + enablePerformanceProfiler?: boolean; |
| 33 | +} |
| 34 | + |
| 35 | +export interface CommonEngineRenderOptions { |
| 36 | + /** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */ |
| 37 | + bootstrap?: Type<{}> | (() => Promise<ApplicationRef>); |
| 38 | + |
| 39 | + /** A set of platform level providers for the current request. */ |
| 40 | + providers?: StaticProvider[]; |
| 41 | + url?: string; |
| 42 | + document?: string; |
| 43 | + documentFilePath?: string; |
| 44 | + |
| 45 | + /** |
| 46 | + * Reduce render blocking requests by inlining critical CSS. |
| 47 | + * Defaults to true. |
| 48 | + */ |
| 49 | + inlineCriticalCss?: boolean; |
| 50 | + |
| 51 | + /** |
| 52 | + * Base path location of index file. |
| 53 | + * Defaults to the 'documentFilePath' dirname when not provided. |
| 54 | + */ |
| 55 | + publicPath?: string; |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * A common engine to use to server render an application. |
| 60 | + */ |
| 61 | + |
| 62 | +export class CommonEngine { |
| 63 | + private readonly templateCache = new Map<string, string>(); |
| 64 | + private readonly inlineCriticalCssProcessor = new CommonEngineInlineCriticalCssProcessor(); |
| 65 | + private readonly pageIsSSG = new Map<string, boolean>(); |
| 66 | + |
| 67 | + constructor(private options?: CommonEngineOptions) {} |
| 68 | + |
| 69 | + /** |
| 70 | + * Render an HTML document for a specific URL with specified |
| 71 | + * render options |
| 72 | + */ |
| 73 | + async render(opts: CommonEngineRenderOptions): Promise<string> { |
| 74 | + const enablePerformanceProfiler = this.options?.enablePerformanceProfiler; |
| 75 | + |
| 76 | + const runMethod = enablePerformanceProfiler |
| 77 | + ? runMethodAndMeasurePerf |
| 78 | + : noopRunMethodAndMeasurePerf; |
| 79 | + |
| 80 | + let html = await runMethod('Retrieve SSG Page', () => this.retrieveSSGPage(opts)); |
| 81 | + |
| 82 | + if (html === undefined) { |
| 83 | + html = await runMethod('Render Page', () => this.renderApplication(opts)); |
| 84 | + |
| 85 | + if (opts.inlineCriticalCss !== false) { |
| 86 | + const content = await runMethod('Inline Critical CSS', () => |
| 87 | + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 88 | + this.inlineCriticalCss(html!, opts), |
| 89 | + ); |
| 90 | + |
| 91 | + html = content; |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + if (enablePerformanceProfiler) { |
| 96 | + printPerformanceLogs(); |
| 97 | + } |
| 98 | + |
| 99 | + return html; |
| 100 | + } |
| 101 | + |
| 102 | + private inlineCriticalCss(html: string, opts: CommonEngineRenderOptions): Promise<string> { |
| 103 | + const outputPath = |
| 104 | + opts.publicPath ?? (opts.documentFilePath ? dirname(opts.documentFilePath) : ''); |
| 105 | + |
| 106 | + return this.inlineCriticalCssProcessor.process(html, outputPath); |
| 107 | + } |
| 108 | + |
| 109 | + private async retrieveSSGPage(opts: CommonEngineRenderOptions): Promise<string | undefined> { |
| 110 | + const { publicPath, documentFilePath, url } = opts; |
| 111 | + if (!publicPath || !documentFilePath || url === undefined) { |
| 112 | + return undefined; |
| 113 | + } |
| 114 | + |
| 115 | + const { pathname } = new URL(url, 'resolve://'); |
| 116 | + // Do not use `resolve` here as otherwise it can lead to path traversal vulnerability. |
| 117 | + // See: https://portswigger.net/web-security/file-path-traversal |
| 118 | + const pagePath = join(publicPath, pathname, 'index.html'); |
| 119 | + |
| 120 | + if (this.pageIsSSG.get(pagePath)) { |
| 121 | + // Serve pre-rendered page. |
| 122 | + return fs.promises.readFile(pagePath, 'utf-8'); |
| 123 | + } |
| 124 | + |
| 125 | + if (!pagePath.startsWith(normalize(publicPath))) { |
| 126 | + // Potential path traversal detected. |
| 127 | + return undefined; |
| 128 | + } |
| 129 | + |
| 130 | + if (pagePath === resolve(documentFilePath) || !(await exists(pagePath))) { |
| 131 | + // View matches with prerender path or file does not exist. |
| 132 | + this.pageIsSSG.set(pagePath, false); |
| 133 | + |
| 134 | + return undefined; |
| 135 | + } |
| 136 | + |
| 137 | + // Static file exists. |
| 138 | + const content = await fs.promises.readFile(pagePath, 'utf-8'); |
| 139 | + const isSSG = SSG_MARKER_REGEXP.test(content); |
| 140 | + this.pageIsSSG.set(pagePath, isSSG); |
| 141 | + |
| 142 | + return isSSG ? content : undefined; |
| 143 | + } |
| 144 | + |
| 145 | + private async renderApplication(opts: CommonEngineRenderOptions): Promise<string> { |
| 146 | + const moduleOrFactory = this.options?.bootstrap ?? opts.bootstrap; |
| 147 | + if (!moduleOrFactory) { |
| 148 | + throw new Error('A module or bootstrap option must be provided.'); |
| 149 | + } |
| 150 | + |
| 151 | + const extraProviders: StaticProvider[] = [ |
| 152 | + { provide: ɵSERVER_CONTEXT, useValue: 'ssr' }, |
| 153 | + ...(opts.providers ?? []), |
| 154 | + ...(this.options?.providers ?? []), |
| 155 | + ]; |
| 156 | + |
| 157 | + let document = opts.document; |
| 158 | + if (!document && opts.documentFilePath) { |
| 159 | + document = await this.getDocument(opts.documentFilePath); |
| 160 | + } |
| 161 | + |
| 162 | + const commonRenderingOptions = { |
| 163 | + url: opts.url, |
| 164 | + document, |
| 165 | + }; |
| 166 | + |
| 167 | + return isBootstrapFn(moduleOrFactory) |
| 168 | + ? renderApplication(moduleOrFactory, { |
| 169 | + platformProviders: extraProviders, |
| 170 | + ...commonRenderingOptions, |
| 171 | + }) |
| 172 | + : renderModule(moduleOrFactory, { extraProviders, ...commonRenderingOptions }); |
| 173 | + } |
| 174 | + |
| 175 | + /** Retrieve the document from the cache or the filesystem */ |
| 176 | + private async getDocument(filePath: string): Promise<string> { |
| 177 | + let doc = this.templateCache.get(filePath); |
| 178 | + |
| 179 | + if (!doc) { |
| 180 | + doc = await fs.promises.readFile(filePath, 'utf-8'); |
| 181 | + this.templateCache.set(filePath, doc); |
| 182 | + } |
| 183 | + |
| 184 | + return doc; |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +async function exists(path: fs.PathLike): Promise<boolean> { |
| 189 | + try { |
| 190 | + await fs.promises.access(path, fs.constants.F_OK); |
| 191 | + |
| 192 | + return true; |
| 193 | + } catch { |
| 194 | + return false; |
| 195 | + } |
| 196 | +} |
| 197 | + |
| 198 | +function isBootstrapFn( |
| 199 | + value: unknown, |
| 200 | +): value is (context: BootstrapContext) => Promise<ApplicationRef> { |
| 201 | + // We can differentiate between a module and a bootstrap function by reading compiler-generated `ɵmod` static property: |
| 202 | + return typeof value === 'function' && !('ɵmod' in value); |
| 203 | +} |
0 commit comments